blob: 00ea45c4e024ab9daf1975fee4274ad07d0c1a7f [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
yuemingw1d13eae2018-01-30 17:27:54 +000019import static android.os.Process.ROOT_UID;
20import static android.os.Process.SHELL_UID;
21import static android.os.Process.SYSTEM_UID;
22
Svetoslav683914b2015-01-15 14:22:26 -080023import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080024import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070025import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070026import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070027import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080028import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070029import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080030import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070032import android.content.ContentValues;
33import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070034import android.content.Intent;
35import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080036import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070037import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080038import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070040import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070041import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080043import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.database.sqlite.SQLiteDatabase;
45import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040047import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080050import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080051import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070052import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080053import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070054import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070055import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070056import android.os.Looper;
57import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070059import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070060import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070061import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070062import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070063import android.os.UserHandle;
64import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070065import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070066import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010067import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080068import android.provider.Settings.Secure;
yuemingw1d13eae2018-01-30 17:27:54 +000069import android.provider.SettingsValidators;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070070import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010071import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080072import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000073import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070076import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080077import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040078
Svetoslav683914b2015-01-15 14:22:26 -080079import com.android.internal.annotations.GuardedBy;
80import com.android.internal.content.PackageMonitor;
81import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080082import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070083import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080084import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040085
Svetoslav683914b2015-01-15 14:22:26 -080086import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080087import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080089import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080090import java.nio.ByteBuffer;
91import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070094import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080095import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000096import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000097import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080098import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080099import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +0100100import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -0800101import java.util.Set;
102import java.util.regex.Pattern;
yuemingw1d13eae2018-01-30 17:27:54 +0000103
Mark Rathjen7599f132017-01-23 14:15:54 -0800104import javax.crypto.Mac;
105import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
Svetoslav Ganove080da92016-12-21 17:10:35 -0800107
Svetoslav683914b2015-01-15 14:22:26 -0800108/**
109 * <p>
110 * This class is a content provider that publishes the system settings.
111 * It can be accessed via the content provider APIs or via custom call
112 * commands. The latter is a bit faster and is the preferred way to access
113 * the platform settings.
114 * </p>
115 * <p>
116 * There are three settings types, global (with signature level protection
117 * and shared across users), secure (with signature permission level
118 * protection and per user), and system (with dangerous permission level
119 * protection and per user). Global settings are stored under the device owner.
120 * Each of these settings is represented by a {@link
121 * com.android.providers.settings.SettingsState} object mapped to an integer
122 * key derived from the setting type in the most significant bits and user
123 * id in the least significant bits. Settings are synchronously loaded on
124 * instantiation of a SettingsState and asynchronously persisted on mutation.
125 * Settings are stored in the user specific system directory.
126 * </p>
127 * <p>
128 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
129 * and get a warning. Targeting higher API version prohibits this as the
130 * system settings are not a place for apps to save their state. When a package
131 * is removed the settings it added are deleted. Apps cannot delete system
132 * settings added by the platform. System settings values are validated to
133 * ensure the clients do not put bad values. Global and secure settings are
134 * changed only by trusted parties, therefore no validation is performed. Also
135 * there is a limit on the amount of app specific settings that can be added
136 * to prevent unlimited growth of the system process memory footprint.
137 * </p>
138 */
139@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700141 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700142
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700143 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800144
145 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700146
Christopher Tate06efb532012-08-24 15:29:27 -0700147 private static final String TABLE_SYSTEM = "system";
148 private static final String TABLE_SECURE = "secure";
149 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800150
151 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final String TABLE_FAVORITES = "favorites";
153 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800154 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
155 private static final String TABLE_BOOKMARKS = "bookmarks";
156 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Svetoslav683914b2015-01-15 14:22:26 -0800158 // The set of removed legacy tables.
159 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700160 static {
Svetoslav683914b2015-01-15 14:22:26 -0800161 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
162 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
163 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
164 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
165 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
166 }
Christopher Tate06efb532012-08-24 15:29:27 -0700167
Svetoslav683914b2015-01-15 14:22:26 -0800168 private static final int MUTATION_OPERATION_INSERT = 1;
169 private static final int MUTATION_OPERATION_DELETE = 2;
170 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800171 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400172
Svetoslav683914b2015-01-15 14:22:26 -0800173 private static final String[] ALL_COLUMNS = new String[] {
174 Settings.NameValueTable._ID,
175 Settings.NameValueTable.NAME,
176 Settings.NameValueTable.VALUE
177 };
178
Makoto Onuki53f0e022017-11-29 13:51:01 -0800179 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
180 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
181 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
182 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Matt Pape1b31a332018-10-17 09:58:28 -0700183 public static final int SETTINGS_TYPE_CONFIG = SettingsState.SETTINGS_TYPE_CONFIG;
Svet Ganov53a441c2016-04-19 19:38:00 -0700184
185 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
186 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700187
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800188 public static final String RESULT_ROWS_DELETED = "result_rows_deleted";
Nicholas Sauer72500532018-11-21 10:30:58 -0800189 public static final String RESULT_SETTINGS_LIST = "result_settings_list";
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800190
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700191 // Overlay specified settings whitelisted for Instant Apps
192 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
193 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
194 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
195
Matt Pape1b31a332018-10-17 09:58:28 -0700196 /**
197 * TODO(b/113100523): Move this to DeviceConfig.java when it is added, and expose it as a System
198 * API.
199 */
200 private static final Uri CONFIG_CONTENT_URI =
201 Uri.parse("content://" + Settings.AUTHORITY + "/config");
202
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700203 static {
204 for (String name : Resources.getSystem().getStringArray(
205 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
206 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
207 }
208 for (String name : Resources.getSystem().getStringArray(
209 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
210 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
211 }
212 for (String name : Resources.getSystem().getStringArray(
213 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
214 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
215 }
216 }
217
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800218 // Changes to these global settings are synchronously persisted
219 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
220 static {
221 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
222 }
223
224 // Changes to these secure settings are synchronously persisted
225 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
226 static {
227 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
228 }
229
Svetoslav683914b2015-01-15 14:22:26 -0800230 // Per user secure settings that moved to the for all users global settings.
231 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
232 static {
233 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700234 }
235
Svetoslav683914b2015-01-15 14:22:26 -0800236 // Per user system settings that moved to the for all users global settings.
237 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
238 static {
239 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700240 }
241
Svetoslav683914b2015-01-15 14:22:26 -0800242 // Per user system settings that moved to the per user secure settings.
243 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
244 static {
245 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 }
247
Svetoslav683914b2015-01-15 14:22:26 -0800248 // Per all users global settings that moved to the per user secure settings.
249 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
250 static {
251 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252 }
253
Svetoslav683914b2015-01-15 14:22:26 -0800254 // Per user secure settings that are cloned for the managed profiles of the user.
255 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
256 static {
257 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700258 }
259
Svetoslav683914b2015-01-15 14:22:26 -0800260 // Per user system settings that are cloned for the managed profiles of the user.
261 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
262 static {
263 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400264 }
265
Andre Lago3fa139c2016-08-04 13:53:44 +0100266 // Per user system settings that are cloned from the profile's parent when a dependency
267 // in {@link Settings.Secure} is set to "1".
268 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
269 static {
270 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
271 }
272
Svetoslav683914b2015-01-15 14:22:26 -0800273 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700274
Svetoslav683914b2015-01-15 14:22:26 -0800275 @GuardedBy("mLock")
276 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700277
Svet Ganova8f90262016-05-10 08:44:48 -0700278 @GuardedBy("mLock")
279 private HandlerThread mHandlerThread;
280
Makoto Onuki73360ab2017-03-17 11:50:13 -0700281 @GuardedBy("mLock")
282 private Handler mHandler;
283
Svetoslav7ec28e82015-05-20 17:01:10 -0700284 // We have to call in the user manager with no lock held,
285 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800286
yuemingw1d13eae2018-01-30 17:27:54 +0000287 private UserManagerInternal mUserManagerInternal;
288
Svetoslav7ec28e82015-05-20 17:01:10 -0700289 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700290 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700291
Svet Ganov53a441c2016-04-19 19:38:00 -0700292 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800293 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700294 }
295
296 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800297 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700298 }
299
300 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800301 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700302 }
303
304 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800305 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700306 }
307
308 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800309 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700310 }
311
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700312 @Override
313 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800314 Settings.setInSystemServer();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000315
316 // fail to boot if there're any backed up settings that don't have a non-null validator
317 ensureAllBackedUpSystemSettingsHaveValidators();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000318 ensureAllBackedUpGlobalSettingsHaveValidators();
Michal Karpinski964943a2018-01-19 16:28:26 +0000319 ensureAllBackedUpSecureSettingsHaveValidators();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000320
Svetoslav683914b2015-01-15 14:22:26 -0800321 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700322 mUserManager = UserManager.get(getContext());
yuemingw1d13eae2018-01-30 17:27:54 +0000323 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
Xiaohui Chen43765b72015-08-31 10:57:33 -0700324 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700325 mHandlerThread = new HandlerThread(LOG_TAG,
326 Process.THREAD_PRIORITY_BACKGROUND);
327 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700328 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800329 mSettingsRegistry = new SettingsRegistry();
330 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700331 mHandler.post(() -> {
332 registerBroadcastReceivers();
333 startWatchingUserRestrictionChanges();
334 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700335 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700336 return true;
337 }
338
Michal Karpinski2c37b082018-01-18 16:14:27 +0000339 private void ensureAllBackedUpSystemSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000340 String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
341 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000342
343 failToBootIfOffendersPresent(offenders, "Settings.System");
344 }
345
346 private void ensureAllBackedUpGlobalSettingsHaveValidators() {
Michal Karpinski964943a2018-01-19 16:28:26 +0000347 String offenders = getOffenders(concat(Settings.Global.SETTINGS_TO_BACKUP,
348 Settings.Global.LEGACY_RESTORE_SETTINGS), Settings.Global.VALIDATORS);
Michal Karpinski5db1e432018-01-18 20:10:24 +0000349
350 failToBootIfOffendersPresent(offenders, "Settings.Global");
351 }
352
Michal Karpinski964943a2018-01-19 16:28:26 +0000353 private void ensureAllBackedUpSecureSettingsHaveValidators() {
354 String offenders = getOffenders(concat(Settings.Secure.SETTINGS_TO_BACKUP,
355 Settings.Secure.LEGACY_RESTORE_SETTINGS), Settings.Secure.VALIDATORS);
356
357 failToBootIfOffendersPresent(offenders, "Settings.Secure");
358 }
359
Michal Karpinski5db1e432018-01-18 20:10:24 +0000360 private void failToBootIfOffendersPresent(String offenders, String settingsType) {
361 if (offenders.length() > 0) {
362 throw new RuntimeException("All " + settingsType + " settings that are backed up"
363 + " have to have a non-null validator, but those don't: " + offenders);
364 }
365 }
366
367 private String getOffenders(String[] settingsToBackup, Map<String,
368 SettingsValidators.Validator> validators) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000369 StringBuilder offenders = new StringBuilder();
Michal Karpinski5db1e432018-01-18 20:10:24 +0000370 for (String setting : settingsToBackup) {
371 if (validators.get(setting) == null) {
Michal Karpinski2c37b082018-01-18 16:14:27 +0000372 offenders.append(setting).append(" ");
373 }
374 }
Michal Karpinski5db1e432018-01-18 20:10:24 +0000375 return offenders.toString();
Michal Karpinski2c37b082018-01-18 16:14:27 +0000376 }
377
Michal Karpinski964943a2018-01-19 16:28:26 +0000378 private final String[] concat(String[] first, String[] second) {
379 if (second == null || second.length == 0) {
380 return first;
381 }
382 final int firstLen = first.length;
383 final int secondLen = second.length;
384 String[] both = new String[firstLen + secondLen];
385 System.arraycopy(first, 0, both, 0, firstLen);
386 System.arraycopy(second, 0, both, firstLen, secondLen);
387 return both;
388 }
389
Svetoslav683914b2015-01-15 14:22:26 -0800390 @Override
391 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700392 final int requestingUserId = getRequestingUserId(args);
393 switch (method) {
Matt Pape1b31a332018-10-17 09:58:28 -0700394 case Settings.CALL_METHOD_GET_CONFIG: {
395 Setting setting = getConfigSetting(name);
396 return packageValueForCallResult(setting, isTrackingGeneration(args));
397 }
398
Svetoslav7ec28e82015-05-20 17:01:10 -0700399 case Settings.CALL_METHOD_GET_GLOBAL: {
400 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700401 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800402 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700403
404 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800405 Setting setting = getSecureSetting(name, requestingUserId,
406 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700407 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700408 }
409
410 case Settings.CALL_METHOD_GET_SYSTEM: {
411 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700412 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700413 }
414
Matt Pape1b31a332018-10-17 09:58:28 -0700415 case Settings.CALL_METHOD_PUT_CONFIG: {
416 String value = getSettingValue(args);
417 String tag = getSettingTag(args);
418 final boolean makeDefault = getSettingMakeDefault(args);
419 insertConfigSetting(name, value, tag, makeDefault, requestingUserId, false);
420 break;
421 }
422
Svetoslav7ec28e82015-05-20 17:01:10 -0700423 case Settings.CALL_METHOD_PUT_GLOBAL: {
424 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800425 String tag = getSettingTag(args);
426 final boolean makeDefault = getSettingMakeDefault(args);
427 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700428 break;
429 }
430
431 case Settings.CALL_METHOD_PUT_SECURE: {
432 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800433 String tag = getSettingTag(args);
434 final boolean makeDefault = getSettingMakeDefault(args);
435 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 break;
437 }
438
439 case Settings.CALL_METHOD_PUT_SYSTEM: {
440 String value = getSettingValue(args);
441 insertSystemSetting(name, value, requestingUserId);
442 break;
443 }
444
Matt Pape1b31a332018-10-17 09:58:28 -0700445 case Settings.CALL_METHOD_RESET_CONFIG: {
446 final int mode = getResetModeEnforcingPermission(args);
447 String tag = getSettingTag(args);
448 resetConfigSetting(requestingUserId, mode, tag);
449 break;
450 }
451
Svetoslav Ganove080da92016-12-21 17:10:35 -0800452 case Settings.CALL_METHOD_RESET_GLOBAL: {
453 final int mode = getResetModeEnforcingPermission(args);
454 String tag = getSettingTag(args);
455 resetGlobalSetting(requestingUserId, mode, tag);
456 break;
457 }
458
459 case Settings.CALL_METHOD_RESET_SECURE: {
460 final int mode = getResetModeEnforcingPermission(args);
461 String tag = getSettingTag(args);
462 resetSecureSetting(requestingUserId, mode, tag);
463 break;
464 }
465
Nicholas Sauer3d87d1e2018-11-06 08:38:39 -0800466 case Settings.CALL_METHOD_DELETE_SYSTEM: {
467 int rows = deleteSystemSetting(name, requestingUserId) ? 1 : 0;
468 Bundle result = new Bundle();
469 result.putInt(RESULT_ROWS_DELETED, rows);
470 return result;
471 }
472
473 case Settings.CALL_METHOD_DELETE_SECURE: {
474 int rows = deleteSecureSetting(name, requestingUserId, false) ? 1 : 0;
475 Bundle result = new Bundle();
476 result.putInt(RESULT_ROWS_DELETED, rows);
477 return result;
478 }
479
480 case Settings.CALL_METHOD_DELETE_GLOBAL: {
481 int rows = deleteGlobalSetting(name, requestingUserId, false) ? 1 : 0;
482 Bundle result = new Bundle();
483 result.putInt(RESULT_ROWS_DELETED, rows);
484 return result;
485 }
486
Nicholas Sauer72500532018-11-21 10:30:58 -0800487 case Settings.CALL_METHOD_LIST_SYSTEM: {
488 Bundle result = new Bundle();
489 result.putStringArrayList(RESULT_SETTINGS_LIST,
490 buildSettingsList(getAllSystemSettings(requestingUserId, null)));
491 return result;
492 }
493
494 case Settings.CALL_METHOD_LIST_SECURE: {
495 Bundle result = new Bundle();
496 result.putStringArrayList(RESULT_SETTINGS_LIST,
497 buildSettingsList(getAllSecureSettings(requestingUserId, null)));
498 return result;
499 }
500
501 case Settings.CALL_METHOD_LIST_GLOBAL: {
502 Bundle result = new Bundle();
503 result.putStringArrayList(RESULT_SETTINGS_LIST,
504 buildSettingsList(getAllGlobalSettings(null)));
505 return result;
506 }
507
Svetoslav7ec28e82015-05-20 17:01:10 -0700508 default: {
509 Slog.w(LOG_TAG, "call() with invalid method: " + method);
510 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700511 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700512
Christopher Tate06efb532012-08-24 15:29:27 -0700513 return null;
514 }
515
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800516 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800517 public String getType(Uri uri) {
518 Arguments args = new Arguments(uri, null, null, true);
519 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700520 return "vnd.android.cursor.dir/" + args.table;
521 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700522 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523 }
524 }
525
526 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800527 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
528 String order) {
529 if (DEBUG) {
530 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700531 }
532
Svetoslav683914b2015-01-15 14:22:26 -0800533 Arguments args = new Arguments(uri, where, whereArgs, true);
534 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700535
Svetoslav683914b2015-01-15 14:22:26 -0800536 // If a legacy table that is gone, done.
537 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
538 return new MatrixCursor(normalizedProjection, 0);
539 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700540
Svetoslav7ec28e82015-05-20 17:01:10 -0700541 switch (args.table) {
542 case TABLE_GLOBAL: {
543 if (args.name != null) {
544 Setting setting = getGlobalSetting(args.name);
545 return packageSettingForQuery(setting, normalizedProjection);
546 } else {
547 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700548 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700549 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700550
Svetoslav7ec28e82015-05-20 17:01:10 -0700551 case TABLE_SECURE: {
552 final int userId = UserHandle.getCallingUserId();
553 if (args.name != null) {
554 Setting setting = getSecureSetting(args.name, userId);
555 return packageSettingForQuery(setting, normalizedProjection);
556 } else {
557 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800558 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700559 }
Svetoslav683914b2015-01-15 14:22:26 -0800560
Svetoslav7ec28e82015-05-20 17:01:10 -0700561 case TABLE_SYSTEM: {
562 final int userId = UserHandle.getCallingUserId();
563 if (args.name != null) {
564 Setting setting = getSystemSetting(args.name, userId);
565 return packageSettingForQuery(setting, normalizedProjection);
566 } else {
567 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800568 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700569 }
Svetoslav683914b2015-01-15 14:22:26 -0800570
Svetoslav7ec28e82015-05-20 17:01:10 -0700571 default: {
572 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700573 }
574 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700575 }
576
Nicholas Sauer72500532018-11-21 10:30:58 -0800577 private ArrayList<String> buildSettingsList(Cursor cursor) {
578 final ArrayList<String> lines = new ArrayList<String>();
579 try {
580 while (cursor != null && cursor.moveToNext()) {
581 lines.add(cursor.getString(1) + "=" + cursor.getString(2));
582 }
583 } finally {
584 if (cursor != null) {
585 cursor.close();
586 }
587 }
588 return lines;
589 }
590
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700591 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800592 public Uri insert(Uri uri, ContentValues values) {
593 if (DEBUG) {
594 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700595 }
596
Svetoslav683914b2015-01-15 14:22:26 -0800597 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700598
Svetoslav683914b2015-01-15 14:22:26 -0800599 // If a legacy table that is gone, done.
600 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 return null;
602 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700603
Svetoslav683914b2015-01-15 14:22:26 -0800604 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700605 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800606 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700607 }
608
Svetoslav683914b2015-01-15 14:22:26 -0800609 String value = values.getAsString(Settings.Secure.VALUE);
610
Svetoslav7ec28e82015-05-20 17:01:10 -0700611 switch (table) {
612 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800613 if (insertGlobalSetting(name, value, null, false,
614 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700615 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700616 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700617 } break;
618
619 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800620 if (insertSecureSetting(name, value, null, false,
621 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700622 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
623 }
624 } break;
625
626 case TABLE_SYSTEM: {
627 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
628 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
629 }
630 } break;
631
632 default: {
633 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700634 }
635 }
636
Svetoslav683914b2015-01-15 14:22:26 -0800637 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700638 }
639
640 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800641 public int bulkInsert(Uri uri, ContentValues[] allValues) {
642 if (DEBUG) {
643 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700645
Svetoslav683914b2015-01-15 14:22:26 -0800646 int insertionCount = 0;
647 final int valuesCount = allValues.length;
648 for (int i = 0; i < valuesCount; i++) {
649 ContentValues values = allValues[i];
650 if (insert(uri, values) != null) {
651 insertionCount++;
652 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700653 }
Svetoslav683914b2015-01-15 14:22:26 -0800654
655 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700656 }
657
658 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800659 public int delete(Uri uri, String where, String[] whereArgs) {
660 if (DEBUG) {
661 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700663
Svetoslav683914b2015-01-15 14:22:26 -0800664 Arguments args = new Arguments(uri, where, whereArgs, false);
665
666 // If a legacy table that is gone, done.
667 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
668 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700669 }
Svetoslav683914b2015-01-15 14:22:26 -0800670
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700671 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800672 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700673 }
Svetoslav683914b2015-01-15 14:22:26 -0800674
Svetoslav7ec28e82015-05-20 17:01:10 -0700675 switch (args.table) {
676 case TABLE_GLOBAL: {
677 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700678 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700679 }
Svetoslav683914b2015-01-15 14:22:26 -0800680
Svetoslav7ec28e82015-05-20 17:01:10 -0700681 case TABLE_SECURE: {
682 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700683 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700684 }
Svetoslav683914b2015-01-15 14:22:26 -0800685
Svetoslav7ec28e82015-05-20 17:01:10 -0700686 case TABLE_SYSTEM: {
687 final int userId = UserHandle.getCallingUserId();
688 return deleteSystemSetting(args.name, userId) ? 1 : 0;
689 }
690
691 default: {
692 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800693 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700694 }
Svetoslav683914b2015-01-15 14:22:26 -0800695 }
696
697 @Override
698 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
699 if (DEBUG) {
700 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700701 }
Svetoslav683914b2015-01-15 14:22:26 -0800702
703 Arguments args = new Arguments(uri, where, whereArgs, false);
704
705 // If a legacy table that is gone, done.
706 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
707 return 0;
708 }
709
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700710 String name = values.getAsString(Settings.Secure.NAME);
711 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800712 return 0;
713 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700714 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800715
Svetoslav7ec28e82015-05-20 17:01:10 -0700716 switch (args.table) {
717 case TABLE_GLOBAL: {
718 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800719 return updateGlobalSetting(args.name, value, null, false,
720 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700721 }
Svetoslav683914b2015-01-15 14:22:26 -0800722
Svetoslav7ec28e82015-05-20 17:01:10 -0700723 case TABLE_SECURE: {
724 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800725 return updateSecureSetting(args.name, value, null, false,
726 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700727 }
Svetoslav683914b2015-01-15 14:22:26 -0800728
Svetoslav7ec28e82015-05-20 17:01:10 -0700729 case TABLE_SYSTEM: {
730 final int userId = UserHandle.getCallingUserId();
731 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
732 }
Svetoslav683914b2015-01-15 14:22:26 -0800733
Svetoslav7ec28e82015-05-20 17:01:10 -0700734 default: {
735 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800736 }
737 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700738 }
739
740 @Override
741 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100742 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
743 if (userId != UserHandle.getCallingUserId()) {
744 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
745 "Access files from the settings of another user");
746 }
747 uri = ContentProvider.getUriWithoutUserId(uri);
748
Andre Lago3fa139c2016-08-04 13:53:44 +0100749 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700750 final String cacheName;
751 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100752 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700753 cacheName = Settings.System.RINGTONE_CACHE;
754 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100755 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700756 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
757 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100758 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700759 cacheName = Settings.System.ALARM_ALERT_CACHE;
760 } else {
761 throw new FileNotFoundException("Direct file access no longer supported; "
762 + "ringtone playback is available through android.media.Ringtone");
763 }
764
Andre Lago3fa139c2016-08-04 13:53:44 +0100765 int actualCacheOwner;
766 // Redirect cache to parent if ringtone setting is owned by profile parent
767 synchronized (mLock) {
768 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
769 cacheRingtoneSetting);
770 }
771 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700772 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
773 }
774
775 private File getRingtoneCacheDir(int userId) {
776 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
777 cacheDir.mkdir();
778 SELinux.restorecon(cacheDir);
779 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700780 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800781
Eugene Suslad72c3972016-12-27 15:49:30 -0800782 /**
783 * Dump all settings as a proto buf.
784 *
785 * @param fd The file to dump to
786 */
787 void dumpProto(@NonNull FileDescriptor fd) {
788 ProtoOutputStream proto = new ProtoOutputStream(fd);
789
790 synchronized (mLock) {
791 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800792 }
793
794 proto.flush();
795 }
796
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700797 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800798 synchronized (mLock) {
799 final long identity = Binder.clearCallingIdentity();
800 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700801 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800802 final int userCount = users.size();
803 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700804 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800805 }
806 } finally {
807 Binder.restoreCallingIdentity(identity);
808 }
809 }
810 }
811
Andreas Gampeb58893072018-09-05 16:52:31 -0700812 @GuardedBy("mLock")
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700813 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700814 if (userId == UserHandle.USER_SYSTEM) {
Matt Pape1b31a332018-10-17 09:58:28 -0700815 pw.println("CONFIG SETTINGS (user " + userId + ")");
816 SettingsState configSettings = mSettingsRegistry.getSettingsLocked(
817 SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
818 if (configSettings != null) {
819 dumpSettingsLocked(configSettings, pw);
820 pw.println();
821 configSettings.dumpHistoricalOperations(pw);
822 }
823
Svetoslavb505ccc2015-02-17 12:41:04 -0800824 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700825 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
826 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700827 if (globalSettings != null) {
828 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800829 pw.println();
830 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700831 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800832 }
833
834 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700835 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
836 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700837 if (secureSettings != null) {
838 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800839 pw.println();
840 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700841 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700842
Svetoslavb505ccc2015-02-17 12:41:04 -0800843 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700844 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
845 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700846 if (systemSettings != null) {
847 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800848 pw.println();
849 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700850 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800851 }
852
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700853 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
854 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800855
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700856 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800857
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700858 for (int i = 0; i < nameCount; i++) {
859 String name = names.get(i);
860 Setting setting = settingsState.getSettingLocked(name);
861 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
862 pw.print(" name:"); pw.print(toDumpString(name));
863 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800864 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700865 }
866 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800867 if (setting.getDefaultValue() != null) {
868 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800869 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800870 }
871 if (setting.getTag() != null) {
872 pw.print(" tag:"); pw.print(setting.getTag());
873 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800874 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700875 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800876 }
877
Svetoslav7e0683b2015-08-03 16:02:52 -0700878 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700879 if (s != null) {
880 return s;
881 }
882 return "{null}";
883 }
884
Svetoslav683914b2015-01-15 14:22:26 -0800885 private void registerBroadcastReceivers() {
886 IntentFilter userFilter = new IntentFilter();
887 userFilter.addAction(Intent.ACTION_USER_REMOVED);
888 userFilter.addAction(Intent.ACTION_USER_STOPPED);
889
890 getContext().registerReceiver(new BroadcastReceiver() {
891 @Override
892 public void onReceive(Context context, Intent intent) {
893 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700894 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800895
896 switch (intent.getAction()) {
897 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700898 synchronized (mLock) {
899 mSettingsRegistry.removeUserStateLocked(userId, true);
900 }
Svetoslav683914b2015-01-15 14:22:26 -0800901 } break;
902
903 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700904 synchronized (mLock) {
905 mSettingsRegistry.removeUserStateLocked(userId, false);
906 }
Svetoslav683914b2015-01-15 14:22:26 -0800907 } break;
908 }
909 }
910 }, userFilter);
911
912 PackageMonitor monitor = new PackageMonitor() {
913 @Override
914 public void onPackageRemoved(String packageName, int uid) {
915 synchronized (mLock) {
Zimuzoc56192c2018-07-25 10:40:01 +0100916 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
Svetoslav683914b2015-01-15 14:22:26 -0800917 UserHandle.getUserId(uid));
918 }
919 }
Mark Rathjend891f012017-01-19 04:10:37 +0000920
921 @Override
922 public void onUidRemoved(int uid) {
923 synchronized (mLock) {
924 mSettingsRegistry.onUidRemovedLocked(uid);
925 }
926 }
Zimuzoc56192c2018-07-25 10:40:01 +0100927
928 @Override
929 public void onPackageDataCleared(String packageName, int uid) {
930 synchronized (mLock) {
931 mSettingsRegistry.removeSettingsForPackageLocked(packageName,
932 UserHandle.getUserId(uid));
933 }
934 }
Svetoslav683914b2015-01-15 14:22:26 -0800935 };
936
937 // package changes
938 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
939 UserHandle.ALL, true);
940 }
941
Svet Ganov53a441c2016-04-19 19:38:00 -0700942 private void startWatchingUserRestrictionChanges() {
943 // TODO: The current design of settings looking different based on user restrictions
944 // should be reworked to keep them separate and system code should check the setting
945 // first followed by checking the user restriction before performing an operation.
946 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
947 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
948 Bundle prevRestrictions) -> {
949 // We are changing the settings affected by restrictions to their current
950 // value with a forced update to ensure that all cross profile dependencies
951 // are taken into account. Also make sure the settings update to.. the same
952 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800953 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
954 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700955 final long identity = Binder.clearCallingIdentity();
956 try {
957 synchronized (mLock) {
958 Setting setting = getSecureSetting(
959 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
960 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800961 setting != null ? setting.getValue() : null, null,
962 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700963 }
964 } finally {
965 Binder.restoreCallingIdentity(identity);
966 }
967 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800968 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
Irina Dumitrescu4638edd2018-09-05 14:08:33 +0100969 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES) ||
970 newRestrictions.getBoolean(
971 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)
972 != prevRestrictions.getBoolean(
973 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700974 final long identity = Binder.clearCallingIdentity();
975 try {
976 synchronized (mLock) {
977 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800978 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700979 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800980 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700981 }
982 } finally {
983 Binder.restoreCallingIdentity(identity);
984 }
985 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800986 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
987 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700988 final long identity = Binder.clearCallingIdentity();
989 try {
990 synchronized (mLock) {
991 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800992 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700993 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800994 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700995 }
996 } finally {
997 Binder.restoreCallingIdentity(identity);
998 }
999 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001000 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
1001 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001002 final long identity = Binder.clearCallingIdentity();
1003 try {
1004 synchronized (mLock) {
1005 Setting enable = getGlobalSetting(
1006 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001007 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001008 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001009 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001010 Setting include = getGlobalSetting(
1011 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001012 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001013 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001014 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001015 }
1016 } finally {
1017 Binder.restoreCallingIdentity(identity);
1018 }
1019 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001020 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
1021 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001022 final long identity = Binder.clearCallingIdentity();
1023 try {
1024 synchronized (mLock) {
1025 Setting setting = getGlobalSetting(
1026 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -08001027 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -07001028 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001029 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -07001030 }
1031 } finally {
1032 Binder.restoreCallingIdentity(identity);
1033 }
1034 }
1035 });
1036 }
1037
Matt Pape1b31a332018-10-17 09:58:28 -07001038 private Setting getConfigSetting(String name) {
1039 if (DEBUG) {
1040 Slog.v(LOG_TAG, "getConfigSetting(" + name + ")");
1041 }
1042
1043 // TODO(b/117663715): Ensure the caller can access the setting.
1044 // enforceSettingReadable(name, SETTINGS_TYPE_CONFIG, UserHandle.getCallingUserId());
1045
1046 // Get the value.
1047 synchronized (mLock) {
1048 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_CONFIG,
1049 UserHandle.USER_SYSTEM, name);
1050 }
1051 }
1052
1053 private boolean insertConfigSetting(String name, String value, String tag,
1054 boolean makeDefault, int requestingUserId, boolean forceNotify) {
1055 if (DEBUG) {
1056 Slog.v(LOG_TAG, "insertConfigSetting(" + name + ", " + value + ", "
1057 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1058 + ", " + forceNotify + ")");
1059 }
1060 return mutateConfigSetting(name, value, tag, makeDefault, requestingUserId,
1061 MUTATION_OPERATION_INSERT, forceNotify, 0);
1062 }
1063
1064 private void resetConfigSetting(int requestingUserId, int mode, String tag) {
1065 if (DEBUG) {
1066 Slog.v(LOG_TAG, "resetConfigSetting(" + requestingUserId + ", "
1067 + mode + ", " + tag + ")");
1068 }
1069 mutateConfigSetting(null, null, tag, false, requestingUserId,
1070 MUTATION_OPERATION_RESET, false, mode);
1071 }
1072
1073 private boolean mutateConfigSetting(String name, String value, String tag,
1074 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1075 int mode) {
1076 // TODO(b/117663715): check the new permission when it's added.
1077 // enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1078
1079 // Resolve the userId on whose behalf the call is made.
1080 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1081
1082 // Perform the mutation.
1083 synchronized (mLock) {
1084 switch (operation) {
1085 case MUTATION_OPERATION_INSERT: {
1086 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_CONFIG,
1087 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
1088 getCallingPackage(), forceNotify, null);
1089 }
1090
1091 case MUTATION_OPERATION_RESET: {
1092 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_CONFIG,
1093 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1094 } return true;
1095 }
1096 }
1097
1098 return false;
1099 }
1100
Svetoslav7ec28e82015-05-20 17:01:10 -07001101 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001102 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001103 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -08001104 }
1105
Svetoslav7ec28e82015-05-20 17:01:10 -07001106 synchronized (mLock) {
1107 // Get the settings.
1108 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001109 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001110
Chad Brubaker97bccee2017-01-05 15:51:41 -08001111 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
1112 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08001113
Svetoslav7ec28e82015-05-20 17:01:10 -07001114 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001115
Svetoslav7ec28e82015-05-20 17:01:10 -07001116 String[] normalizedProjection = normalizeProjection(projection);
1117 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001118
Svetoslav7ec28e82015-05-20 17:01:10 -07001119 // Anyone can get the global settings, so no security checks.
1120 for (int i = 0; i < nameCount; i++) {
1121 String name = names.get(i);
1122 Setting setting = settingsState.getSettingLocked(name);
1123 appendSettingToCursor(result, setting);
1124 }
1125
1126 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001127 }
Svetoslav683914b2015-01-15 14:22:26 -08001128 }
1129
Svetoslav7ec28e82015-05-20 17:01:10 -07001130 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -08001131 if (DEBUG) {
1132 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
1133 }
1134
Chad Brubakera6830e72017-04-28 17:34:36 -07001135 // Ensure the caller can access the setting.
1136 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
1137
Svetoslav683914b2015-01-15 14:22:26 -08001138 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001139 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001140 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001141 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -08001142 }
Svetoslav683914b2015-01-15 14:22:26 -08001143 }
1144
Svetoslav Ganove080da92016-12-21 17:10:35 -08001145 private boolean updateGlobalSetting(String name, String value, String tag,
1146 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001147 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001148 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
1149 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1150 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001151 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001152 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1153 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001154 }
1155
Svetoslav Ganove080da92016-12-21 17:10:35 -08001156 private boolean insertGlobalSetting(String name, String value, String tag,
1157 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001158 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001159 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
1160 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1161 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -07001162 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001163 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
1164 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -07001165 }
1166
Svet Ganov53a441c2016-04-19 19:38:00 -07001167 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001168 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001169 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
1170 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001171 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001172 return mutateGlobalSetting(name, null, null, false, requestingUserId,
1173 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001174 }
1175
Svetoslav Ganove080da92016-12-21 17:10:35 -08001176 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
1177 if (DEBUG) {
1178 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
1179 + mode + ", " + tag + ")");
1180 }
1181 mutateGlobalSetting(null, null, tag, false, requestingUserId,
1182 MUTATION_OPERATION_RESET, false, mode);
1183 }
1184
1185 private boolean mutateGlobalSetting(String name, String value, String tag,
1186 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1187 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001188 // Make sure the caller can change the settings - treated as secure.
1189 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1190
Svetoslav683914b2015-01-15 14:22:26 -08001191 // Resolve the userId on whose behalf the call is made.
1192 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1193
Makoto Onuki28da2e32015-11-20 11:30:44 -08001194 // If this is a setting that is currently restricted for this user, do not allow
1195 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001196 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1197 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001198 return false;
1199 }
1200
1201 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -07001202 synchronized (mLock) {
1203 switch (operation) {
1204 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001205 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
1206 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001207 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001208 }
Svetoslav683914b2015-01-15 14:22:26 -08001209
Svetoslav7ec28e82015-05-20 17:01:10 -07001210 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001211 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001212 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001213 }
Svetoslav683914b2015-01-15 14:22:26 -08001214
Svetoslav7ec28e82015-05-20 17:01:10 -07001215 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001216 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
1217 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001218 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001220
1221 case MUTATION_OPERATION_RESET: {
1222 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
1223 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1224 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001225 }
1226 }
1227
1228 return false;
1229 }
1230
Christopher Tateb218e762017-04-05 16:34:07 -07001231 private PackageInfo getCallingPackageInfo(int userId) {
1232 try {
1233 return mPackageManager.getPackageInfo(getCallingPackage(),
1234 PackageManager.GET_SIGNATURES, userId);
1235 } catch (RemoteException e) {
1236 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1237 }
1238 }
1239
Svetoslav7ec28e82015-05-20 17:01:10 -07001240 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001241 if (DEBUG) {
1242 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1243 }
1244
1245 // Resolve the userId on whose behalf the call is made.
1246 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1247
Christopher Tateb218e762017-04-05 16:34:07 -07001248 // The relevant "calling package" userId will be the owning userId for some
1249 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1250 // up front who the effective "new SSAID" user ID for that settings name will be.
1251 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1252 Settings.Secure.ANDROID_ID);
1253 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1254
Svetoslav7ec28e82015-05-20 17:01:10 -07001255 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001256 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001257
Svetoslav7ec28e82015-05-20 17:01:10 -07001258 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001259
Svetoslav7ec28e82015-05-20 17:01:10 -07001260 String[] normalizedProjection = normalizeProjection(projection);
1261 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001262
Svetoslav7ec28e82015-05-20 17:01:10 -07001263 for (int i = 0; i < nameCount; i++) {
1264 String name = names.get(i);
1265 // Determine the owning user as some profile settings are cloned from the parent.
1266 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1267 name);
Svetoslav683914b2015-01-15 14:22:26 -08001268
Alex Klyubin1991f572017-03-03 14:08:36 -08001269 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1270 // This caller is not permitted to access this setting. Pretend the setting
1271 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001272 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001273 }
Svetoslav683914b2015-01-15 14:22:26 -08001274
Mark Rathjen7599f132017-01-23 14:15:54 -08001275 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001276 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1277 final Setting setting;
1278 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001279 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001280 } else {
1281 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1282 name);
1283 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001284 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001285 }
1286
Svetoslav7ec28e82015-05-20 17:01:10 -07001287 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001288 }
Svetoslav683914b2015-01-15 14:22:26 -08001289 }
1290
Svetoslav7ec28e82015-05-20 17:01:10 -07001291 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001292 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1293 }
1294
1295 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001296 if (DEBUG) {
1297 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1298 }
1299
1300 // Resolve the userId on whose behalf the call is made.
1301 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1302
Chad Brubakera6830e72017-04-28 17:34:36 -07001303 // Ensure the caller can access the setting.
1304 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1305
Svetoslav683914b2015-01-15 14:22:26 -08001306 // Determine the owning user as some profile settings are cloned from the parent.
1307 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1308
Alex Klyubin1991f572017-03-03 14:08:36 -08001309 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1310 // This caller is not permitted to access this setting. Pretend the setting doesn't
1311 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001312 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1313 owningUserId);
1314 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001315 }
1316
Christopher Tateb218e762017-04-05 16:34:07 -07001317 // As of Android O, the SSAID is read from an app-specific entry in table
1318 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1319 if (isNewSsaidSetting(name)) {
1320 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1321 synchronized (mLock) {
1322 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001323 }
Christopher Tateb218e762017-04-05 16:34:07 -07001324 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001325 if (enableOverride) {
1326 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1327 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1328 if (overridden != null) {
1329 return overridden;
1330 }
1331 }
1332 }
Mark Rathjend891f012017-01-19 04:10:37 +00001333
Christopher Tateb218e762017-04-05 16:34:07 -07001334 // Not the SSAID; do a straight lookup
1335 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001336 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001337 owningUserId, name);
1338 }
Svetoslav683914b2015-01-15 14:22:26 -08001339 }
1340
Mark Rathjend891f012017-01-19 04:10:37 +00001341 private boolean isNewSsaidSetting(String name) {
1342 return Settings.Secure.ANDROID_ID.equals(name)
1343 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1344 }
1345
Andreas Gampeb58893072018-09-05 16:52:31 -07001346 @GuardedBy("mLock")
Christopher Tateb218e762017-04-05 16:34:07 -07001347 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001348 // Get uid of caller (key) used to store ssaid value
1349 String name = Integer.toString(
1350 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1351
1352 if (DEBUG) {
1353 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1354 }
1355
1356 // Retrieve the ssaid from the table if present.
1357 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1358 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001359 // If the app is an Instant App use its stored SSAID instead of our own.
1360 final String instantSsaid;
1361 final long token = Binder.clearCallingIdentity();
1362 try {
1363 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1364 owningUserId);
1365 } catch (RemoteException e) {
1366 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1367 return null;
1368 } finally {
1369 Binder.restoreCallingIdentity(token);
1370 }
Svet Ganov96c99462017-05-05 14:27:13 -07001371
1372 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1373 SETTINGS_TYPE_SSAID, owningUserId);
1374
Chad Brubaker0d277a72017-04-12 16:56:53 -07001375 if (instantSsaid != null) {
1376 // Use the stored value if it is still valid.
1377 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001378 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001379 }
1380 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001381 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1382 true, callingPkg.packageName);
1383 if (!success) {
1384 throw new IllegalStateException("Failed to update instant app android id");
1385 }
Svet Ganov96c99462017-05-05 14:27:13 -07001386 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1387 owningUserId, name);
1388 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001389 }
Mark Rathjend891f012017-01-19 04:10:37 +00001390
1391 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001392 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001393 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1394 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001395 }
1396
Svet Ganov96c99462017-05-05 14:27:13 -07001397 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1398 }
1399
1400 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1401 // SSAID settings are located in a dedicated table for internal bookkeeping
1402 // but for the world they reside in the secure table, so adjust the key here.
1403 // We have a special name when looking it up but want the world to see it as
1404 // "android_id".
1405 if (ssaidSetting != null) {
1406 return settingsState.new Setting(ssaidSetting) {
1407 @Override
1408 public int getKey() {
1409 final int userId = getUserIdFromKey(super.getKey());
1410 return makeKey(SETTINGS_TYPE_SECURE, userId);
1411 }
1412
1413 @Override
1414 public String getName() {
1415 return Settings.Secure.ANDROID_ID;
1416 }
1417 };
1418 }
1419 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001420 }
1421
Makoto Onuki0000d322017-11-28 16:31:47 -08001422 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1423 synchronized (mLock) {
1424 final Setting setting = getGlobalSetting(
1425 Global.LOCATION_GLOBAL_KILL_SWITCH);
1426 if (!"1".equals(setting.getValue())) {
1427 return null;
1428 }
1429 // Global kill-switch is enabled. Return an empty value.
1430 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1431 SETTINGS_TYPE_SECURE, owningUserId);
1432 return settingsState.new Setting(
1433 Secure.LOCATION_PROVIDERS_ALLOWED,
1434 "", // value
1435 "", // tag
1436 "", // default value
1437 "", // package name
1438 false, // from system
1439 "0" // id
1440 ) {
1441 @Override
1442 public boolean update(String value, boolean setDefault, String packageName,
1443 String tag, boolean forceNonSystemPackage) {
1444 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1445 return false;
1446 }
1447 };
1448 }
1449 }
1450
Svetoslav Ganove080da92016-12-21 17:10:35 -08001451 private boolean insertSecureSetting(String name, String value, String tag,
1452 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001453 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001454 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001455 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1456 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001457 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001458 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1459 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001460 }
1461
Svet Ganov53a441c2016-04-19 19:38:00 -07001462 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001463 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001464 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1465 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001466 }
1467
Svetoslav Ganove080da92016-12-21 17:10:35 -08001468 return mutateSecureSetting(name, null, null, false, requestingUserId,
1469 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001470 }
1471
Svetoslav Ganove080da92016-12-21 17:10:35 -08001472 private boolean updateSecureSetting(String name, String value, String tag,
1473 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001474 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001475 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001476 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1477 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001478 }
1479
Svetoslav Ganove080da92016-12-21 17:10:35 -08001480 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1481 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001482 }
1483
Svetoslav Ganove080da92016-12-21 17:10:35 -08001484 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1485 if (DEBUG) {
1486 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1487 + mode + ", " + tag + ")");
1488 }
1489
1490 mutateSecureSetting(null, null, tag, false, requestingUserId,
1491 MUTATION_OPERATION_RESET, false, mode);
1492 }
1493
1494 private boolean mutateSecureSetting(String name, String value, String tag,
1495 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1496 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001497 // Make sure the caller can change the settings.
1498 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1499
Svetoslav683914b2015-01-15 14:22:26 -08001500 // Resolve the userId on whose behalf the call is made.
1501 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1502
Makoto Onuki28da2e32015-11-20 11:30:44 -08001503 // If this is a setting that is currently restricted for this user, do not allow
1504 // unrestricting changes.
yuemingw1d13eae2018-01-30 17:27:54 +00001505 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1506 name, callingUserId, value, Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001507 return false;
1508 }
1509
1510 // Determine the owning user as some profile settings are cloned from the parent.
1511 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1512
1513 // Only the owning user can change the setting.
1514 if (owningUserId != callingUserId) {
1515 return false;
1516 }
1517
1518 // Special cases for location providers (sigh).
1519 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001520 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1521 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001522 }
1523
1524 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001525 synchronized (mLock) {
1526 switch (operation) {
1527 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001528 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001529 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001530 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001531 }
Svetoslav683914b2015-01-15 14:22:26 -08001532
Svetoslav7ec28e82015-05-20 17:01:10 -07001533 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001534 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001535 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001536 }
Svetoslav683914b2015-01-15 14:22:26 -08001537
Svetoslav7ec28e82015-05-20 17:01:10 -07001538 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001539 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001540 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001541 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001542 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001543
1544 case MUTATION_OPERATION_RESET: {
1545 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1546 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1547 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001548 }
1549 }
1550
1551 return false;
1552 }
1553
Svetoslav7ec28e82015-05-20 17:01:10 -07001554 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001555 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001556 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001557 }
1558
1559 // Resolve the userId on whose behalf the call is made.
1560 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1561
Svetoslav7ec28e82015-05-20 17:01:10 -07001562 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001563 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001564
Svetoslav7ec28e82015-05-20 17:01:10 -07001565 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001566
Svetoslav7ec28e82015-05-20 17:01:10 -07001567 String[] normalizedProjection = normalizeProjection(projection);
1568 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001569
Svetoslav7ec28e82015-05-20 17:01:10 -07001570 for (int i = 0; i < nameCount; i++) {
1571 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001572
Svetoslav7ec28e82015-05-20 17:01:10 -07001573 // Determine the owning user as some profile settings are cloned from the parent.
1574 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1575 name);
Svetoslav683914b2015-01-15 14:22:26 -08001576
Svetoslav7ec28e82015-05-20 17:01:10 -07001577 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001578 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001579 appendSettingToCursor(result, setting);
1580 }
1581
1582 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001583 }
Svetoslav683914b2015-01-15 14:22:26 -08001584 }
1585
Svetoslav7ec28e82015-05-20 17:01:10 -07001586 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001587 if (DEBUG) {
1588 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1589 }
1590
1591 // Resolve the userId on whose behalf the call is made.
1592 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1593
Chad Brubakera6830e72017-04-28 17:34:36 -07001594 // Ensure the caller can access the setting.
1595 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001596
Svetoslav683914b2015-01-15 14:22:26 -08001597 // Determine the owning user as some profile settings are cloned from the parent.
1598 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1599
1600 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001601 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001602 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001603 }
Svetoslav683914b2015-01-15 14:22:26 -08001604 }
1605
Svetoslav7ec28e82015-05-20 17:01:10 -07001606 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001607 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001608 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001609 + requestingUserId + ")");
1610 }
1611
Svetoslav7ec28e82015-05-20 17:01:10 -07001612 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001613 }
1614
Svetoslav7ec28e82015-05-20 17:01:10 -07001615 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001616 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001617 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001618 }
1619
Svetoslav7ec28e82015-05-20 17:01:10 -07001620 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001621 }
1622
Svetoslav7ec28e82015-05-20 17:01:10 -07001623 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001624 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001625 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001626 + requestingUserId + ")");
1627 }
1628
Svetoslav7ec28e82015-05-20 17:01:10 -07001629 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001630 }
1631
Svetoslav7ec28e82015-05-20 17:01:10 -07001632 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001633 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001634 if (!hasWriteSecureSettingsPermission()) {
1635 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1636 // operation is allowed for the calling package through appops.
1637 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1638 Binder.getCallingUid(), getCallingPackage(), true)) {
1639 return false;
1640 }
Svetoslav683914b2015-01-15 14:22:26 -08001641 }
1642
Svetoslav683914b2015-01-15 14:22:26 -08001643 // Resolve the userId on whose behalf the call is made.
1644 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1645
yuemingw1d13eae2018-01-30 17:27:54 +00001646 if (name != null && mUserManagerInternal.isSettingRestrictedForUser(
1647 name, callingUserId, value, Binder.getCallingUid())) {
1648 return false;
1649 }
1650
Svetoslavd8d25e02015-11-20 13:09:26 -08001651 // Enforce what the calling package can mutate the system settings.
1652 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1653
Svetoslav683914b2015-01-15 14:22:26 -08001654 // Determine the owning user as some profile settings are cloned from the parent.
1655 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1656
1657 // Only the owning user id can change the setting.
1658 if (owningUserId != callingUserId) {
1659 return false;
1660 }
1661
Jeff Sharkey413573a2016-02-22 17:52:45 -07001662 // Invalidate any relevant cache files
1663 String cacheName = null;
1664 if (Settings.System.RINGTONE.equals(name)) {
1665 cacheName = Settings.System.RINGTONE_CACHE;
1666 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1667 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1668 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1669 cacheName = Settings.System.ALARM_ALERT_CACHE;
1670 }
1671 if (cacheName != null) {
1672 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001673 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001674 cacheFile.delete();
1675 }
1676
Svetoslav683914b2015-01-15 14:22:26 -08001677 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001678 synchronized (mLock) {
1679 switch (operation) {
1680 case MUTATION_OPERATION_INSERT: {
1681 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001682 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001683 owningUserId, name, value, null, false, getCallingPackage(),
1684 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001685 }
1686
1687 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001688 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001689 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001690 }
1691
1692 case MUTATION_OPERATION_UPDATE: {
1693 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001694 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001695 owningUserId, name, value, null, false, getCallingPackage(),
1696 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001697 }
Svetoslav683914b2015-01-15 14:22:26 -08001698 }
1699
Svetoslav7ec28e82015-05-20 17:01:10 -07001700 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001701 }
Svetoslav683914b2015-01-15 14:22:26 -08001702 }
1703
Billy Lau6ad2d662015-07-18 00:26:58 +01001704 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001705 // Write secure settings is a more protected permission. If caller has it we are good.
1706 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1707 == PackageManager.PERMISSION_GRANTED) {
1708 return true;
1709 }
1710
Svetoslavf41334b2015-06-23 12:06:03 -07001711 return false;
1712 }
1713
Svetoslav683914b2015-01-15 14:22:26 -08001714 private void validateSystemSettingValue(String name, String value) {
Michal Karpinski2c37b082018-01-18 16:14:27 +00001715 SettingsValidators.Validator validator = Settings.System.VALIDATORS.get(name);
Svetoslav683914b2015-01-15 14:22:26 -08001716 if (validator != null && !validator.validate(value)) {
1717 throw new IllegalArgumentException("Invalid value: " + value
1718 + " for setting: " + name);
1719 }
1720 }
1721
Alex Klyubin1991f572017-03-03 14:08:36 -08001722 /**
1723 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1724 */
1725 private boolean isSecureSettingAccessible(String name, int callingUserId,
1726 int owningUserId) {
1727 // Special case for location (sigh).
1728 // This check is not inside the name-based checks below because this method performs checks
1729 // only if the calling user ID is not the same as the owning user ID.
1730 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1731 return false;
1732 }
1733
1734 switch (name) {
1735 case "bluetooth_address":
1736 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1737 // address in this secure setting. Secure settings can normally be read by any app,
1738 // which thus enables them to bypass the recently introduced restrictions on access
1739 // to device identifiers.
1740 // To mitigate this we make this setting available only to callers privileged to see
1741 // this device's MAC addresses, same as through public API
1742 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1743 return getContext().checkCallingOrSelfPermission(
1744 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1745 default:
1746 return true;
1747 }
1748 }
1749
Svetoslav683914b2015-01-15 14:22:26 -08001750 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1751 int owningUserId) {
1752 // Optimization - location providers are restricted only for managed profiles.
1753 if (callingUserId == owningUserId) {
1754 return false;
1755 }
1756 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1757 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1758 new UserHandle(callingUserId))) {
1759 return true;
1760 }
1761 return false;
1762 }
1763
Svetoslav683914b2015-01-15 14:22:26 -08001764 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1765 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1766 }
1767
1768 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001769 final int parentId;
1770 // Resolves dependency if setting has a dependency and the calling user has a parent
1771 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1772 && (parentId = getGroupParentLocked(userId)) != userId) {
1773 // The setting has a dependency and the profile has a parent
1774 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001775 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1776 final long token = Binder.clearCallingIdentity();
1777 try {
1778 Setting settingObj = getSecureSetting(dependency, userId);
1779 if (settingObj != null && settingObj.getValue().equals("1")) {
1780 return parentId;
1781 }
1782 } finally {
1783 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001784 }
1785 }
Svetoslav683914b2015-01-15 14:22:26 -08001786 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1787 }
1788
1789 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1790 final int parentId = getGroupParentLocked(userId);
1791 if (parentId != userId && keys.contains(name)) {
1792 return parentId;
1793 }
1794 return userId;
1795 }
1796
Svetoslavf41334b2015-06-23 12:06:03 -07001797 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001798 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001799 // System/root/shell can mutate whatever secure settings they want.
1800 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001801 final int appId = UserHandle.getAppId(callingUid);
1802 if (appId == android.os.Process.SYSTEM_UID
1803 || appId == Process.SHELL_UID
1804 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001805 return;
1806 }
1807
1808 switch (operation) {
1809 case MUTATION_OPERATION_INSERT:
1810 // Insert updates.
1811 case MUTATION_OPERATION_UPDATE: {
1812 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1813 return;
1814 }
1815
1816 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001817 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001818
1819 // Privileged apps can do whatever they want.
1820 if ((packageInfo.applicationInfo.privateFlags
1821 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1822 return;
1823 }
1824
1825 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1826 packageInfo.applicationInfo.targetSdkVersion, name);
1827 } break;
1828
1829 case MUTATION_OPERATION_DELETE: {
1830 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1831 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1832 throw new IllegalArgumentException("You cannot delete system defined"
1833 + " secure settings.");
1834 }
1835
1836 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001837 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001838
1839 // Privileged apps can do whatever they want.
1840 if ((packageInfo.applicationInfo.privateFlags &
1841 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1842 return;
1843 }
1844
1845 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1846 packageInfo.applicationInfo.targetSdkVersion, name);
1847 } break;
1848 }
1849 }
1850
Todd Kennedybe0b8892017-02-15 14:13:52 -08001851 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001852 switch (settingsType) {
1853 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001854 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001855 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001856 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001857 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001858 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001859 default:
1860 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1861 }
1862 }
1863
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001864 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1865 switch (settingsType) {
1866 case SETTINGS_TYPE_GLOBAL:
1867 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1868 case SETTINGS_TYPE_SYSTEM:
1869 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1870 case SETTINGS_TYPE_SECURE:
1871 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1872 default:
1873 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1874 }
1875 }
1876
Andreas Gampeb58893072018-09-05 16:52:31 -07001877 @GuardedBy("mLock")
Chad Brubaker97bccee2017-01-05 15:51:41 -08001878 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001879 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1880 // in the current form.
1881 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001882 }
1883
Chad Brubakera6830e72017-04-28 17:34:36 -07001884 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001885 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1886 return;
1887 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001888 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001889 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001890 return;
1891 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001892 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1893 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001894 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1895 // breakage in the current form.
1896 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1897 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001898 }
1899 }
1900
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001901 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1902 // We always use the callingUid for this lookup. This means that if hypothetically an
1903 // app was installed in user A with cross user and in user B as an Instant App
1904 // the app in A would be able to see all the settings in user B. However since cross
1905 // user is a system permission and the app must be uninstalled in B and then installed as
1906 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001907 ApplicationInfo ai = null;
1908 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001909 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1910 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001911 } catch (RemoteException ignored) {
1912 }
1913 if (ai == null) {
1914 throw new IllegalStateException("Failed to lookup info for package "
1915 + getCallingPackage());
1916 }
1917 return ai;
1918 }
1919
Xiaohui Chen43765b72015-08-31 10:57:33 -07001920 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001921 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001922 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1923 getCallingPackage(), 0, userId);
1924 if (packageInfo != null) {
1925 return packageInfo;
1926 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001927 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001928 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001929 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001930 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001931 }
1932
1933 private int getGroupParentLocked(int userId) {
1934 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001935 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001936 return userId;
1937 }
1938 // We are in the same process with the user manager and the returned
1939 // user info is a cached instance, so just look up instead of cache.
1940 final long identity = Binder.clearCallingIdentity();
1941 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001942 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001943 UserInfo userInfo = mUserManager.getProfileParent(userId);
1944 return (userInfo != null) ? userInfo.id : userId;
1945 } finally {
1946 Binder.restoreCallingIdentity(identity);
1947 }
1948 }
1949
Svetoslav683914b2015-01-15 14:22:26 -08001950 private void enforceWritePermission(String permission) {
1951 if (getContext().checkCallingOrSelfPermission(permission)
1952 != PackageManager.PERMISSION_GRANTED) {
1953 throw new SecurityException("Permission denial: writing to settings requires:"
1954 + permission);
1955 }
1956 }
1957
1958 /*
1959 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1960 * This setting contains a list of the currently enabled location providers.
1961 * But helper functions in android.providers.Settings can enable or disable
1962 * a single provider by using a "+" or "-" prefix before the provider name.
1963 *
yuemingw1d13eae2018-01-30 17:27:54 +00001964 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#isSettingRestrictedForUser()}.
1965 * If DISALLOW_SHARE_LOCATION is set, the said method will only allow values with
1966 * the "-" prefix.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001967 *
Svetoslav683914b2015-01-15 14:22:26 -08001968 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001969 */
Andreas Gampeb58893072018-09-05 16:52:31 -07001970 @GuardedBy("mLock")
Svetoslav Ganove080da92016-12-21 17:10:35 -08001971 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1972 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001973 if (TextUtils.isEmpty(value)) {
1974 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001975 }
Maggie83e03f52018-03-16 12:22:20 -07001976 Setting oldSetting = getSecureSetting(
1977 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
1978 if (oldSetting == null) {
Svetoslav683914b2015-01-15 14:22:26 -08001979 return false;
1980 }
Maggie83e03f52018-03-16 12:22:20 -07001981 String oldProviders = oldSetting.getValue();
1982 List<String> oldProvidersList = TextUtils.isEmpty(oldProviders)
1983 ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldProviders.split(",")));
1984 Set<String> newProvidersSet = new ArraySet<>();
1985 newProvidersSet.addAll(oldProvidersList);
Svetoslav683914b2015-01-15 14:22:26 -08001986
Maggie83e03f52018-03-16 12:22:20 -07001987 String[] providerUpdates = value.split(",");
1988 boolean inputError = false;
1989 for (String provider : providerUpdates) {
1990 // do not update location_providers_allowed when input is invalid
1991 if (TextUtils.isEmpty(provider)) {
1992 inputError = true;
1993 break;
Svetoslav683914b2015-01-15 14:22:26 -08001994 }
Maggie83e03f52018-03-16 12:22:20 -07001995 final char prefix = provider.charAt(0);
1996 // do not update location_providers_allowed when input is invalid
1997 if (prefix != '+' && prefix != '-') {
1998 inputError = true;
1999 break;
Svetoslav683914b2015-01-15 14:22:26 -08002000 }
Maggie83e03f52018-03-16 12:22:20 -07002001 // skip prefix
2002 provider = provider.substring(1);
2003 if (prefix == '+') {
2004 newProvidersSet.add(provider);
2005 } else if (prefix == '-') {
2006 newProvidersSet.remove(provider);
Svetoslav683914b2015-01-15 14:22:26 -08002007 }
Maggie83e03f52018-03-16 12:22:20 -07002008 }
2009 String newProviders = TextUtils.join(",", newProvidersSet.toArray());
2010 if (inputError == true || newProviders.equals(oldProviders)) {
Svetoslav683914b2015-01-15 14:22:26 -08002011 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07002012 if (forceNotify) {
Maggie83e03f52018-03-16 12:22:20 -07002013 mSettingsRegistry.notifyForSettingsChange(
2014 makeKey(SETTINGS_TYPE_SECURE, owningUserId),
Svet Ganov53a441c2016-04-19 19:38:00 -07002015 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
2016 }
Svetoslav683914b2015-01-15 14:22:26 -08002017 return false;
2018 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002019 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Maggie83e03f52018-03-16 12:22:20 -07002020 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders, tag,
2021 makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08002022 }
2023
Svetoslav683914b2015-01-15 14:22:26 -08002024 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
2025 int targetSdkVersion, String name) {
2026 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
2027 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
2028 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2029 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
2030 + " This will soon become an error.");
2031 } else {
2032 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
2033 + " This will soon become an error.");
2034 }
2035 } else {
2036 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
2037 throw new IllegalArgumentException("You cannot change private secure settings.");
2038 } else {
2039 throw new IllegalArgumentException("You cannot keep your settings in"
2040 + " the secure settings.");
2041 }
2042 }
2043 }
2044
2045 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
2046 if (requestingUserId == UserHandle.getCallingUserId()) {
2047 return requestingUserId;
2048 }
2049 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2050 Binder.getCallingUid(), requestingUserId, false, true,
2051 "get/set setting for user", null);
2052 }
2053
Svet Ganov53a441c2016-04-19 19:38:00 -07002054 private Bundle packageValueForCallResult(Setting setting,
2055 boolean trackingGeneration) {
2056 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002057 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002058 return NULL_SETTING_BUNDLE;
2059 }
2060 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08002061 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002062 Bundle result = new Bundle();
2063 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002064 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07002065
Svetoslav Ganove080da92016-12-21 17:10:35 -08002066 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07002067 return result;
Svetoslav683914b2015-01-15 14:22:26 -08002068 }
2069
2070 private static int getRequestingUserId(Bundle args) {
2071 final int callingUserId = UserHandle.getCallingUserId();
2072 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
2073 : callingUserId;
2074 }
2075
Svet Ganov53a441c2016-04-19 19:38:00 -07002076 private boolean isTrackingGeneration(Bundle args) {
2077 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
2078 }
2079
Svetoslav683914b2015-01-15 14:22:26 -08002080 private static String getSettingValue(Bundle args) {
2081 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
2082 }
2083
Svetoslav Ganove080da92016-12-21 17:10:35 -08002084 private static String getSettingTag(Bundle args) {
2085 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
2086 }
2087
2088 private static boolean getSettingMakeDefault(Bundle args) {
2089 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
2090 }
2091
2092 private static int getResetModeEnforcingPermission(Bundle args) {
2093 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
2094 switch (mode) {
2095 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2096 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2097 throw new SecurityException("Only system, shell/root on a "
2098 + "debuggable build can reset to untrusted defaults");
2099 }
2100 return mode;
2101 }
2102 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2103 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2104 throw new SecurityException("Only system, shell/root on a "
2105 + "debuggable build can reset untrusted changes");
2106 }
2107 return mode;
2108 }
2109 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2110 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
2111 throw new SecurityException("Only system, shell/root on a "
2112 + "debuggable build can reset to trusted defaults");
2113 }
2114 return mode;
2115 }
2116 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2117 return mode;
2118 }
2119 }
2120 throw new IllegalArgumentException("Invalid reset mode: " + mode);
2121 }
2122
2123 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
2124 final int appId = UserHandle.getAppId(Binder.getCallingUid());
2125 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
2126 && (appId == SHELL_UID || appId == ROOT_UID));
2127 }
2128
Svetoslav683914b2015-01-15 14:22:26 -08002129 private static String getValidTableOrThrow(Uri uri) {
2130 if (uri.getPathSegments().size() > 0) {
2131 String table = uri.getPathSegments().get(0);
2132 if (DatabaseHelper.isValidTable(table)) {
2133 return table;
2134 }
2135 throw new IllegalArgumentException("Bad root path: " + table);
2136 }
2137 throw new IllegalArgumentException("Invalid URI:" + uri);
2138 }
2139
2140 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002141 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002142 return new MatrixCursor(projection, 0);
2143 }
2144 MatrixCursor cursor = new MatrixCursor(projection, 1);
2145 appendSettingToCursor(cursor, setting);
2146 return cursor;
2147 }
2148
2149 private static String[] normalizeProjection(String[] projection) {
2150 if (projection == null) {
2151 return ALL_COLUMNS;
2152 }
2153
2154 final int columnCount = projection.length;
2155 for (int i = 0; i < columnCount; i++) {
2156 String column = projection[i];
2157 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2158 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002159 }
2160 }
2161
Svetoslav683914b2015-01-15 14:22:26 -08002162 return projection;
2163 }
2164
2165 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002166 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002167 return;
2168 }
Svetoslav683914b2015-01-15 14:22:26 -08002169 final int columnCount = cursor.getColumnCount();
2170
2171 String[] values = new String[columnCount];
2172
2173 for (int i = 0; i < columnCount; i++) {
2174 String column = cursor.getColumnName(i);
2175
2176 switch (column) {
2177 case Settings.NameValueTable._ID: {
2178 values[i] = setting.getId();
2179 } break;
2180
2181 case Settings.NameValueTable.NAME: {
2182 values[i] = setting.getName();
2183 } break;
2184
2185 case Settings.NameValueTable.VALUE: {
2186 values[i] = setting.getValue();
2187 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002188 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002189 }
2190
Svetoslav683914b2015-01-15 14:22:26 -08002191 cursor.addRow(values);
2192 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002193
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002194 private static boolean isKeyValid(String key) {
2195 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2196 }
2197
Svetoslav683914b2015-01-15 14:22:26 -08002198 private static final class Arguments {
2199 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2200 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2201
2202 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2203 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2204
2205 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2206 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2207
2208 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2209 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2210
2211 public final String table;
2212 public final String name;
2213
2214 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2215 final int segmentSize = uri.getPathSegments().size();
2216 switch (segmentSize) {
2217 case 1: {
2218 if (where != null
2219 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2220 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2221 && whereArgs.length == 1) {
2222 name = whereArgs[0];
2223 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002224 return;
Svetoslav683914b2015-01-15 14:22:26 -08002225 } else if (where != null
2226 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2227 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2228 final int startIndex = Math.max(where.indexOf("'"),
2229 where.indexOf("\"")) + 1;
2230 final int endIndex = Math.max(where.lastIndexOf("'"),
2231 where.lastIndexOf("\""));
2232 name = where.substring(startIndex, endIndex);
2233 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002234 return;
Svetoslav683914b2015-01-15 14:22:26 -08002235 } else if (supportAll && where == null && whereArgs == null) {
2236 name = null;
2237 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002238 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002239 }
Svetoslav683914b2015-01-15 14:22:26 -08002240 } break;
2241
Svetoslav28494652015-02-12 14:11:42 -08002242 case 2: {
2243 if (where == null && whereArgs == null) {
2244 name = uri.getPathSegments().get(1);
2245 table = computeTableForSetting(uri, name);
2246 return;
2247 }
2248 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002249 }
Svetoslav28494652015-02-12 14:11:42 -08002250
2251 EventLogTags.writeUnsupportedSettingsQuery(
2252 uri.toSafeString(), where, Arrays.toString(whereArgs));
2253 String message = String.format( "Supported SQL:\n"
2254 + " uri content://some_table/some_property with null where and where args\n"
2255 + " uri content://some_table with query name=? and single name as arg\n"
2256 + " uri content://some_table with query name=some_name and null args\n"
2257 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2258 Arrays.toString(whereArgs));
2259 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002260 }
2261
Svetoslav28494652015-02-12 14:11:42 -08002262 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002263 String table = getValidTableOrThrow(uri);
2264
2265 if (name != null) {
2266 if (sSystemMovedToSecureSettings.contains(name)) {
2267 table = TABLE_SECURE;
2268 }
2269
2270 if (sSystemMovedToGlobalSettings.contains(name)) {
2271 table = TABLE_GLOBAL;
2272 }
2273
2274 if (sSecureMovedToGlobalSettings.contains(name)) {
2275 table = TABLE_GLOBAL;
2276 }
2277
2278 if (sGlobalMovedToSecureSettings.contains(name)) {
2279 table = TABLE_SECURE;
2280 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002281 }
Svetoslav683914b2015-01-15 14:22:26 -08002282
2283 return table;
2284 }
2285 }
2286
2287 final class SettingsRegistry {
2288 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2289
Svetoslav683914b2015-01-15 14:22:26 -08002290 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2291 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2292 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002293 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
Matt Pape1b31a332018-10-17 09:58:28 -07002294 private static final String SETTINGS_FILE_CONFIG = "settings_config.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002295
2296 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002297
2298 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2299
Svet Ganov53a441c2016-04-19 19:38:00 -07002300 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002301
Svetoslav7e0683b2015-08-03 16:02:52 -07002302 private final Handler mHandler;
2303
Svet Ganov53a441c2016-04-19 19:38:00 -07002304 private final BackupManager mBackupManager;
2305
Amith Yamasani39452022017-03-21 15:23:47 -07002306 private String mSettingsCreationBuildId;
2307
Svetoslav683914b2015-01-15 14:22:26 -08002308 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002309 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002310 mGenerationRegistry = new GenerationRegistry(mLock);
2311 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002312 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002313 syncSsaidTableOnStart();
2314 }
2315
2316 private void generateUserKeyLocked(int userId) {
2317 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002318 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002319 final SecureRandom rand = new SecureRandom();
2320 rand.nextBytes(keyBytes);
2321
2322 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002323 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002324
2325 // Store the key in the ssaid table.
2326 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2327 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2328 true, SettingsState.SYSTEM_PACKAGE_NAME);
2329
2330 if (!success) {
2331 throw new IllegalStateException("Ssaid settings not accessible");
2332 }
2333 }
2334
Mark Rathjen7599f132017-01-23 14:15:54 -08002335 private byte[] getLengthPrefix(byte[] data) {
2336 return ByteBuffer.allocate(4).putInt(data.length).array();
2337 }
2338
Christopher Tateb218e762017-04-05 16:34:07 -07002339 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002340 // Read the user's key from the ssaid table.
2341 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002342 if (userKeySetting == null || userKeySetting.isNull()
2343 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002344 // Lazy initialize and store the user key.
2345 generateUserKeyLocked(userId);
2346 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002347 if (userKeySetting == null || userKeySetting.isNull()
2348 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002349 throw new IllegalStateException("User key not accessible");
2350 }
2351 }
2352 final String userKey = userKeySetting.getValue();
2353
2354 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002355 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2356
2357 // Validate that the key is of expected length.
2358 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2359 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002360 throw new IllegalStateException("User key invalid");
2361 }
2362
Mark Rathjen7599f132017-01-23 14:15:54 -08002363 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002364 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002365 m = Mac.getInstance("HmacSHA256");
2366 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002367 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002368 throw new IllegalStateException("HmacSHA256 is not available", e);
2369 } catch (InvalidKeyException e) {
2370 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002371 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002372
Mark Rathjenf42dd912017-06-05 19:04:34 -07002373 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002374 for (int i = 0; i < callingPkg.signatures.length; i++) {
2375 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002376 m.update(getLengthPrefix(sig), 0, 4);
2377 m.update(sig);
2378 }
Mark Rathjend891f012017-01-19 04:10:37 +00002379
2380 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002381 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2382 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002383
2384 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002385 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002386 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2387 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002388 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002389
2390 if (!success) {
2391 throw new IllegalStateException("Ssaid settings not accessible");
2392 }
2393
2394 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2395 }
2396
2397 public void syncSsaidTableOnStart() {
2398 synchronized (mLock) {
2399 // Verify that each user's packages and ssaid's are in sync.
2400 for (UserInfo user : mUserManager.getUsers(true)) {
2401 // Get all uids for the user's packages.
2402 final List<PackageInfo> packages;
2403 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09002404 packages = mPackageManager.getInstalledPackages(
2405 PackageManager.MATCH_UNINSTALLED_PACKAGES,
2406 user.id).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00002407 } catch (RemoteException e) {
2408 throw new IllegalStateException("Package manager not available");
2409 }
2410 final Set<String> appUids = new HashSet<>();
2411 for (PackageInfo info : packages) {
2412 appUids.add(Integer.toString(info.applicationInfo.uid));
2413 }
2414
2415 // Get all uids currently stored in the user's ssaid table.
2416 final Set<String> ssaidUids = new HashSet<>(
2417 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2418 ssaidUids.remove(SSAID_USER_KEY);
2419
2420 // Perform a set difference for the appUids and ssaidUids.
2421 ssaidUids.removeAll(appUids);
2422
2423 // If there are ssaidUids left over they need to be removed from the table.
2424 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2425 user.id);
2426 for (String uid : ssaidUids) {
2427 ssaidSettings.deleteSettingLocked(uid);
2428 }
2429 }
2430 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002431 }
2432
Svetoslav683914b2015-01-15 14:22:26 -08002433 public List<String> getSettingsNamesLocked(int type, int userId) {
2434 final int key = makeKey(type, userId);
2435 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002436 if (settingsState == null) {
2437 return new ArrayList<String>();
2438 }
Svetoslav683914b2015-01-15 14:22:26 -08002439 return settingsState.getSettingNamesLocked();
2440 }
2441
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002442 public SparseBooleanArray getKnownUsersLocked() {
2443 SparseBooleanArray users = new SparseBooleanArray();
2444 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2445 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2446 }
2447 return users;
2448 }
2449
Kweku Adamsb0886f32017-10-31 15:32:09 -07002450 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002451 public SettingsState getSettingsLocked(int type, int userId) {
2452 final int key = makeKey(type, userId);
2453 return peekSettingsStateLocked(key);
2454 }
2455
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002456 public boolean ensureSettingsForUserLocked(int userId) {
2457 // First make sure this user actually exists.
2458 if (mUserManager.getUserInfo(userId) == null) {
2459 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2460 return false;
2461 }
2462
Svetoslav683914b2015-01-15 14:22:26 -08002463 // Migrate the setting for this user if needed.
2464 migrateLegacySettingsForUserIfNeededLocked(userId);
2465
Matt Pape1b31a332018-10-17 09:58:28 -07002466 // Ensure config settings loaded if owner.
2467 if (userId == UserHandle.USER_SYSTEM) {
2468 final int configKey
2469 = makeKey(SETTINGS_TYPE_CONFIG, UserHandle.USER_SYSTEM);
2470 ensureSettingsStateLocked(configKey);
2471 }
2472
Svetoslav683914b2015-01-15 14:22:26 -08002473 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002474 if (userId == UserHandle.USER_SYSTEM) {
2475 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002476 ensureSettingsStateLocked(globalKey);
2477 }
2478
2479 // Ensure secure settings loaded.
2480 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2481 ensureSettingsStateLocked(secureKey);
2482
2483 // Make sure the secure settings have an Android id set.
2484 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2485 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2486
2487 // Ensure system settings loaded.
2488 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2489 ensureSettingsStateLocked(systemKey);
2490
Mark Rathjend891f012017-01-19 04:10:37 +00002491 // Ensure secure settings loaded.
2492 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2493 ensureSettingsStateLocked(ssaidKey);
2494
Svetoslav683914b2015-01-15 14:22:26 -08002495 // Upgrade the settings to the latest version.
2496 UpgradeController upgrader = new UpgradeController(userId);
2497 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002498 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002499 }
2500
2501 private void ensureSettingsStateLocked(int key) {
2502 if (mSettingsStates.get(key) == null) {
2503 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002504 SettingsState settingsState = new SettingsState(getContext(), mLock,
2505 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002506 mSettingsStates.put(key, settingsState);
2507 }
2508 }
2509
2510 public void removeUserStateLocked(int userId, boolean permanently) {
2511 // We always keep the global settings in memory.
2512
2513 // Nuke system settings.
2514 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2515 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2516 if (systemSettingsState != null) {
2517 if (permanently) {
2518 mSettingsStates.remove(systemKey);
2519 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002520 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002521 systemSettingsState.destroyLocked(new Runnable() {
2522 @Override
2523 public void run() {
2524 mSettingsStates.remove(systemKey);
2525 }
2526 });
2527 }
2528 }
2529
2530 // Nuke secure settings.
2531 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2532 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2533 if (secureSettingsState != null) {
2534 if (permanently) {
2535 mSettingsStates.remove(secureKey);
2536 secureSettingsState.destroyLocked(null);
2537 } else {
2538 secureSettingsState.destroyLocked(new Runnable() {
2539 @Override
2540 public void run() {
2541 mSettingsStates.remove(secureKey);
2542 }
2543 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002544 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002545 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002546
Mark Rathjend891f012017-01-19 04:10:37 +00002547 // Nuke ssaid settings.
2548 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2549 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2550 if (ssaidSettingsState != null) {
2551 if (permanently) {
2552 mSettingsStates.remove(ssaidKey);
2553 ssaidSettingsState.destroyLocked(null);
2554 } else {
2555 ssaidSettingsState.destroyLocked(new Runnable() {
2556 @Override
2557 public void run() {
2558 mSettingsStates.remove(ssaidKey);
2559 }
2560 });
2561 }
2562 }
2563
Svet Ganov53a441c2016-04-19 19:38:00 -07002564 // Nuke generation tracking data
2565 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002566 }
2567
Svetoslav683914b2015-01-15 14:22:26 -08002568 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002569 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2570 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002571 final int key = makeKey(type, userId);
2572
Svetoslav Ganove080da92016-12-21 17:10:35 -08002573 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002574 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002575 if (settingsState != null) {
2576 success = settingsState.insertSettingLocked(name, value,
2577 tag, makeDefault, packageName);
2578 }
Svetoslav683914b2015-01-15 14:22:26 -08002579
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002580 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2581 settingsState.persistSyncLocked();
2582 }
2583
Svet Ganov53a441c2016-04-19 19:38:00 -07002584 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002585 notifyForSettingsChange(key, name);
2586 }
2587 return success;
2588 }
2589
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002590 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2591 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002592 final int key = makeKey(type, userId);
2593
Svetoslav Ganove080da92016-12-21 17:10:35 -08002594 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002595 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002596 if (settingsState != null) {
2597 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002598 }
Svetoslav683914b2015-01-15 14:22:26 -08002599
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002600 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2601 settingsState.persistSyncLocked();
2602 }
2603
Svet Ganov53a441c2016-04-19 19:38:00 -07002604 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002605 notifyForSettingsChange(key, name);
2606 }
2607 return success;
2608 }
2609
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002610 public boolean updateSettingLocked(int type, int userId, String name, String value,
2611 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2612 Set<String> criticalSettings) {
2613 final int key = makeKey(type, userId);
2614
2615 boolean success = false;
2616 SettingsState settingsState = peekSettingsStateLocked(key);
2617 if (settingsState != null) {
2618 success = settingsState.updateSettingLocked(name, value, tag,
2619 makeDefault, packageName);
2620 }
2621
2622 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2623 settingsState.persistSyncLocked();
2624 }
2625
2626 if (forceNotify || success) {
2627 notifyForSettingsChange(key, name);
2628 }
2629
2630 return success;
2631 }
2632
Svetoslav683914b2015-01-15 14:22:26 -08002633 public Setting getSettingLocked(int type, int userId, String name) {
2634 final int key = makeKey(type, userId);
2635
2636 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002637 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002638 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002639 }
Mark Rathjend891f012017-01-19 04:10:37 +00002640
2641 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002642 return settingsState.getSettingLocked(name);
2643 }
2644
Svetoslav Ganove080da92016-12-21 17:10:35 -08002645 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2646 String tag) {
2647 final int key = makeKey(type, userId);
2648 SettingsState settingsState = peekSettingsStateLocked(key);
2649 if (settingsState == null) {
2650 return;
2651 }
2652
2653 switch (mode) {
2654 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2655 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002656 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002657 Setting setting = settingsState.getSettingLocked(name);
2658 if (packageName.equals(setting.getPackageName())) {
2659 if (tag != null && !tag.equals(setting.getTag())) {
2660 continue;
2661 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002662 if (settingsState.resetSettingLocked(name)) {
2663 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002664 notifyForSettingsChange(key, name);
2665 }
2666 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002667 if (someSettingChanged) {
2668 settingsState.persistSyncLocked();
2669 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002670 }
2671 } break;
2672
2673 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2674 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002675 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002676 Setting setting = settingsState.getSettingLocked(name);
2677 if (!SettingsState.isSystemPackage(getContext(),
2678 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002679 if (settingsState.resetSettingLocked(name)) {
2680 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002681 notifyForSettingsChange(key, name);
2682 }
2683 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002684 if (someSettingChanged) {
2685 settingsState.persistSyncLocked();
2686 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002687 }
2688 } break;
2689
2690 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2691 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002692 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002693 Setting setting = settingsState.getSettingLocked(name);
2694 if (!SettingsState.isSystemPackage(getContext(),
2695 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002696 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002697 if (settingsState.resetSettingLocked(name)) {
2698 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002699 notifyForSettingsChange(key, name);
2700 }
2701 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002702 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002703 notifyForSettingsChange(key, name);
2704 }
2705 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002706 if (someSettingChanged) {
2707 settingsState.persistSyncLocked();
2708 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002709 }
2710 } break;
2711
2712 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2713 for (String name : settingsState.getSettingNamesLocked()) {
2714 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002715 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002716 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002717 if (settingsState.resetSettingLocked(name)) {
2718 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002719 notifyForSettingsChange(key, name);
2720 }
2721 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002722 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002723 notifyForSettingsChange(key, name);
2724 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002725 if (someSettingChanged) {
2726 settingsState.persistSyncLocked();
2727 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002728 }
2729 } break;
2730 }
2731 }
2732
Zimuzoc56192c2018-07-25 10:40:01 +01002733 public void removeSettingsForPackageLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002734 // Global and secure settings are signature protected. Apps signed
2735 // by the platform certificate are generally not uninstalled and
2736 // the main exception is tests. We trust components signed
2737 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002738
2739 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2740 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002741 if (systemSettings != null) {
Zimuzoc56192c2018-07-25 10:40:01 +01002742 systemSettings.removeSettingsForPackageLocked(packageName);
Svet Ganov8de34802015-04-27 09:33:40 -07002743 }
Svetoslav683914b2015-01-15 14:22:26 -08002744 }
2745
Mark Rathjend891f012017-01-19 04:10:37 +00002746 public void onUidRemovedLocked(int uid) {
2747 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2748 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002749 if (ssaidSettings != null) {
2750 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2751 }
Mark Rathjend891f012017-01-19 04:10:37 +00002752 }
2753
Kweku Adamsb0886f32017-10-31 15:32:09 -07002754 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002755 private SettingsState peekSettingsStateLocked(int key) {
2756 SettingsState settingsState = mSettingsStates.get(key);
2757 if (settingsState != null) {
2758 return settingsState;
2759 }
2760
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002761 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2762 return null;
2763 }
Svetoslav683914b2015-01-15 14:22:26 -08002764 return mSettingsStates.get(key);
2765 }
2766
2767 private void migrateAllLegacySettingsIfNeeded() {
2768 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002769 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002770 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002771 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002772 return;
2773 }
2774
Amith Yamasani39452022017-03-21 15:23:47 -07002775 mSettingsCreationBuildId = Build.ID;
2776
Svetoslav683914b2015-01-15 14:22:26 -08002777 final long identity = Binder.clearCallingIdentity();
2778 try {
2779 List<UserInfo> users = mUserManager.getUsers(true);
2780
2781 final int userCount = users.size();
2782 for (int i = 0; i < userCount; i++) {
2783 final int userId = users.get(i).id;
2784
2785 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2786 SQLiteDatabase database = dbHelper.getWritableDatabase();
2787 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2788
2789 // Upgrade to the latest version.
2790 UpgradeController upgrader = new UpgradeController(userId);
2791 upgrader.upgradeIfNeededLocked();
2792
2793 // Drop from memory if not a running user.
2794 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2795 removeUserStateLocked(userId, false);
2796 }
2797 }
2798 } finally {
2799 Binder.restoreCallingIdentity(identity);
2800 }
2801 }
2802 }
2803
2804 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2805 // Every user has secure settings and if no file we need to migrate.
2806 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2807 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002808 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002809 return;
2810 }
2811
2812 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2813 SQLiteDatabase database = dbHelper.getWritableDatabase();
2814
2815 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2816 }
2817
2818 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2819 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002820 // Move over the system settings.
2821 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2822 ensureSettingsStateLocked(systemKey);
2823 SettingsState systemSettings = mSettingsStates.get(systemKey);
2824 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2825 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002826
2827 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002828 // Do this after System settings, since this is the first thing we check when deciding
2829 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002830 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2831 ensureSettingsStateLocked(secureKey);
2832 SettingsState secureSettings = mSettingsStates.get(secureKey);
2833 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2834 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2835 secureSettings.persistSyncLocked();
2836
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002837 // Move over the global settings if owner.
2838 // Do this last, since this is the first thing we check when deciding
2839 // to skip over migration from db to xml for owner user.
2840 if (userId == UserHandle.USER_SYSTEM) {
2841 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2842 ensureSettingsStateLocked(globalKey);
2843 SettingsState globalSettings = mSettingsStates.get(globalKey);
2844 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002845 // If this was just created
2846 if (mSettingsCreationBuildId != null) {
2847 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2848 mSettingsCreationBuildId, null, true,
2849 SettingsState.SYSTEM_PACKAGE_NAME);
2850 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002851 globalSettings.persistSyncLocked();
2852 }
Svetoslav683914b2015-01-15 14:22:26 -08002853
2854 // Drop the database as now all is moved and persisted.
2855 if (DROP_DATABASE_ON_MIGRATION) {
2856 dbHelper.dropDatabase();
2857 } else {
2858 dbHelper.backupDatabase();
2859 }
2860 }
2861
2862 private void migrateLegacySettingsLocked(SettingsState settingsState,
2863 SQLiteDatabase database, String table) {
2864 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2865 queryBuilder.setTables(table);
2866
2867 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2868 null, null, null, null, null);
2869
2870 if (cursor == null) {
2871 return;
2872 }
2873
2874 try {
2875 if (!cursor.moveToFirst()) {
2876 return;
2877 }
2878
2879 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2880 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2881
2882 settingsState.setVersionLocked(database.getVersion());
2883
2884 while (!cursor.isAfterLast()) {
2885 String name = cursor.getString(nameColumnIdx);
2886 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002887 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002888 SettingsState.SYSTEM_PACKAGE_NAME);
2889 cursor.moveToNext();
2890 }
2891 } finally {
2892 cursor.close();
2893 }
2894 }
2895
Andreas Gampeb58893072018-09-05 16:52:31 -07002896 @GuardedBy("secureSettings.mLock")
Svetoslav683914b2015-01-15 14:22:26 -08002897 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2898 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2899
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002900 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002901 return;
2902 }
2903
2904 final int userId = getUserIdFromKey(secureSettings.mKey);
2905
2906 final UserInfo user;
2907 final long identity = Binder.clearCallingIdentity();
2908 try {
2909 user = mUserManager.getUserInfo(userId);
2910 } finally {
2911 Binder.restoreCallingIdentity(identity);
2912 }
2913 if (user == null) {
2914 // Can happen due to races when deleting users - treat as benign.
2915 return;
2916 }
2917
2918 String androidId = Long.toHexString(new SecureRandom().nextLong());
2919 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002920 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002921
2922 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2923 + "] for user " + userId);
2924
2925 // Write a drop box entry if it's a restricted profile
2926 if (user.isRestricted()) {
2927 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2928 Context.DROPBOX_SERVICE);
2929 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2930 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2931 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2932 }
2933 }
2934 }
2935
2936 private void notifyForSettingsChange(int key, String name) {
Svet Ganov945864c2018-03-22 21:49:10 -07002937 // Increment the generation first, so observers always see the new value
Phil Weaver83fec002016-05-11 10:55:29 -07002938 mGenerationRegistry.incrementGeneration(key);
2939
Svet Ganov945864c2018-03-22 21:49:10 -07002940 if (isGlobalSettingsKey(key)) {
Jeff Sharkey308093f2018-03-25 22:53:29 -06002941 final long token = Binder.clearCallingIdentity();
2942 try {
2943 if (Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2944 // When the global kill switch is updated, send the
2945 // change notification for the location setting.
2946 notifyLocationChangeForRunningUsers();
2947 }
2948 notifyGlobalSettingChangeForRunningUsers(key, name);
2949 } finally {
2950 Binder.restoreCallingIdentity(token);
Svet Ganov945864c2018-03-22 21:49:10 -07002951 }
Svet Ganov945864c2018-03-22 21:49:10 -07002952 } else {
2953 final int userId = getUserIdFromKey(key);
2954 final Uri uri = getNotificationUriFor(key, name);
2955 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2956 userId, 0, uri).sendToTarget();
2957 if (isSecureSettingsKey(key)) {
2958 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2959 sSecureCloneToManagedSettings);
2960 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2961 sSystemCloneFromParentOnDependency.values());
2962 } else if (isSystemSettingsKey(key)) {
2963 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2964 sSystemCloneToManagedSettings);
2965 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002966 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002967
Svet Ganov945864c2018-03-22 21:49:10 -07002968 // Always notify that our data changed
Svet Ganov53a441c2016-04-19 19:38:00 -07002969 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002970 }
2971
Svet Ganov53a441c2016-04-19 19:38:00 -07002972 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002973 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002974 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002975 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002976 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002977 if (profileId != userId) {
Svet Ganov945864c2018-03-22 21:49:10 -07002978 final int key = makeKey(type, profileId);
2979 // Increment the generation first, so observers always see the new value
2980 mGenerationRegistry.incrementGeneration(key);
Svetoslav7e0683b2015-08-03 16:02:52 -07002981 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002982 profileId, 0, uri).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002983 }
2984 }
2985 }
Svetoslav683914b2015-01-15 14:22:26 -08002986 }
2987
Svet Ganov945864c2018-03-22 21:49:10 -07002988 private void notifyGlobalSettingChangeForRunningUsers(int key, String name) {
2989 // Important: No need to update generation for each user as there
2990 // is a singleton generation entry for the global settings which
2991 // is already incremented be the caller.
2992 final Uri uri = getNotificationUriFor(key, name);
2993 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying*/ true);
2994 for (int i = 0; i < users.size(); i++) {
2995 final int userId = users.get(i).id;
2996 if (mUserManager.isUserRunning(UserHandle.of(userId))) {
2997 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2998 userId, 0, uri).sendToTarget();
2999 }
3000 }
3001 }
3002
Makoto Onuki0000d322017-11-28 16:31:47 -08003003 private void notifyLocationChangeForRunningUsers() {
3004 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
3005
3006 for (int i = 0; i < users.size(); i++) {
3007 final int userId = users.get(i).id;
3008
3009 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
3010 continue;
3011 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003012
Svet Ganov945864c2018-03-22 21:49:10 -07003013 // Increment the generation first, so observers always see the new value
3014 final int key = makeKey(SETTINGS_TYPE_SECURE, userId);
3015 mGenerationRegistry.incrementGeneration(key);
3016
3017 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
Makoto Onuki0000d322017-11-28 16:31:47 -08003018 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
3019 userId, 0, uri).sendToTarget();
3020 }
3021 }
3022
Matt Pape1b31a332018-10-17 09:58:28 -07003023 private boolean isConfigSettingsKey(int key) {
3024 return getTypeFromKey(key) == SETTINGS_TYPE_CONFIG;
3025 }
3026
Svetoslav683914b2015-01-15 14:22:26 -08003027 private boolean isGlobalSettingsKey(int key) {
3028 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
3029 }
3030
3031 private boolean isSystemSettingsKey(int key) {
3032 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
3033 }
3034
3035 private boolean isSecureSettingsKey(int key) {
3036 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
3037 }
3038
Mark Rathjend891f012017-01-19 04:10:37 +00003039 private boolean isSsaidSettingsKey(int key) {
3040 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
3041 }
3042
Svetoslav683914b2015-01-15 14:22:26 -08003043 private File getSettingsFile(int key) {
Matt Pape1b31a332018-10-17 09:58:28 -07003044 if (isConfigSettingsKey(key)) {
3045 final int userId = getUserIdFromKey(key);
3046 return new File(Environment.getUserSystemDirectory(userId),
3047 SETTINGS_FILE_CONFIG);
3048 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003049 final int userId = getUserIdFromKey(key);
3050 return new File(Environment.getUserSystemDirectory(userId),
3051 SETTINGS_FILE_GLOBAL);
3052 } else if (isSystemSettingsKey(key)) {
3053 final int userId = getUserIdFromKey(key);
3054 return new File(Environment.getUserSystemDirectory(userId),
3055 SETTINGS_FILE_SYSTEM);
3056 } else if (isSecureSettingsKey(key)) {
3057 final int userId = getUserIdFromKey(key);
3058 return new File(Environment.getUserSystemDirectory(userId),
3059 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00003060 } else if (isSsaidSettingsKey(key)) {
3061 final int userId = getUserIdFromKey(key);
3062 return new File(Environment.getUserSystemDirectory(userId),
3063 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08003064 } else {
3065 throw new IllegalArgumentException("Invalid settings key:" + key);
3066 }
3067 }
3068
3069 private Uri getNotificationUriFor(int key, String name) {
Matt Pape1b31a332018-10-17 09:58:28 -07003070 if (isConfigSettingsKey(key)) {
3071 return (name != null) ? Uri.withAppendedPath(CONFIG_CONTENT_URI, name)
3072 : CONFIG_CONTENT_URI;
3073 } else if (isGlobalSettingsKey(key)) {
Svetoslav683914b2015-01-15 14:22:26 -08003074 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
3075 : Settings.Global.CONTENT_URI;
3076 } else if (isSecureSettingsKey(key)) {
3077 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
3078 : Settings.Secure.CONTENT_URI;
3079 } else if (isSystemSettingsKey(key)) {
3080 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
3081 : Settings.System.CONTENT_URI;
3082 } else {
3083 throw new IllegalArgumentException("Invalid settings key:" + key);
3084 }
3085 }
3086
3087 private int getMaxBytesPerPackageForType(int type) {
3088 switch (type) {
Matt Pape1b31a332018-10-17 09:58:28 -07003089 case SETTINGS_TYPE_CONFIG:
Svetoslav683914b2015-01-15 14:22:26 -08003090 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00003091 case SETTINGS_TYPE_SECURE:
3092 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08003093 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
3094 }
3095
3096 default: {
3097 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
3098 }
3099 }
3100 }
3101
Svetoslav7e0683b2015-08-03 16:02:52 -07003102 private final class MyHandler extends Handler {
3103 private static final int MSG_NOTIFY_URI_CHANGED = 1;
3104 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
3105
3106 public MyHandler(Looper looper) {
3107 super(looper);
3108 }
3109
3110 @Override
3111 public void handleMessage(Message msg) {
3112 switch (msg.what) {
3113 case MSG_NOTIFY_URI_CHANGED: {
3114 final int userId = msg.arg1;
3115 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06003116 try {
3117 getContext().getContentResolver().notifyChange(uri, null, true, userId);
3118 } catch (SecurityException e) {
3119 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
3120 }
Makoto Onuki0000d322017-11-28 16:31:47 -08003121 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07003122 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
3123 }
3124 } break;
3125
3126 case MSG_NOTIFY_DATA_CHANGED: {
3127 mBackupManager.dataChanged();
3128 } break;
3129 }
3130 }
3131 }
3132
Svetoslav683914b2015-01-15 14:22:26 -08003133 private final class UpgradeController {
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03003134 private static final int SETTINGS_VERSION = 172;
Svetoslav683914b2015-01-15 14:22:26 -08003135
3136 private final int mUserId;
3137
3138 public UpgradeController(int userId) {
3139 mUserId = userId;
3140 }
3141
3142 public void upgradeIfNeededLocked() {
3143 // The version of all settings for a user is the same (all users have secure).
3144 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003145 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003146
3147 // Try an update from the current state.
3148 final int oldVersion = secureSettings.getVersionLocked();
3149 final int newVersion = SETTINGS_VERSION;
3150
Svet Ganovc9755bc2015-03-28 13:21:22 -07003151 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08003152 if (oldVersion == newVersion) {
3153 return;
3154 }
3155
3156 // Try to upgrade.
3157 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
3158
3159 // If upgrade failed start from scratch and upgrade.
3160 if (curVersion != newVersion) {
3161 // Drop state we have for this user.
3162 removeUserStateLocked(mUserId, true);
3163
3164 // Recreate the database.
3165 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
3166 SQLiteDatabase database = dbHelper.getWritableDatabase();
3167 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
3168
3169 // Migrate the settings for this user.
3170 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
3171
3172 // Now upgrade should work fine.
3173 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003174
3175 // Make a note what happened, so we don't wonder why data was lost
3176 String reason = "Settings rebuilt! Current version: "
3177 + curVersion + " while expected: " + newVersion;
3178 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003179 Settings.Global.DATABASE_DOWNGRADE_REASON,
3180 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08003181 }
3182
3183 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07003184 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08003185 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003186 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003187 globalSettings.setVersionLocked(newVersion);
3188 }
3189
3190 // Set the secure settings version.
3191 secureSettings.setVersionLocked(newVersion);
3192
3193 // Set the system settings version.
3194 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003195 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003196 systemSettings.setVersionLocked(newVersion);
3197 }
3198
3199 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003200 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003201 }
3202
3203 private SettingsState getSecureSettingsLocked(int userId) {
3204 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3205 }
3206
Mark Rathjend891f012017-01-19 04:10:37 +00003207 private SettingsState getSsaidSettingsLocked(int userId) {
3208 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3209 }
3210
Svetoslav683914b2015-01-15 14:22:26 -08003211 private SettingsState getSystemSettingsLocked(int userId) {
3212 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3213 }
3214
Jeff Brown503cffc2015-03-26 18:08:51 -07003215 /**
3216 * You must perform all necessary mutations to bring the settings
3217 * for this user from the old to the new version. When you add a new
3218 * upgrade step you *must* update SETTINGS_VERSION.
3219 *
3220 * This is an example of moving a setting from secure to global.
3221 *
3222 * // v119: Example settings changes.
3223 * if (currentVersion == 118) {
3224 * if (userId == UserHandle.USER_OWNER) {
3225 * // Remove from the secure settings.
3226 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3227 * String name = "example_setting_to_move";
3228 * String value = secureSettings.getSetting(name);
3229 * secureSettings.deleteSetting(name);
3230 *
3231 * // Add to the global settings.
3232 * SettingsState globalSettings = getGlobalSettingsLocked();
3233 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3234 * }
3235 *
3236 * // Update the current version.
3237 * currentVersion = 119;
3238 * }
3239 */
Svetoslav683914b2015-01-15 14:22:26 -08003240 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3241 if (DEBUG) {
3242 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3243 + oldVersion + " to version: " + newVersion);
3244 }
3245
Jeff Brown503cffc2015-03-26 18:08:51 -07003246 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003247
John Spurlocke11ae112015-05-11 16:09:03 -04003248 // v119: Reset zen + ringer mode.
3249 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003250 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003251 final SettingsState globalSettings = getGlobalSettingsLocked();
3252 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003253 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3254 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003255 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003256 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3257 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003258 }
3259 currentVersion = 119;
3260 }
3261
Jason Monk27bbb2d2015-03-31 16:46:39 -04003262 // v120: Add double tap to wake setting.
3263 if (currentVersion == 119) {
3264 SettingsState secureSettings = getSecureSettingsLocked(userId);
3265 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3266 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003267 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003268 SettingsState.SYSTEM_PACKAGE_NAME);
3269
3270 currentVersion = 120;
3271 }
3272
Svetoslav7e0683b2015-08-03 16:02:52 -07003273 if (currentVersion == 120) {
3274 // Before 121, we used a different string encoding logic. We just bump the
3275 // version here; SettingsState knows how to handle pre-version 120 files.
3276 currentVersion = 121;
3277 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003278
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003279 if (currentVersion == 121) {
3280 // Version 122: allow OEMs to set a default payment component in resources.
3281 // Note that we only write the default if no default has been set;
3282 // if there is, we just leave the default at whatever it currently is.
3283 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3284 String defaultComponent = (getContext().getResources().getString(
3285 R.string.def_nfc_payment_component));
3286 Setting currentSetting = secureSettings.getSettingLocked(
3287 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3288 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003289 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003290 secureSettings.insertSettingLocked(
3291 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003292 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003293 }
3294 currentVersion = 122;
3295 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003296
3297 if (currentVersion == 122) {
3298 // Version 123: Adding a default value for the ability to add a user from
3299 // the lock screen.
3300 if (userId == UserHandle.USER_SYSTEM) {
3301 final SettingsState globalSettings = getGlobalSettingsLocked();
3302 Setting currentSetting = globalSettings.getSettingLocked(
3303 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003304 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003305 globalSettings.insertSettingLocked(
3306 Settings.Global.ADD_USERS_WHEN_LOCKED,
3307 getContext().getResources().getBoolean(
3308 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003309 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003310 }
3311 }
3312 currentVersion = 123;
3313 }
Bryce Leebd179282015-12-17 19:01:37 -08003314
3315 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003316 final SettingsState globalSettings = getGlobalSettingsLocked();
3317 String defaultDisabledProfiles = (getContext().getResources().getString(
3318 R.string.def_bluetooth_disabled_profiles));
3319 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003320 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003321 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003322 }
3323
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003324 if (currentVersion == 124) {
3325 // Version 124: allow OEMs to set a default value for whether IME should be
3326 // shown when a physical keyboard is connected.
3327 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3328 Setting currentSetting = secureSettings.getSettingLocked(
3329 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003330 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003331 secureSettings.insertSettingLocked(
3332 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3333 getContext().getResources().getBoolean(
3334 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003335 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003336 }
3337 currentVersion = 125;
3338 }
3339
Ruben Brunk98576cf2016-03-07 18:54:28 -08003340 if (currentVersion == 125) {
3341 // Version 125: Allow OEMs to set the default VR service.
3342 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3343
3344 Setting currentSetting = secureSettings.getSettingLocked(
3345 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003346 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003347 ArraySet<ComponentName> l =
3348 SystemConfig.getInstance().getDefaultVrComponents();
3349
3350 if (l != null && !l.isEmpty()) {
3351 StringBuilder b = new StringBuilder();
3352 boolean start = true;
3353 for (ComponentName c : l) {
3354 if (!start) {
3355 b.append(':');
3356 }
3357 b.append(c.flattenToString());
3358 start = false;
3359 }
3360 secureSettings.insertSettingLocked(
3361 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003362 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003363 }
3364
3365 }
3366 currentVersion = 126;
3367 }
3368
Daniel U02ba6122016-04-01 18:41:42 +01003369 if (currentVersion == 126) {
3370 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3371 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3372 if (mUserManager.isManagedProfile(userId)) {
3373 final SettingsState systemSecureSettings =
3374 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3375
3376 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3377 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003378 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003379 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3380 secureSettings.insertSettingLocked(
3381 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003382 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003383 SettingsState.SYSTEM_PACKAGE_NAME);
3384 }
3385
3386 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3387 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003388 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003389 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3390 secureSettings.insertSettingLocked(
3391 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003392 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003393 SettingsState.SYSTEM_PACKAGE_NAME);
3394 }
3395 }
3396 currentVersion = 127;
3397 }
3398
Steven Ngdc20ba62016-04-26 18:19:04 +01003399 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003400 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003401 currentVersion = 128;
3402 }
3403
Julia Reynolds1f721e12016-07-11 08:50:58 -04003404 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003405 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003406 currentVersion = 129;
3407 }
3408
Dan Sandler71f85e92016-07-20 13:46:05 -04003409 if (currentVersion == 129) {
3410 // default longpress timeout changed from 500 to 400. If unchanged from the old
3411 // default, update to the new default.
3412 final SettingsState systemSecureSettings =
3413 getSecureSettingsLocked(userId);
3414 final String oldValue = systemSecureSettings.getSettingLocked(
3415 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3416 if (TextUtils.equals("500", oldValue)) {
3417 systemSecureSettings.insertSettingLocked(
3418 Settings.Secure.LONG_PRESS_TIMEOUT,
3419 String.valueOf(getContext().getResources().getInteger(
3420 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003421 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003422 }
3423 currentVersion = 130;
3424 }
3425
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003426 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003427 // Split Ambient settings
3428 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3429 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3430 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3431
3432 if (dozeExplicitlyDisabled) {
Lucas Dupin4359b552018-08-09 15:07:54 -07003433 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PICK_UP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003434 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Lucas Dupin4359b552018-08-09 15:07:54 -07003435 secureSettings.insertSettingLocked(Settings.Secure.DOZE_DOUBLE_TAP_GESTURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003436 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003437 }
3438 currentVersion = 131;
3439 }
3440
3441 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003442 // Initialize new multi-press timeout to default value
3443 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3444 final String oldValue = systemSecureSettings.getSettingLocked(
3445 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3446 if (TextUtils.equals(null, oldValue)) {
3447 systemSecureSettings.insertSettingLocked(
3448 Settings.Secure.MULTI_PRESS_TIMEOUT,
3449 String.valueOf(getContext().getResources().getInteger(
3450 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003451 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003452 }
3453
Adrian Roos69741a22016-10-21 14:49:17 -07003454 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003455 }
3456
Adrian Roos69741a22016-10-21 14:49:17 -07003457 if (currentVersion == 132) {
3458 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003459 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3460 String defaultSyncParentSounds = (getContext().getResources()
3461 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3462 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003463 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3464 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003465 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003466 }
3467
Adrian Roos69741a22016-10-21 14:49:17 -07003468 if (currentVersion == 133) {
3469 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003470 final SettingsState systemSettings = getSystemSettingsLocked(userId);
davidlnedb31e12018-09-25 10:21:20 -07003471 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR)
3472 .isNull()) {
Keun-young Parkec7a1182016-10-18 11:52:38 -07003473 String defaultEndButtonBehavior = Integer.toString(getContext()
3474 .getResources().getInteger(R.integer.def_end_button_behavior));
3475 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003476 defaultEndButtonBehavior, null, true,
3477 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003478 }
Adrian Roos69741a22016-10-21 14:49:17 -07003479 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003480 }
3481
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003482 if (currentVersion == 134) {
3483 // Remove setting that specifies if magnification values should be preserved.
3484 // This setting defaulted to true and never has a UI.
3485 getSecureSettingsLocked(userId).deleteSettingLocked(
3486 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3487 currentVersion = 135;
3488 }
3489
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003490 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003491 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003492 currentVersion = 136;
3493 }
3494
Mark Rathjend891f012017-01-19 04:10:37 +00003495 if (currentVersion == 136) {
3496 // Version 136: Store legacy SSAID for all apps currently installed on the
3497 // device as first step in migrating SSAID to be unique per application.
3498
3499 final boolean isUpgrade;
3500 try {
3501 isUpgrade = mPackageManager.isUpgrade();
3502 } catch (RemoteException e) {
3503 throw new IllegalStateException("Package manager not available");
3504 }
3505 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3506 // user data or first boot on a new device should use new ssaid generation.
3507 if (isUpgrade) {
3508 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003509 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3510 userId, Settings.Secure.ANDROID_ID);
3511 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3512 || legacySsaidSetting.getValue() == null) {
3513 throw new IllegalStateException("Legacy ssaid not accessible");
3514 }
3515 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003516
3517 // Fill each uid with the legacy ssaid to be backwards compatible.
3518 final List<PackageInfo> packages;
3519 try {
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003520 packages = mPackageManager.getInstalledPackages(
3521 PackageManager.MATCH_UNINSTALLED_PACKAGES,
3522 userId).getList();
Mark Rathjend891f012017-01-19 04:10:37 +00003523 } catch (RemoteException e) {
3524 throw new IllegalStateException("Package manager not available");
3525 }
3526
3527 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3528 for (PackageInfo info : packages) {
3529 // Check if the UID already has an entry in the table.
3530 final String uid = Integer.toString(info.applicationInfo.uid);
3531 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3532
3533 if (ssaid.isNull() || ssaid.getValue() == null) {
3534 // Android Id doesn't exist for this package so create it.
3535 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3536 info.packageName);
Tetsutoki Shiozawaebe0e5f2018-01-17 11:07:09 +09003537 if (DEBUG) {
3538 Slog.d(LOG_TAG, "Keep the legacy ssaid for uid=" + uid);
3539 }
Mark Rathjend891f012017-01-19 04:10:37 +00003540 }
3541 }
3542 }
3543
3544 currentVersion = 137;
3545 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003546 if (currentVersion == 137) {
3547 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3548 // default value set to 1. The user can no longer change the value of this
3549 // setting through the UI.
3550 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3551 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003552 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3553 && secureSetting.getSettingLocked(
3554 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3555
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003556 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3557 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003558 // For managed profiles with profile owners, DevicePolicyManagerService
3559 // may want to set the user restriction in this case
3560 secureSetting.insertSettingLocked(
3561 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3562 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003563 }
3564 currentVersion = 138;
3565 }
Mark Rathjend891f012017-01-19 04:10:37 +00003566
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003567 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003568 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003569 currentVersion = 139;
3570 }
3571
Phil Weaver385912e2017-02-10 10:06:56 -08003572 if (currentVersion == 139) {
3573 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3574 // the user can no longer change the value of this setting through the UI.
3575 // Force to true.
3576 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3577 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3578 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3579 currentVersion = 140;
3580 }
3581
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003582 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003583 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003584 currentVersion = 141;
3585 }
3586
Svet Ganov13701552017-02-23 12:45:17 -08003587 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003588 // This implementation was incorrectly setting the current value of
3589 // settings changed by non-system packages as the default which default
3590 // is set by the system. We add a new upgrade step at the end to properly
3591 // handle this case which would also fix incorrect changes made by the
3592 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003593 currentVersion = 142;
3594 }
3595
Stephen Chen5d0922f2017-03-27 10:28:04 -07003596 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003597 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003598 if (userId == UserHandle.USER_SYSTEM) {
3599 final SettingsState globalSettings = getGlobalSettingsLocked();
3600 Setting currentSetting = globalSettings.getSettingLocked(
3601 Settings.Global.WIFI_WAKEUP_ENABLED);
3602 if (currentSetting.isNull()) {
3603 globalSettings.insertSettingLocked(
3604 Settings.Global.WIFI_WAKEUP_ENABLED,
3605 getContext().getResources().getBoolean(
3606 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3607 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3608 }
3609 }
3610
3611 currentVersion = 143;
3612 }
3613
Felipe Lemeff355092017-04-03 12:55:02 -07003614 if (currentVersion == 143) {
3615 // Version 144: Set a default value for Autofill service.
3616 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3617 final Setting currentSetting = secureSettings
3618 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3619 if (currentSetting.isNull()) {
3620 final String defaultValue = getContext().getResources().getString(
3621 com.android.internal.R.string.config_defaultAutofillService);
3622 if (defaultValue != null) {
3623 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3624 + "for user " + userId);
3625 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3626 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3627 }
3628 }
3629
3630 currentVersion = 144;
3631 }
3632
Jeremy Joslin45caa252017-05-04 11:22:46 -07003633 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003634 // Version 145: Removed
3635 currentVersion = 145;
3636 }
3637
3638 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003639 // Version 146: In step 142 we had a bug where incorrectly
3640 // some settings were considered system set and as a result
3641 // made the default and marked as the default being set by
3642 // the system. Here reevaluate the default and default system
3643 // set flags. This would both fix corruption by the old impl
3644 // of step 142 and also properly handle devices which never
3645 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003646 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003647 SettingsState globalSettings = getGlobalSettingsLocked();
3648 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3649 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003650 }
3651
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003652 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3653 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3654 secureSettings.persistSyncLocked();
3655
3656 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3657 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3658 systemSettings.persistSyncLocked();
3659
Amin Shaikh86367962017-06-07 08:58:22 -07003660 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003661 }
3662
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003663 if (currentVersion == 146) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003664 // Version 147: Removed. (This version previously allowed showing the
3665 // "wifi_wakeup_available" setting).
3666 // The setting that was added here is deleted in 153.
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003667 currentVersion = 147;
3668 }
3669
3670 if (currentVersion == 147) {
3671 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003672 if (userId == UserHandle.USER_SYSTEM) {
3673 final SettingsState globalSettings = getGlobalSettingsLocked();
3674 final Setting currentSetting = globalSettings.getSettingLocked(
3675 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3676 if (currentSetting.isNull()) {
3677 globalSettings.insertSettingLocked(
3678 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3679 getContext().getResources().getBoolean(
3680 R.bool.def_restrict_background_data) ? "1" : "0",
3681 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3682 }
3683 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003684 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003685 }
3686
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003687 if (currentVersion == 148) {
3688 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3689 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3690 final String oldValue = systemSecureSettings.getSettingLocked(
3691 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3692 if (TextUtils.equals(null, oldValue)) {
3693 final String defaultValue = getContext().getResources().getString(
3694 R.string.def_backup_manager_constants);
3695 if (!TextUtils.isEmpty(defaultValue)) {
3696 systemSecureSettings.insertSettingLocked(
3697 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3698 true, SettingsState.SYSTEM_PACKAGE_NAME);
3699 }
3700 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003701 currentVersion = 149;
3702 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003703
3704 if (currentVersion == 149) {
3705 // Version 150: Set a default value for mobile data always on
3706 final SettingsState globalSettings = getGlobalSettingsLocked();
3707 final Setting currentSetting = globalSettings.getSettingLocked(
3708 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3709 if (currentSetting.isNull()) {
3710 globalSettings.insertSettingLocked(
3711 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3712 getContext().getResources().getBoolean(
3713 R.bool.def_mobile_data_always_on) ? "1" : "0",
3714 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3715 }
3716
3717 currentVersion = 150;
3718 }
3719
Mike Digman4af4a6f2018-01-16 14:49:38 -08003720 if (currentVersion == 150) {
Mike Digman32e03312018-05-16 16:43:23 -07003721 // Version 151: Removed.
Mike Digman4af4a6f2018-01-16 14:49:38 -08003722 currentVersion = 151;
3723 }
3724
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003725 if (currentVersion == 151) {
Joe LaPenna250d7842018-01-25 10:19:42 -08003726 // Version 152: Removed. (This version made the setting for wifi_wakeup enabled
3727 // by default but it is now no longer configurable).
3728 // The setting updated here is deleted in 153.
Joe LaPenna4f50ed42018-01-22 14:54:45 -08003729 currentVersion = 152;
3730 }
3731
Joe LaPenna250d7842018-01-25 10:19:42 -08003732 if (currentVersion == 152) {
3733 getGlobalSettingsLocked().deleteSettingLocked("wifi_wakeup_available");
3734 currentVersion = 153;
3735 }
3736
Ben Linb4df8bc2018-01-29 11:48:20 -08003737 if (currentVersion == 153) {
3738 // Version 154: Read notification badge configuration from config.
3739 // If user has already set the value, don't do anything.
3740 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3741 final Setting showNotificationBadges = systemSecureSettings.getSettingLocked(
3742 Settings.Secure.NOTIFICATION_BADGING);
3743 if (showNotificationBadges.isNull()) {
3744 final boolean defaultValue = getContext().getResources().getBoolean(
3745 com.android.internal.R.bool.config_notificationBadging);
3746 systemSecureSettings.insertSettingLocked(
3747 Secure.NOTIFICATION_BADGING,
3748 defaultValue ? "1" : "0",
3749 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3750 }
3751 currentVersion = 154;
3752 }
3753
Bernardo Rufinoeaa78b92018-01-26 11:25:37 +00003754 if (currentVersion == 154) {
3755 // Version 155: Set the default value for BACKUP_LOCAL_TRANSPORT_PARAMETERS.
3756 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3757 final String oldValue = systemSecureSettings.getSettingLocked(
3758 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS).getValue();
3759 if (TextUtils.equals(null, oldValue)) {
3760 final String defaultValue = getContext().getResources().getString(
3761 R.string.def_backup_local_transport_parameters);
3762 if (!TextUtils.isEmpty(defaultValue)) {
3763 systemSecureSettings.insertSettingLocked(
3764 Settings.Secure.BACKUP_LOCAL_TRANSPORT_PARAMETERS, defaultValue,
3765 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3766 }
3767
3768 }
3769 currentVersion = 155;
3770 }
3771
Beverlyda904812018-03-02 09:55:30 -05003772 if (currentVersion == 155) {
Annie Mengd069a882018-03-13 15:31:40 +00003773 // Version 156: Set the default value for CHARGING_STARTED_SOUND.
Beverlyda904812018-03-02 09:55:30 -05003774 final SettingsState globalSettings = getGlobalSettingsLocked();
3775 final String oldValue = globalSettings.getSettingLocked(
3776 Global.CHARGING_STARTED_SOUND).getValue();
3777 final String oldDefault = getContext().getResources().getString(
3778 R.string.def_wireless_charging_started_sound);
3779 if (TextUtils.equals(null, oldValue)
3780 || TextUtils.equals(oldValue, oldDefault)) {
3781 final String defaultValue = getContext().getResources().getString(
3782 R.string.def_charging_started_sound);
3783 if (!TextUtils.isEmpty(defaultValue)) {
3784 globalSettings.insertSettingLocked(
3785 Settings.Global.CHARGING_STARTED_SOUND, defaultValue,
3786 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3787 }
3788
3789 }
3790 currentVersion = 156;
3791 }
3792
Beverly09da25f2018-02-26 09:17:07 -05003793 if (currentVersion == 156) {
Beverly91d0a632018-07-02 16:45:00 -04003794 // Version 157: Set a default value for zen duration,
3795 // in version 169, zen duration is moved to secure settings
Beverly09da25f2018-02-26 09:17:07 -05003796 final SettingsState globalSettings = getGlobalSettingsLocked();
3797 final Setting currentSetting = globalSettings.getSettingLocked(
3798 Global.ZEN_DURATION);
3799 if (currentSetting.isNull()) {
3800 String defaultZenDuration = Integer.toString(getContext()
3801 .getResources().getInteger(R.integer.def_zen_duration));
3802 globalSettings.insertSettingLocked(
3803 Global.ZEN_DURATION, defaultZenDuration,
3804 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3805 }
Beverly09da25f2018-02-26 09:17:07 -05003806 currentVersion = 157;
3807 }
Annie Mengd069a882018-03-13 15:31:40 +00003808
3809 if (currentVersion == 157) {
3810 // Version 158: Set default value for BACKUP_AGENT_TIMEOUT_PARAMETERS.
3811 final SettingsState globalSettings = getGlobalSettingsLocked();
3812 final String oldValue = globalSettings.getSettingLocked(
3813 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS).getValue();
3814 if (TextUtils.equals(null, oldValue)) {
3815 final String defaultValue = getContext().getResources().getString(
3816 R.string.def_backup_agent_timeout_parameters);
3817 if (!TextUtils.isEmpty(defaultValue)) {
3818 globalSettings.insertSettingLocked(
3819 Settings.Global.BACKUP_AGENT_TIMEOUT_PARAMETERS, defaultValue,
3820 null, true,
3821 SettingsState.SYSTEM_PACKAGE_NAME);
3822 }
3823 }
3824 currentVersion = 158;
3825 }
Roshan Pius9c396672018-03-02 14:54:13 -08003826
3827 if (currentVersion == 158) {
3828 // Remove setting that specifies wifi bgscan throttling params
3829 getGlobalSettingsLocked().deleteSettingLocked(
3830 "wifi_scan_background_throttle_interval_ms");
3831 getGlobalSettingsLocked().deleteSettingLocked(
3832 "wifi_scan_background_throttle_package_whitelist");
3833 currentVersion = 159;
3834 }
3835
Pavel Grafovc5c97302018-03-19 13:37:15 +00003836 if (currentVersion == 159) {
3837 // Version 160: Hiding notifications from the lockscreen is only available as
3838 // primary user option, profiles can only make them redacted. If a profile was
3839 // configured to not show lockscreen notifications, ensure that at the very
3840 // least these will be come hidden.
3841 if (mUserManager.isManagedProfile(userId)) {
3842 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3843 Setting showNotifications = secureSettings.getSettingLocked(
3844 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3845 // The default value is "1", check if user has turned it off.
3846 if ("0".equals(showNotifications.getValue())) {
3847 secureSettings.insertSettingLocked(
3848 Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, "0",
3849 null /* tag */, false /* makeDefault */,
3850 SettingsState.SYSTEM_PACKAGE_NAME);
3851 }
3852 // The setting is no longer valid for managed profiles, it should be
3853 // treated as if it was set to "1".
3854 secureSettings.deleteSettingLocked(Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
3855 }
3856 currentVersion = 160;
3857 }
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003858
3859 if (currentVersion == 160) {
3860 // Version 161: Set the default value for
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003861 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY and
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003862 // SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT
3863 final SettingsState globalSettings = getGlobalSettingsLocked();
3864
3865 String oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann7e25b3d2018-03-09 20:22:58 -08003866 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY).getValue();
3867 if (TextUtils.equals(null, oldValue)) {
3868 globalSettings.insertSettingLocked(
3869 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3870 Integer.toString(getContext().getResources().getInteger(
3871 R.integer.def_max_sound_trigger_detection_service_ops_per_day)),
3872 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3873 }
3874
3875 oldValue = globalSettings.getSettingLocked(
Philip P. Moltmann18e3eb82018-03-09 16:55:55 -08003876 Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT).getValue();
3877 if (TextUtils.equals(null, oldValue)) {
3878 globalSettings.insertSettingLocked(
3879 Settings.Global.SOUND_TRIGGER_DETECTION_SERVICE_OP_TIMEOUT,
3880 Integer.toString(getContext().getResources().getInteger(
3881 R.integer.def_sound_trigger_detection_service_op_timeout)),
3882 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3883 }
3884 currentVersion = 161;
3885 }
3886
Mike Digman55272862018-02-20 14:35:17 -08003887 if (currentVersion == 161) {
3888 // Version 161: Add a gesture for silencing phones
3889 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3890 final Setting currentSetting = secureSettings.getSettingLocked(
3891 Secure.VOLUME_HUSH_GESTURE);
3892 if (currentSetting.isNull()) {
3893 secureSettings.insertSettingLocked(
3894 Secure.VOLUME_HUSH_GESTURE,
3895 Integer.toString(Secure.VOLUME_HUSH_VIBRATE),
3896 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3897 }
3898
3899 currentVersion = 162;
3900 }
3901
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003902 if (currentVersion == 162) {
Julia Reynolds76bfa602018-04-23 09:38:47 -04003903 // Version 162: REMOVED: Add a gesture for silencing phones
Julia Reynoldsc4e5ecf2018-04-11 11:33:32 -04003904 currentVersion = 163;
3905 }
3906
Philip P. Moltmanncb58a832018-04-16 09:19:42 -07003907 if (currentVersion == 163) {
3908 // Version 163: Update default value of
3909 // MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY from old to new default
3910 final SettingsState settings = getGlobalSettingsLocked();
3911 final Setting currentSetting = settings.getSettingLocked(
3912 Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY);
3913 if (currentSetting.isDefaultFromSystem()) {
3914 settings.insertSettingLocked(
3915 Settings.Global.MAX_SOUND_TRIGGER_DETECTION_SERVICE_OPS_PER_DAY,
3916 Integer.toString(getContext().getResources().getInteger(
3917 R.integer
3918 .def_max_sound_trigger_detection_service_ops_per_day)),
3919 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3920 }
3921
3922 currentVersion = 164;
3923 }
3924
Julia Reynolds76bfa602018-04-23 09:38:47 -04003925 if (currentVersion == 164) {
Julia Reynolds24836c52018-06-06 14:36:03 -04003926 // Version 164: REMOVED: show zen upgrade notification
Julia Reynolds76bfa602018-04-23 09:38:47 -04003927 currentVersion = 165;
3928 }
3929
Beverly301e92a2018-04-27 09:43:05 -04003930 if (currentVersion == 165) {
Beverly91d0a632018-07-02 16:45:00 -04003931 // Version 165: MOVED: Show zen settings suggestion and zen updated settings
3932 // moved to secure settings and are set in version 169
Beverly301e92a2018-04-27 09:43:05 -04003933 currentVersion = 166;
3934 }
3935
Beverly38fcfd02018-05-18 17:33:40 -04003936 if (currentVersion == 166) {
3937 // Version 166: add default values for hush gesture used and manual ringer
3938 // toggle
3939 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3940 Setting currentHushUsedSetting = secureSettings.getSettingLocked(
3941 Secure.HUSH_GESTURE_USED);
3942 if (currentHushUsedSetting.isNull()) {
3943 secureSettings.insertSettingLocked(
3944 Settings.Secure.HUSH_GESTURE_USED, "0", null, true,
3945 SettingsState.SYSTEM_PACKAGE_NAME);
3946 }
3947
3948 Setting currentRingerToggleCountSetting = secureSettings.getSettingLocked(
3949 Secure.MANUAL_RINGER_TOGGLE_COUNT);
3950 if (currentRingerToggleCountSetting.isNull()) {
3951 secureSettings.insertSettingLocked(
3952 Settings.Secure.MANUAL_RINGER_TOGGLE_COUNT, "0", null, true,
3953 SettingsState.SYSTEM_PACKAGE_NAME);
3954 }
3955 currentVersion = 167;
3956 }
3957
Beverly155c9d22018-05-23 18:03:23 -04003958 if (currentVersion == 167) {
Beverly91d0a632018-07-02 16:45:00 -04003959 // Version 167: MOVED - Settings.Global.CHARGING_VIBRATION_ENABLED moved to
3960 // Settings.Secure.CHARGING_VIBRATION_ENABLED, set in version 170
Beverly155c9d22018-05-23 18:03:23 -04003961 currentVersion = 168;
3962 }
3963
Michael Wright0e9eeee2018-05-26 00:31:20 +01003964 if (currentVersion == 168) {
3965 // Version 168: by default, vibrate for phone calls
3966 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3967 final Setting currentSetting = systemSettings.getSettingLocked(
3968 Settings.System.VIBRATE_WHEN_RINGING);
3969 if (currentSetting.isNull()) {
3970 systemSettings.insertSettingLocked(
3971 Settings.System.VIBRATE_WHEN_RINGING,
3972 getContext().getResources().getBoolean(
3973 R.bool.def_vibrate_when_ringing) ? "1" : "0",
3974 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3975 }
3976 currentVersion = 169;
3977 }
3978
Nadav Barf9f115d2018-06-24 10:06:50 +03003979 if (currentVersion == 169) {
Beverly91d0a632018-07-02 16:45:00 -04003980 // Version 169: Set the default value for Secure Settings ZEN_DURATION,
3981 // SHOW_ZEN_SETTINGS_SUGGESTION, ZEN_SETTINGS_UPDATE and
3982 // ZEN_SETTINGS_SUGGESTION_VIEWED
Nadav Barf9f115d2018-06-24 10:06:50 +03003983
Beverly91d0a632018-07-02 16:45:00 -04003984 final SettingsState globalSettings = getGlobalSettingsLocked();
3985 final Setting globalZenDuration = globalSettings.getSettingLocked(
3986 Global.ZEN_DURATION);
3987
3988 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3989 final Setting secureZenDuration = secureSettings.getSettingLocked(
3990 Secure.ZEN_DURATION);
3991
3992 // ZEN_DURATION
3993 if (!globalZenDuration.isNull()) {
3994 secureSettings.insertSettingLocked(
3995 Secure.ZEN_DURATION, globalZenDuration.getValue(), null, false,
3996 SettingsState.SYSTEM_PACKAGE_NAME);
3997
3998 // set global zen duration setting to null since it's deprecated
3999 globalSettings.insertSettingLocked(
4000 Global.ZEN_DURATION, null, null, true,
4001 SettingsState.SYSTEM_PACKAGE_NAME);
4002 } else if (secureZenDuration.isNull()) {
4003 String defaultZenDuration = Integer.toString(getContext()
4004 .getResources().getInteger(R.integer.def_zen_duration));
4005 secureSettings.insertSettingLocked(
4006 Secure.ZEN_DURATION, defaultZenDuration, null, true,
4007 SettingsState.SYSTEM_PACKAGE_NAME);
Nadav Barf9f115d2018-06-24 10:06:50 +03004008 }
Beverly91d0a632018-07-02 16:45:00 -04004009
4010 // SHOW_ZEN_SETTINGS_SUGGESTION
4011 final Setting currentShowZenSettingSuggestion = secureSettings.getSettingLocked(
4012 Secure.SHOW_ZEN_SETTINGS_SUGGESTION);
4013 if (currentShowZenSettingSuggestion.isNull()) {
4014 secureSettings.insertSettingLocked(
4015 Secure.SHOW_ZEN_SETTINGS_SUGGESTION, "1",
4016 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4017 }
4018
4019 // ZEN_SETTINGS_UPDATED
4020 final Setting currentUpdatedSetting = secureSettings.getSettingLocked(
4021 Secure.ZEN_SETTINGS_UPDATED);
4022 if (currentUpdatedSetting.isNull()) {
4023 secureSettings.insertSettingLocked(
4024 Secure.ZEN_SETTINGS_UPDATED, "0",
4025 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4026 }
4027
4028 // ZEN_SETTINGS_SUGGESTION_VIEWED
4029 final Setting currentSettingSuggestionViewed = secureSettings.getSettingLocked(
4030 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED);
4031 if (currentSettingSuggestionViewed.isNull()) {
4032 secureSettings.insertSettingLocked(
4033 Secure.ZEN_SETTINGS_SUGGESTION_VIEWED, "0",
4034 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4035 }
4036
Nadav Barf9f115d2018-06-24 10:06:50 +03004037 currentVersion = 170;
4038 }
4039
Beverly91d0a632018-07-02 16:45:00 -04004040 if (currentVersion == 170) {
4041 // Version 170: Set the default value for Secure Settings:
4042 // CHARGING_SOUNDS_ENABLED and CHARGING_VIBRATION_ENABLED
4043
4044 final SettingsState globalSettings = getGlobalSettingsLocked();
4045 final SettingsState secureSettings = getSecureSettingsLocked(userId);
4046
4047 // CHARGING_SOUNDS_ENABLED
4048 final Setting globalChargingSoundEnabled = globalSettings.getSettingLocked(
4049 Global.CHARGING_SOUNDS_ENABLED);
4050 final Setting secureChargingSoundsEnabled = secureSettings.getSettingLocked(
4051 Secure.CHARGING_SOUNDS_ENABLED);
4052
4053 if (!globalChargingSoundEnabled.isNull()) {
4054 secureSettings.insertSettingLocked(
4055 Secure.CHARGING_SOUNDS_ENABLED,
4056 globalChargingSoundEnabled.getValue(), null, false,
4057 SettingsState.SYSTEM_PACKAGE_NAME);
4058
4059 // set global charging_sounds_enabled setting to null since it's deprecated
4060 globalSettings.insertSettingLocked(
4061 Global.CHARGING_SOUNDS_ENABLED, null, null, true,
4062 SettingsState.SYSTEM_PACKAGE_NAME);
4063 } else if (secureChargingSoundsEnabled.isNull()) {
4064 String defChargingSoundsEnabled = getContext().getResources()
4065 .getBoolean(R.bool.def_charging_sounds_enabled) ? "1" : "0";
4066 secureSettings.insertSettingLocked(
4067 Secure.CHARGING_SOUNDS_ENABLED, defChargingSoundsEnabled, null,
4068 true, SettingsState.SYSTEM_PACKAGE_NAME);
4069 }
4070
4071 // CHARGING_VIBRATION_ENABLED
4072 final Setting secureChargingVibrationEnabled = secureSettings.getSettingLocked(
4073 Secure.CHARGING_VIBRATION_ENABLED);
4074
4075 if (secureChargingVibrationEnabled.isNull()) {
4076 String defChargingVibrationEnabled = getContext().getResources()
4077 .getBoolean(R.bool.def_charging_vibration_enabled) ? "1" : "0";
4078 secureSettings.insertSettingLocked(
4079 Secure.CHARGING_VIBRATION_ENABLED, defChargingVibrationEnabled,
4080 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4081 }
4082
4083 currentVersion = 171;
4084 }
4085
Nadav Bar8bc8c9e2018-09-12 15:41:51 +03004086 if (currentVersion == 171) {
4087 // Version 171: by default, add STREAM_VOICE_CALL to list of streams that can
4088 // be muted.
4089 final SettingsState systemSettings = getSystemSettingsLocked(userId);
4090 final Setting currentSetting = systemSettings.getSettingLocked(
4091 Settings.System.MUTE_STREAMS_AFFECTED);
4092 if (!currentSetting.isNull()) {
4093 try {
4094 int currentSettingIntegerValue = Integer.parseInt(
4095 currentSetting.getValue());
4096 if ((currentSettingIntegerValue
4097 & (1 << AudioManager.STREAM_VOICE_CALL)) == 0) {
4098 systemSettings.insertSettingLocked(
4099 Settings.System.MUTE_STREAMS_AFFECTED,
4100 Integer.toString(
4101 currentSettingIntegerValue
4102 | (1 << AudioManager.STREAM_VOICE_CALL)),
4103 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
4104 }
4105 } catch (NumberFormatException e) {
4106 // remove the setting in case it is not a valid integer
4107 Slog.w("Failed to parse integer value of MUTE_STREAMS_AFFECTED"
4108 + "setting, removing setting", e);
4109 systemSettings.deleteSettingLocked(
4110 Settings.System.MUTE_STREAMS_AFFECTED);
4111 }
4112
4113 }
4114 currentVersion = 172;
4115 }
4116
Felipe Lemeff355092017-04-03 12:55:02 -07004117 // vXXX: Add new settings above this point.
4118
Dan Sandler71f85e92016-07-20 13:46:05 -04004119 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07004120 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04004121 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07004122 + currentVersion +
4123 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
4124 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04004125 if (DEBUG) {
4126 throw new RuntimeException("db upgrade error");
4127 }
4128 }
4129
Jeff Brown503cffc2015-03-26 18:08:51 -07004130 // Return the current version.
4131 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08004132 }
4133 }
Svet Ganov13701552017-02-23 12:45:17 -08004134
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004135 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
4136 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08004137 List<String> names = settings.getSettingNamesLocked();
4138 final int nameCount = names.size();
4139 for (int i = 0; i < nameCount; i++) {
4140 String name = names.get(i);
4141 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004142
4143 // In the upgrade case we pretend the call is made from the app
4144 // that made the last change to the setting to properly determine
4145 // whether the call has been made by a system component.
4146 int callingUid = -1;
4147 try {
4148 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
4149 } catch (RemoteException e) {
4150 /* ignore - handled below */
4151 }
4152 if (callingUid < 0) {
4153 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
4154 continue;
4155 }
4156 try {
4157 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
4158 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08004159 if (systemSet) {
4160 settings.insertSettingLocked(name, setting.getValue(),
4161 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004162 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
4163 // We had a bug where changes by non-system packages were marked
4164 // as system made and as a result set as the default. Therefore, if
4165 // the package changed the setting last is not a system one but the
4166 // setting is marked as its default coming from the system we clear
4167 // the default and clear the system set flag.
4168 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08004169 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07004170 } catch (IllegalStateException e) {
4171 // If the package goes over its quota during the upgrade, don't
4172 // crash but just log the error as the system does the upgrade.
4173 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
4174
Svet Ganov13701552017-02-23 12:45:17 -08004175 }
4176 }
4177 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08004178 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004179}