blob: 8c0f89aef1e70e3d5a3bd2cd711daab56cf6dcaa [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
Svetoslav683914b2015-01-15 14:22:26 -080019import android.Manifest;
Eugene Suslad72c3972016-12-27 15:49:30 -080020import android.annotation.NonNull;
Kweku Adamsb0886f32017-10-31 15:32:09 -070021import android.annotation.Nullable;
Christopher Tated5fe1472012-09-10 15:48:38 -070022import android.app.ActivityManager;
Xiaohui Chen43765b72015-08-31 10:57:33 -070023import android.app.AppGlobals;
Christopher Tate45281862010-03-05 15:46:30 -080024import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070025import android.content.BroadcastReceiver;
Ruben Brunk98576cf2016-03-07 18:54:28 -080026import android.content.ComponentName;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070027import android.content.ContentProvider;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentValues;
29import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070030import android.content.Intent;
31import android.content.IntentFilter;
Svetoslav683914b2015-01-15 14:22:26 -080032import android.content.pm.ApplicationInfo;
Xiaohui Chen43765b72015-08-31 10:57:33 -070033import android.content.pm.IPackageManager;
Svetoslav683914b2015-01-15 14:22:26 -080034import android.content.pm.PackageInfo;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate38e7a602013-09-03 16:57:34 -070036import android.content.pm.UserInfo;
Chad Brubaker20e0dc32017-04-28 18:24:55 -070037import android.content.res.Resources;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
Svetoslav683914b2015-01-15 14:22:26 -080039import android.database.MatrixCursor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteQueryBuilder;
Svetoslav683914b2015-01-15 14:22:26 -080042import android.hardware.camera2.utils.ArrayUtils;
John Spurlocke11ae112015-05-11 16:09:03 -040043import android.media.AudioManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070044import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Svetoslav683914b2015-01-15 14:22:26 -080046import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080047import android.os.Bundle;
Amith Yamasani5cdf7f52013-06-27 15:12:01 -070048import android.os.DropBoxManager;
Svetoslav683914b2015-01-15 14:22:26 -080049import android.os.Environment;
Svetoslav7e0683b2015-08-03 16:02:52 -070050import android.os.Handler;
Svet Ganova8f90262016-05-10 08:44:48 -070051import android.os.HandlerThread;
Svetoslav7e0683b2015-08-03 16:02:52 -070052import android.os.Looper;
53import android.os.Message;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070054import android.os.ParcelFileDescriptor;
Christopher Tate0da13572013-10-13 17:34:49 -070055import android.os.Process;
Xiaohui Chen43765b72015-08-31 10:57:33 -070056import android.os.RemoteException;
Jeff Sharkey413573a2016-02-22 17:52:45 -070057import android.os.SELinux;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070058import android.os.ServiceManager;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.os.UserHandle;
60import android.os.UserManager;
Svet Ganov53a441c2016-04-19 19:38:00 -070061import android.os.UserManagerInternal;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +010063import android.provider.Settings.Global;
Makoto Onuki0000d322017-11-28 16:31:47 -080064import android.provider.Settings.Secure;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065import android.text.TextUtils;
Andre Lago3fa139c2016-08-04 13:53:44 +010066import android.util.ArrayMap;
Svetoslav683914b2015-01-15 14:22:26 -080067import android.util.ArraySet;
Mark Rathjend891f012017-01-19 04:10:37 +000068import android.util.ByteStringUtils;
Christopher Tate06efb532012-08-24 15:29:27 -070069import android.util.Slog;
70import android.util.SparseArray;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070071import android.util.SparseBooleanArray;
Eugene Suslad72c3972016-12-27 15:49:30 -080072import android.util.proto.ProtoOutputStream;
John Spurlocke11ae112015-05-11 16:09:03 -040073
Svetoslav683914b2015-01-15 14:22:26 -080074import com.android.internal.annotations.GuardedBy;
75import com.android.internal.content.PackageMonitor;
76import com.android.internal.os.BackgroundThread;
Suprabh Shukla269c11e2015-12-02 16:51:16 -080077import com.android.providers.settings.SettingsState.Setting;
Svet Ganov53a441c2016-04-19 19:38:00 -070078import com.android.server.LocalServices;
Ruben Brunk98576cf2016-03-07 18:54:28 -080079import com.android.server.SystemConfig;
John Spurlocke11ae112015-05-11 16:09:03 -040080
Svetoslav683914b2015-01-15 14:22:26 -080081import java.io.File;
Svetoslavb505ccc2015-02-17 12:41:04 -080082import java.io.FileDescriptor;
Svetoslav683914b2015-01-15 14:22:26 -080083import java.io.FileNotFoundException;
Svetoslavb505ccc2015-02-17 12:41:04 -080084import java.io.PrintWriter;
Mark Rathjen7599f132017-01-23 14:15:54 -080085import java.nio.ByteBuffer;
86import java.security.InvalidKeyException;
Mark Rathjend891f012017-01-19 04:10:37 +000087import java.security.NoSuchAlgorithmException;
Svetoslav683914b2015-01-15 14:22:26 -080088import java.security.SecureRandom;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -070089import java.util.ArrayList;
Svetoslav683914b2015-01-15 14:22:26 -080090import java.util.Arrays;
Robin Lee7af9a742017-02-20 14:47:30 +000091import java.util.Collection;
Mark Rathjend891f012017-01-19 04:10:37 +000092import java.util.HashSet;
Svetoslav683914b2015-01-15 14:22:26 -080093import java.util.List;
Mark Rathjen7599f132017-01-23 14:15:54 -080094import java.util.Locale;
Andre Lago3fa139c2016-08-04 13:53:44 +010095import java.util.Map;
Svetoslav683914b2015-01-15 14:22:26 -080096import java.util.Set;
97import java.util.regex.Pattern;
Mark Rathjen7599f132017-01-23 14:15:54 -080098import javax.crypto.Mac;
99import javax.crypto.spec.SecretKeySpec;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700100
Svetoslav Ganove080da92016-12-21 17:10:35 -0800101import static android.os.Process.ROOT_UID;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800102import static android.os.Process.SHELL_UID;
Eugene Suslad72c3972016-12-27 15:49:30 -0800103import static android.os.Process.SYSTEM_UID;
104
Svetoslav Ganove080da92016-12-21 17:10:35 -0800105
Svetoslav683914b2015-01-15 14:22:26 -0800106/**
107 * <p>
108 * This class is a content provider that publishes the system settings.
109 * It can be accessed via the content provider APIs or via custom call
110 * commands. The latter is a bit faster and is the preferred way to access
111 * the platform settings.
112 * </p>
113 * <p>
114 * There are three settings types, global (with signature level protection
115 * and shared across users), secure (with signature permission level
116 * protection and per user), and system (with dangerous permission level
117 * protection and per user). Global settings are stored under the device owner.
118 * Each of these settings is represented by a {@link
119 * com.android.providers.settings.SettingsState} object mapped to an integer
120 * key derived from the setting type in the most significant bits and user
121 * id in the least significant bits. Settings are synchronously loaded on
122 * instantiation of a SettingsState and asynchronously persisted on mutation.
123 * Settings are stored in the user specific system directory.
124 * </p>
125 * <p>
126 * Apps targeting APIs Lollipop MR1 and lower can add custom settings entries
127 * and get a warning. Targeting higher API version prohibits this as the
128 * system settings are not a place for apps to save their state. When a package
129 * is removed the settings it added are deleted. Apps cannot delete system
130 * settings added by the platform. System settings values are validated to
131 * ensure the clients do not put bad values. Global and secure settings are
132 * changed only by trusted parties, therefore no validation is performed. Also
133 * there is a limit on the amount of app specific settings that can be added
134 * to prevent unlimited growth of the system process memory footprint.
135 * </p>
136 */
137@SuppressWarnings("deprecation")
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700138public class SettingsProvider extends ContentProvider {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700139 static final boolean DEBUG = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700140
Svetoslav Ganov264c7a92016-08-24 17:31:14 -0700141 private static final boolean DROP_DATABASE_ON_MIGRATION = true;
Svetoslav683914b2015-01-15 14:22:26 -0800142
143 private static final String LOG_TAG = "SettingsProvider";
Christopher Tate0da13572013-10-13 17:34:49 -0700144
Christopher Tate06efb532012-08-24 15:29:27 -0700145 private static final String TABLE_SYSTEM = "system";
146 private static final String TABLE_SECURE = "secure";
147 private static final String TABLE_GLOBAL = "global";
Svetoslav683914b2015-01-15 14:22:26 -0800148
149 // Old tables no longer exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private static final String TABLE_FAVORITES = "favorites";
151 private static final String TABLE_OLD_FAVORITES = "old_favorites";
Svetoslav683914b2015-01-15 14:22:26 -0800152 private static final String TABLE_BLUETOOTH_DEVICES = "bluetooth_devices";
153 private static final String TABLE_BOOKMARKS = "bookmarks";
154 private static final String TABLE_ANDROID_METADATA = "android_metadata";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Svetoslav683914b2015-01-15 14:22:26 -0800156 // The set of removed legacy tables.
157 private static final Set<String> REMOVED_LEGACY_TABLES = new ArraySet<>();
Christopher Tate06efb532012-08-24 15:29:27 -0700158 static {
Svetoslav683914b2015-01-15 14:22:26 -0800159 REMOVED_LEGACY_TABLES.add(TABLE_FAVORITES);
160 REMOVED_LEGACY_TABLES.add(TABLE_OLD_FAVORITES);
161 REMOVED_LEGACY_TABLES.add(TABLE_BLUETOOTH_DEVICES);
162 REMOVED_LEGACY_TABLES.add(TABLE_BOOKMARKS);
163 REMOVED_LEGACY_TABLES.add(TABLE_ANDROID_METADATA);
164 }
Christopher Tate06efb532012-08-24 15:29:27 -0700165
Svetoslav683914b2015-01-15 14:22:26 -0800166 private static final int MUTATION_OPERATION_INSERT = 1;
167 private static final int MUTATION_OPERATION_DELETE = 2;
168 private static final int MUTATION_OPERATION_UPDATE = 3;
Svetoslav Ganove080da92016-12-21 17:10:35 -0800169 private static final int MUTATION_OPERATION_RESET = 4;
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400170
Svetoslav683914b2015-01-15 14:22:26 -0800171 private static final String[] ALL_COLUMNS = new String[] {
172 Settings.NameValueTable._ID,
173 Settings.NameValueTable.NAME,
174 Settings.NameValueTable.VALUE
175 };
176
Makoto Onuki53f0e022017-11-29 13:51:01 -0800177 public static final int SETTINGS_TYPE_GLOBAL = SettingsState.SETTINGS_TYPE_GLOBAL;
178 public static final int SETTINGS_TYPE_SYSTEM = SettingsState.SETTINGS_TYPE_SYSTEM;
179 public static final int SETTINGS_TYPE_SECURE = SettingsState.SETTINGS_TYPE_SECURE;
180 public static final int SETTINGS_TYPE_SSAID = SettingsState.SETTINGS_TYPE_SSAID;
Svet Ganov53a441c2016-04-19 19:38:00 -0700181
182 private static final Bundle NULL_SETTING_BUNDLE = Bundle.forPair(
183 Settings.NameValueTable.VALUE, null);
Christopher Tate06efb532012-08-24 15:29:27 -0700184
Chad Brubaker20e0dc32017-04-28 18:24:55 -0700185 // Overlay specified settings whitelisted for Instant Apps
186 private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
187 private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
188 private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
189
190 static {
191 for (String name : Resources.getSystem().getStringArray(
192 com.android.internal.R.array.config_allowedGlobalInstantAppSettings)) {
193 OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS.add(name);
194 }
195 for (String name : Resources.getSystem().getStringArray(
196 com.android.internal.R.array.config_allowedSystemInstantAppSettings)) {
197 OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS.add(name);
198 }
199 for (String name : Resources.getSystem().getStringArray(
200 com.android.internal.R.array.config_allowedSecureInstantAppSettings)) {
201 OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS.add(name);
202 }
203 }
204
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800205 // Changes to these global settings are synchronously persisted
206 private static final Set<String> CRITICAL_GLOBAL_SETTINGS = new ArraySet<>();
207 static {
208 CRITICAL_GLOBAL_SETTINGS.add(Settings.Global.DEVICE_PROVISIONED);
209 }
210
211 // Changes to these secure settings are synchronously persisted
212 private static final Set<String> CRITICAL_SECURE_SETTINGS = new ArraySet<>();
213 static {
214 CRITICAL_SECURE_SETTINGS.add(Settings.Secure.USER_SETUP_COMPLETE);
215 }
216
Svetoslav683914b2015-01-15 14:22:26 -0800217 // Per user secure settings that moved to the for all users global settings.
218 static final Set<String> sSecureMovedToGlobalSettings = new ArraySet<>();
219 static {
220 Settings.Secure.getMovedToGlobalSettings(sSecureMovedToGlobalSettings);
Christopher Tate06efb532012-08-24 15:29:27 -0700221 }
222
Svetoslav683914b2015-01-15 14:22:26 -0800223 // Per user system settings that moved to the for all users global settings.
224 static final Set<String> sSystemMovedToGlobalSettings = new ArraySet<>();
225 static {
226 Settings.System.getMovedToGlobalSettings(sSystemMovedToGlobalSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700227 }
228
Svetoslav683914b2015-01-15 14:22:26 -0800229 // Per user system settings that moved to the per user secure settings.
230 static final Set<String> sSystemMovedToSecureSettings = new ArraySet<>();
231 static {
232 Settings.System.getMovedToSecureSettings(sSystemMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700233 }
234
Svetoslav683914b2015-01-15 14:22:26 -0800235 // Per all users global settings that moved to the per user secure settings.
236 static final Set<String> sGlobalMovedToSecureSettings = new ArraySet<>();
237 static {
238 Settings.Global.getMovedToSecureSettings(sGlobalMovedToSecureSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700239 }
240
Svetoslav683914b2015-01-15 14:22:26 -0800241 // Per user secure settings that are cloned for the managed profiles of the user.
242 private static final Set<String> sSecureCloneToManagedSettings = new ArraySet<>();
243 static {
244 Settings.Secure.getCloneToManagedProfileSettings(sSecureCloneToManagedSettings);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700245 }
246
Svetoslav683914b2015-01-15 14:22:26 -0800247 // Per user system settings that are cloned for the managed profiles of the user.
248 private static final Set<String> sSystemCloneToManagedSettings = new ArraySet<>();
249 static {
250 Settings.System.getCloneToManagedProfileSettings(sSystemCloneToManagedSettings);
Julia Reynolds5e458dd2014-07-07 16:07:01 -0400251 }
252
Andre Lago3fa139c2016-08-04 13:53:44 +0100253 // Per user system settings that are cloned from the profile's parent when a dependency
254 // in {@link Settings.Secure} is set to "1".
255 public static final Map<String, String> sSystemCloneFromParentOnDependency = new ArrayMap<>();
256 static {
257 Settings.System.getCloneFromParentOnValueSettings(sSystemCloneFromParentOnDependency);
258 }
259
Svetoslav683914b2015-01-15 14:22:26 -0800260 private final Object mLock = new Object();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700261
Svetoslav683914b2015-01-15 14:22:26 -0800262 @GuardedBy("mLock")
263 private SettingsRegistry mSettingsRegistry;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700264
Svet Ganova8f90262016-05-10 08:44:48 -0700265 @GuardedBy("mLock")
266 private HandlerThread mHandlerThread;
267
Makoto Onuki73360ab2017-03-17 11:50:13 -0700268 @GuardedBy("mLock")
269 private Handler mHandler;
270
Svetoslav7ec28e82015-05-20 17:01:10 -0700271 // We have to call in the user manager with no lock held,
272 private volatile UserManager mUserManager;
Svetoslav683914b2015-01-15 14:22:26 -0800273
Svetoslav7ec28e82015-05-20 17:01:10 -0700274 // We have to call in the package manager with no lock held,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700275 private volatile IPackageManager mPackageManager;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700276
Svet Ganov53a441c2016-04-19 19:38:00 -0700277 public static int makeKey(int type, int userId) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800278 return SettingsState.makeKey(type, userId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700279 }
280
281 public static int getTypeFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800282 return SettingsState.getTypeFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700283 }
284
285 public static int getUserIdFromKey(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800286 return SettingsState.getUserIdFromKey(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700287 }
288
289 public static String settingTypeToString(int type) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800290 return SettingsState.settingTypeToString(type);
Svet Ganov53a441c2016-04-19 19:38:00 -0700291 }
292
293 public static String keyToString(int key) {
Makoto Onuki53f0e022017-11-29 13:51:01 -0800294 return SettingsState.keyToString(key);
Svet Ganov53a441c2016-04-19 19:38:00 -0700295 }
296
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297 @Override
298 public boolean onCreate() {
Chad Brubaker97bccee2017-01-05 15:51:41 -0800299 Settings.setInSystemServer();
Svetoslav683914b2015-01-15 14:22:26 -0800300 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700301 mUserManager = UserManager.get(getContext());
302 mPackageManager = AppGlobals.getPackageManager();
Svet Ganova8f90262016-05-10 08:44:48 -0700303 mHandlerThread = new HandlerThread(LOG_TAG,
304 Process.THREAD_PRIORITY_BACKGROUND);
305 mHandlerThread.start();
Makoto Onuki73360ab2017-03-17 11:50:13 -0700306 mHandler = new Handler(mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -0800307 mSettingsRegistry = new SettingsRegistry();
308 }
Makoto Onuki73360ab2017-03-17 11:50:13 -0700309 mHandler.post(() -> {
310 registerBroadcastReceivers();
311 startWatchingUserRestrictionChanges();
312 });
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700313 ServiceManager.addService("settings", new SettingsService(this));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 return true;
315 }
316
Svetoslav683914b2015-01-15 14:22:26 -0800317 @Override
318 public Bundle call(String method, String name, Bundle args) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700319 final int requestingUserId = getRequestingUserId(args);
320 switch (method) {
321 case Settings.CALL_METHOD_GET_GLOBAL: {
322 Setting setting = getGlobalSetting(name);
Svet Ganov53a441c2016-04-19 19:38:00 -0700323 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav683914b2015-01-15 14:22:26 -0800324 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700325
326 case Settings.CALL_METHOD_GET_SECURE: {
Makoto Onuki0000d322017-11-28 16:31:47 -0800327 Setting setting = getSecureSetting(name, requestingUserId,
328 /*enableOverride=*/ true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700329 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700330 }
331
332 case Settings.CALL_METHOD_GET_SYSTEM: {
333 Setting setting = getSystemSetting(name, requestingUserId);
Svet Ganov53a441c2016-04-19 19:38:00 -0700334 return packageValueForCallResult(setting, isTrackingGeneration(args));
Svetoslav7ec28e82015-05-20 17:01:10 -0700335 }
336
337 case Settings.CALL_METHOD_PUT_GLOBAL: {
338 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800339 String tag = getSettingTag(args);
340 final boolean makeDefault = getSettingMakeDefault(args);
341 insertGlobalSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700342 break;
343 }
344
345 case Settings.CALL_METHOD_PUT_SECURE: {
346 String value = getSettingValue(args);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800347 String tag = getSettingTag(args);
348 final boolean makeDefault = getSettingMakeDefault(args);
349 insertSecureSetting(name, value, tag, makeDefault, requestingUserId, false);
Svetoslav7ec28e82015-05-20 17:01:10 -0700350 break;
351 }
352
353 case Settings.CALL_METHOD_PUT_SYSTEM: {
354 String value = getSettingValue(args);
355 insertSystemSetting(name, value, requestingUserId);
356 break;
357 }
358
Svetoslav Ganove080da92016-12-21 17:10:35 -0800359 case Settings.CALL_METHOD_RESET_GLOBAL: {
360 final int mode = getResetModeEnforcingPermission(args);
361 String tag = getSettingTag(args);
362 resetGlobalSetting(requestingUserId, mode, tag);
363 break;
364 }
365
366 case Settings.CALL_METHOD_RESET_SECURE: {
367 final int mode = getResetModeEnforcingPermission(args);
368 String tag = getSettingTag(args);
369 resetSecureSetting(requestingUserId, mode, tag);
370 break;
371 }
372
Svetoslav7ec28e82015-05-20 17:01:10 -0700373 default: {
374 Slog.w(LOG_TAG, "call() with invalid method: " + method);
375 } break;
Christopher Tate06efb532012-08-24 15:29:27 -0700376 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700377
Christopher Tate06efb532012-08-24 15:29:27 -0700378 return null;
379 }
380
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800381 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800382 public String getType(Uri uri) {
383 Arguments args = new Arguments(uri, null, null, true);
384 if (TextUtils.isEmpty(args.name)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700385 return "vnd.android.cursor.dir/" + args.table;
386 } else {
Svetoslav7ec28e82015-05-20 17:01:10 -0700387 return "vnd.android.cursor.item/" + args.table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700388 }
389 }
390
391 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800392 public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
393 String order) {
394 if (DEBUG) {
395 Slog.v(LOG_TAG, "query() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700396 }
397
Svetoslav683914b2015-01-15 14:22:26 -0800398 Arguments args = new Arguments(uri, where, whereArgs, true);
399 String[] normalizedProjection = normalizeProjection(projection);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700400
Svetoslav683914b2015-01-15 14:22:26 -0800401 // If a legacy table that is gone, done.
402 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
403 return new MatrixCursor(normalizedProjection, 0);
404 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700405
Svetoslav7ec28e82015-05-20 17:01:10 -0700406 switch (args.table) {
407 case TABLE_GLOBAL: {
408 if (args.name != null) {
409 Setting setting = getGlobalSetting(args.name);
410 return packageSettingForQuery(setting, normalizedProjection);
411 } else {
412 return getAllGlobalSettings(projection);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700413 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700414 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700415
Svetoslav7ec28e82015-05-20 17:01:10 -0700416 case TABLE_SECURE: {
417 final int userId = UserHandle.getCallingUserId();
418 if (args.name != null) {
419 Setting setting = getSecureSetting(args.name, userId);
420 return packageSettingForQuery(setting, normalizedProjection);
421 } else {
422 return getAllSecureSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800423 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700424 }
Svetoslav683914b2015-01-15 14:22:26 -0800425
Svetoslav7ec28e82015-05-20 17:01:10 -0700426 case TABLE_SYSTEM: {
427 final int userId = UserHandle.getCallingUserId();
428 if (args.name != null) {
429 Setting setting = getSystemSetting(args.name, userId);
430 return packageSettingForQuery(setting, normalizedProjection);
431 } else {
432 return getAllSystemSettings(userId, projection);
Svetoslav683914b2015-01-15 14:22:26 -0800433 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700434 }
Svetoslav683914b2015-01-15 14:22:26 -0800435
Svetoslav7ec28e82015-05-20 17:01:10 -0700436 default: {
437 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700438 }
439 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700440 }
441
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700442 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800443 public Uri insert(Uri uri, ContentValues values) {
444 if (DEBUG) {
445 Slog.v(LOG_TAG, "insert() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700446 }
447
Svetoslav683914b2015-01-15 14:22:26 -0800448 String table = getValidTableOrThrow(uri);
Christopher Tate06efb532012-08-24 15:29:27 -0700449
Svetoslav683914b2015-01-15 14:22:26 -0800450 // If a legacy table that is gone, done.
451 if (REMOVED_LEGACY_TABLES.contains(table)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 return null;
453 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454
Svetoslav683914b2015-01-15 14:22:26 -0800455 String name = values.getAsString(Settings.Secure.NAME);
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700456 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800457 return null;
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700458 }
459
Svetoslav683914b2015-01-15 14:22:26 -0800460 String value = values.getAsString(Settings.Secure.VALUE);
461
Svetoslav7ec28e82015-05-20 17:01:10 -0700462 switch (table) {
463 case TABLE_GLOBAL: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800464 if (insertGlobalSetting(name, value, null, false,
465 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700466 return Uri.withAppendedPath(Settings.Global.CONTENT_URI, name);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700467 }
Svetoslav7ec28e82015-05-20 17:01:10 -0700468 } break;
469
470 case TABLE_SECURE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800471 if (insertSecureSetting(name, value, null, false,
472 UserHandle.getCallingUserId(), false)) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700473 return Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
474 }
475 } break;
476
477 case TABLE_SYSTEM: {
478 if (insertSystemSetting(name, value, UserHandle.getCallingUserId())) {
479 return Uri.withAppendedPath(Settings.System.CONTENT_URI, name);
480 }
481 } break;
482
483 default: {
484 throw new IllegalArgumentException("Bad Uri path:" + uri);
Christopher Tatec221d2b2012-10-03 18:33:52 -0700485 }
486 }
487
Svetoslav683914b2015-01-15 14:22:26 -0800488 return null;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489 }
490
491 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800492 public int bulkInsert(Uri uri, ContentValues[] allValues) {
493 if (DEBUG) {
494 Slog.v(LOG_TAG, "bulkInsert() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700496
Svetoslav683914b2015-01-15 14:22:26 -0800497 int insertionCount = 0;
498 final int valuesCount = allValues.length;
499 for (int i = 0; i < valuesCount; i++) {
500 ContentValues values = allValues[i];
501 if (insert(uri, values) != null) {
502 insertionCount++;
503 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700504 }
Svetoslav683914b2015-01-15 14:22:26 -0800505
506 return insertionCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700507 }
508
509 @Override
Svetoslav683914b2015-01-15 14:22:26 -0800510 public int delete(Uri uri, String where, String[] whereArgs) {
511 if (DEBUG) {
512 Slog.v(LOG_TAG, "delete() for user: " + UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700514
Svetoslav683914b2015-01-15 14:22:26 -0800515 Arguments args = new Arguments(uri, where, whereArgs, false);
516
517 // If a legacy table that is gone, done.
518 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
519 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700520 }
Svetoslav683914b2015-01-15 14:22:26 -0800521
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700522 if (!isKeyValid(args.name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800523 return 0;
Dianne Hackborn8d051722014-10-01 14:59:58 -0700524 }
Svetoslav683914b2015-01-15 14:22:26 -0800525
Svetoslav7ec28e82015-05-20 17:01:10 -0700526 switch (args.table) {
527 case TABLE_GLOBAL: {
528 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700529 return deleteGlobalSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700530 }
Svetoslav683914b2015-01-15 14:22:26 -0800531
Svetoslav7ec28e82015-05-20 17:01:10 -0700532 case TABLE_SECURE: {
533 final int userId = UserHandle.getCallingUserId();
Svet Ganov53a441c2016-04-19 19:38:00 -0700534 return deleteSecureSetting(args.name, userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700535 }
Svetoslav683914b2015-01-15 14:22:26 -0800536
Svetoslav7ec28e82015-05-20 17:01:10 -0700537 case TABLE_SYSTEM: {
538 final int userId = UserHandle.getCallingUserId();
539 return deleteSystemSetting(args.name, userId) ? 1 : 0;
540 }
541
542 default: {
543 throw new IllegalArgumentException("Bad Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800544 }
Dianne Hackborn8d051722014-10-01 14:59:58 -0700545 }
Svetoslav683914b2015-01-15 14:22:26 -0800546 }
547
548 @Override
549 public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
550 if (DEBUG) {
551 Slog.v(LOG_TAG, "update() for user: " + UserHandle.getCallingUserId());
Christopher Tate06efb532012-08-24 15:29:27 -0700552 }
Svetoslav683914b2015-01-15 14:22:26 -0800553
554 Arguments args = new Arguments(uri, where, whereArgs, false);
555
556 // If a legacy table that is gone, done.
557 if (REMOVED_LEGACY_TABLES.contains(args.table)) {
558 return 0;
559 }
560
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700561 String name = values.getAsString(Settings.Secure.NAME);
562 if (!isKeyValid(name)) {
Svetoslav683914b2015-01-15 14:22:26 -0800563 return 0;
564 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700565 String value = values.getAsString(Settings.Secure.VALUE);
Svetoslav683914b2015-01-15 14:22:26 -0800566
Svetoslav7ec28e82015-05-20 17:01:10 -0700567 switch (args.table) {
568 case TABLE_GLOBAL: {
569 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800570 return updateGlobalSetting(args.name, value, null, false,
571 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700572 }
Svetoslav683914b2015-01-15 14:22:26 -0800573
Svetoslav7ec28e82015-05-20 17:01:10 -0700574 case TABLE_SECURE: {
575 final int userId = UserHandle.getCallingUserId();
Svetoslav Ganove080da92016-12-21 17:10:35 -0800576 return updateSecureSetting(args.name, value, null, false,
577 userId, false) ? 1 : 0;
Svetoslav7ec28e82015-05-20 17:01:10 -0700578 }
Svetoslav683914b2015-01-15 14:22:26 -0800579
Svetoslav7ec28e82015-05-20 17:01:10 -0700580 case TABLE_SYSTEM: {
581 final int userId = UserHandle.getCallingUserId();
582 return updateSystemSetting(args.name, value, userId) ? 1 : 0;
583 }
Svetoslav683914b2015-01-15 14:22:26 -0800584
Svetoslav7ec28e82015-05-20 17:01:10 -0700585 default: {
586 throw new IllegalArgumentException("Invalid Uri path:" + uri);
Svetoslav683914b2015-01-15 14:22:26 -0800587 }
588 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700589 }
590
591 @Override
592 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
Robin Lee2ab02e22016-07-28 18:41:23 +0100593 final int userId = getUserIdFromUri(uri, UserHandle.getCallingUserId());
594 if (userId != UserHandle.getCallingUserId()) {
595 getContext().enforceCallingPermission(Manifest.permission.INTERACT_ACROSS_USERS,
596 "Access files from the settings of another user");
597 }
598 uri = ContentProvider.getUriWithoutUserId(uri);
599
Andre Lago3fa139c2016-08-04 13:53:44 +0100600 final String cacheRingtoneSetting;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700601 final String cacheName;
602 if (Settings.System.RINGTONE_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100603 cacheRingtoneSetting = Settings.System.RINGTONE;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700604 cacheName = Settings.System.RINGTONE_CACHE;
605 } else if (Settings.System.NOTIFICATION_SOUND_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100606 cacheRingtoneSetting = Settings.System.NOTIFICATION_SOUND;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700607 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
608 } else if (Settings.System.ALARM_ALERT_CACHE_URI.equals(uri)) {
Andre Lago3fa139c2016-08-04 13:53:44 +0100609 cacheRingtoneSetting = Settings.System.ALARM_ALERT;
Jeff Sharkey413573a2016-02-22 17:52:45 -0700610 cacheName = Settings.System.ALARM_ALERT_CACHE;
611 } else {
612 throw new FileNotFoundException("Direct file access no longer supported; "
613 + "ringtone playback is available through android.media.Ringtone");
614 }
615
Andre Lago3fa139c2016-08-04 13:53:44 +0100616 int actualCacheOwner;
617 // Redirect cache to parent if ringtone setting is owned by profile parent
618 synchronized (mLock) {
619 actualCacheOwner = resolveOwningUserIdForSystemSettingLocked(userId,
620 cacheRingtoneSetting);
621 }
622 final File cacheFile = new File(getRingtoneCacheDir(actualCacheOwner), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -0700623 return ParcelFileDescriptor.open(cacheFile, ParcelFileDescriptor.parseMode(mode));
624 }
625
626 private File getRingtoneCacheDir(int userId) {
627 final File cacheDir = new File(Environment.getDataSystemDeDirectory(userId), "ringtones");
628 cacheDir.mkdir();
629 SELinux.restorecon(cacheDir);
630 return cacheDir;
Marco Nelissen69f593c2009-07-28 09:55:04 -0700631 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800632
Eugene Suslad72c3972016-12-27 15:49:30 -0800633 /**
634 * Dump all settings as a proto buf.
635 *
636 * @param fd The file to dump to
637 */
638 void dumpProto(@NonNull FileDescriptor fd) {
639 ProtoOutputStream proto = new ProtoOutputStream(fd);
640
641 synchronized (mLock) {
642 SettingsProtoDumpUtil.dumpProtoLocked(mSettingsRegistry, proto);
Eugene Suslad72c3972016-12-27 15:49:30 -0800643 }
644
645 proto.flush();
646 }
647
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700648 public void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800649 synchronized (mLock) {
650 final long identity = Binder.clearCallingIdentity();
651 try {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700652 SparseBooleanArray users = mSettingsRegistry.getKnownUsersLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800653 final int userCount = users.size();
654 for (int i = 0; i < userCount; i++) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700655 dumpForUserLocked(users.keyAt(i), pw);
Svetoslavb505ccc2015-02-17 12:41:04 -0800656 }
657 } finally {
658 Binder.restoreCallingIdentity(identity);
659 }
660 }
661 }
662
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700663 private void dumpForUserLocked(int userId, PrintWriter pw) {
Xiaohui Chen43765b72015-08-31 10:57:33 -0700664 if (userId == UserHandle.USER_SYSTEM) {
Svetoslavb505ccc2015-02-17 12:41:04 -0800665 pw.println("GLOBAL SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700666 SettingsState globalSettings = mSettingsRegistry.getSettingsLocked(
667 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700668 if (globalSettings != null) {
669 dumpSettingsLocked(globalSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800670 pw.println();
671 globalSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700672 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800673 }
674
675 pw.println("SECURE SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700676 SettingsState secureSettings = mSettingsRegistry.getSettingsLocked(
677 SETTINGS_TYPE_SECURE, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700678 if (secureSettings != null) {
679 dumpSettingsLocked(secureSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800680 pw.println();
681 secureSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700682 }
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700683
Svetoslavb505ccc2015-02-17 12:41:04 -0800684 pw.println("SYSTEM SETTINGS (user " + userId + ")");
Svetoslav Ganova340bfd2016-08-02 18:24:49 -0700685 SettingsState systemSettings = mSettingsRegistry.getSettingsLocked(
686 SETTINGS_TYPE_SYSTEM, userId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700687 if (systemSettings != null) {
688 dumpSettingsLocked(systemSettings, pw);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800689 pw.println();
690 systemSettings.dumpHistoricalOperations(pw);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700691 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800692 }
693
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700694 private void dumpSettingsLocked(SettingsState settingsState, PrintWriter pw) {
695 List<String> names = settingsState.getSettingNamesLocked();
Svetoslavb505ccc2015-02-17 12:41:04 -0800696
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700697 final int nameCount = names.size();
Svetoslavb505ccc2015-02-17 12:41:04 -0800698
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700699 for (int i = 0; i < nameCount; i++) {
700 String name = names.get(i);
701 Setting setting = settingsState.getSettingLocked(name);
702 pw.print("_id:"); pw.print(toDumpString(setting.getId()));
703 pw.print(" name:"); pw.print(toDumpString(name));
704 if (setting.getPackageName() != null) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800705 pw.print(" pkg:"); pw.print(setting.getPackageName());
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700706 }
707 pw.print(" value:"); pw.print(toDumpString(setting.getValue()));
Svetoslav Ganove080da92016-12-21 17:10:35 -0800708 if (setting.getDefaultValue() != null) {
709 pw.print(" default:"); pw.print(setting.getDefaultValue());
Eugene Suslad72c3972016-12-27 15:49:30 -0800710 pw.print(" defaultSystemSet:"); pw.print(setting.isDefaultFromSystem());
Svetoslav Ganove080da92016-12-21 17:10:35 -0800711 }
712 if (setting.getTag() != null) {
713 pw.print(" tag:"); pw.print(setting.getTag());
714 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800715 pw.println();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -0700716 }
Svetoslavb505ccc2015-02-17 12:41:04 -0800717 }
718
Svetoslav7e0683b2015-08-03 16:02:52 -0700719 private static String toDumpString(String s) {
Makoto Onuki3a2c35782015-06-18 11:21:58 -0700720 if (s != null) {
721 return s;
722 }
723 return "{null}";
724 }
725
Svetoslav683914b2015-01-15 14:22:26 -0800726 private void registerBroadcastReceivers() {
727 IntentFilter userFilter = new IntentFilter();
728 userFilter.addAction(Intent.ACTION_USER_REMOVED);
729 userFilter.addAction(Intent.ACTION_USER_STOPPED);
730
731 getContext().registerReceiver(new BroadcastReceiver() {
732 @Override
733 public void onReceive(Context context, Intent intent) {
734 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700735 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800736
737 switch (intent.getAction()) {
738 case Intent.ACTION_USER_REMOVED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700739 synchronized (mLock) {
740 mSettingsRegistry.removeUserStateLocked(userId, true);
741 }
Svetoslav683914b2015-01-15 14:22:26 -0800742 } break;
743
744 case Intent.ACTION_USER_STOPPED: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700745 synchronized (mLock) {
746 mSettingsRegistry.removeUserStateLocked(userId, false);
747 }
Svetoslav683914b2015-01-15 14:22:26 -0800748 } break;
749 }
750 }
751 }, userFilter);
752
753 PackageMonitor monitor = new PackageMonitor() {
754 @Override
755 public void onPackageRemoved(String packageName, int uid) {
756 synchronized (mLock) {
757 mSettingsRegistry.onPackageRemovedLocked(packageName,
758 UserHandle.getUserId(uid));
759 }
760 }
Mark Rathjend891f012017-01-19 04:10:37 +0000761
762 @Override
763 public void onUidRemoved(int uid) {
764 synchronized (mLock) {
765 mSettingsRegistry.onUidRemovedLocked(uid);
766 }
767 }
Svetoslav683914b2015-01-15 14:22:26 -0800768 };
769
770 // package changes
771 monitor.register(getContext(), BackgroundThread.getHandler().getLooper(),
772 UserHandle.ALL, true);
773 }
774
Svet Ganov53a441c2016-04-19 19:38:00 -0700775 private void startWatchingUserRestrictionChanges() {
776 // TODO: The current design of settings looking different based on user restrictions
777 // should be reworked to keep them separate and system code should check the setting
778 // first followed by checking the user restriction before performing an operation.
779 UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class);
780 userManager.addUserRestrictionsListener((int userId, Bundle newRestrictions,
781 Bundle prevRestrictions) -> {
782 // We are changing the settings affected by restrictions to their current
783 // value with a forced update to ensure that all cross profile dependencies
784 // are taken into account. Also make sure the settings update to.. the same
785 // value passes the security checks, so clear binder calling id.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800786 if (newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)
787 != prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_LOCATION)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700788 final long identity = Binder.clearCallingIdentity();
789 try {
790 synchronized (mLock) {
791 Setting setting = getSecureSetting(
792 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
793 updateSecureSetting(Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800794 setting != null ? setting.getValue() : null, null,
795 true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700796 }
797 } finally {
798 Binder.restoreCallingIdentity(identity);
799 }
800 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800801 if (newRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
802 != prevRestrictions.getBoolean(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700803 final long identity = Binder.clearCallingIdentity();
804 try {
805 synchronized (mLock) {
806 Setting setting = getGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800807 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700808 updateGlobalSetting(Settings.Global.INSTALL_NON_MARKET_APPS,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800809 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700810 }
811 } finally {
812 Binder.restoreCallingIdentity(identity);
813 }
814 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800815 if (newRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)
816 != prevRestrictions.getBoolean(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700817 final long identity = Binder.clearCallingIdentity();
818 try {
819 synchronized (mLock) {
820 Setting setting = getGlobalSetting(Settings.Global.ADB_ENABLED);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800821 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700822 updateGlobalSetting(Settings.Global.ADB_ENABLED,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800823 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700824 }
825 } finally {
826 Binder.restoreCallingIdentity(identity);
827 }
828 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800829 if (newRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)
830 != prevRestrictions.getBoolean(UserManager.ENSURE_VERIFY_APPS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700831 final long identity = Binder.clearCallingIdentity();
832 try {
833 synchronized (mLock) {
834 Setting enable = getGlobalSetting(
835 Settings.Global.PACKAGE_VERIFIER_ENABLE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800836 String enableValue = enable != null ? enable.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700837 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_ENABLE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800838 enableValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700839 Setting include = getGlobalSetting(
840 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800841 String includeValue = include != null ? include.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700842 updateGlobalSetting(Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800843 includeValue, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700844 }
845 } finally {
846 Binder.restoreCallingIdentity(identity);
847 }
848 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800849 if (newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)
850 != prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
Svet Ganov53a441c2016-04-19 19:38:00 -0700851 final long identity = Binder.clearCallingIdentity();
852 try {
853 synchronized (mLock) {
854 Setting setting = getGlobalSetting(
855 Settings.Global.PREFERRED_NETWORK_MODE);
Svetoslav Ganove080da92016-12-21 17:10:35 -0800856 String value = setting != null ? setting.getValue() : null;
Svet Ganov53a441c2016-04-19 19:38:00 -0700857 updateGlobalSetting(Settings.Global.PREFERRED_NETWORK_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -0800858 value, null, true, userId, true);
Svet Ganov53a441c2016-04-19 19:38:00 -0700859 }
860 } finally {
861 Binder.restoreCallingIdentity(identity);
862 }
863 }
864 });
865 }
866
Svetoslav7ec28e82015-05-20 17:01:10 -0700867 private Cursor getAllGlobalSettings(String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -0800868 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700869 Slog.v(LOG_TAG, "getAllGlobalSettings()");
Svetoslav683914b2015-01-15 14:22:26 -0800870 }
871
Svetoslav7ec28e82015-05-20 17:01:10 -0700872 synchronized (mLock) {
873 // Get the settings.
874 SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -0700875 SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800876
Chad Brubaker97bccee2017-01-05 15:51:41 -0800877 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_GLOBAL,
878 UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -0800879
Svetoslav7ec28e82015-05-20 17:01:10 -0700880 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -0800881
Svetoslav7ec28e82015-05-20 17:01:10 -0700882 String[] normalizedProjection = normalizeProjection(projection);
883 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -0800884
Svetoslav7ec28e82015-05-20 17:01:10 -0700885 // Anyone can get the global settings, so no security checks.
886 for (int i = 0; i < nameCount; i++) {
887 String name = names.get(i);
888 Setting setting = settingsState.getSettingLocked(name);
889 appendSettingToCursor(result, setting);
890 }
891
892 return result;
Svetoslav683914b2015-01-15 14:22:26 -0800893 }
Svetoslav683914b2015-01-15 14:22:26 -0800894 }
895
Svetoslav7ec28e82015-05-20 17:01:10 -0700896 private Setting getGlobalSetting(String name) {
Svetoslav683914b2015-01-15 14:22:26 -0800897 if (DEBUG) {
898 Slog.v(LOG_TAG, "getGlobalSetting(" + name + ")");
899 }
900
Chad Brubakera6830e72017-04-28 17:34:36 -0700901 // Ensure the caller can access the setting.
902 enforceSettingReadable(name, SETTINGS_TYPE_GLOBAL, UserHandle.getCallingUserId());
903
Svetoslav683914b2015-01-15 14:22:26 -0800904 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -0700905 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -0700906 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_GLOBAL,
Xiaohui Chen43765b72015-08-31 10:57:33 -0700907 UserHandle.USER_SYSTEM, name);
Svetoslav683914b2015-01-15 14:22:26 -0800908 }
Svetoslav683914b2015-01-15 14:22:26 -0800909 }
910
Svetoslav Ganove080da92016-12-21 17:10:35 -0800911 private boolean updateGlobalSetting(String name, String value, String tag,
912 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800913 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800914 Slog.v(LOG_TAG, "updateGlobalSetting(" + name + ", " + value + ", "
915 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
916 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800917 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800918 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
919 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800920 }
921
Svetoslav Ganove080da92016-12-21 17:10:35 -0800922 private boolean insertGlobalSetting(String name, String value, String tag,
923 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav7ec28e82015-05-20 17:01:10 -0700924 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800925 Slog.v(LOG_TAG, "insertGlobalSetting(" + name + ", " + value + ", "
926 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
927 + ", " + forceNotify + ")");
Svetoslav7ec28e82015-05-20 17:01:10 -0700928 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800929 return mutateGlobalSetting(name, value, tag, makeDefault, requestingUserId,
930 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav7ec28e82015-05-20 17:01:10 -0700931 }
932
Svet Ganov53a441c2016-04-19 19:38:00 -0700933 private boolean deleteGlobalSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -0800934 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800935 Slog.v(LOG_TAG, "deleteGlobalSetting(" + name + ", " + requestingUserId
936 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -0800937 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800938 return mutateGlobalSetting(name, null, null, false, requestingUserId,
939 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -0800940 }
941
Svetoslav Ganove080da92016-12-21 17:10:35 -0800942 private void resetGlobalSetting(int requestingUserId, int mode, String tag) {
943 if (DEBUG) {
944 Slog.v(LOG_TAG, "resetGlobalSetting(" + requestingUserId + ", "
945 + mode + ", " + tag + ")");
946 }
947 mutateGlobalSetting(null, null, tag, false, requestingUserId,
948 MUTATION_OPERATION_RESET, false, mode);
949 }
950
951 private boolean mutateGlobalSetting(String name, String value, String tag,
952 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
953 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -0800954 // Make sure the caller can change the settings - treated as secure.
955 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
956
Svetoslav683914b2015-01-15 14:22:26 -0800957 // Resolve the userId on whose behalf the call is made.
958 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
959
Makoto Onuki28da2e32015-11-20 11:30:44 -0800960 // If this is a setting that is currently restricted for this user, do not allow
961 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -0800962 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +0100963 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -0800964 return false;
965 }
966
967 // Perform the mutation.
Svetoslav7ec28e82015-05-20 17:01:10 -0700968 synchronized (mLock) {
969 switch (operation) {
970 case MUTATION_OPERATION_INSERT: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800971 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL,
972 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800973 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700974 }
Svetoslav683914b2015-01-15 14:22:26 -0800975
Svetoslav7ec28e82015-05-20 17:01:10 -0700976 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -0700977 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_GLOBAL,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800978 UserHandle.USER_SYSTEM, name, forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700979 }
Svetoslav683914b2015-01-15 14:22:26 -0800980
Svetoslav7ec28e82015-05-20 17:01:10 -0700981 case MUTATION_OPERATION_UPDATE: {
Svetoslav Ganove080da92016-12-21 17:10:35 -0800982 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_GLOBAL,
983 UserHandle.USER_SYSTEM, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -0800984 getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -0700985 }
Svetoslav Ganove080da92016-12-21 17:10:35 -0800986
987 case MUTATION_OPERATION_RESET: {
988 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_GLOBAL,
989 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
990 } return true;
Svetoslav683914b2015-01-15 14:22:26 -0800991 }
992 }
993
994 return false;
995 }
996
Christopher Tateb218e762017-04-05 16:34:07 -0700997 private PackageInfo getCallingPackageInfo(int userId) {
998 try {
999 return mPackageManager.getPackageInfo(getCallingPackage(),
1000 PackageManager.GET_SIGNATURES, userId);
1001 } catch (RemoteException e) {
1002 throw new IllegalStateException("Package " + getCallingPackage() + " doesn't exist");
1003 }
1004 }
1005
Svetoslav7ec28e82015-05-20 17:01:10 -07001006 private Cursor getAllSecureSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001007 if (DEBUG) {
1008 Slog.v(LOG_TAG, "getAllSecureSettings(" + userId + ")");
1009 }
1010
1011 // Resolve the userId on whose behalf the call is made.
1012 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1013
Christopher Tateb218e762017-04-05 16:34:07 -07001014 // The relevant "calling package" userId will be the owning userId for some
1015 // profiles, and we can't do the lookup inside our [lock held] loop, so work out
1016 // up front who the effective "new SSAID" user ID for that settings name will be.
1017 final int ssaidUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1018 Settings.Secure.ANDROID_ID);
1019 final PackageInfo ssaidCallingPkg = getCallingPackageInfo(ssaidUserId);
1020
Svetoslav7ec28e82015-05-20 17:01:10 -07001021 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001022 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SECURE, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001023
Svetoslav7ec28e82015-05-20 17:01:10 -07001024 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001025
Svetoslav7ec28e82015-05-20 17:01:10 -07001026 String[] normalizedProjection = normalizeProjection(projection);
1027 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001028
Svetoslav7ec28e82015-05-20 17:01:10 -07001029 for (int i = 0; i < nameCount; i++) {
1030 String name = names.get(i);
1031 // Determine the owning user as some profile settings are cloned from the parent.
1032 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId,
1033 name);
Svetoslav683914b2015-01-15 14:22:26 -08001034
Alex Klyubin1991f572017-03-03 14:08:36 -08001035 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1036 // This caller is not permitted to access this setting. Pretend the setting
1037 // doesn't exist.
Svetoslav Ganov83a1f7f2016-04-27 13:50:49 -07001038 continue;
Svetoslav7ec28e82015-05-20 17:01:10 -07001039 }
Svetoslav683914b2015-01-15 14:22:26 -08001040
Mark Rathjen7599f132017-01-23 14:15:54 -08001041 // As of Android O, the SSAID is read from an app-specific entry in table
Mark Rathjend891f012017-01-19 04:10:37 +00001042 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1043 final Setting setting;
1044 if (isNewSsaidSetting(name)) {
Christopher Tateb218e762017-04-05 16:34:07 -07001045 setting = getSsaidSettingLocked(ssaidCallingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001046 } else {
1047 setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE, owningUserId,
1048 name);
1049 }
Svetoslav7ec28e82015-05-20 17:01:10 -07001050 appendSettingToCursor(result, setting);
Svetoslav683914b2015-01-15 14:22:26 -08001051 }
1052
Svetoslav7ec28e82015-05-20 17:01:10 -07001053 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001054 }
Svetoslav683914b2015-01-15 14:22:26 -08001055 }
1056
Svetoslav7ec28e82015-05-20 17:01:10 -07001057 private Setting getSecureSetting(String name, int requestingUserId) {
Makoto Onuki0000d322017-11-28 16:31:47 -08001058 return getSecureSetting(name, requestingUserId, /*enableOverride=*/ false);
1059 }
1060
1061 private Setting getSecureSetting(String name, int requestingUserId, boolean enableOverride) {
Svetoslav683914b2015-01-15 14:22:26 -08001062 if (DEBUG) {
1063 Slog.v(LOG_TAG, "getSecureSetting(" + name + ", " + requestingUserId + ")");
1064 }
1065
1066 // Resolve the userId on whose behalf the call is made.
1067 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1068
Chad Brubakera6830e72017-04-28 17:34:36 -07001069 // Ensure the caller can access the setting.
1070 enforceSettingReadable(name, SETTINGS_TYPE_SECURE, UserHandle.getCallingUserId());
1071
Svetoslav683914b2015-01-15 14:22:26 -08001072 // Determine the owning user as some profile settings are cloned from the parent.
1073 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1074
Alex Klyubin1991f572017-03-03 14:08:36 -08001075 if (!isSecureSettingAccessible(name, callingUserId, owningUserId)) {
1076 // This caller is not permitted to access this setting. Pretend the setting doesn't
1077 // exist.
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001078 SettingsState settings = mSettingsRegistry.getSettingsLocked(SETTINGS_TYPE_SECURE,
1079 owningUserId);
1080 return settings != null ? settings.getNullSetting() : null;
Svetoslav683914b2015-01-15 14:22:26 -08001081 }
1082
Christopher Tateb218e762017-04-05 16:34:07 -07001083 // As of Android O, the SSAID is read from an app-specific entry in table
1084 // SETTINGS_FILE_SSAID, unless accessed by a system process.
1085 if (isNewSsaidSetting(name)) {
1086 PackageInfo callingPkg = getCallingPackageInfo(owningUserId);
1087 synchronized (mLock) {
1088 return getSsaidSettingLocked(callingPkg, owningUserId);
Mark Rathjend891f012017-01-19 04:10:37 +00001089 }
Christopher Tateb218e762017-04-05 16:34:07 -07001090 }
Makoto Onuki0000d322017-11-28 16:31:47 -08001091 if (enableOverride) {
1092 if (Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
1093 final Setting overridden = getLocationProvidersAllowedSetting(owningUserId);
1094 if (overridden != null) {
1095 return overridden;
1096 }
1097 }
1098 }
Mark Rathjend891f012017-01-19 04:10:37 +00001099
Christopher Tateb218e762017-04-05 16:34:07 -07001100 // Not the SSAID; do a straight lookup
1101 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001102 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav7ec28e82015-05-20 17:01:10 -07001103 owningUserId, name);
1104 }
Svetoslav683914b2015-01-15 14:22:26 -08001105 }
1106
Mark Rathjend891f012017-01-19 04:10:37 +00001107 private boolean isNewSsaidSetting(String name) {
1108 return Settings.Secure.ANDROID_ID.equals(name)
1109 && UserHandle.getAppId(Binder.getCallingUid()) >= Process.FIRST_APPLICATION_UID;
1110 }
1111
Christopher Tateb218e762017-04-05 16:34:07 -07001112 private Setting getSsaidSettingLocked(PackageInfo callingPkg, int owningUserId) {
Mark Rathjend891f012017-01-19 04:10:37 +00001113 // Get uid of caller (key) used to store ssaid value
1114 String name = Integer.toString(
1115 UserHandle.getUid(owningUserId, UserHandle.getAppId(Binder.getCallingUid())));
1116
1117 if (DEBUG) {
1118 Slog.v(LOG_TAG, "getSsaidSettingLocked(" + name + "," + owningUserId + ")");
1119 }
1120
1121 // Retrieve the ssaid from the table if present.
1122 final Setting ssaid = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID, owningUserId,
1123 name);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001124 // If the app is an Instant App use its stored SSAID instead of our own.
1125 final String instantSsaid;
1126 final long token = Binder.clearCallingIdentity();
1127 try {
1128 instantSsaid = mPackageManager.getInstantAppAndroidId(callingPkg.packageName,
1129 owningUserId);
1130 } catch (RemoteException e) {
1131 Slog.e(LOG_TAG, "Failed to get Instant App Android ID", e);
1132 return null;
1133 } finally {
1134 Binder.restoreCallingIdentity(token);
1135 }
Svet Ganov96c99462017-05-05 14:27:13 -07001136
1137 final SettingsState ssaidSettings = mSettingsRegistry.getSettingsLocked(
1138 SETTINGS_TYPE_SSAID, owningUserId);
1139
Chad Brubaker0d277a72017-04-12 16:56:53 -07001140 if (instantSsaid != null) {
1141 // Use the stored value if it is still valid.
1142 if (ssaid != null && instantSsaid.equals(ssaid.getValue())) {
Svet Ganov96c99462017-05-05 14:27:13 -07001143 return mascaradeSsaidSetting(ssaidSettings, ssaid);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001144 }
1145 // The value has changed, update the stored value.
Chad Brubaker0d277a72017-04-12 16:56:53 -07001146 final boolean success = ssaidSettings.insertSettingLocked(name, instantSsaid, null,
1147 true, callingPkg.packageName);
1148 if (!success) {
1149 throw new IllegalStateException("Failed to update instant app android id");
1150 }
Svet Ganov96c99462017-05-05 14:27:13 -07001151 Setting setting = mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SSAID,
1152 owningUserId, name);
1153 return mascaradeSsaidSetting(ssaidSettings, setting);
Chad Brubaker0d277a72017-04-12 16:56:53 -07001154 }
Mark Rathjend891f012017-01-19 04:10:37 +00001155
1156 // Lazy initialize ssaid if not yet present in ssaid table.
Mark Rathjenea617592017-01-18 23:03:41 -08001157 if (ssaid == null || ssaid.isNull() || ssaid.getValue() == null) {
Svet Ganov96c99462017-05-05 14:27:13 -07001158 Setting setting = mSettingsRegistry.generateSsaidLocked(callingPkg, owningUserId);
1159 return mascaradeSsaidSetting(ssaidSettings, setting);
Mark Rathjend891f012017-01-19 04:10:37 +00001160 }
1161
Svet Ganov96c99462017-05-05 14:27:13 -07001162 return mascaradeSsaidSetting(ssaidSettings, ssaid);
1163 }
1164
1165 private Setting mascaradeSsaidSetting(SettingsState settingsState, Setting ssaidSetting) {
1166 // SSAID settings are located in a dedicated table for internal bookkeeping
1167 // but for the world they reside in the secure table, so adjust the key here.
1168 // We have a special name when looking it up but want the world to see it as
1169 // "android_id".
1170 if (ssaidSetting != null) {
1171 return settingsState.new Setting(ssaidSetting) {
1172 @Override
1173 public int getKey() {
1174 final int userId = getUserIdFromKey(super.getKey());
1175 return makeKey(SETTINGS_TYPE_SECURE, userId);
1176 }
1177
1178 @Override
1179 public String getName() {
1180 return Settings.Secure.ANDROID_ID;
1181 }
1182 };
1183 }
1184 return null;
Mark Rathjend891f012017-01-19 04:10:37 +00001185 }
1186
Makoto Onuki0000d322017-11-28 16:31:47 -08001187 private Setting getLocationProvidersAllowedSetting(int owningUserId) {
1188 synchronized (mLock) {
1189 final Setting setting = getGlobalSetting(
1190 Global.LOCATION_GLOBAL_KILL_SWITCH);
1191 if (!"1".equals(setting.getValue())) {
1192 return null;
1193 }
1194 // Global kill-switch is enabled. Return an empty value.
1195 final SettingsState settingsState = mSettingsRegistry.getSettingsLocked(
1196 SETTINGS_TYPE_SECURE, owningUserId);
1197 return settingsState.new Setting(
1198 Secure.LOCATION_PROVIDERS_ALLOWED,
1199 "", // value
1200 "", // tag
1201 "", // default value
1202 "", // package name
1203 false, // from system
1204 "0" // id
1205 ) {
1206 @Override
1207 public boolean update(String value, boolean setDefault, String packageName,
1208 String tag, boolean forceNonSystemPackage) {
1209 Slog.wtf(LOG_TAG, "update shoudln't be called on this instance.");
1210 return false;
1211 }
1212 };
1213 }
1214 }
1215
Svetoslav Ganove080da92016-12-21 17:10:35 -08001216 private boolean insertSecureSetting(String name, String value, String tag,
1217 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001218 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001219 Slog.v(LOG_TAG, "insertSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001220 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1221 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001222 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001223 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1224 MUTATION_OPERATION_INSERT, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001225 }
1226
Svet Ganov53a441c2016-04-19 19:38:00 -07001227 private boolean deleteSecureSetting(String name, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001228 if (DEBUG) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001229 Slog.v(LOG_TAG, "deleteSecureSetting(" + name + ", " + requestingUserId
1230 + ", " + forceNotify + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001231 }
1232
Svetoslav Ganove080da92016-12-21 17:10:35 -08001233 return mutateSecureSetting(name, null, null, false, requestingUserId,
1234 MUTATION_OPERATION_DELETE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001235 }
1236
Svetoslav Ganove080da92016-12-21 17:10:35 -08001237 private boolean updateSecureSetting(String name, String value, String tag,
1238 boolean makeDefault, int requestingUserId, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001239 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001240 Slog.v(LOG_TAG, "updateSecureSetting(" + name + ", " + value + ", "
Svetoslav Ganove080da92016-12-21 17:10:35 -08001241 + ", " + tag + ", " + makeDefault + ", " + requestingUserId
1242 + ", " + forceNotify +")");
Svetoslav683914b2015-01-15 14:22:26 -08001243 }
1244
Svetoslav Ganove080da92016-12-21 17:10:35 -08001245 return mutateSecureSetting(name, value, tag, makeDefault, requestingUserId,
1246 MUTATION_OPERATION_UPDATE, forceNotify, 0);
Svetoslav683914b2015-01-15 14:22:26 -08001247 }
1248
Svetoslav Ganove080da92016-12-21 17:10:35 -08001249 private void resetSecureSetting(int requestingUserId, int mode, String tag) {
1250 if (DEBUG) {
1251 Slog.v(LOG_TAG, "resetSecureSetting(" + requestingUserId + ", "
1252 + mode + ", " + tag + ")");
1253 }
1254
1255 mutateSecureSetting(null, null, tag, false, requestingUserId,
1256 MUTATION_OPERATION_RESET, false, mode);
1257 }
1258
1259 private boolean mutateSecureSetting(String name, String value, String tag,
1260 boolean makeDefault, int requestingUserId, int operation, boolean forceNotify,
1261 int mode) {
Svetoslav683914b2015-01-15 14:22:26 -08001262 // Make sure the caller can change the settings.
1263 enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS);
1264
Svetoslav683914b2015-01-15 14:22:26 -08001265 // Resolve the userId on whose behalf the call is made.
1266 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1267
Makoto Onuki28da2e32015-11-20 11:30:44 -08001268 // If this is a setting that is currently restricted for this user, do not allow
1269 // unrestricting changes.
Svetoslav Ganove080da92016-12-21 17:10:35 -08001270 if (name != null && isGlobalOrSecureSettingRestrictedForUser(name, callingUserId, value,
Victor Chang9c7b7062016-07-12 23:47:29 +01001271 Binder.getCallingUid())) {
Svetoslav683914b2015-01-15 14:22:26 -08001272 return false;
1273 }
1274
1275 // Determine the owning user as some profile settings are cloned from the parent.
1276 final int owningUserId = resolveOwningUserIdForSecureSettingLocked(callingUserId, name);
1277
1278 // Only the owning user can change the setting.
1279 if (owningUserId != callingUserId) {
1280 return false;
1281 }
1282
1283 // Special cases for location providers (sigh).
1284 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
Svetoslav Ganove080da92016-12-21 17:10:35 -08001285 return updateLocationProvidersAllowedLocked(value, tag, owningUserId, makeDefault,
1286 forceNotify);
Svetoslav683914b2015-01-15 14:22:26 -08001287 }
1288
1289 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001290 synchronized (mLock) {
1291 switch (operation) {
1292 case MUTATION_OPERATION_INSERT: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001293 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001294 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001295 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001296 }
Svetoslav683914b2015-01-15 14:22:26 -08001297
Svetoslav7ec28e82015-05-20 17:01:10 -07001298 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001299 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001300 owningUserId, name, forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001301 }
Svetoslav683914b2015-01-15 14:22:26 -08001302
Svetoslav7ec28e82015-05-20 17:01:10 -07001303 case MUTATION_OPERATION_UPDATE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001304 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001305 owningUserId, name, value, tag, makeDefault,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001306 getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav7ec28e82015-05-20 17:01:10 -07001307 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08001308
1309 case MUTATION_OPERATION_RESET: {
1310 mSettingsRegistry.resetSettingsLocked(SETTINGS_TYPE_SECURE,
1311 UserHandle.USER_SYSTEM, getCallingPackage(), mode, tag);
1312 } return true;
Svetoslav683914b2015-01-15 14:22:26 -08001313 }
1314 }
1315
1316 return false;
1317 }
1318
Svetoslav7ec28e82015-05-20 17:01:10 -07001319 private Cursor getAllSystemSettings(int userId, String[] projection) {
Svetoslav683914b2015-01-15 14:22:26 -08001320 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001321 Slog.v(LOG_TAG, "getAllSecureSystem(" + userId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001322 }
1323
1324 // Resolve the userId on whose behalf the call is made.
1325 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(userId);
1326
Svetoslav7ec28e82015-05-20 17:01:10 -07001327 synchronized (mLock) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001328 List<String> names = getSettingsNamesLocked(SETTINGS_TYPE_SYSTEM, callingUserId);
Svetoslav683914b2015-01-15 14:22:26 -08001329
Svetoslav7ec28e82015-05-20 17:01:10 -07001330 final int nameCount = names.size();
Svetoslav683914b2015-01-15 14:22:26 -08001331
Svetoslav7ec28e82015-05-20 17:01:10 -07001332 String[] normalizedProjection = normalizeProjection(projection);
1333 MatrixCursor result = new MatrixCursor(normalizedProjection, nameCount);
Svetoslav683914b2015-01-15 14:22:26 -08001334
Svetoslav7ec28e82015-05-20 17:01:10 -07001335 for (int i = 0; i < nameCount; i++) {
1336 String name = names.get(i);
Svetoslav683914b2015-01-15 14:22:26 -08001337
Svetoslav7ec28e82015-05-20 17:01:10 -07001338 // Determine the owning user as some profile settings are cloned from the parent.
1339 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId,
1340 name);
Svetoslav683914b2015-01-15 14:22:26 -08001341
Svetoslav7ec28e82015-05-20 17:01:10 -07001342 Setting setting = mSettingsRegistry.getSettingLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07001343 SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001344 appendSettingToCursor(result, setting);
1345 }
1346
1347 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001348 }
Svetoslav683914b2015-01-15 14:22:26 -08001349 }
1350
Svetoslav7ec28e82015-05-20 17:01:10 -07001351 private Setting getSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001352 if (DEBUG) {
1353 Slog.v(LOG_TAG, "getSystemSetting(" + name + ", " + requestingUserId + ")");
1354 }
1355
1356 // Resolve the userId on whose behalf the call is made.
1357 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(requestingUserId);
1358
Chad Brubakera6830e72017-04-28 17:34:36 -07001359 // Ensure the caller can access the setting.
1360 enforceSettingReadable(name, SETTINGS_TYPE_SYSTEM, UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001361
Svetoslav683914b2015-01-15 14:22:26 -08001362 // Determine the owning user as some profile settings are cloned from the parent.
1363 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1364
1365 // Get the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001366 synchronized (mLock) {
Chad Brubakera6830e72017-04-28 17:34:36 -07001367 return mSettingsRegistry.getSettingLocked(SETTINGS_TYPE_SYSTEM, owningUserId, name);
Svetoslav7ec28e82015-05-20 17:01:10 -07001368 }
Svetoslav683914b2015-01-15 14:22:26 -08001369 }
1370
Svetoslav7ec28e82015-05-20 17:01:10 -07001371 private boolean insertSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001372 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001373 Slog.v(LOG_TAG, "insertSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001374 + requestingUserId + ")");
1375 }
1376
Svetoslav7ec28e82015-05-20 17:01:10 -07001377 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_INSERT);
Svetoslav683914b2015-01-15 14:22:26 -08001378 }
1379
Svetoslav7ec28e82015-05-20 17:01:10 -07001380 private boolean deleteSystemSetting(String name, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001381 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001382 Slog.v(LOG_TAG, "deleteSystemSetting(" + name + ", " + requestingUserId + ")");
Svetoslav683914b2015-01-15 14:22:26 -08001383 }
1384
Svetoslav7ec28e82015-05-20 17:01:10 -07001385 return mutateSystemSetting(name, null, requestingUserId, MUTATION_OPERATION_DELETE);
Svetoslav683914b2015-01-15 14:22:26 -08001386 }
1387
Svetoslav7ec28e82015-05-20 17:01:10 -07001388 private boolean updateSystemSetting(String name, String value, int requestingUserId) {
Svetoslav683914b2015-01-15 14:22:26 -08001389 if (DEBUG) {
Svetoslav7ec28e82015-05-20 17:01:10 -07001390 Slog.v(LOG_TAG, "updateSystemSetting(" + name + ", " + value + ", "
Svetoslav683914b2015-01-15 14:22:26 -08001391 + requestingUserId + ")");
1392 }
1393
Svetoslav7ec28e82015-05-20 17:01:10 -07001394 return mutateSystemSetting(name, value, requestingUserId, MUTATION_OPERATION_UPDATE);
Svetoslav683914b2015-01-15 14:22:26 -08001395 }
1396
Svetoslav7ec28e82015-05-20 17:01:10 -07001397 private boolean mutateSystemSetting(String name, String value, int runAsUserId,
Svetoslav683914b2015-01-15 14:22:26 -08001398 int operation) {
Billy Lau6ad2d662015-07-18 00:26:58 +01001399 if (!hasWriteSecureSettingsPermission()) {
1400 // If the caller doesn't hold WRITE_SECURE_SETTINGS, we verify whether this
1401 // operation is allowed for the calling package through appops.
1402 if (!Settings.checkAndNoteWriteSettingsOperation(getContext(),
1403 Binder.getCallingUid(), getCallingPackage(), true)) {
1404 return false;
1405 }
Svetoslav683914b2015-01-15 14:22:26 -08001406 }
1407
Svetoslav683914b2015-01-15 14:22:26 -08001408 // Resolve the userId on whose behalf the call is made.
1409 final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId);
1410
Svetoslavd8d25e02015-11-20 13:09:26 -08001411 // Enforce what the calling package can mutate the system settings.
1412 enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId);
1413
Svetoslav683914b2015-01-15 14:22:26 -08001414 // Determine the owning user as some profile settings are cloned from the parent.
1415 final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name);
1416
1417 // Only the owning user id can change the setting.
1418 if (owningUserId != callingUserId) {
1419 return false;
1420 }
1421
Jeff Sharkey413573a2016-02-22 17:52:45 -07001422 // Invalidate any relevant cache files
1423 String cacheName = null;
1424 if (Settings.System.RINGTONE.equals(name)) {
1425 cacheName = Settings.System.RINGTONE_CACHE;
1426 } else if (Settings.System.NOTIFICATION_SOUND.equals(name)) {
1427 cacheName = Settings.System.NOTIFICATION_SOUND_CACHE;
1428 } else if (Settings.System.ALARM_ALERT.equals(name)) {
1429 cacheName = Settings.System.ALARM_ALERT_CACHE;
1430 }
1431 if (cacheName != null) {
1432 final File cacheFile = new File(
Andre Lago3fa139c2016-08-04 13:53:44 +01001433 getRingtoneCacheDir(owningUserId), cacheName);
Jeff Sharkey413573a2016-02-22 17:52:45 -07001434 cacheFile.delete();
1435 }
1436
Svetoslav683914b2015-01-15 14:22:26 -08001437 // Mutate the value.
Svetoslav7ec28e82015-05-20 17:01:10 -07001438 synchronized (mLock) {
1439 switch (operation) {
1440 case MUTATION_OPERATION_INSERT: {
1441 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001442 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001443 owningUserId, name, value, null, false, getCallingPackage(),
1444 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001445 }
1446
1447 case MUTATION_OPERATION_DELETE: {
Svet Ganov53a441c2016-04-19 19:38:00 -07001448 return mSettingsRegistry.deleteSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001449 owningUserId, name, false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001450 }
1451
1452 case MUTATION_OPERATION_UPDATE: {
1453 validateSystemSettingValue(name, value);
Svet Ganov53a441c2016-04-19 19:38:00 -07001454 return mSettingsRegistry.updateSettingLocked(SETTINGS_TYPE_SYSTEM,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001455 owningUserId, name, value, null, false, getCallingPackage(),
1456 false, null);
Svetoslav7ec28e82015-05-20 17:01:10 -07001457 }
Svetoslav683914b2015-01-15 14:22:26 -08001458 }
1459
Svetoslav7ec28e82015-05-20 17:01:10 -07001460 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001461 }
Svetoslav683914b2015-01-15 14:22:26 -08001462 }
1463
Billy Lau6ad2d662015-07-18 00:26:58 +01001464 private boolean hasWriteSecureSettingsPermission() {
Svetoslavf41334b2015-06-23 12:06:03 -07001465 // Write secure settings is a more protected permission. If caller has it we are good.
1466 if (getContext().checkCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS)
1467 == PackageManager.PERMISSION_GRANTED) {
1468 return true;
1469 }
1470
Svetoslavf41334b2015-06-23 12:06:03 -07001471 return false;
1472 }
1473
Svetoslav683914b2015-01-15 14:22:26 -08001474 private void validateSystemSettingValue(String name, String value) {
1475 Settings.System.Validator validator = Settings.System.VALIDATORS.get(name);
1476 if (validator != null && !validator.validate(value)) {
1477 throw new IllegalArgumentException("Invalid value: " + value
1478 + " for setting: " + name);
1479 }
1480 }
1481
Alex Klyubin1991f572017-03-03 14:08:36 -08001482 /**
1483 * Returns {@code true} if the specified secure setting should be accessible to the caller.
1484 */
1485 private boolean isSecureSettingAccessible(String name, int callingUserId,
1486 int owningUserId) {
1487 // Special case for location (sigh).
1488 // This check is not inside the name-based checks below because this method performs checks
1489 // only if the calling user ID is not the same as the owning user ID.
1490 if (isLocationProvidersAllowedRestricted(name, callingUserId, owningUserId)) {
1491 return false;
1492 }
1493
1494 switch (name) {
1495 case "bluetooth_address":
1496 // BluetoothManagerService for some reason stores the Android's Bluetooth MAC
1497 // address in this secure setting. Secure settings can normally be read by any app,
1498 // which thus enables them to bypass the recently introduced restrictions on access
1499 // to device identifiers.
1500 // To mitigate this we make this setting available only to callers privileged to see
1501 // this device's MAC addresses, same as through public API
1502 // BluetoothAdapter.getAddress() (see BluetoothManagerService for details).
1503 return getContext().checkCallingOrSelfPermission(
1504 Manifest.permission.LOCAL_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
1505 default:
1506 return true;
1507 }
1508 }
1509
Svetoslav683914b2015-01-15 14:22:26 -08001510 private boolean isLocationProvidersAllowedRestricted(String name, int callingUserId,
1511 int owningUserId) {
1512 // Optimization - location providers are restricted only for managed profiles.
1513 if (callingUserId == owningUserId) {
1514 return false;
1515 }
1516 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)
1517 && mUserManager.hasUserRestriction(UserManager.DISALLOW_SHARE_LOCATION,
1518 new UserHandle(callingUserId))) {
1519 return true;
1520 }
1521 return false;
1522 }
1523
Makoto Onuki28da2e32015-11-20 11:30:44 -08001524 /**
1525 * Checks whether changing a setting to a value is prohibited by the corresponding user
1526 * restriction.
1527 *
Svet Ganov53a441c2016-04-19 19:38:00 -07001528 * <p>See also {@link com.android.server.pm.UserRestrictionsUtils#applyUserRestriction(
1529 * Context, int, String, boolean)}, which should be in sync with this method.
Makoto Onuki28da2e32015-11-20 11:30:44 -08001530 *
1531 * @return true if the change is prohibited, false if the change is allowed.
1532 */
1533 private boolean isGlobalOrSecureSettingRestrictedForUser(String setting, int userId,
Victor Chang9c7b7062016-07-12 23:47:29 +01001534 String value, int callingUid) {
Makoto Onuki28da2e32015-11-20 11:30:44 -08001535 String restriction;
1536 switch (setting) {
1537 case Settings.Secure.LOCATION_MODE:
1538 // Note LOCATION_MODE will be converted into LOCATION_PROVIDERS_ALLOWED
1539 // in android.provider.Settings.Secure.putStringForUser(), so we shouldn't come
1540 // here normally, but we still protect it here from a direct provider write.
1541 if (String.valueOf(Settings.Secure.LOCATION_MODE_OFF).equals(value)) return false;
1542 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1543 break;
1544
1545 case Settings.Secure.LOCATION_PROVIDERS_ALLOWED:
1546 // See SettingsProvider.updateLocationProvidersAllowedLocked. "-" is to disable
1547 // a provider, which should be allowed even if the user restriction is set.
1548 if (value != null && value.startsWith("-")) return false;
1549 restriction = UserManager.DISALLOW_SHARE_LOCATION;
1550 break;
1551
1552 case Settings.Secure.INSTALL_NON_MARKET_APPS:
1553 if ("0".equals(value)) return false;
1554 restriction = UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES;
1555 break;
1556
1557 case Settings.Global.ADB_ENABLED:
1558 if ("0".equals(value)) return false;
1559 restriction = UserManager.DISALLOW_DEBUGGING_FEATURES;
1560 break;
1561
1562 case Settings.Global.PACKAGE_VERIFIER_ENABLE:
1563 case Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB:
1564 if ("1".equals(value)) return false;
1565 restriction = UserManager.ENSURE_VERIFY_APPS;
1566 break;
1567
1568 case Settings.Global.PREFERRED_NETWORK_MODE:
1569 restriction = UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS;
1570 break;
1571
Victor Chang9c7b7062016-07-12 23:47:29 +01001572 case Settings.Secure.ALWAYS_ON_VPN_APP:
1573 case Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN:
1574 // Whitelist system uid (ConnectivityService) and root uid to change always-on vpn
Svetoslav Ganove080da92016-12-21 17:10:35 -08001575 final int appId = UserHandle.getAppId(callingUid);
1576 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID) {
Victor Chang9c7b7062016-07-12 23:47:29 +01001577 return false;
1578 }
1579 restriction = UserManager.DISALLOW_CONFIG_VPN;
1580 break;
1581
Benjamin Franz0ff13fc2016-07-12 13:42:21 +01001582 case Settings.Global.SAFE_BOOT_DISALLOWED:
1583 if ("1".equals(value)) return false;
1584 restriction = UserManager.DISALLOW_SAFE_BOOT;
1585 break;
1586
Makoto Onuki28da2e32015-11-20 11:30:44 -08001587 default:
Mahaver Chopra87648752016-01-08 19:23:57 +00001588 if (setting != null && setting.startsWith(Settings.Global.DATA_ROAMING)) {
Mahaver Chopradea471e2015-12-17 11:02:37 +00001589 if ("0".equals(value)) return false;
1590 restriction = UserManager.DISALLOW_DATA_ROAMING;
1591 break;
1592 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001593 return false;
Svetoslav683914b2015-01-15 14:22:26 -08001594 }
Makoto Onuki28da2e32015-11-20 11:30:44 -08001595
1596 return mUserManager.hasUserRestriction(restriction, UserHandle.of(userId));
Svetoslav683914b2015-01-15 14:22:26 -08001597 }
1598
1599 private int resolveOwningUserIdForSecureSettingLocked(int userId, String setting) {
1600 return resolveOwningUserIdLocked(userId, sSecureCloneToManagedSettings, setting);
1601 }
1602
1603 private int resolveOwningUserIdForSystemSettingLocked(int userId, String setting) {
Andre Lago3fa139c2016-08-04 13:53:44 +01001604 final int parentId;
1605 // Resolves dependency if setting has a dependency and the calling user has a parent
1606 if (sSystemCloneFromParentOnDependency.containsKey(setting)
1607 && (parentId = getGroupParentLocked(userId)) != userId) {
1608 // The setting has a dependency and the profile has a parent
1609 String dependency = sSystemCloneFromParentOnDependency.get(setting);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001610 // Lookup the dependency setting as ourselves, some callers may not have access to it.
1611 final long token = Binder.clearCallingIdentity();
1612 try {
1613 Setting settingObj = getSecureSetting(dependency, userId);
1614 if (settingObj != null && settingObj.getValue().equals("1")) {
1615 return parentId;
1616 }
1617 } finally {
1618 Binder.restoreCallingIdentity(token);
Andre Lago3fa139c2016-08-04 13:53:44 +01001619 }
1620 }
Svetoslav683914b2015-01-15 14:22:26 -08001621 return resolveOwningUserIdLocked(userId, sSystemCloneToManagedSettings, setting);
1622 }
1623
1624 private int resolveOwningUserIdLocked(int userId, Set<String> keys, String name) {
1625 final int parentId = getGroupParentLocked(userId);
1626 if (parentId != userId && keys.contains(name)) {
1627 return parentId;
1628 }
1629 return userId;
1630 }
1631
Svetoslavf41334b2015-06-23 12:06:03 -07001632 private void enforceRestrictedSystemSettingsMutationForCallingPackage(int operation,
Xiaohui Chen43765b72015-08-31 10:57:33 -07001633 String name, int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001634 // System/root/shell can mutate whatever secure settings they want.
1635 final int callingUid = Binder.getCallingUid();
Svetoslav Ganove080da92016-12-21 17:10:35 -08001636 final int appId = UserHandle.getAppId(callingUid);
1637 if (appId == android.os.Process.SYSTEM_UID
1638 || appId == Process.SHELL_UID
1639 || appId == Process.ROOT_UID) {
Svetoslav683914b2015-01-15 14:22:26 -08001640 return;
1641 }
1642
1643 switch (operation) {
1644 case MUTATION_OPERATION_INSERT:
1645 // Insert updates.
1646 case MUTATION_OPERATION_UPDATE: {
1647 if (Settings.System.PUBLIC_SETTINGS.contains(name)) {
1648 return;
1649 }
1650
1651 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001652 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001653
1654 // Privileged apps can do whatever they want.
1655 if ((packageInfo.applicationInfo.privateFlags
1656 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1657 return;
1658 }
1659
1660 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1661 packageInfo.applicationInfo.targetSdkVersion, name);
1662 } break;
1663
1664 case MUTATION_OPERATION_DELETE: {
1665 if (Settings.System.PUBLIC_SETTINGS.contains(name)
1666 || Settings.System.PRIVATE_SETTINGS.contains(name)) {
1667 throw new IllegalArgumentException("You cannot delete system defined"
1668 + " secure settings.");
1669 }
1670
1671 // The calling package is already verified.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001672 PackageInfo packageInfo = getCallingPackageInfoOrThrow(userId);
Svetoslav683914b2015-01-15 14:22:26 -08001673
1674 // Privileged apps can do whatever they want.
1675 if ((packageInfo.applicationInfo.privateFlags &
1676 ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1677 return;
1678 }
1679
1680 warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1681 packageInfo.applicationInfo.targetSdkVersion, name);
1682 } break;
1683 }
1684 }
1685
Todd Kennedybe0b8892017-02-15 14:13:52 -08001686 private Set<String> getInstantAppAccessibleSettings(int settingsType) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001687 switch (settingsType) {
1688 case SETTINGS_TYPE_GLOBAL:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001689 return Settings.Global.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001690 case SETTINGS_TYPE_SECURE:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001691 return Settings.Secure.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001692 case SETTINGS_TYPE_SYSTEM:
Todd Kennedybe0b8892017-02-15 14:13:52 -08001693 return Settings.System.INSTANT_APP_SETTINGS;
Chad Brubaker97bccee2017-01-05 15:51:41 -08001694 default:
1695 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1696 }
1697 }
1698
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001699 private Set<String> getOverlayInstantAppAccessibleSettings(int settingsType) {
1700 switch (settingsType) {
1701 case SETTINGS_TYPE_GLOBAL:
1702 return OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS;
1703 case SETTINGS_TYPE_SYSTEM:
1704 return OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS;
1705 case SETTINGS_TYPE_SECURE:
1706 return OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS;
1707 default:
1708 throw new IllegalArgumentException("Invalid settings type: " + settingsType);
1709 }
1710 }
1711
Chad Brubaker97bccee2017-01-05 15:51:41 -08001712 private List<String> getSettingsNamesLocked(int settingsType, int userId) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001713 // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
1714 // in the current form.
1715 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
Chad Brubaker97bccee2017-01-05 15:51:41 -08001716 }
1717
Chad Brubakera6830e72017-04-28 17:34:36 -07001718 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001719 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1720 return;
1721 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001722 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001723 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001724 return;
1725 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001726 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1727 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubakerb6108d62017-12-23 20:06:44 -08001728 // Don't enforce the instant app whitelist for now -- its too prone to unintended
1729 // breakage in the current form.
1730 Slog.w(LOG_TAG, "Instant App " + ai.packageName
1731 + " trying to access unexposed setting, this will be an error in the future.");
Chad Brubaker97bccee2017-01-05 15:51:41 -08001732 }
1733 }
1734
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001735 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1736 // We always use the callingUid for this lookup. This means that if hypothetically an
1737 // app was installed in user A with cross user and in user B as an Instant App
1738 // the app in A would be able to see all the settings in user B. However since cross
1739 // user is a system permission and the app must be uninstalled in B and then installed as
1740 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001741 ApplicationInfo ai = null;
1742 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001743 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1744 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001745 } catch (RemoteException ignored) {
1746 }
1747 if (ai == null) {
1748 throw new IllegalStateException("Failed to lookup info for package "
1749 + getCallingPackage());
1750 }
1751 return ai;
1752 }
1753
Xiaohui Chen43765b72015-08-31 10:57:33 -07001754 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001755 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001756 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1757 getCallingPackage(), 0, userId);
1758 if (packageInfo != null) {
1759 return packageInfo;
1760 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001761 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001762 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001763 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001764 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001765 }
1766
1767 private int getGroupParentLocked(int userId) {
1768 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001769 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001770 return userId;
1771 }
1772 // We are in the same process with the user manager and the returned
1773 // user info is a cached instance, so just look up instead of cache.
1774 final long identity = Binder.clearCallingIdentity();
1775 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001776 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001777 UserInfo userInfo = mUserManager.getProfileParent(userId);
1778 return (userInfo != null) ? userInfo.id : userId;
1779 } finally {
1780 Binder.restoreCallingIdentity(identity);
1781 }
1782 }
1783
Svetoslav683914b2015-01-15 14:22:26 -08001784 private void enforceWritePermission(String permission) {
1785 if (getContext().checkCallingOrSelfPermission(permission)
1786 != PackageManager.PERMISSION_GRANTED) {
1787 throw new SecurityException("Permission denial: writing to settings requires:"
1788 + permission);
1789 }
1790 }
1791
1792 /*
1793 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1794 * This setting contains a list of the currently enabled location providers.
1795 * But helper functions in android.providers.Settings can enable or disable
1796 * a single provider by using a "+" or "-" prefix before the provider name.
1797 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001798 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1799 * is set, the said method will only allow values with the "-" prefix.
1800 *
Svetoslav683914b2015-01-15 14:22:26 -08001801 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001802 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001803 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1804 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001805 if (TextUtils.isEmpty(value)) {
1806 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001807 }
1808
Svetoslav683914b2015-01-15 14:22:26 -08001809 final char prefix = value.charAt(0);
1810 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001811 if (forceNotify) {
1812 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1813 mSettingsRegistry.notifyForSettingsChange(key,
1814 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1815 }
Svetoslav683914b2015-01-15 14:22:26 -08001816 return false;
1817 }
1818
1819 // skip prefix
1820 value = value.substring(1);
1821
Svetoslav7ec28e82015-05-20 17:01:10 -07001822 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001823 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001824 if (settingValue == null) {
1825 return false;
1826 }
Svetoslav683914b2015-01-15 14:22:26 -08001827
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001828 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001829
1830 int index = oldProviders.indexOf(value);
1831 int end = index + value.length();
1832
1833 // check for commas to avoid matching on partial string
1834 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1835 index = -1;
1836 }
1837
1838 // check for commas to avoid matching on partial string
1839 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1840 index = -1;
1841 }
1842
1843 String newProviders;
1844
1845 if (prefix == '+' && index < 0) {
1846 // append the provider to the list if not present
1847 if (oldProviders.length() == 0) {
1848 newProviders = value;
1849 } else {
1850 newProviders = oldProviders + ',' + value;
1851 }
1852 } else if (prefix == '-' && index >= 0) {
1853 // remove the provider from the list if present
1854 // remove leading or trailing comma
1855 if (index > 0) {
1856 index--;
1857 } else if (end < oldProviders.length()) {
1858 end++;
1859 }
1860
1861 newProviders = oldProviders.substring(0, index);
1862 if (end < oldProviders.length()) {
1863 newProviders += oldProviders.substring(end);
1864 }
1865 } else {
1866 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001867 if (forceNotify) {
1868 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1869 mSettingsRegistry.notifyForSettingsChange(key,
1870 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1871 }
Svetoslav683914b2015-01-15 14:22:26 -08001872 return false;
1873 }
1874
Svet Ganov53a441c2016-04-19 19:38:00 -07001875 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001876 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001877 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001878 }
1879
Svetoslav683914b2015-01-15 14:22:26 -08001880 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1881 int targetSdkVersion, String name) {
1882 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1883 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1884 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1885 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1886 + " This will soon become an error.");
1887 } else {
1888 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1889 + " This will soon become an error.");
1890 }
1891 } else {
1892 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1893 throw new IllegalArgumentException("You cannot change private secure settings.");
1894 } else {
1895 throw new IllegalArgumentException("You cannot keep your settings in"
1896 + " the secure settings.");
1897 }
1898 }
1899 }
1900
1901 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1902 if (requestingUserId == UserHandle.getCallingUserId()) {
1903 return requestingUserId;
1904 }
1905 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1906 Binder.getCallingUid(), requestingUserId, false, true,
1907 "get/set setting for user", null);
1908 }
1909
Svet Ganov53a441c2016-04-19 19:38:00 -07001910 private Bundle packageValueForCallResult(Setting setting,
1911 boolean trackingGeneration) {
1912 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001913 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001914 return NULL_SETTING_BUNDLE;
1915 }
1916 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001917 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001918 Bundle result = new Bundle();
1919 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001920 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001921
Svetoslav Ganove080da92016-12-21 17:10:35 -08001922 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001923 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001924 }
1925
1926 private static int getRequestingUserId(Bundle args) {
1927 final int callingUserId = UserHandle.getCallingUserId();
1928 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1929 : callingUserId;
1930 }
1931
Svet Ganov53a441c2016-04-19 19:38:00 -07001932 private boolean isTrackingGeneration(Bundle args) {
1933 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1934 }
1935
Svetoslav683914b2015-01-15 14:22:26 -08001936 private static String getSettingValue(Bundle args) {
1937 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1938 }
1939
Svetoslav Ganove080da92016-12-21 17:10:35 -08001940 private static String getSettingTag(Bundle args) {
1941 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1942 }
1943
1944 private static boolean getSettingMakeDefault(Bundle args) {
1945 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1946 }
1947
1948 private static int getResetModeEnforcingPermission(Bundle args) {
1949 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1950 switch (mode) {
1951 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1952 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1953 throw new SecurityException("Only system, shell/root on a "
1954 + "debuggable build can reset to untrusted defaults");
1955 }
1956 return mode;
1957 }
1958 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1959 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1960 throw new SecurityException("Only system, shell/root on a "
1961 + "debuggable build can reset untrusted changes");
1962 }
1963 return mode;
1964 }
1965 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1966 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1967 throw new SecurityException("Only system, shell/root on a "
1968 + "debuggable build can reset to trusted defaults");
1969 }
1970 return mode;
1971 }
1972 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1973 return mode;
1974 }
1975 }
1976 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1977 }
1978
1979 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1980 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1981 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1982 && (appId == SHELL_UID || appId == ROOT_UID));
1983 }
1984
Svetoslav683914b2015-01-15 14:22:26 -08001985 private static String getValidTableOrThrow(Uri uri) {
1986 if (uri.getPathSegments().size() > 0) {
1987 String table = uri.getPathSegments().get(0);
1988 if (DatabaseHelper.isValidTable(table)) {
1989 return table;
1990 }
1991 throw new IllegalArgumentException("Bad root path: " + table);
1992 }
1993 throw new IllegalArgumentException("Invalid URI:" + uri);
1994 }
1995
1996 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07001997 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08001998 return new MatrixCursor(projection, 0);
1999 }
2000 MatrixCursor cursor = new MatrixCursor(projection, 1);
2001 appendSettingToCursor(cursor, setting);
2002 return cursor;
2003 }
2004
2005 private static String[] normalizeProjection(String[] projection) {
2006 if (projection == null) {
2007 return ALL_COLUMNS;
2008 }
2009
2010 final int columnCount = projection.length;
2011 for (int i = 0; i < columnCount; i++) {
2012 String column = projection[i];
2013 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2014 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002015 }
2016 }
2017
Svetoslav683914b2015-01-15 14:22:26 -08002018 return projection;
2019 }
2020
2021 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002022 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002023 return;
2024 }
Svetoslav683914b2015-01-15 14:22:26 -08002025 final int columnCount = cursor.getColumnCount();
2026
2027 String[] values = new String[columnCount];
2028
2029 for (int i = 0; i < columnCount; i++) {
2030 String column = cursor.getColumnName(i);
2031
2032 switch (column) {
2033 case Settings.NameValueTable._ID: {
2034 values[i] = setting.getId();
2035 } break;
2036
2037 case Settings.NameValueTable.NAME: {
2038 values[i] = setting.getName();
2039 } break;
2040
2041 case Settings.NameValueTable.VALUE: {
2042 values[i] = setting.getValue();
2043 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002044 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002045 }
2046
Svetoslav683914b2015-01-15 14:22:26 -08002047 cursor.addRow(values);
2048 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002049
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002050 private static boolean isKeyValid(String key) {
2051 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2052 }
2053
Svetoslav683914b2015-01-15 14:22:26 -08002054 private static final class Arguments {
2055 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2056 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2057
2058 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2059 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2060
2061 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2062 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2063
2064 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2065 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2066
2067 public final String table;
2068 public final String name;
2069
2070 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2071 final int segmentSize = uri.getPathSegments().size();
2072 switch (segmentSize) {
2073 case 1: {
2074 if (where != null
2075 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2076 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2077 && whereArgs.length == 1) {
2078 name = whereArgs[0];
2079 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002080 return;
Svetoslav683914b2015-01-15 14:22:26 -08002081 } else if (where != null
2082 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2083 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2084 final int startIndex = Math.max(where.indexOf("'"),
2085 where.indexOf("\"")) + 1;
2086 final int endIndex = Math.max(where.lastIndexOf("'"),
2087 where.lastIndexOf("\""));
2088 name = where.substring(startIndex, endIndex);
2089 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002090 return;
Svetoslav683914b2015-01-15 14:22:26 -08002091 } else if (supportAll && where == null && whereArgs == null) {
2092 name = null;
2093 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002094 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002095 }
Svetoslav683914b2015-01-15 14:22:26 -08002096 } break;
2097
Svetoslav28494652015-02-12 14:11:42 -08002098 case 2: {
2099 if (where == null && whereArgs == null) {
2100 name = uri.getPathSegments().get(1);
2101 table = computeTableForSetting(uri, name);
2102 return;
2103 }
2104 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002105 }
Svetoslav28494652015-02-12 14:11:42 -08002106
2107 EventLogTags.writeUnsupportedSettingsQuery(
2108 uri.toSafeString(), where, Arrays.toString(whereArgs));
2109 String message = String.format( "Supported SQL:\n"
2110 + " uri content://some_table/some_property with null where and where args\n"
2111 + " uri content://some_table with query name=? and single name as arg\n"
2112 + " uri content://some_table with query name=some_name and null args\n"
2113 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2114 Arrays.toString(whereArgs));
2115 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002116 }
2117
Svetoslav28494652015-02-12 14:11:42 -08002118 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002119 String table = getValidTableOrThrow(uri);
2120
2121 if (name != null) {
2122 if (sSystemMovedToSecureSettings.contains(name)) {
2123 table = TABLE_SECURE;
2124 }
2125
2126 if (sSystemMovedToGlobalSettings.contains(name)) {
2127 table = TABLE_GLOBAL;
2128 }
2129
2130 if (sSecureMovedToGlobalSettings.contains(name)) {
2131 table = TABLE_GLOBAL;
2132 }
2133
2134 if (sGlobalMovedToSecureSettings.contains(name)) {
2135 table = TABLE_SECURE;
2136 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002137 }
Svetoslav683914b2015-01-15 14:22:26 -08002138
2139 return table;
2140 }
2141 }
2142
2143 final class SettingsRegistry {
2144 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2145
Svetoslav683914b2015-01-15 14:22:26 -08002146 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2147 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2148 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002149 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2150
2151 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002152
2153 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2154
Svet Ganov53a441c2016-04-19 19:38:00 -07002155 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002156
Svetoslav7e0683b2015-08-03 16:02:52 -07002157 private final Handler mHandler;
2158
Svet Ganov53a441c2016-04-19 19:38:00 -07002159 private final BackupManager mBackupManager;
2160
Amith Yamasani39452022017-03-21 15:23:47 -07002161 private String mSettingsCreationBuildId;
2162
Svetoslav683914b2015-01-15 14:22:26 -08002163 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002164 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002165 mGenerationRegistry = new GenerationRegistry(mLock);
2166 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002167 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002168 syncSsaidTableOnStart();
2169 }
2170
2171 private void generateUserKeyLocked(int userId) {
2172 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002173 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002174 final SecureRandom rand = new SecureRandom();
2175 rand.nextBytes(keyBytes);
2176
2177 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002178 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002179
2180 // Store the key in the ssaid table.
2181 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2182 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2183 true, SettingsState.SYSTEM_PACKAGE_NAME);
2184
2185 if (!success) {
2186 throw new IllegalStateException("Ssaid settings not accessible");
2187 }
2188 }
2189
Mark Rathjen7599f132017-01-23 14:15:54 -08002190 private byte[] getLengthPrefix(byte[] data) {
2191 return ByteBuffer.allocate(4).putInt(data.length).array();
2192 }
2193
Christopher Tateb218e762017-04-05 16:34:07 -07002194 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002195 // Read the user's key from the ssaid table.
2196 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002197 if (userKeySetting == null || userKeySetting.isNull()
2198 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002199 // Lazy initialize and store the user key.
2200 generateUserKeyLocked(userId);
2201 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002202 if (userKeySetting == null || userKeySetting.isNull()
2203 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002204 throw new IllegalStateException("User key not accessible");
2205 }
2206 }
2207 final String userKey = userKeySetting.getValue();
2208
2209 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002210 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2211
2212 // Validate that the key is of expected length.
2213 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2214 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002215 throw new IllegalStateException("User key invalid");
2216 }
2217
Mark Rathjen7599f132017-01-23 14:15:54 -08002218 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002219 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002220 m = Mac.getInstance("HmacSHA256");
2221 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002222 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002223 throw new IllegalStateException("HmacSHA256 is not available", e);
2224 } catch (InvalidKeyException e) {
2225 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002226 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002227
Mark Rathjenf42dd912017-06-05 19:04:34 -07002228 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002229 for (int i = 0; i < callingPkg.signatures.length; i++) {
2230 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002231 m.update(getLengthPrefix(sig), 0, 4);
2232 m.update(sig);
2233 }
Mark Rathjend891f012017-01-19 04:10:37 +00002234
2235 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002236 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2237 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002238
2239 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002240 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002241 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2242 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002243 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002244
2245 if (!success) {
2246 throw new IllegalStateException("Ssaid settings not accessible");
2247 }
2248
2249 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2250 }
2251
2252 public void syncSsaidTableOnStart() {
2253 synchronized (mLock) {
2254 // Verify that each user's packages and ssaid's are in sync.
2255 for (UserInfo user : mUserManager.getUsers(true)) {
2256 // Get all uids for the user's packages.
2257 final List<PackageInfo> packages;
2258 try {
2259 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2260 } catch (RemoteException e) {
2261 throw new IllegalStateException("Package manager not available");
2262 }
2263 final Set<String> appUids = new HashSet<>();
2264 for (PackageInfo info : packages) {
2265 appUids.add(Integer.toString(info.applicationInfo.uid));
2266 }
2267
2268 // Get all uids currently stored in the user's ssaid table.
2269 final Set<String> ssaidUids = new HashSet<>(
2270 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2271 ssaidUids.remove(SSAID_USER_KEY);
2272
2273 // Perform a set difference for the appUids and ssaidUids.
2274 ssaidUids.removeAll(appUids);
2275
2276 // If there are ssaidUids left over they need to be removed from the table.
2277 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2278 user.id);
2279 for (String uid : ssaidUids) {
2280 ssaidSettings.deleteSettingLocked(uid);
2281 }
2282 }
2283 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002284 }
2285
Svetoslav683914b2015-01-15 14:22:26 -08002286 public List<String> getSettingsNamesLocked(int type, int userId) {
2287 final int key = makeKey(type, userId);
2288 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002289 if (settingsState == null) {
2290 return new ArrayList<String>();
2291 }
Svetoslav683914b2015-01-15 14:22:26 -08002292 return settingsState.getSettingNamesLocked();
2293 }
2294
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002295 public SparseBooleanArray getKnownUsersLocked() {
2296 SparseBooleanArray users = new SparseBooleanArray();
2297 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2298 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2299 }
2300 return users;
2301 }
2302
Kweku Adamsb0886f32017-10-31 15:32:09 -07002303 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002304 public SettingsState getSettingsLocked(int type, int userId) {
2305 final int key = makeKey(type, userId);
2306 return peekSettingsStateLocked(key);
2307 }
2308
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002309 public boolean ensureSettingsForUserLocked(int userId) {
2310 // First make sure this user actually exists.
2311 if (mUserManager.getUserInfo(userId) == null) {
2312 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2313 return false;
2314 }
2315
Svetoslav683914b2015-01-15 14:22:26 -08002316 // Migrate the setting for this user if needed.
2317 migrateLegacySettingsForUserIfNeededLocked(userId);
2318
2319 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002320 if (userId == UserHandle.USER_SYSTEM) {
2321 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002322 ensureSettingsStateLocked(globalKey);
2323 }
2324
2325 // Ensure secure settings loaded.
2326 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2327 ensureSettingsStateLocked(secureKey);
2328
2329 // Make sure the secure settings have an Android id set.
2330 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2331 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2332
2333 // Ensure system settings loaded.
2334 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2335 ensureSettingsStateLocked(systemKey);
2336
Mark Rathjend891f012017-01-19 04:10:37 +00002337 // Ensure secure settings loaded.
2338 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2339 ensureSettingsStateLocked(ssaidKey);
2340
Svetoslav683914b2015-01-15 14:22:26 -08002341 // Upgrade the settings to the latest version.
2342 UpgradeController upgrader = new UpgradeController(userId);
2343 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002344 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002345 }
2346
2347 private void ensureSettingsStateLocked(int key) {
2348 if (mSettingsStates.get(key) == null) {
2349 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002350 SettingsState settingsState = new SettingsState(getContext(), mLock,
2351 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002352 mSettingsStates.put(key, settingsState);
2353 }
2354 }
2355
2356 public void removeUserStateLocked(int userId, boolean permanently) {
2357 // We always keep the global settings in memory.
2358
2359 // Nuke system settings.
2360 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2361 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2362 if (systemSettingsState != null) {
2363 if (permanently) {
2364 mSettingsStates.remove(systemKey);
2365 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002366 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002367 systemSettingsState.destroyLocked(new Runnable() {
2368 @Override
2369 public void run() {
2370 mSettingsStates.remove(systemKey);
2371 }
2372 });
2373 }
2374 }
2375
2376 // Nuke secure settings.
2377 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2378 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2379 if (secureSettingsState != null) {
2380 if (permanently) {
2381 mSettingsStates.remove(secureKey);
2382 secureSettingsState.destroyLocked(null);
2383 } else {
2384 secureSettingsState.destroyLocked(new Runnable() {
2385 @Override
2386 public void run() {
2387 mSettingsStates.remove(secureKey);
2388 }
2389 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002390 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002391 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002392
Mark Rathjend891f012017-01-19 04:10:37 +00002393 // Nuke ssaid settings.
2394 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2395 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2396 if (ssaidSettingsState != null) {
2397 if (permanently) {
2398 mSettingsStates.remove(ssaidKey);
2399 ssaidSettingsState.destroyLocked(null);
2400 } else {
2401 ssaidSettingsState.destroyLocked(new Runnable() {
2402 @Override
2403 public void run() {
2404 mSettingsStates.remove(ssaidKey);
2405 }
2406 });
2407 }
2408 }
2409
Svet Ganov53a441c2016-04-19 19:38:00 -07002410 // Nuke generation tracking data
2411 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002412 }
2413
Svetoslav683914b2015-01-15 14:22:26 -08002414 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002415 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2416 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002417 final int key = makeKey(type, userId);
2418
Svetoslav Ganove080da92016-12-21 17:10:35 -08002419 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002420 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002421 if (settingsState != null) {
2422 success = settingsState.insertSettingLocked(name, value,
2423 tag, makeDefault, packageName);
2424 }
Svetoslav683914b2015-01-15 14:22:26 -08002425
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002426 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2427 settingsState.persistSyncLocked();
2428 }
2429
Svet Ganov53a441c2016-04-19 19:38:00 -07002430 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002431 notifyForSettingsChange(key, name);
2432 }
2433 return success;
2434 }
2435
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002436 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2437 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002438 final int key = makeKey(type, userId);
2439
Svetoslav Ganove080da92016-12-21 17:10:35 -08002440 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002441 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002442 if (settingsState != null) {
2443 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002444 }
Svetoslav683914b2015-01-15 14:22:26 -08002445
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002446 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2447 settingsState.persistSyncLocked();
2448 }
2449
Svet Ganov53a441c2016-04-19 19:38:00 -07002450 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002451 notifyForSettingsChange(key, name);
2452 }
2453 return success;
2454 }
2455
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002456 public boolean updateSettingLocked(int type, int userId, String name, String value,
2457 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2458 Set<String> criticalSettings) {
2459 final int key = makeKey(type, userId);
2460
2461 boolean success = false;
2462 SettingsState settingsState = peekSettingsStateLocked(key);
2463 if (settingsState != null) {
2464 success = settingsState.updateSettingLocked(name, value, tag,
2465 makeDefault, packageName);
2466 }
2467
2468 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2469 settingsState.persistSyncLocked();
2470 }
2471
2472 if (forceNotify || success) {
2473 notifyForSettingsChange(key, name);
2474 }
2475
2476 return success;
2477 }
2478
Svetoslav683914b2015-01-15 14:22:26 -08002479 public Setting getSettingLocked(int type, int userId, String name) {
2480 final int key = makeKey(type, userId);
2481
2482 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002483 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002484 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002485 }
Mark Rathjend891f012017-01-19 04:10:37 +00002486
2487 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002488 return settingsState.getSettingLocked(name);
2489 }
2490
Svetoslav Ganove080da92016-12-21 17:10:35 -08002491 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2492 String tag) {
2493 final int key = makeKey(type, userId);
2494 SettingsState settingsState = peekSettingsStateLocked(key);
2495 if (settingsState == null) {
2496 return;
2497 }
2498
2499 switch (mode) {
2500 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2501 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002502 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002503 Setting setting = settingsState.getSettingLocked(name);
2504 if (packageName.equals(setting.getPackageName())) {
2505 if (tag != null && !tag.equals(setting.getTag())) {
2506 continue;
2507 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002508 if (settingsState.resetSettingLocked(name)) {
2509 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002510 notifyForSettingsChange(key, name);
2511 }
2512 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002513 if (someSettingChanged) {
2514 settingsState.persistSyncLocked();
2515 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002516 }
2517 } break;
2518
2519 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2520 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002521 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002522 Setting setting = settingsState.getSettingLocked(name);
2523 if (!SettingsState.isSystemPackage(getContext(),
2524 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002525 if (settingsState.resetSettingLocked(name)) {
2526 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002527 notifyForSettingsChange(key, name);
2528 }
2529 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002530 if (someSettingChanged) {
2531 settingsState.persistSyncLocked();
2532 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002533 }
2534 } break;
2535
2536 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2537 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002538 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002539 Setting setting = settingsState.getSettingLocked(name);
2540 if (!SettingsState.isSystemPackage(getContext(),
2541 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002542 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002543 if (settingsState.resetSettingLocked(name)) {
2544 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002545 notifyForSettingsChange(key, name);
2546 }
2547 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002548 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002549 notifyForSettingsChange(key, name);
2550 }
2551 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002552 if (someSettingChanged) {
2553 settingsState.persistSyncLocked();
2554 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002555 }
2556 } break;
2557
2558 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2559 for (String name : settingsState.getSettingNamesLocked()) {
2560 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002561 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002562 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002563 if (settingsState.resetSettingLocked(name)) {
2564 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002565 notifyForSettingsChange(key, name);
2566 }
2567 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002568 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002569 notifyForSettingsChange(key, name);
2570 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002571 if (someSettingChanged) {
2572 settingsState.persistSyncLocked();
2573 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002574 }
2575 } break;
2576 }
2577 }
2578
Svetoslav683914b2015-01-15 14:22:26 -08002579 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002580 // Global and secure settings are signature protected. Apps signed
2581 // by the platform certificate are generally not uninstalled and
2582 // the main exception is tests. We trust components signed
2583 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002584
2585 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2586 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002587 if (systemSettings != null) {
2588 systemSettings.onPackageRemovedLocked(packageName);
2589 }
Svetoslav683914b2015-01-15 14:22:26 -08002590 }
2591
Mark Rathjend891f012017-01-19 04:10:37 +00002592 public void onUidRemovedLocked(int uid) {
2593 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2594 UserHandle.getUserId(uid));
Tony Mak24c6ab42018-01-08 14:35:34 +00002595 if (ssaidSettings != null) {
2596 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2597 }
Mark Rathjend891f012017-01-19 04:10:37 +00002598 }
2599
Kweku Adamsb0886f32017-10-31 15:32:09 -07002600 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002601 private SettingsState peekSettingsStateLocked(int key) {
2602 SettingsState settingsState = mSettingsStates.get(key);
2603 if (settingsState != null) {
2604 return settingsState;
2605 }
2606
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002607 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2608 return null;
2609 }
Svetoslav683914b2015-01-15 14:22:26 -08002610 return mSettingsStates.get(key);
2611 }
2612
2613 private void migrateAllLegacySettingsIfNeeded() {
2614 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002615 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002616 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002617 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002618 return;
2619 }
2620
Amith Yamasani39452022017-03-21 15:23:47 -07002621 mSettingsCreationBuildId = Build.ID;
2622
Svetoslav683914b2015-01-15 14:22:26 -08002623 final long identity = Binder.clearCallingIdentity();
2624 try {
2625 List<UserInfo> users = mUserManager.getUsers(true);
2626
2627 final int userCount = users.size();
2628 for (int i = 0; i < userCount; i++) {
2629 final int userId = users.get(i).id;
2630
2631 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2632 SQLiteDatabase database = dbHelper.getWritableDatabase();
2633 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2634
2635 // Upgrade to the latest version.
2636 UpgradeController upgrader = new UpgradeController(userId);
2637 upgrader.upgradeIfNeededLocked();
2638
2639 // Drop from memory if not a running user.
2640 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2641 removeUserStateLocked(userId, false);
2642 }
2643 }
2644 } finally {
2645 Binder.restoreCallingIdentity(identity);
2646 }
2647 }
2648 }
2649
2650 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2651 // Every user has secure settings and if no file we need to migrate.
2652 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2653 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002654 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002655 return;
2656 }
2657
2658 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2659 SQLiteDatabase database = dbHelper.getWritableDatabase();
2660
2661 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2662 }
2663
2664 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2665 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002666 // Move over the system settings.
2667 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2668 ensureSettingsStateLocked(systemKey);
2669 SettingsState systemSettings = mSettingsStates.get(systemKey);
2670 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2671 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002672
2673 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002674 // Do this after System settings, since this is the first thing we check when deciding
2675 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002676 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2677 ensureSettingsStateLocked(secureKey);
2678 SettingsState secureSettings = mSettingsStates.get(secureKey);
2679 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2680 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2681 secureSettings.persistSyncLocked();
2682
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002683 // Move over the global settings if owner.
2684 // Do this last, since this is the first thing we check when deciding
2685 // to skip over migration from db to xml for owner user.
2686 if (userId == UserHandle.USER_SYSTEM) {
2687 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2688 ensureSettingsStateLocked(globalKey);
2689 SettingsState globalSettings = mSettingsStates.get(globalKey);
2690 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002691 // If this was just created
2692 if (mSettingsCreationBuildId != null) {
2693 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2694 mSettingsCreationBuildId, null, true,
2695 SettingsState.SYSTEM_PACKAGE_NAME);
2696 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002697 globalSettings.persistSyncLocked();
2698 }
Svetoslav683914b2015-01-15 14:22:26 -08002699
2700 // Drop the database as now all is moved and persisted.
2701 if (DROP_DATABASE_ON_MIGRATION) {
2702 dbHelper.dropDatabase();
2703 } else {
2704 dbHelper.backupDatabase();
2705 }
2706 }
2707
2708 private void migrateLegacySettingsLocked(SettingsState settingsState,
2709 SQLiteDatabase database, String table) {
2710 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2711 queryBuilder.setTables(table);
2712
2713 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2714 null, null, null, null, null);
2715
2716 if (cursor == null) {
2717 return;
2718 }
2719
2720 try {
2721 if (!cursor.moveToFirst()) {
2722 return;
2723 }
2724
2725 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2726 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2727
2728 settingsState.setVersionLocked(database.getVersion());
2729
2730 while (!cursor.isAfterLast()) {
2731 String name = cursor.getString(nameColumnIdx);
2732 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002733 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002734 SettingsState.SYSTEM_PACKAGE_NAME);
2735 cursor.moveToNext();
2736 }
2737 } finally {
2738 cursor.close();
2739 }
2740 }
2741
2742 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2743 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2744
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002745 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002746 return;
2747 }
2748
2749 final int userId = getUserIdFromKey(secureSettings.mKey);
2750
2751 final UserInfo user;
2752 final long identity = Binder.clearCallingIdentity();
2753 try {
2754 user = mUserManager.getUserInfo(userId);
2755 } finally {
2756 Binder.restoreCallingIdentity(identity);
2757 }
2758 if (user == null) {
2759 // Can happen due to races when deleting users - treat as benign.
2760 return;
2761 }
2762
2763 String androidId = Long.toHexString(new SecureRandom().nextLong());
2764 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002765 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002766
2767 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2768 + "] for user " + userId);
2769
2770 // Write a drop box entry if it's a restricted profile
2771 if (user.isRestricted()) {
2772 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2773 Context.DROPBOX_SERVICE);
2774 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2775 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2776 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2777 }
2778 }
2779 }
2780
2781 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002782 final int userId = getUserIdFromKey(key);
2783 Uri uri = getNotificationUriFor(key, name);
2784
Phil Weaver83fec002016-05-11 10:55:29 -07002785 mGenerationRegistry.incrementGeneration(key);
2786
Svetoslav7e0683b2015-08-03 16:02:52 -07002787 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2788 userId, 0, uri).sendToTarget();
2789
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002790 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002791 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2792 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002793 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2794 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002795 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002796 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2797 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002798 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002799
Svet Ganov53a441c2016-04-19 19:38:00 -07002800 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002801
2802 // When the global kill switch is updated, send the change notification for
2803 // the location setting.
2804 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2805 notifyLocationChangeForRunningUsers();
2806 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002807 }
2808
Svet Ganov53a441c2016-04-19 19:38:00 -07002809 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002810 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002811 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002812 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002813 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002814 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002815 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002816 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002817 final int key = makeKey(type, profileId);
2818 mGenerationRegistry.incrementGeneration(key);
2819
2820 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002821 }
2822 }
2823 }
Svetoslav683914b2015-01-15 14:22:26 -08002824 }
2825
Makoto Onuki0000d322017-11-28 16:31:47 -08002826 private void notifyLocationChangeForRunningUsers() {
2827 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2828
2829 for (int i = 0; i < users.size(); i++) {
2830 final int userId = users.get(i).id;
2831
2832 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2833 continue;
2834 }
2835
2836 final int key = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2837 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2838
2839 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2840 userId, 0, uri).sendToTarget();
2841 }
2842 }
2843
Svetoslav683914b2015-01-15 14:22:26 -08002844 private boolean isGlobalSettingsKey(int key) {
2845 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2846 }
2847
2848 private boolean isSystemSettingsKey(int key) {
2849 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2850 }
2851
2852 private boolean isSecureSettingsKey(int key) {
2853 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2854 }
2855
Mark Rathjend891f012017-01-19 04:10:37 +00002856 private boolean isSsaidSettingsKey(int key) {
2857 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2858 }
2859
Svetoslav683914b2015-01-15 14:22:26 -08002860 private File getSettingsFile(int key) {
2861 if (isGlobalSettingsKey(key)) {
2862 final int userId = getUserIdFromKey(key);
2863 return new File(Environment.getUserSystemDirectory(userId),
2864 SETTINGS_FILE_GLOBAL);
2865 } else if (isSystemSettingsKey(key)) {
2866 final int userId = getUserIdFromKey(key);
2867 return new File(Environment.getUserSystemDirectory(userId),
2868 SETTINGS_FILE_SYSTEM);
2869 } else if (isSecureSettingsKey(key)) {
2870 final int userId = getUserIdFromKey(key);
2871 return new File(Environment.getUserSystemDirectory(userId),
2872 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002873 } else if (isSsaidSettingsKey(key)) {
2874 final int userId = getUserIdFromKey(key);
2875 return new File(Environment.getUserSystemDirectory(userId),
2876 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002877 } else {
2878 throw new IllegalArgumentException("Invalid settings key:" + key);
2879 }
2880 }
2881
2882 private Uri getNotificationUriFor(int key, String name) {
2883 if (isGlobalSettingsKey(key)) {
2884 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2885 : Settings.Global.CONTENT_URI;
2886 } else if (isSecureSettingsKey(key)) {
2887 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2888 : Settings.Secure.CONTENT_URI;
2889 } else if (isSystemSettingsKey(key)) {
2890 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2891 : Settings.System.CONTENT_URI;
2892 } else {
2893 throw new IllegalArgumentException("Invalid settings key:" + key);
2894 }
2895 }
2896
2897 private int getMaxBytesPerPackageForType(int type) {
2898 switch (type) {
2899 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002900 case SETTINGS_TYPE_SECURE:
2901 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002902 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2903 }
2904
2905 default: {
2906 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2907 }
2908 }
2909 }
2910
Svetoslav7e0683b2015-08-03 16:02:52 -07002911 private final class MyHandler extends Handler {
2912 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2913 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2914
2915 public MyHandler(Looper looper) {
2916 super(looper);
2917 }
2918
2919 @Override
2920 public void handleMessage(Message msg) {
2921 switch (msg.what) {
2922 case MSG_NOTIFY_URI_CHANGED: {
2923 final int userId = msg.arg1;
2924 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002925 try {
2926 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2927 } catch (SecurityException e) {
2928 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2929 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002930 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002931 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2932 }
2933 } break;
2934
2935 case MSG_NOTIFY_DATA_CHANGED: {
2936 mBackupManager.dataChanged();
2937 } break;
2938 }
2939 }
2940 }
2941
Svetoslav683914b2015-01-15 14:22:26 -08002942 private final class UpgradeController {
Mike Digman4af4a6f2018-01-16 14:49:38 -08002943 private static final int SETTINGS_VERSION = 151;
Svetoslav683914b2015-01-15 14:22:26 -08002944
2945 private final int mUserId;
2946
2947 public UpgradeController(int userId) {
2948 mUserId = userId;
2949 }
2950
2951 public void upgradeIfNeededLocked() {
2952 // The version of all settings for a user is the same (all users have secure).
2953 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002954 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002955
2956 // Try an update from the current state.
2957 final int oldVersion = secureSettings.getVersionLocked();
2958 final int newVersion = SETTINGS_VERSION;
2959
Svet Ganovc9755bc2015-03-28 13:21:22 -07002960 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002961 if (oldVersion == newVersion) {
2962 return;
2963 }
2964
2965 // Try to upgrade.
2966 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2967
2968 // If upgrade failed start from scratch and upgrade.
2969 if (curVersion != newVersion) {
2970 // Drop state we have for this user.
2971 removeUserStateLocked(mUserId, true);
2972
2973 // Recreate the database.
2974 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2975 SQLiteDatabase database = dbHelper.getWritableDatabase();
2976 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2977
2978 // Migrate the settings for this user.
2979 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2980
2981 // Now upgrade should work fine.
2982 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002983
2984 // Make a note what happened, so we don't wonder why data was lost
2985 String reason = "Settings rebuilt! Current version: "
2986 + curVersion + " while expected: " + newVersion;
2987 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002988 Settings.Global.DATABASE_DOWNGRADE_REASON,
2989 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002990 }
2991
2992 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002993 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002994 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002995 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002996 globalSettings.setVersionLocked(newVersion);
2997 }
2998
2999 // Set the secure settings version.
3000 secureSettings.setVersionLocked(newVersion);
3001
3002 // Set the system settings version.
3003 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003004 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003005 systemSettings.setVersionLocked(newVersion);
3006 }
3007
3008 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003009 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003010 }
3011
3012 private SettingsState getSecureSettingsLocked(int userId) {
3013 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3014 }
3015
Mark Rathjend891f012017-01-19 04:10:37 +00003016 private SettingsState getSsaidSettingsLocked(int userId) {
3017 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3018 }
3019
Svetoslav683914b2015-01-15 14:22:26 -08003020 private SettingsState getSystemSettingsLocked(int userId) {
3021 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3022 }
3023
Jeff Brown503cffc2015-03-26 18:08:51 -07003024 /**
3025 * You must perform all necessary mutations to bring the settings
3026 * for this user from the old to the new version. When you add a new
3027 * upgrade step you *must* update SETTINGS_VERSION.
3028 *
3029 * This is an example of moving a setting from secure to global.
3030 *
3031 * // v119: Example settings changes.
3032 * if (currentVersion == 118) {
3033 * if (userId == UserHandle.USER_OWNER) {
3034 * // Remove from the secure settings.
3035 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3036 * String name = "example_setting_to_move";
3037 * String value = secureSettings.getSetting(name);
3038 * secureSettings.deleteSetting(name);
3039 *
3040 * // Add to the global settings.
3041 * SettingsState globalSettings = getGlobalSettingsLocked();
3042 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3043 * }
3044 *
3045 * // Update the current version.
3046 * currentVersion = 119;
3047 * }
3048 */
Svetoslav683914b2015-01-15 14:22:26 -08003049 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3050 if (DEBUG) {
3051 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3052 + oldVersion + " to version: " + newVersion);
3053 }
3054
Jeff Brown503cffc2015-03-26 18:08:51 -07003055 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003056
John Spurlocke11ae112015-05-11 16:09:03 -04003057 // v119: Reset zen + ringer mode.
3058 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003059 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003060 final SettingsState globalSettings = getGlobalSettingsLocked();
3061 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003062 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3063 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003064 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003065 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3066 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003067 }
3068 currentVersion = 119;
3069 }
3070
Jason Monk27bbb2d2015-03-31 16:46:39 -04003071 // v120: Add double tap to wake setting.
3072 if (currentVersion == 119) {
3073 SettingsState secureSettings = getSecureSettingsLocked(userId);
3074 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3075 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003076 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003077 SettingsState.SYSTEM_PACKAGE_NAME);
3078
3079 currentVersion = 120;
3080 }
3081
Svetoslav7e0683b2015-08-03 16:02:52 -07003082 if (currentVersion == 120) {
3083 // Before 121, we used a different string encoding logic. We just bump the
3084 // version here; SettingsState knows how to handle pre-version 120 files.
3085 currentVersion = 121;
3086 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003087
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003088 if (currentVersion == 121) {
3089 // Version 122: allow OEMs to set a default payment component in resources.
3090 // Note that we only write the default if no default has been set;
3091 // if there is, we just leave the default at whatever it currently is.
3092 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3093 String defaultComponent = (getContext().getResources().getString(
3094 R.string.def_nfc_payment_component));
3095 Setting currentSetting = secureSettings.getSettingLocked(
3096 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3097 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003098 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003099 secureSettings.insertSettingLocked(
3100 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003101 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003102 }
3103 currentVersion = 122;
3104 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003105
3106 if (currentVersion == 122) {
3107 // Version 123: Adding a default value for the ability to add a user from
3108 // the lock screen.
3109 if (userId == UserHandle.USER_SYSTEM) {
3110 final SettingsState globalSettings = getGlobalSettingsLocked();
3111 Setting currentSetting = globalSettings.getSettingLocked(
3112 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003113 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003114 globalSettings.insertSettingLocked(
3115 Settings.Global.ADD_USERS_WHEN_LOCKED,
3116 getContext().getResources().getBoolean(
3117 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003118 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003119 }
3120 }
3121 currentVersion = 123;
3122 }
Bryce Leebd179282015-12-17 19:01:37 -08003123
3124 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003125 final SettingsState globalSettings = getGlobalSettingsLocked();
3126 String defaultDisabledProfiles = (getContext().getResources().getString(
3127 R.string.def_bluetooth_disabled_profiles));
3128 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003129 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003130 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003131 }
3132
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003133 if (currentVersion == 124) {
3134 // Version 124: allow OEMs to set a default value for whether IME should be
3135 // shown when a physical keyboard is connected.
3136 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3137 Setting currentSetting = secureSettings.getSettingLocked(
3138 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003139 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003140 secureSettings.insertSettingLocked(
3141 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3142 getContext().getResources().getBoolean(
3143 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003144 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003145 }
3146 currentVersion = 125;
3147 }
3148
Ruben Brunk98576cf2016-03-07 18:54:28 -08003149 if (currentVersion == 125) {
3150 // Version 125: Allow OEMs to set the default VR service.
3151 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3152
3153 Setting currentSetting = secureSettings.getSettingLocked(
3154 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003155 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003156 ArraySet<ComponentName> l =
3157 SystemConfig.getInstance().getDefaultVrComponents();
3158
3159 if (l != null && !l.isEmpty()) {
3160 StringBuilder b = new StringBuilder();
3161 boolean start = true;
3162 for (ComponentName c : l) {
3163 if (!start) {
3164 b.append(':');
3165 }
3166 b.append(c.flattenToString());
3167 start = false;
3168 }
3169 secureSettings.insertSettingLocked(
3170 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003171 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003172 }
3173
3174 }
3175 currentVersion = 126;
3176 }
3177
Daniel U02ba6122016-04-01 18:41:42 +01003178 if (currentVersion == 126) {
3179 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3180 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3181 if (mUserManager.isManagedProfile(userId)) {
3182 final SettingsState systemSecureSettings =
3183 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3184
3185 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3186 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003187 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003188 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3189 secureSettings.insertSettingLocked(
3190 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003191 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003192 SettingsState.SYSTEM_PACKAGE_NAME);
3193 }
3194
3195 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3196 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003197 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003198 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3199 secureSettings.insertSettingLocked(
3200 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003201 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003202 SettingsState.SYSTEM_PACKAGE_NAME);
3203 }
3204 }
3205 currentVersion = 127;
3206 }
3207
Steven Ngdc20ba62016-04-26 18:19:04 +01003208 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003209 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003210 currentVersion = 128;
3211 }
3212
Julia Reynolds1f721e12016-07-11 08:50:58 -04003213 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003214 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003215 currentVersion = 129;
3216 }
3217
Dan Sandler71f85e92016-07-20 13:46:05 -04003218 if (currentVersion == 129) {
3219 // default longpress timeout changed from 500 to 400. If unchanged from the old
3220 // default, update to the new default.
3221 final SettingsState systemSecureSettings =
3222 getSecureSettingsLocked(userId);
3223 final String oldValue = systemSecureSettings.getSettingLocked(
3224 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3225 if (TextUtils.equals("500", oldValue)) {
3226 systemSecureSettings.insertSettingLocked(
3227 Settings.Secure.LONG_PRESS_TIMEOUT,
3228 String.valueOf(getContext().getResources().getInteger(
3229 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003230 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003231 }
3232 currentVersion = 130;
3233 }
3234
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003235 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003236 // Split Ambient settings
3237 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3238 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3239 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3240
3241 if (dozeExplicitlyDisabled) {
3242 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003243 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003244 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003245 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003246 }
3247 currentVersion = 131;
3248 }
3249
3250 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003251 // Initialize new multi-press timeout to default value
3252 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3253 final String oldValue = systemSecureSettings.getSettingLocked(
3254 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3255 if (TextUtils.equals(null, oldValue)) {
3256 systemSecureSettings.insertSettingLocked(
3257 Settings.Secure.MULTI_PRESS_TIMEOUT,
3258 String.valueOf(getContext().getResources().getInteger(
3259 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003260 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003261 }
3262
Adrian Roos69741a22016-10-21 14:49:17 -07003263 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003264 }
3265
Adrian Roos69741a22016-10-21 14:49:17 -07003266 if (currentVersion == 132) {
3267 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003268 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3269 String defaultSyncParentSounds = (getContext().getResources()
3270 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3271 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003272 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3273 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003274 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003275 }
3276
Adrian Roos69741a22016-10-21 14:49:17 -07003277 if (currentVersion == 133) {
3278 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003279 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3280 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3281 null) {
3282 String defaultEndButtonBehavior = Integer.toString(getContext()
3283 .getResources().getInteger(R.integer.def_end_button_behavior));
3284 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003285 defaultEndButtonBehavior, null, true,
3286 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003287 }
Adrian Roos69741a22016-10-21 14:49:17 -07003288 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003289 }
3290
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003291 if (currentVersion == 134) {
3292 // Remove setting that specifies if magnification values should be preserved.
3293 // This setting defaulted to true and never has a UI.
3294 getSecureSettingsLocked(userId).deleteSettingLocked(
3295 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3296 currentVersion = 135;
3297 }
3298
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003299 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003300 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003301 currentVersion = 136;
3302 }
3303
Mark Rathjend891f012017-01-19 04:10:37 +00003304 if (currentVersion == 136) {
3305 // Version 136: Store legacy SSAID for all apps currently installed on the
3306 // device as first step in migrating SSAID to be unique per application.
3307
3308 final boolean isUpgrade;
3309 try {
3310 isUpgrade = mPackageManager.isUpgrade();
3311 } catch (RemoteException e) {
3312 throw new IllegalStateException("Package manager not available");
3313 }
3314 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3315 // user data or first boot on a new device should use new ssaid generation.
3316 if (isUpgrade) {
3317 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003318 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3319 userId, Settings.Secure.ANDROID_ID);
3320 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3321 || legacySsaidSetting.getValue() == null) {
3322 throw new IllegalStateException("Legacy ssaid not accessible");
3323 }
3324 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003325
3326 // Fill each uid with the legacy ssaid to be backwards compatible.
3327 final List<PackageInfo> packages;
3328 try {
3329 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3330 } catch (RemoteException e) {
3331 throw new IllegalStateException("Package manager not available");
3332 }
3333
3334 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3335 for (PackageInfo info : packages) {
3336 // Check if the UID already has an entry in the table.
3337 final String uid = Integer.toString(info.applicationInfo.uid);
3338 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3339
3340 if (ssaid.isNull() || ssaid.getValue() == null) {
3341 // Android Id doesn't exist for this package so create it.
3342 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3343 info.packageName);
3344 }
3345 }
3346 }
3347
3348 currentVersion = 137;
3349 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003350 if (currentVersion == 137) {
3351 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3352 // default value set to 1. The user can no longer change the value of this
3353 // setting through the UI.
3354 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3355 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003356 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3357 && secureSetting.getSettingLocked(
3358 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3359
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003360 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3361 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003362 // For managed profiles with profile owners, DevicePolicyManagerService
3363 // may want to set the user restriction in this case
3364 secureSetting.insertSettingLocked(
3365 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3366 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003367 }
3368 currentVersion = 138;
3369 }
Mark Rathjend891f012017-01-19 04:10:37 +00003370
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003371 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003372 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003373 currentVersion = 139;
3374 }
3375
Phil Weaver385912e2017-02-10 10:06:56 -08003376 if (currentVersion == 139) {
3377 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3378 // the user can no longer change the value of this setting through the UI.
3379 // Force to true.
3380 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3381 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3382 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3383 currentVersion = 140;
3384 }
3385
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003386 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003387 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003388 currentVersion = 141;
3389 }
3390
Svet Ganov13701552017-02-23 12:45:17 -08003391 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003392 // This implementation was incorrectly setting the current value of
3393 // settings changed by non-system packages as the default which default
3394 // is set by the system. We add a new upgrade step at the end to properly
3395 // handle this case which would also fix incorrect changes made by the
3396 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003397 currentVersion = 142;
3398 }
3399
Stephen Chen5d0922f2017-03-27 10:28:04 -07003400 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003401 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003402 if (userId == UserHandle.USER_SYSTEM) {
3403 final SettingsState globalSettings = getGlobalSettingsLocked();
3404 Setting currentSetting = globalSettings.getSettingLocked(
3405 Settings.Global.WIFI_WAKEUP_ENABLED);
3406 if (currentSetting.isNull()) {
3407 globalSettings.insertSettingLocked(
3408 Settings.Global.WIFI_WAKEUP_ENABLED,
3409 getContext().getResources().getBoolean(
3410 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3411 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3412 }
3413 }
3414
3415 currentVersion = 143;
3416 }
3417
Felipe Lemeff355092017-04-03 12:55:02 -07003418 if (currentVersion == 143) {
3419 // Version 144: Set a default value for Autofill service.
3420 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3421 final Setting currentSetting = secureSettings
3422 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3423 if (currentSetting.isNull()) {
3424 final String defaultValue = getContext().getResources().getString(
3425 com.android.internal.R.string.config_defaultAutofillService);
3426 if (defaultValue != null) {
3427 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3428 + "for user " + userId);
3429 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3430 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3431 }
3432 }
3433
3434 currentVersion = 144;
3435 }
3436
Jeremy Joslin45caa252017-05-04 11:22:46 -07003437 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003438 // Version 145: Removed
3439 currentVersion = 145;
3440 }
3441
3442 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003443 // Version 146: In step 142 we had a bug where incorrectly
3444 // some settings were considered system set and as a result
3445 // made the default and marked as the default being set by
3446 // the system. Here reevaluate the default and default system
3447 // set flags. This would both fix corruption by the old impl
3448 // of step 142 and also properly handle devices which never
3449 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003450 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003451 SettingsState globalSettings = getGlobalSettingsLocked();
3452 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3453 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003454 }
3455
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003456 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3457 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3458 secureSettings.persistSyncLocked();
3459
3460 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3461 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3462 systemSettings.persistSyncLocked();
3463
Amin Shaikh86367962017-06-07 08:58:22 -07003464 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003465 }
3466
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003467 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003468 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3469 if (userId == UserHandle.USER_SYSTEM) {
3470 final SettingsState globalSettings = getGlobalSettingsLocked();
3471 final Setting currentSetting = globalSettings.getSettingLocked(
3472 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3473 if (currentSetting.getValue() == null) {
3474 final int defaultValue = getContext().getResources().getInteger(
3475 com.android.internal.R.integer.config_wifi_wakeup_available);
3476 globalSettings.insertSettingLocked(
3477 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3478 String.valueOf(defaultValue),
3479 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3480 }
3481 }
3482
3483 currentVersion = 147;
3484 }
3485
3486 if (currentVersion == 147) {
3487 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003488 if (userId == UserHandle.USER_SYSTEM) {
3489 final SettingsState globalSettings = getGlobalSettingsLocked();
3490 final Setting currentSetting = globalSettings.getSettingLocked(
3491 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3492 if (currentSetting.isNull()) {
3493 globalSettings.insertSettingLocked(
3494 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3495 getContext().getResources().getBoolean(
3496 R.bool.def_restrict_background_data) ? "1" : "0",
3497 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3498 }
3499 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003500 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003501 }
3502
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003503 if (currentVersion == 148) {
3504 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3505 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3506 final String oldValue = systemSecureSettings.getSettingLocked(
3507 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3508 if (TextUtils.equals(null, oldValue)) {
3509 final String defaultValue = getContext().getResources().getString(
3510 R.string.def_backup_manager_constants);
3511 if (!TextUtils.isEmpty(defaultValue)) {
3512 systemSecureSettings.insertSettingLocked(
3513 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3514 true, SettingsState.SYSTEM_PACKAGE_NAME);
3515 }
3516 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003517 currentVersion = 149;
3518 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003519
3520 if (currentVersion == 149) {
3521 // Version 150: Set a default value for mobile data always on
3522 final SettingsState globalSettings = getGlobalSettingsLocked();
3523 final Setting currentSetting = globalSettings.getSettingLocked(
3524 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3525 if (currentSetting.isNull()) {
3526 globalSettings.insertSettingLocked(
3527 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3528 getContext().getResources().getBoolean(
3529 R.bool.def_mobile_data_always_on) ? "1" : "0",
3530 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3531 }
3532
3533 currentVersion = 150;
3534 }
3535
Mike Digman4af4a6f2018-01-16 14:49:38 -08003536 if (currentVersion == 150) {
3537 // Version 151: Reset rotate locked setting for upgrading users
3538 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3539 systemSettings.insertSettingLocked(
3540 Settings.System.ACCELEROMETER_ROTATION,
3541 getContext().getResources().getBoolean(
3542 R.bool.def_accelerometer_rotation) ? "1" : "0",
3543 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3544
3545 currentVersion = 151;
3546 }
3547
Felipe Lemeff355092017-04-03 12:55:02 -07003548 // vXXX: Add new settings above this point.
3549
Dan Sandler71f85e92016-07-20 13:46:05 -04003550 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003551 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003552 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003553 + currentVersion +
3554 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3555 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003556 if (DEBUG) {
3557 throw new RuntimeException("db upgrade error");
3558 }
3559 }
3560
Jeff Brown503cffc2015-03-26 18:08:51 -07003561 // Return the current version.
3562 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003563 }
3564 }
Svet Ganov13701552017-02-23 12:45:17 -08003565
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003566 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3567 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003568 List<String> names = settings.getSettingNamesLocked();
3569 final int nameCount = names.size();
3570 for (int i = 0; i < nameCount; i++) {
3571 String name = names.get(i);
3572 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003573
3574 // In the upgrade case we pretend the call is made from the app
3575 // that made the last change to the setting to properly determine
3576 // whether the call has been made by a system component.
3577 int callingUid = -1;
3578 try {
3579 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3580 } catch (RemoteException e) {
3581 /* ignore - handled below */
3582 }
3583 if (callingUid < 0) {
3584 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3585 continue;
3586 }
3587 try {
3588 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3589 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003590 if (systemSet) {
3591 settings.insertSettingLocked(name, setting.getValue(),
3592 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003593 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3594 // We had a bug where changes by non-system packages were marked
3595 // as system made and as a result set as the default. Therefore, if
3596 // the package changed the setting last is not a system one but the
3597 // setting is marked as its default coming from the system we clear
3598 // the default and clear the system set flag.
3599 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003600 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003601 } catch (IllegalStateException e) {
3602 // If the package goes over its quota during the upgrade, don't
3603 // crash but just log the error as the system does the upgrade.
3604 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3605
Svet Ganov13701552017-02-23 12:45:17 -08003606 }
3607 }
3608 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003609 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003610}