blob: f4ec9366649068e24bfe061eb0263acdf6af0c9f [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 Brubakerf0fa8532017-02-23 10:45:20 -08001713 boolean instantApp;
1714 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1715 instantApp = false;
1716 } else {
1717 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
1718 instantApp = ai.isInstantApp();
1719 }
1720 if (instantApp) {
Todd Kennedybe0b8892017-02-15 14:13:52 -08001721 return new ArrayList<String>(getInstantAppAccessibleSettings(settingsType));
Chad Brubaker97bccee2017-01-05 15:51:41 -08001722 } else {
1723 return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
1724 }
1725 }
1726
Chad Brubakera6830e72017-04-28 17:34:36 -07001727 private void enforceSettingReadable(String settingName, int settingsType, int userId) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001728 if (UserHandle.getAppId(Binder.getCallingUid()) < Process.FIRST_APPLICATION_UID) {
1729 return;
1730 }
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001731 ApplicationInfo ai = getCallingApplicationInfoOrThrow();
Svetoslav Ganov096d3042017-01-30 16:34:13 -08001732 if (!ai.isInstantApp()) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001733 return;
1734 }
Chad Brubaker20e0dc32017-04-28 18:24:55 -07001735 if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
1736 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
Chad Brubaker97bccee2017-01-05 15:51:41 -08001737 throw new SecurityException("Setting " + settingName + " is not accessible from"
1738 + " ephemeral package " + getCallingPackage());
1739 }
1740 }
1741
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001742 private ApplicationInfo getCallingApplicationInfoOrThrow() {
1743 // We always use the callingUid for this lookup. This means that if hypothetically an
1744 // app was installed in user A with cross user and in user B as an Instant App
1745 // the app in A would be able to see all the settings in user B. However since cross
1746 // user is a system permission and the app must be uninstalled in B and then installed as
1747 // an Instant App that situation is not realistic or supported.
Chad Brubaker97bccee2017-01-05 15:51:41 -08001748 ApplicationInfo ai = null;
1749 try {
Chad Brubakerf0fa8532017-02-23 10:45:20 -08001750 ai = mPackageManager.getApplicationInfo(getCallingPackage(), 0
1751 , UserHandle.getCallingUserId());
Chad Brubaker97bccee2017-01-05 15:51:41 -08001752 } catch (RemoteException ignored) {
1753 }
1754 if (ai == null) {
1755 throw new IllegalStateException("Failed to lookup info for package "
1756 + getCallingPackage());
1757 }
1758 return ai;
1759 }
1760
Xiaohui Chen43765b72015-08-31 10:57:33 -07001761 private PackageInfo getCallingPackageInfoOrThrow(int userId) {
Svetoslav683914b2015-01-15 14:22:26 -08001762 try {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001763 PackageInfo packageInfo = mPackageManager.getPackageInfo(
1764 getCallingPackage(), 0, userId);
1765 if (packageInfo != null) {
1766 return packageInfo;
1767 }
Xiaohui Chen43765b72015-08-31 10:57:33 -07001768 } catch (RemoteException e) {
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001769 /* ignore */
Svetoslav683914b2015-01-15 14:22:26 -08001770 }
Svetoslav Ganov67a8d352016-03-02 13:26:40 -08001771 throw new IllegalStateException("Calling package doesn't exist");
Svetoslav683914b2015-01-15 14:22:26 -08001772 }
1773
1774 private int getGroupParentLocked(int userId) {
1775 // Most frequent use case.
Xiaohui Chen43765b72015-08-31 10:57:33 -07001776 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08001777 return userId;
1778 }
1779 // We are in the same process with the user manager and the returned
1780 // user info is a cached instance, so just look up instead of cache.
1781 final long identity = Binder.clearCallingIdentity();
1782 try {
Svetoslav7ec28e82015-05-20 17:01:10 -07001783 // Just a lookup and not reentrant, so holding a lock is fine.
Svetoslav683914b2015-01-15 14:22:26 -08001784 UserInfo userInfo = mUserManager.getProfileParent(userId);
1785 return (userInfo != null) ? userInfo.id : userId;
1786 } finally {
1787 Binder.restoreCallingIdentity(identity);
1788 }
1789 }
1790
Svetoslav683914b2015-01-15 14:22:26 -08001791 private void enforceWritePermission(String permission) {
1792 if (getContext().checkCallingOrSelfPermission(permission)
1793 != PackageManager.PERMISSION_GRANTED) {
1794 throw new SecurityException("Permission denial: writing to settings requires:"
1795 + permission);
1796 }
1797 }
1798
1799 /*
1800 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
1801 * This setting contains a list of the currently enabled location providers.
1802 * But helper functions in android.providers.Settings can enable or disable
1803 * a single provider by using a "+" or "-" prefix before the provider name.
1804 *
Makoto Onuki28da2e32015-11-20 11:30:44 -08001805 * <p>See also {@link #isGlobalOrSecureSettingRestrictedForUser()}. If DISALLOW_SHARE_LOCATION
1806 * is set, the said method will only allow values with the "-" prefix.
1807 *
Svetoslav683914b2015-01-15 14:22:26 -08001808 * @returns whether the enabled location providers changed.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001809 */
Svetoslav Ganove080da92016-12-21 17:10:35 -08001810 private boolean updateLocationProvidersAllowedLocked(String value, String tag,
1811 int owningUserId, boolean makeDefault, boolean forceNotify) {
Svetoslav683914b2015-01-15 14:22:26 -08001812 if (TextUtils.isEmpty(value)) {
1813 return false;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001814 }
1815
Svetoslav683914b2015-01-15 14:22:26 -08001816 final char prefix = value.charAt(0);
1817 if (prefix != '+' && prefix != '-') {
Svet Ganov53a441c2016-04-19 19:38:00 -07001818 if (forceNotify) {
1819 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1820 mSettingsRegistry.notifyForSettingsChange(key,
1821 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1822 }
Svetoslav683914b2015-01-15 14:22:26 -08001823 return false;
1824 }
1825
1826 // skip prefix
1827 value = value.substring(1);
1828
Svetoslav7ec28e82015-05-20 17:01:10 -07001829 Setting settingValue = getSecureSetting(
Chad Brubaker97bccee2017-01-05 15:51:41 -08001830 Settings.Secure.LOCATION_PROVIDERS_ALLOWED, owningUserId);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001831 if (settingValue == null) {
1832 return false;
1833 }
Svetoslav683914b2015-01-15 14:22:26 -08001834
Svetoslav Ganovcac64f62017-02-21 13:24:09 -08001835 String oldProviders = !settingValue.isNull() ? settingValue.getValue() : "";
Svetoslav683914b2015-01-15 14:22:26 -08001836
1837 int index = oldProviders.indexOf(value);
1838 int end = index + value.length();
1839
1840 // check for commas to avoid matching on partial string
1841 if (index > 0 && oldProviders.charAt(index - 1) != ',') {
1842 index = -1;
1843 }
1844
1845 // check for commas to avoid matching on partial string
1846 if (end < oldProviders.length() && oldProviders.charAt(end) != ',') {
1847 index = -1;
1848 }
1849
1850 String newProviders;
1851
1852 if (prefix == '+' && index < 0) {
1853 // append the provider to the list if not present
1854 if (oldProviders.length() == 0) {
1855 newProviders = value;
1856 } else {
1857 newProviders = oldProviders + ',' + value;
1858 }
1859 } else if (prefix == '-' && index >= 0) {
1860 // remove the provider from the list if present
1861 // remove leading or trailing comma
1862 if (index > 0) {
1863 index--;
1864 } else if (end < oldProviders.length()) {
1865 end++;
1866 }
1867
1868 newProviders = oldProviders.substring(0, index);
1869 if (end < oldProviders.length()) {
1870 newProviders += oldProviders.substring(end);
1871 }
1872 } else {
1873 // nothing changed, so no need to update the database
Svet Ganov53a441c2016-04-19 19:38:00 -07001874 if (forceNotify) {
1875 final int key = makeKey(SETTINGS_TYPE_SECURE, owningUserId);
1876 mSettingsRegistry.notifyForSettingsChange(key,
1877 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
1878 }
Svetoslav683914b2015-01-15 14:22:26 -08001879 return false;
1880 }
1881
Svet Ganov53a441c2016-04-19 19:38:00 -07001882 return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_SECURE,
Svetoslavb596a2c2015-02-17 21:37:09 -08001883 owningUserId, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, newProviders,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08001884 tag, makeDefault, getCallingPackage(), forceNotify, CRITICAL_SECURE_SETTINGS);
Svetoslav683914b2015-01-15 14:22:26 -08001885 }
1886
Svetoslav683914b2015-01-15 14:22:26 -08001887 private static void warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(
1888 int targetSdkVersion, String name) {
1889 // If the app targets Lollipop MR1 or older SDK we warn, otherwise crash.
1890 if (targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
1891 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1892 Slog.w(LOG_TAG, "You shouldn't not change private system settings."
1893 + " This will soon become an error.");
1894 } else {
1895 Slog.w(LOG_TAG, "You shouldn't keep your settings in the secure settings."
1896 + " This will soon become an error.");
1897 }
1898 } else {
1899 if (Settings.System.PRIVATE_SETTINGS.contains(name)) {
1900 throw new IllegalArgumentException("You cannot change private secure settings.");
1901 } else {
1902 throw new IllegalArgumentException("You cannot keep your settings in"
1903 + " the secure settings.");
1904 }
1905 }
1906 }
1907
1908 private static int resolveCallingUserIdEnforcingPermissionsLocked(int requestingUserId) {
1909 if (requestingUserId == UserHandle.getCallingUserId()) {
1910 return requestingUserId;
1911 }
1912 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1913 Binder.getCallingUid(), requestingUserId, false, true,
1914 "get/set setting for user", null);
1915 }
1916
Svet Ganov53a441c2016-04-19 19:38:00 -07001917 private Bundle packageValueForCallResult(Setting setting,
1918 boolean trackingGeneration) {
1919 if (!trackingGeneration) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07001920 if (setting == null || setting.isNull()) {
Svet Ganov53a441c2016-04-19 19:38:00 -07001921 return NULL_SETTING_BUNDLE;
1922 }
1923 return Bundle.forPair(Settings.NameValueTable.VALUE, setting.getValue());
Svetoslav683914b2015-01-15 14:22:26 -08001924 }
Svet Ganov53a441c2016-04-19 19:38:00 -07001925 Bundle result = new Bundle();
1926 result.putString(Settings.NameValueTable.VALUE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08001927 !setting.isNull() ? setting.getValue() : null);
Svet Ganov96c99462017-05-05 14:27:13 -07001928
Svetoslav Ganove080da92016-12-21 17:10:35 -08001929 mSettingsRegistry.mGenerationRegistry.addGenerationData(result, setting.getKey());
Svet Ganov53a441c2016-04-19 19:38:00 -07001930 return result;
Svetoslav683914b2015-01-15 14:22:26 -08001931 }
1932
1933 private static int getRequestingUserId(Bundle args) {
1934 final int callingUserId = UserHandle.getCallingUserId();
1935 return (args != null) ? args.getInt(Settings.CALL_METHOD_USER_KEY, callingUserId)
1936 : callingUserId;
1937 }
1938
Svet Ganov53a441c2016-04-19 19:38:00 -07001939 private boolean isTrackingGeneration(Bundle args) {
1940 return args != null && args.containsKey(Settings.CALL_METHOD_TRACK_GENERATION_KEY);
1941 }
1942
Svetoslav683914b2015-01-15 14:22:26 -08001943 private static String getSettingValue(Bundle args) {
1944 return (args != null) ? args.getString(Settings.NameValueTable.VALUE) : null;
1945 }
1946
Svetoslav Ganove080da92016-12-21 17:10:35 -08001947 private static String getSettingTag(Bundle args) {
1948 return (args != null) ? args.getString(Settings.CALL_METHOD_TAG_KEY) : null;
1949 }
1950
1951 private static boolean getSettingMakeDefault(Bundle args) {
1952 return (args != null) && args.getBoolean(Settings.CALL_METHOD_MAKE_DEFAULT_KEY);
1953 }
1954
1955 private static int getResetModeEnforcingPermission(Bundle args) {
1956 final int mode = (args != null) ? args.getInt(Settings.CALL_METHOD_RESET_MODE_KEY) : 0;
1957 switch (mode) {
1958 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
1959 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1960 throw new SecurityException("Only system, shell/root on a "
1961 + "debuggable build can reset to untrusted defaults");
1962 }
1963 return mode;
1964 }
1965 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
1966 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1967 throw new SecurityException("Only system, shell/root on a "
1968 + "debuggable build can reset untrusted changes");
1969 }
1970 return mode;
1971 }
1972 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
1973 if (!isCallerSystemOrShellOrRootOnDebuggableBuild()) {
1974 throw new SecurityException("Only system, shell/root on a "
1975 + "debuggable build can reset to trusted defaults");
1976 }
1977 return mode;
1978 }
1979 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
1980 return mode;
1981 }
1982 }
1983 throw new IllegalArgumentException("Invalid reset mode: " + mode);
1984 }
1985
1986 private static boolean isCallerSystemOrShellOrRootOnDebuggableBuild() {
1987 final int appId = UserHandle.getAppId(Binder.getCallingUid());
1988 return appId == SYSTEM_UID || (Build.IS_DEBUGGABLE
1989 && (appId == SHELL_UID || appId == ROOT_UID));
1990 }
1991
Svetoslav683914b2015-01-15 14:22:26 -08001992 private static String getValidTableOrThrow(Uri uri) {
1993 if (uri.getPathSegments().size() > 0) {
1994 String table = uri.getPathSegments().get(0);
1995 if (DatabaseHelper.isValidTable(table)) {
1996 return table;
1997 }
1998 throw new IllegalArgumentException("Bad root path: " + table);
1999 }
2000 throw new IllegalArgumentException("Invalid URI:" + uri);
2001 }
2002
2003 private static MatrixCursor packageSettingForQuery(Setting setting, String[] projection) {
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07002004 if (setting.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002005 return new MatrixCursor(projection, 0);
2006 }
2007 MatrixCursor cursor = new MatrixCursor(projection, 1);
2008 appendSettingToCursor(cursor, setting);
2009 return cursor;
2010 }
2011
2012 private static String[] normalizeProjection(String[] projection) {
2013 if (projection == null) {
2014 return ALL_COLUMNS;
2015 }
2016
2017 final int columnCount = projection.length;
2018 for (int i = 0; i < columnCount; i++) {
2019 String column = projection[i];
2020 if (!ArrayUtils.contains(ALL_COLUMNS, column)) {
2021 throw new IllegalArgumentException("Invalid column: " + column);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002022 }
2023 }
2024
Svetoslav683914b2015-01-15 14:22:26 -08002025 return projection;
2026 }
2027
2028 private static void appendSettingToCursor(MatrixCursor cursor, Setting setting) {
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002029 if (setting == null || setting.isNull()) {
Suprabh Shuklac9d064a2016-04-12 18:45:34 -07002030 return;
2031 }
Svetoslav683914b2015-01-15 14:22:26 -08002032 final int columnCount = cursor.getColumnCount();
2033
2034 String[] values = new String[columnCount];
2035
2036 for (int i = 0; i < columnCount; i++) {
2037 String column = cursor.getColumnName(i);
2038
2039 switch (column) {
2040 case Settings.NameValueTable._ID: {
2041 values[i] = setting.getId();
2042 } break;
2043
2044 case Settings.NameValueTable.NAME: {
2045 values[i] = setting.getName();
2046 } break;
2047
2048 case Settings.NameValueTable.VALUE: {
2049 values[i] = setting.getValue();
2050 } break;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002051 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002052 }
2053
Svetoslav683914b2015-01-15 14:22:26 -08002054 cursor.addRow(values);
2055 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002056
Makoto Onuki3a2c35782015-06-18 11:21:58 -07002057 private static boolean isKeyValid(String key) {
2058 return !(TextUtils.isEmpty(key) || SettingsState.isBinary(key));
2059 }
2060
Svetoslav683914b2015-01-15 14:22:26 -08002061 private static final class Arguments {
2062 private static final Pattern WHERE_PATTERN_WITH_PARAM_NO_BRACKETS =
2063 Pattern.compile("[\\s]*name[\\s]*=[\\s]*\\?[\\s]*");
2064
2065 private static final Pattern WHERE_PATTERN_WITH_PARAM_IN_BRACKETS =
2066 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*\\?[\\s]*\\)[\\s]*");
2067
2068 private static final Pattern WHERE_PATTERN_NO_PARAM_IN_BRACKETS =
2069 Pattern.compile("[\\s]*\\([\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*\\)[\\s]*");
2070
2071 private static final Pattern WHERE_PATTERN_NO_PARAM_NO_BRACKETS =
2072 Pattern.compile("[\\s]*name[\\s]*=[\\s]*['\"].*['\"][\\s]*");
2073
2074 public final String table;
2075 public final String name;
2076
2077 public Arguments(Uri uri, String where, String[] whereArgs, boolean supportAll) {
2078 final int segmentSize = uri.getPathSegments().size();
2079 switch (segmentSize) {
2080 case 1: {
2081 if (where != null
2082 && (WHERE_PATTERN_WITH_PARAM_NO_BRACKETS.matcher(where).matches()
2083 || WHERE_PATTERN_WITH_PARAM_IN_BRACKETS.matcher(where).matches())
2084 && whereArgs.length == 1) {
2085 name = whereArgs[0];
2086 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002087 return;
Svetoslav683914b2015-01-15 14:22:26 -08002088 } else if (where != null
2089 && (WHERE_PATTERN_NO_PARAM_NO_BRACKETS.matcher(where).matches()
2090 || WHERE_PATTERN_NO_PARAM_IN_BRACKETS.matcher(where).matches())) {
2091 final int startIndex = Math.max(where.indexOf("'"),
2092 where.indexOf("\"")) + 1;
2093 final int endIndex = Math.max(where.lastIndexOf("'"),
2094 where.lastIndexOf("\""));
2095 name = where.substring(startIndex, endIndex);
2096 table = computeTableForSetting(uri, name);
Svetoslav28494652015-02-12 14:11:42 -08002097 return;
Svetoslav683914b2015-01-15 14:22:26 -08002098 } else if (supportAll && where == null && whereArgs == null) {
2099 name = null;
2100 table = computeTableForSetting(uri, null);
Svetoslav28494652015-02-12 14:11:42 -08002101 return;
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002102 }
Svetoslav683914b2015-01-15 14:22:26 -08002103 } break;
2104
Svetoslav28494652015-02-12 14:11:42 -08002105 case 2: {
2106 if (where == null && whereArgs == null) {
2107 name = uri.getPathSegments().get(1);
2108 table = computeTableForSetting(uri, name);
2109 return;
2110 }
2111 } break;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002112 }
Svetoslav28494652015-02-12 14:11:42 -08002113
2114 EventLogTags.writeUnsupportedSettingsQuery(
2115 uri.toSafeString(), where, Arrays.toString(whereArgs));
2116 String message = String.format( "Supported SQL:\n"
2117 + " uri content://some_table/some_property with null where and where args\n"
2118 + " uri content://some_table with query name=? and single name as arg\n"
2119 + " uri content://some_table with query name=some_name and null args\n"
2120 + " but got - uri:%1s, where:%2s whereArgs:%3s", uri, where,
2121 Arrays.toString(whereArgs));
2122 throw new IllegalArgumentException(message);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002123 }
2124
Svetoslav28494652015-02-12 14:11:42 -08002125 private static String computeTableForSetting(Uri uri, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002126 String table = getValidTableOrThrow(uri);
2127
2128 if (name != null) {
2129 if (sSystemMovedToSecureSettings.contains(name)) {
2130 table = TABLE_SECURE;
2131 }
2132
2133 if (sSystemMovedToGlobalSettings.contains(name)) {
2134 table = TABLE_GLOBAL;
2135 }
2136
2137 if (sSecureMovedToGlobalSettings.contains(name)) {
2138 table = TABLE_GLOBAL;
2139 }
2140
2141 if (sGlobalMovedToSecureSettings.contains(name)) {
2142 table = TABLE_SECURE;
2143 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002144 }
Svetoslav683914b2015-01-15 14:22:26 -08002145
2146 return table;
2147 }
2148 }
2149
2150 final class SettingsRegistry {
2151 private static final String DROPBOX_TAG_USERLOG = "restricted_profile_ssaid";
2152
Svetoslav683914b2015-01-15 14:22:26 -08002153 private static final String SETTINGS_FILE_GLOBAL = "settings_global.xml";
2154 private static final String SETTINGS_FILE_SYSTEM = "settings_system.xml";
2155 private static final String SETTINGS_FILE_SECURE = "settings_secure.xml";
Mark Rathjend891f012017-01-19 04:10:37 +00002156 private static final String SETTINGS_FILE_SSAID = "settings_ssaid.xml";
2157
2158 private static final String SSAID_USER_KEY = "userkey";
Svetoslav683914b2015-01-15 14:22:26 -08002159
2160 private final SparseArray<SettingsState> mSettingsStates = new SparseArray<>();
2161
Svet Ganov53a441c2016-04-19 19:38:00 -07002162 private GenerationRegistry mGenerationRegistry;
Svetoslav683914b2015-01-15 14:22:26 -08002163
Svetoslav7e0683b2015-08-03 16:02:52 -07002164 private final Handler mHandler;
2165
Svet Ganov53a441c2016-04-19 19:38:00 -07002166 private final BackupManager mBackupManager;
2167
Amith Yamasani39452022017-03-21 15:23:47 -07002168 private String mSettingsCreationBuildId;
2169
Svetoslav683914b2015-01-15 14:22:26 -08002170 public SettingsRegistry() {
Svetoslav7e0683b2015-08-03 16:02:52 -07002171 mHandler = new MyHandler(getContext().getMainLooper());
Svet Ganov53a441c2016-04-19 19:38:00 -07002172 mGenerationRegistry = new GenerationRegistry(mLock);
2173 mBackupManager = new BackupManager(getContext());
Svetoslav683914b2015-01-15 14:22:26 -08002174 migrateAllLegacySettingsIfNeeded();
Mark Rathjend891f012017-01-19 04:10:37 +00002175 syncSsaidTableOnStart();
2176 }
2177
2178 private void generateUserKeyLocked(int userId) {
2179 // Generate a random key for each user used for creating a new ssaid.
Mark Rathjen7599f132017-01-23 14:15:54 -08002180 final byte[] keyBytes = new byte[32];
Mark Rathjend891f012017-01-19 04:10:37 +00002181 final SecureRandom rand = new SecureRandom();
2182 rand.nextBytes(keyBytes);
2183
2184 // Convert to string for storage in settings table.
Mark Rathjen7599f132017-01-23 14:15:54 -08002185 final String userKey = ByteStringUtils.toHexString(keyBytes);
Mark Rathjend891f012017-01-19 04:10:37 +00002186
2187 // Store the key in the ssaid table.
2188 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2189 final boolean success = ssaidSettings.insertSettingLocked(SSAID_USER_KEY, userKey, null,
2190 true, SettingsState.SYSTEM_PACKAGE_NAME);
2191
2192 if (!success) {
2193 throw new IllegalStateException("Ssaid settings not accessible");
2194 }
2195 }
2196
Mark Rathjen7599f132017-01-23 14:15:54 -08002197 private byte[] getLengthPrefix(byte[] data) {
2198 return ByteBuffer.allocate(4).putInt(data.length).array();
2199 }
2200
Christopher Tateb218e762017-04-05 16:34:07 -07002201 public Setting generateSsaidLocked(PackageInfo callingPkg, int userId) {
Mark Rathjend891f012017-01-19 04:10:37 +00002202 // Read the user's key from the ssaid table.
2203 Setting userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002204 if (userKeySetting == null || userKeySetting.isNull()
2205 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002206 // Lazy initialize and store the user key.
2207 generateUserKeyLocked(userId);
2208 userKeySetting = getSettingLocked(SETTINGS_TYPE_SSAID, userId, SSAID_USER_KEY);
Mark Rathjenea617592017-01-18 23:03:41 -08002209 if (userKeySetting == null || userKeySetting.isNull()
2210 || userKeySetting.getValue() == null) {
Mark Rathjend891f012017-01-19 04:10:37 +00002211 throw new IllegalStateException("User key not accessible");
2212 }
2213 }
2214 final String userKey = userKeySetting.getValue();
2215
2216 // Convert the user's key back to a byte array.
Mark Rathjen7599f132017-01-23 14:15:54 -08002217 final byte[] keyBytes = ByteStringUtils.fromHexToByteArray(userKey);
2218
2219 // Validate that the key is of expected length.
2220 // Keys are currently 32 bytes, but were once 16 bytes during Android O development.
2221 if (keyBytes == null || (keyBytes.length != 16 && keyBytes.length != 32)) {
Mark Rathjend891f012017-01-19 04:10:37 +00002222 throw new IllegalStateException("User key invalid");
2223 }
2224
Mark Rathjen7599f132017-01-23 14:15:54 -08002225 final Mac m;
Mark Rathjend891f012017-01-19 04:10:37 +00002226 try {
Mark Rathjen7599f132017-01-23 14:15:54 -08002227 m = Mac.getInstance("HmacSHA256");
2228 m.init(new SecretKeySpec(keyBytes, m.getAlgorithm()));
Mark Rathjend891f012017-01-19 04:10:37 +00002229 } catch (NoSuchAlgorithmException e) {
Mark Rathjen7599f132017-01-23 14:15:54 -08002230 throw new IllegalStateException("HmacSHA256 is not available", e);
2231 } catch (InvalidKeyException e) {
2232 throw new IllegalStateException("Key is corrupted", e);
Mark Rathjend891f012017-01-19 04:10:37 +00002233 }
Mark Rathjen7599f132017-01-23 14:15:54 -08002234
Mark Rathjenf42dd912017-06-05 19:04:34 -07002235 // Mac each of the developer signatures.
Christopher Tateb218e762017-04-05 16:34:07 -07002236 for (int i = 0; i < callingPkg.signatures.length; i++) {
2237 byte[] sig = callingPkg.signatures[i].toByteArray();
Mark Rathjen7599f132017-01-23 14:15:54 -08002238 m.update(getLengthPrefix(sig), 0, 4);
2239 m.update(sig);
2240 }
Mark Rathjend891f012017-01-19 04:10:37 +00002241
2242 // Convert result to a string for storage in settings table. Only want first 64 bits.
Mark Rathjen7599f132017-01-23 14:15:54 -08002243 final String ssaid = ByteStringUtils.toHexString(m.doFinal()).substring(0, 16)
2244 .toLowerCase(Locale.US);
Mark Rathjend891f012017-01-19 04:10:37 +00002245
2246 // Save the ssaid in the ssaid table.
Christopher Tateb218e762017-04-05 16:34:07 -07002247 final String uid = Integer.toString(callingPkg.applicationInfo.uid);
Mark Rathjend891f012017-01-19 04:10:37 +00002248 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
2249 final boolean success = ssaidSettings.insertSettingLocked(uid, ssaid, null, true,
Mark Rathjenf42dd912017-06-05 19:04:34 -07002250 callingPkg.packageName);
Mark Rathjend891f012017-01-19 04:10:37 +00002251
2252 if (!success) {
2253 throw new IllegalStateException("Ssaid settings not accessible");
2254 }
2255
2256 return getSettingLocked(SETTINGS_TYPE_SSAID, userId, uid);
2257 }
2258
2259 public void syncSsaidTableOnStart() {
2260 synchronized (mLock) {
2261 // Verify that each user's packages and ssaid's are in sync.
2262 for (UserInfo user : mUserManager.getUsers(true)) {
2263 // Get all uids for the user's packages.
2264 final List<PackageInfo> packages;
2265 try {
2266 packages = mPackageManager.getInstalledPackages(0, user.id).getList();
2267 } catch (RemoteException e) {
2268 throw new IllegalStateException("Package manager not available");
2269 }
2270 final Set<String> appUids = new HashSet<>();
2271 for (PackageInfo info : packages) {
2272 appUids.add(Integer.toString(info.applicationInfo.uid));
2273 }
2274
2275 // Get all uids currently stored in the user's ssaid table.
2276 final Set<String> ssaidUids = new HashSet<>(
2277 getSettingsNamesLocked(SETTINGS_TYPE_SSAID, user.id));
2278 ssaidUids.remove(SSAID_USER_KEY);
2279
2280 // Perform a set difference for the appUids and ssaidUids.
2281 ssaidUids.removeAll(appUids);
2282
2283 // If there are ssaidUids left over they need to be removed from the table.
2284 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2285 user.id);
2286 for (String uid : ssaidUids) {
2287 ssaidSettings.deleteSettingLocked(uid);
2288 }
2289 }
2290 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07002291 }
2292
Svetoslav683914b2015-01-15 14:22:26 -08002293 public List<String> getSettingsNamesLocked(int type, int userId) {
2294 final int key = makeKey(type, userId);
2295 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002296 if (settingsState == null) {
2297 return new ArrayList<String>();
2298 }
Svetoslav683914b2015-01-15 14:22:26 -08002299 return settingsState.getSettingNamesLocked();
2300 }
2301
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002302 public SparseBooleanArray getKnownUsersLocked() {
2303 SparseBooleanArray users = new SparseBooleanArray();
2304 for (int i = mSettingsStates.size()-1; i >= 0; i--) {
2305 users.put(getUserIdFromKey(mSettingsStates.keyAt(i)), true);
2306 }
2307 return users;
2308 }
2309
Kweku Adamsb0886f32017-10-31 15:32:09 -07002310 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002311 public SettingsState getSettingsLocked(int type, int userId) {
2312 final int key = makeKey(type, userId);
2313 return peekSettingsStateLocked(key);
2314 }
2315
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002316 public boolean ensureSettingsForUserLocked(int userId) {
2317 // First make sure this user actually exists.
2318 if (mUserManager.getUserInfo(userId) == null) {
2319 Slog.wtf(LOG_TAG, "Requested user " + userId + " does not exist");
2320 return false;
2321 }
2322
Svetoslav683914b2015-01-15 14:22:26 -08002323 // Migrate the setting for this user if needed.
2324 migrateLegacySettingsForUserIfNeededLocked(userId);
2325
2326 // Ensure global settings loaded if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002327 if (userId == UserHandle.USER_SYSTEM) {
2328 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002329 ensureSettingsStateLocked(globalKey);
2330 }
2331
2332 // Ensure secure settings loaded.
2333 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2334 ensureSettingsStateLocked(secureKey);
2335
2336 // Make sure the secure settings have an Android id set.
2337 SettingsState secureSettings = getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
2338 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2339
2340 // Ensure system settings loaded.
2341 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2342 ensureSettingsStateLocked(systemKey);
2343
Mark Rathjend891f012017-01-19 04:10:37 +00002344 // Ensure secure settings loaded.
2345 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2346 ensureSettingsStateLocked(ssaidKey);
2347
Svetoslav683914b2015-01-15 14:22:26 -08002348 // Upgrade the settings to the latest version.
2349 UpgradeController upgrader = new UpgradeController(userId);
2350 upgrader.upgradeIfNeededLocked();
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002351 return true;
Svetoslav683914b2015-01-15 14:22:26 -08002352 }
2353
2354 private void ensureSettingsStateLocked(int key) {
2355 if (mSettingsStates.get(key) == null) {
2356 final int maxBytesPerPackage = getMaxBytesPerPackageForType(getTypeFromKey(key));
Svetoslav Ganove080da92016-12-21 17:10:35 -08002357 SettingsState settingsState = new SettingsState(getContext(), mLock,
2358 getSettingsFile(key), key, maxBytesPerPackage, mHandlerThread.getLooper());
Svetoslav683914b2015-01-15 14:22:26 -08002359 mSettingsStates.put(key, settingsState);
2360 }
2361 }
2362
2363 public void removeUserStateLocked(int userId, boolean permanently) {
2364 // We always keep the global settings in memory.
2365
2366 // Nuke system settings.
2367 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2368 final SettingsState systemSettingsState = mSettingsStates.get(systemKey);
2369 if (systemSettingsState != null) {
2370 if (permanently) {
2371 mSettingsStates.remove(systemKey);
2372 systemSettingsState.destroyLocked(null);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002373 } else {
Svetoslav683914b2015-01-15 14:22:26 -08002374 systemSettingsState.destroyLocked(new Runnable() {
2375 @Override
2376 public void run() {
2377 mSettingsStates.remove(systemKey);
2378 }
2379 });
2380 }
2381 }
2382
2383 // Nuke secure settings.
2384 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2385 final SettingsState secureSettingsState = mSettingsStates.get(secureKey);
2386 if (secureSettingsState != null) {
2387 if (permanently) {
2388 mSettingsStates.remove(secureKey);
2389 secureSettingsState.destroyLocked(null);
2390 } else {
2391 secureSettingsState.destroyLocked(new Runnable() {
2392 @Override
2393 public void run() {
2394 mSettingsStates.remove(secureKey);
2395 }
2396 });
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08002397 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002398 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002399
Mark Rathjend891f012017-01-19 04:10:37 +00002400 // Nuke ssaid settings.
2401 final int ssaidKey = makeKey(SETTINGS_TYPE_SSAID, userId);
2402 final SettingsState ssaidSettingsState = mSettingsStates.get(ssaidKey);
2403 if (ssaidSettingsState != null) {
2404 if (permanently) {
2405 mSettingsStates.remove(ssaidKey);
2406 ssaidSettingsState.destroyLocked(null);
2407 } else {
2408 ssaidSettingsState.destroyLocked(new Runnable() {
2409 @Override
2410 public void run() {
2411 mSettingsStates.remove(ssaidKey);
2412 }
2413 });
2414 }
2415 }
2416
Svet Ganov53a441c2016-04-19 19:38:00 -07002417 // Nuke generation tracking data
2418 mGenerationRegistry.onUserRemoved(userId);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08002419 }
2420
Svetoslav683914b2015-01-15 14:22:26 -08002421 public boolean insertSettingLocked(int type, int userId, String name, String value,
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002422 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2423 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002424 final int key = makeKey(type, userId);
2425
Svetoslav Ganove080da92016-12-21 17:10:35 -08002426 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002427 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002428 if (settingsState != null) {
2429 success = settingsState.insertSettingLocked(name, value,
2430 tag, makeDefault, packageName);
2431 }
Svetoslav683914b2015-01-15 14:22:26 -08002432
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002433 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2434 settingsState.persistSyncLocked();
2435 }
2436
Svet Ganov53a441c2016-04-19 19:38:00 -07002437 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002438 notifyForSettingsChange(key, name);
2439 }
2440 return success;
2441 }
2442
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002443 public boolean deleteSettingLocked(int type, int userId, String name, boolean forceNotify,
2444 Set<String> criticalSettings) {
Svetoslav683914b2015-01-15 14:22:26 -08002445 final int key = makeKey(type, userId);
2446
Svetoslav Ganove080da92016-12-21 17:10:35 -08002447 boolean success = false;
Svetoslav683914b2015-01-15 14:22:26 -08002448 SettingsState settingsState = peekSettingsStateLocked(key);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002449 if (settingsState != null) {
2450 success = settingsState.deleteSettingLocked(name);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002451 }
Svetoslav683914b2015-01-15 14:22:26 -08002452
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002453 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2454 settingsState.persistSyncLocked();
2455 }
2456
Svet Ganov53a441c2016-04-19 19:38:00 -07002457 if (forceNotify || success) {
Svetoslav683914b2015-01-15 14:22:26 -08002458 notifyForSettingsChange(key, name);
2459 }
2460 return success;
2461 }
2462
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002463 public boolean updateSettingLocked(int type, int userId, String name, String value,
2464 String tag, boolean makeDefault, String packageName, boolean forceNotify,
2465 Set<String> criticalSettings) {
2466 final int key = makeKey(type, userId);
2467
2468 boolean success = false;
2469 SettingsState settingsState = peekSettingsStateLocked(key);
2470 if (settingsState != null) {
2471 success = settingsState.updateSettingLocked(name, value, tag,
2472 makeDefault, packageName);
2473 }
2474
2475 if (success && criticalSettings != null && criticalSettings.contains(name)) {
2476 settingsState.persistSyncLocked();
2477 }
2478
2479 if (forceNotify || success) {
2480 notifyForSettingsChange(key, name);
2481 }
2482
2483 return success;
2484 }
2485
Svetoslav683914b2015-01-15 14:22:26 -08002486 public Setting getSettingLocked(int type, int userId, String name) {
2487 final int key = makeKey(type, userId);
2488
2489 SettingsState settingsState = peekSettingsStateLocked(key);
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002490 if (settingsState == null) {
Mark Rathjenea617592017-01-18 23:03:41 -08002491 return null;
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002492 }
Mark Rathjend891f012017-01-19 04:10:37 +00002493
2494 // getSettingLocked will return non-null result
Svetoslav683914b2015-01-15 14:22:26 -08002495 return settingsState.getSettingLocked(name);
2496 }
2497
Svetoslav Ganove080da92016-12-21 17:10:35 -08002498 public void resetSettingsLocked(int type, int userId, String packageName, int mode,
2499 String tag) {
2500 final int key = makeKey(type, userId);
2501 SettingsState settingsState = peekSettingsStateLocked(key);
2502 if (settingsState == null) {
2503 return;
2504 }
2505
2506 switch (mode) {
2507 case Settings.RESET_MODE_PACKAGE_DEFAULTS: {
2508 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002509 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002510 Setting setting = settingsState.getSettingLocked(name);
2511 if (packageName.equals(setting.getPackageName())) {
2512 if (tag != null && !tag.equals(setting.getTag())) {
2513 continue;
2514 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002515 if (settingsState.resetSettingLocked(name)) {
2516 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002517 notifyForSettingsChange(key, name);
2518 }
2519 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002520 if (someSettingChanged) {
2521 settingsState.persistSyncLocked();
2522 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002523 }
2524 } break;
2525
2526 case Settings.RESET_MODE_UNTRUSTED_DEFAULTS: {
2527 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002528 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002529 Setting setting = settingsState.getSettingLocked(name);
2530 if (!SettingsState.isSystemPackage(getContext(),
2531 setting.getPackageName())) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002532 if (settingsState.resetSettingLocked(name)) {
2533 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002534 notifyForSettingsChange(key, name);
2535 }
2536 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002537 if (someSettingChanged) {
2538 settingsState.persistSyncLocked();
2539 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002540 }
2541 } break;
2542
2543 case Settings.RESET_MODE_UNTRUSTED_CHANGES: {
2544 for (String name : settingsState.getSettingNamesLocked()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002545 boolean someSettingChanged = false;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002546 Setting setting = settingsState.getSettingLocked(name);
2547 if (!SettingsState.isSystemPackage(getContext(),
2548 setting.getPackageName())) {
Eugene Suslad72c3972016-12-27 15:49:30 -08002549 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002550 if (settingsState.resetSettingLocked(name)) {
2551 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002552 notifyForSettingsChange(key, name);
2553 }
2554 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002555 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002556 notifyForSettingsChange(key, name);
2557 }
2558 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002559 if (someSettingChanged) {
2560 settingsState.persistSyncLocked();
2561 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002562 }
2563 } break;
2564
2565 case Settings.RESET_MODE_TRUSTED_DEFAULTS: {
2566 for (String name : settingsState.getSettingNamesLocked()) {
2567 Setting setting = settingsState.getSettingLocked(name);
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002568 boolean someSettingChanged = false;
Eugene Suslad72c3972016-12-27 15:49:30 -08002569 if (setting.isDefaultFromSystem()) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002570 if (settingsState.resetSettingLocked(name)) {
2571 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002572 notifyForSettingsChange(key, name);
2573 }
2574 } else if (settingsState.deleteSettingLocked(name)) {
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002575 someSettingChanged = true;
Svetoslav Ganove080da92016-12-21 17:10:35 -08002576 notifyForSettingsChange(key, name);
2577 }
Svetoslav Ganov5fb405b2017-01-26 22:43:09 -08002578 if (someSettingChanged) {
2579 settingsState.persistSyncLocked();
2580 }
Svetoslav Ganove080da92016-12-21 17:10:35 -08002581 }
2582 } break;
2583 }
2584 }
2585
Svetoslav683914b2015-01-15 14:22:26 -08002586 public void onPackageRemovedLocked(String packageName, int userId) {
Svet Ganov8de34802015-04-27 09:33:40 -07002587 // Global and secure settings are signature protected. Apps signed
2588 // by the platform certificate are generally not uninstalled and
2589 // the main exception is tests. We trust components signed
2590 // by the platform certificate and do not do a clean up after them.
Svetoslav683914b2015-01-15 14:22:26 -08002591
2592 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2593 SettingsState systemSettings = mSettingsStates.get(systemKey);
Svet Ganov8de34802015-04-27 09:33:40 -07002594 if (systemSettings != null) {
2595 systemSettings.onPackageRemovedLocked(packageName);
2596 }
Svetoslav683914b2015-01-15 14:22:26 -08002597 }
2598
Mark Rathjend891f012017-01-19 04:10:37 +00002599 public void onUidRemovedLocked(int uid) {
2600 final SettingsState ssaidSettings = getSettingsLocked(SETTINGS_TYPE_SSAID,
2601 UserHandle.getUserId(uid));
2602 ssaidSettings.deleteSettingLocked(Integer.toString(uid));
2603 }
2604
Kweku Adamsb0886f32017-10-31 15:32:09 -07002605 @Nullable
Svetoslav683914b2015-01-15 14:22:26 -08002606 private SettingsState peekSettingsStateLocked(int key) {
2607 SettingsState settingsState = mSettingsStates.get(key);
2608 if (settingsState != null) {
2609 return settingsState;
2610 }
2611
Dianne Hackborn32f40ee2016-10-20 15:54:14 -07002612 if (!ensureSettingsForUserLocked(getUserIdFromKey(key))) {
2613 return null;
2614 }
Svetoslav683914b2015-01-15 14:22:26 -08002615 return mSettingsStates.get(key);
2616 }
2617
2618 private void migrateAllLegacySettingsIfNeeded() {
2619 synchronized (mLock) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07002620 final int key = makeKey(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08002621 File globalFile = getSettingsFile(key);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002622 if (SettingsState.stateFileExists(globalFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002623 return;
2624 }
2625
Amith Yamasani39452022017-03-21 15:23:47 -07002626 mSettingsCreationBuildId = Build.ID;
2627
Svetoslav683914b2015-01-15 14:22:26 -08002628 final long identity = Binder.clearCallingIdentity();
2629 try {
2630 List<UserInfo> users = mUserManager.getUsers(true);
2631
2632 final int userCount = users.size();
2633 for (int i = 0; i < userCount; i++) {
2634 final int userId = users.get(i).id;
2635
2636 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2637 SQLiteDatabase database = dbHelper.getWritableDatabase();
2638 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2639
2640 // Upgrade to the latest version.
2641 UpgradeController upgrader = new UpgradeController(userId);
2642 upgrader.upgradeIfNeededLocked();
2643
2644 // Drop from memory if not a running user.
2645 if (!mUserManager.isUserRunning(new UserHandle(userId))) {
2646 removeUserStateLocked(userId, false);
2647 }
2648 }
2649 } finally {
2650 Binder.restoreCallingIdentity(identity);
2651 }
2652 }
2653 }
2654
2655 private void migrateLegacySettingsForUserIfNeededLocked(int userId) {
2656 // Every user has secure settings and if no file we need to migrate.
2657 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2658 File secureFile = getSettingsFile(secureKey);
Amith Yamasani74bf71b2017-07-19 16:49:52 -07002659 if (SettingsState.stateFileExists(secureFile)) {
Svetoslav683914b2015-01-15 14:22:26 -08002660 return;
2661 }
2662
2663 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), userId);
2664 SQLiteDatabase database = dbHelper.getWritableDatabase();
2665
2666 migrateLegacySettingsForUserLocked(dbHelper, database, userId);
2667 }
2668
2669 private void migrateLegacySettingsForUserLocked(DatabaseHelper dbHelper,
2670 SQLiteDatabase database, int userId) {
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002671 // Move over the system settings.
2672 final int systemKey = makeKey(SETTINGS_TYPE_SYSTEM, userId);
2673 ensureSettingsStateLocked(systemKey);
2674 SettingsState systemSettings = mSettingsStates.get(systemKey);
2675 migrateLegacySettingsLocked(systemSettings, database, TABLE_SYSTEM);
2676 systemSettings.persistSyncLocked();
Svetoslav683914b2015-01-15 14:22:26 -08002677
2678 // Move over the secure settings.
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002679 // Do this after System settings, since this is the first thing we check when deciding
2680 // to skip over migration from db to xml for a secondary user.
Svetoslav683914b2015-01-15 14:22:26 -08002681 final int secureKey = makeKey(SETTINGS_TYPE_SECURE, userId);
2682 ensureSettingsStateLocked(secureKey);
2683 SettingsState secureSettings = mSettingsStates.get(secureKey);
2684 migrateLegacySettingsLocked(secureSettings, database, TABLE_SECURE);
2685 ensureSecureSettingAndroidIdSetLocked(secureSettings);
2686 secureSettings.persistSyncLocked();
2687
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002688 // Move over the global settings if owner.
2689 // Do this last, since this is the first thing we check when deciding
2690 // to skip over migration from db to xml for owner user.
2691 if (userId == UserHandle.USER_SYSTEM) {
2692 final int globalKey = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2693 ensureSettingsStateLocked(globalKey);
2694 SettingsState globalSettings = mSettingsStates.get(globalKey);
2695 migrateLegacySettingsLocked(globalSettings, database, TABLE_GLOBAL);
Amith Yamasani39452022017-03-21 15:23:47 -07002696 // If this was just created
2697 if (mSettingsCreationBuildId != null) {
2698 globalSettings.insertSettingLocked(Settings.Global.DATABASE_CREATION_BUILDID,
2699 mSettingsCreationBuildId, null, true,
2700 SettingsState.SYSTEM_PACKAGE_NAME);
2701 }
Amith Yamasanibf2ef612016-03-07 16:37:18 -08002702 globalSettings.persistSyncLocked();
2703 }
Svetoslav683914b2015-01-15 14:22:26 -08002704
2705 // Drop the database as now all is moved and persisted.
2706 if (DROP_DATABASE_ON_MIGRATION) {
2707 dbHelper.dropDatabase();
2708 } else {
2709 dbHelper.backupDatabase();
2710 }
2711 }
2712
2713 private void migrateLegacySettingsLocked(SettingsState settingsState,
2714 SQLiteDatabase database, String table) {
2715 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
2716 queryBuilder.setTables(table);
2717
2718 Cursor cursor = queryBuilder.query(database, ALL_COLUMNS,
2719 null, null, null, null, null);
2720
2721 if (cursor == null) {
2722 return;
2723 }
2724
2725 try {
2726 if (!cursor.moveToFirst()) {
2727 return;
2728 }
2729
2730 final int nameColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.NAME);
2731 final int valueColumnIdx = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
2732
2733 settingsState.setVersionLocked(database.getVersion());
2734
2735 while (!cursor.isAfterLast()) {
2736 String name = cursor.getString(nameColumnIdx);
2737 String value = cursor.getString(valueColumnIdx);
Svetoslav Ganove080da92016-12-21 17:10:35 -08002738 settingsState.insertSettingLocked(name, value, null, true,
Svetoslav683914b2015-01-15 14:22:26 -08002739 SettingsState.SYSTEM_PACKAGE_NAME);
2740 cursor.moveToNext();
2741 }
2742 } finally {
2743 cursor.close();
2744 }
2745 }
2746
2747 private void ensureSecureSettingAndroidIdSetLocked(SettingsState secureSettings) {
2748 Setting value = secureSettings.getSettingLocked(Settings.Secure.ANDROID_ID);
2749
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09002750 if (!value.isNull()) {
Svetoslav683914b2015-01-15 14:22:26 -08002751 return;
2752 }
2753
2754 final int userId = getUserIdFromKey(secureSettings.mKey);
2755
2756 final UserInfo user;
2757 final long identity = Binder.clearCallingIdentity();
2758 try {
2759 user = mUserManager.getUserInfo(userId);
2760 } finally {
2761 Binder.restoreCallingIdentity(identity);
2762 }
2763 if (user == null) {
2764 // Can happen due to races when deleting users - treat as benign.
2765 return;
2766 }
2767
2768 String androidId = Long.toHexString(new SecureRandom().nextLong());
2769 secureSettings.insertSettingLocked(Settings.Secure.ANDROID_ID, androidId,
Svetoslav Ganove080da92016-12-21 17:10:35 -08002770 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002771
2772 Slog.d(LOG_TAG, "Generated and saved new ANDROID_ID [" + androidId
2773 + "] for user " + userId);
2774
2775 // Write a drop box entry if it's a restricted profile
2776 if (user.isRestricted()) {
2777 DropBoxManager dbm = (DropBoxManager) getContext().getSystemService(
2778 Context.DROPBOX_SERVICE);
2779 if (dbm != null && dbm.isTagEnabled(DROPBOX_TAG_USERLOG)) {
2780 dbm.addText(DROPBOX_TAG_USERLOG, System.currentTimeMillis()
2781 + "," + DROPBOX_TAG_USERLOG + "," + androidId + "\n");
2782 }
2783 }
2784 }
2785
2786 private void notifyForSettingsChange(int key, String name) {
Svetoslav683914b2015-01-15 14:22:26 -08002787 final int userId = getUserIdFromKey(key);
2788 Uri uri = getNotificationUriFor(key, name);
2789
Phil Weaver83fec002016-05-11 10:55:29 -07002790 mGenerationRegistry.incrementGeneration(key);
2791
Svetoslav7e0683b2015-08-03 16:02:52 -07002792 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2793 userId, 0, uri).sendToTarget();
2794
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002795 if (isSecureSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002796 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2797 sSecureCloneToManagedSettings);
Robin Lee7af9a742017-02-20 14:47:30 +00002798 maybeNotifyProfiles(SETTINGS_TYPE_SYSTEM, userId, uri, name,
2799 sSystemCloneFromParentOnDependency.values());
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002800 } else if (isSystemSettingsKey(key)) {
Svet Ganov53a441c2016-04-19 19:38:00 -07002801 maybeNotifyProfiles(getTypeFromKey(key), userId, uri, name,
2802 sSystemCloneToManagedSettings);
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002803 }
Svet Ganov53a441c2016-04-19 19:38:00 -07002804
Svet Ganov53a441c2016-04-19 19:38:00 -07002805 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Makoto Onuki0000d322017-11-28 16:31:47 -08002806
2807 // When the global kill switch is updated, send the change notification for
2808 // the location setting.
2809 if (isGlobalSettingsKey(key) && Global.LOCATION_GLOBAL_KILL_SWITCH.equals(name)) {
2810 notifyLocationChangeForRunningUsers();
2811 }
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002812 }
2813
Svet Ganov53a441c2016-04-19 19:38:00 -07002814 private void maybeNotifyProfiles(int type, int userId, Uri uri, String name,
Robin Lee7af9a742017-02-20 14:47:30 +00002815 Collection<String> keysCloned) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002816 if (keysCloned.contains(name)) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002817 for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002818 // the notification for userId has already been sent.
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002819 if (profileId != userId) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002820 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -07002821 profileId, 0, uri).sendToTarget();
Svet Ganov53a441c2016-04-19 19:38:00 -07002822 final int key = makeKey(type, profileId);
2823 mGenerationRegistry.incrementGeneration(key);
2824
2825 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_DATA_CHANGED).sendToTarget();
Nicolas Prevot310e1ee2015-07-02 14:03:06 +01002826 }
2827 }
2828 }
Svetoslav683914b2015-01-15 14:22:26 -08002829 }
2830
Makoto Onuki0000d322017-11-28 16:31:47 -08002831 private void notifyLocationChangeForRunningUsers() {
2832 final List<UserInfo> users = mUserManager.getUsers(/*excludeDying=*/ true);
2833
2834 for (int i = 0; i < users.size(); i++) {
2835 final int userId = users.get(i).id;
2836
2837 if (!mUserManager.isUserRunning(UserHandle.of(userId))) {
2838 continue;
2839 }
2840
2841 final int key = makeKey(SETTINGS_TYPE_GLOBAL, userId);
2842 final Uri uri = getNotificationUriFor(key, Secure.LOCATION_PROVIDERS_ALLOWED);
2843
2844 mHandler.obtainMessage(MyHandler.MSG_NOTIFY_URI_CHANGED,
2845 userId, 0, uri).sendToTarget();
2846 }
2847 }
2848
Svetoslav683914b2015-01-15 14:22:26 -08002849 private boolean isGlobalSettingsKey(int key) {
2850 return getTypeFromKey(key) == SETTINGS_TYPE_GLOBAL;
2851 }
2852
2853 private boolean isSystemSettingsKey(int key) {
2854 return getTypeFromKey(key) == SETTINGS_TYPE_SYSTEM;
2855 }
2856
2857 private boolean isSecureSettingsKey(int key) {
2858 return getTypeFromKey(key) == SETTINGS_TYPE_SECURE;
2859 }
2860
Mark Rathjend891f012017-01-19 04:10:37 +00002861 private boolean isSsaidSettingsKey(int key) {
2862 return getTypeFromKey(key) == SETTINGS_TYPE_SSAID;
2863 }
2864
Svetoslav683914b2015-01-15 14:22:26 -08002865 private File getSettingsFile(int key) {
2866 if (isGlobalSettingsKey(key)) {
2867 final int userId = getUserIdFromKey(key);
2868 return new File(Environment.getUserSystemDirectory(userId),
2869 SETTINGS_FILE_GLOBAL);
2870 } else if (isSystemSettingsKey(key)) {
2871 final int userId = getUserIdFromKey(key);
2872 return new File(Environment.getUserSystemDirectory(userId),
2873 SETTINGS_FILE_SYSTEM);
2874 } else if (isSecureSettingsKey(key)) {
2875 final int userId = getUserIdFromKey(key);
2876 return new File(Environment.getUserSystemDirectory(userId),
2877 SETTINGS_FILE_SECURE);
Mark Rathjend891f012017-01-19 04:10:37 +00002878 } else if (isSsaidSettingsKey(key)) {
2879 final int userId = getUserIdFromKey(key);
2880 return new File(Environment.getUserSystemDirectory(userId),
2881 SETTINGS_FILE_SSAID);
Svetoslav683914b2015-01-15 14:22:26 -08002882 } else {
2883 throw new IllegalArgumentException("Invalid settings key:" + key);
2884 }
2885 }
2886
2887 private Uri getNotificationUriFor(int key, String name) {
2888 if (isGlobalSettingsKey(key)) {
2889 return (name != null) ? Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
2890 : Settings.Global.CONTENT_URI;
2891 } else if (isSecureSettingsKey(key)) {
2892 return (name != null) ? Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name)
2893 : Settings.Secure.CONTENT_URI;
2894 } else if (isSystemSettingsKey(key)) {
2895 return (name != null) ? Uri.withAppendedPath(Settings.System.CONTENT_URI, name)
2896 : Settings.System.CONTENT_URI;
2897 } else {
2898 throw new IllegalArgumentException("Invalid settings key:" + key);
2899 }
2900 }
2901
2902 private int getMaxBytesPerPackageForType(int type) {
2903 switch (type) {
2904 case SETTINGS_TYPE_GLOBAL:
Mark Rathjend891f012017-01-19 04:10:37 +00002905 case SETTINGS_TYPE_SECURE:
2906 case SETTINGS_TYPE_SSAID: {
Svetoslav683914b2015-01-15 14:22:26 -08002907 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_UNLIMITED;
2908 }
2909
2910 default: {
2911 return SettingsState.MAX_BYTES_PER_APP_PACKAGE_LIMITED;
2912 }
2913 }
2914 }
2915
Svetoslav7e0683b2015-08-03 16:02:52 -07002916 private final class MyHandler extends Handler {
2917 private static final int MSG_NOTIFY_URI_CHANGED = 1;
2918 private static final int MSG_NOTIFY_DATA_CHANGED = 2;
2919
2920 public MyHandler(Looper looper) {
2921 super(looper);
2922 }
2923
2924 @Override
2925 public void handleMessage(Message msg) {
2926 switch (msg.what) {
2927 case MSG_NOTIFY_URI_CHANGED: {
2928 final int userId = msg.arg1;
2929 Uri uri = (Uri) msg.obj;
Jeff Sharkey88f9d0b2017-08-11 15:29:40 -06002930 try {
2931 getContext().getContentResolver().notifyChange(uri, null, true, userId);
2932 } catch (SecurityException e) {
2933 Slog.w(LOG_TAG, "Failed to notify for " + userId + ": " + uri, e);
2934 }
Makoto Onuki0000d322017-11-28 16:31:47 -08002935 if (DEBUG || true) {
Svetoslav7e0683b2015-08-03 16:02:52 -07002936 Slog.v(LOG_TAG, "Notifying for " + userId + ": " + uri);
2937 }
2938 } break;
2939
2940 case MSG_NOTIFY_DATA_CHANGED: {
2941 mBackupManager.dataChanged();
2942 } break;
2943 }
2944 }
2945 }
2946
Svetoslav683914b2015-01-15 14:22:26 -08002947 private final class UpgradeController {
Jacky Cheung7076a312017-10-02 10:40:48 -07002948 private static final int SETTINGS_VERSION = 150;
Svetoslav683914b2015-01-15 14:22:26 -08002949
2950 private final int mUserId;
2951
2952 public UpgradeController(int userId) {
2953 mUserId = userId;
2954 }
2955
2956 public void upgradeIfNeededLocked() {
2957 // The version of all settings for a user is the same (all users have secure).
2958 SettingsState secureSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07002959 SETTINGS_TYPE_SECURE, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08002960
2961 // Try an update from the current state.
2962 final int oldVersion = secureSettings.getVersionLocked();
2963 final int newVersion = SETTINGS_VERSION;
2964
Svet Ganovc9755bc2015-03-28 13:21:22 -07002965 // If up do date - done.
Svetoslav683914b2015-01-15 14:22:26 -08002966 if (oldVersion == newVersion) {
2967 return;
2968 }
2969
2970 // Try to upgrade.
2971 final int curVersion = onUpgradeLocked(mUserId, oldVersion, newVersion);
2972
2973 // If upgrade failed start from scratch and upgrade.
2974 if (curVersion != newVersion) {
2975 // Drop state we have for this user.
2976 removeUserStateLocked(mUserId, true);
2977
2978 // Recreate the database.
2979 DatabaseHelper dbHelper = new DatabaseHelper(getContext(), mUserId);
2980 SQLiteDatabase database = dbHelper.getWritableDatabase();
2981 dbHelper.recreateDatabase(database, newVersion, curVersion, oldVersion);
2982
2983 // Migrate the settings for this user.
2984 migrateLegacySettingsForUserLocked(dbHelper, database, mUserId);
2985
2986 // Now upgrade should work fine.
2987 onUpgradeLocked(mUserId, oldVersion, newVersion);
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07002988
2989 // Make a note what happened, so we don't wonder why data was lost
2990 String reason = "Settings rebuilt! Current version: "
2991 + curVersion + " while expected: " + newVersion;
2992 getGlobalSettingsLocked().insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08002993 Settings.Global.DATABASE_DOWNGRADE_REASON,
2994 reason, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Svetoslav683914b2015-01-15 14:22:26 -08002995 }
2996
2997 // Set the global settings version if owner.
Xiaohui Chen43765b72015-08-31 10:57:33 -07002998 if (mUserId == UserHandle.USER_SYSTEM) {
Svetoslav683914b2015-01-15 14:22:26 -08002999 SettingsState globalSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003000 SETTINGS_TYPE_GLOBAL, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003001 globalSettings.setVersionLocked(newVersion);
3002 }
3003
3004 // Set the secure settings version.
3005 secureSettings.setVersionLocked(newVersion);
3006
3007 // Set the system settings version.
3008 SettingsState systemSettings = getSettingsLocked(
Svet Ganov53a441c2016-04-19 19:38:00 -07003009 SETTINGS_TYPE_SYSTEM, mUserId);
Svetoslav683914b2015-01-15 14:22:26 -08003010 systemSettings.setVersionLocked(newVersion);
3011 }
3012
3013 private SettingsState getGlobalSettingsLocked() {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003014 return getSettingsLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM);
Svetoslav683914b2015-01-15 14:22:26 -08003015 }
3016
3017 private SettingsState getSecureSettingsLocked(int userId) {
3018 return getSettingsLocked(SETTINGS_TYPE_SECURE, userId);
3019 }
3020
Mark Rathjend891f012017-01-19 04:10:37 +00003021 private SettingsState getSsaidSettingsLocked(int userId) {
3022 return getSettingsLocked(SETTINGS_TYPE_SSAID, userId);
3023 }
3024
Svetoslav683914b2015-01-15 14:22:26 -08003025 private SettingsState getSystemSettingsLocked(int userId) {
3026 return getSettingsLocked(SETTINGS_TYPE_SYSTEM, userId);
3027 }
3028
Jeff Brown503cffc2015-03-26 18:08:51 -07003029 /**
3030 * You must perform all necessary mutations to bring the settings
3031 * for this user from the old to the new version. When you add a new
3032 * upgrade step you *must* update SETTINGS_VERSION.
3033 *
3034 * This is an example of moving a setting from secure to global.
3035 *
3036 * // v119: Example settings changes.
3037 * if (currentVersion == 118) {
3038 * if (userId == UserHandle.USER_OWNER) {
3039 * // Remove from the secure settings.
3040 * SettingsState secureSettings = getSecureSettingsLocked(userId);
3041 * String name = "example_setting_to_move";
3042 * String value = secureSettings.getSetting(name);
3043 * secureSettings.deleteSetting(name);
3044 *
3045 * // Add to the global settings.
3046 * SettingsState globalSettings = getGlobalSettingsLocked();
3047 * globalSettings.insertSetting(name, value, SettingsState.SYSTEM_PACKAGE_NAME);
3048 * }
3049 *
3050 * // Update the current version.
3051 * currentVersion = 119;
3052 * }
3053 */
Svetoslav683914b2015-01-15 14:22:26 -08003054 private int onUpgradeLocked(int userId, int oldVersion, int newVersion) {
3055 if (DEBUG) {
3056 Slog.w(LOG_TAG, "Upgrading settings for user: " + userId + " from version: "
3057 + oldVersion + " to version: " + newVersion);
3058 }
3059
Jeff Brown503cffc2015-03-26 18:08:51 -07003060 int currentVersion = oldVersion;
Svetoslav683914b2015-01-15 14:22:26 -08003061
John Spurlocke11ae112015-05-11 16:09:03 -04003062 // v119: Reset zen + ringer mode.
3063 if (currentVersion == 118) {
Xiaohui Chen43765b72015-08-31 10:57:33 -07003064 if (userId == UserHandle.USER_SYSTEM) {
John Spurlocke11ae112015-05-11 16:09:03 -04003065 final SettingsState globalSettings = getGlobalSettingsLocked();
3066 globalSettings.updateSettingLocked(Settings.Global.ZEN_MODE,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003067 Integer.toString(Settings.Global.ZEN_MODE_OFF), null,
3068 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003069 globalSettings.updateSettingLocked(Settings.Global.MODE_RINGER,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003070 Integer.toString(AudioManager.RINGER_MODE_NORMAL), null,
3071 true, SettingsState.SYSTEM_PACKAGE_NAME);
John Spurlocke11ae112015-05-11 16:09:03 -04003072 }
3073 currentVersion = 119;
3074 }
3075
Jason Monk27bbb2d2015-03-31 16:46:39 -04003076 // v120: Add double tap to wake setting.
3077 if (currentVersion == 119) {
3078 SettingsState secureSettings = getSecureSettingsLocked(userId);
3079 secureSettings.insertSettingLocked(Settings.Secure.DOUBLE_TAP_TO_WAKE,
3080 getContext().getResources().getBoolean(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003081 R.bool.def_double_tap_to_wake) ? "1" : "0", null, true,
Jason Monk27bbb2d2015-03-31 16:46:39 -04003082 SettingsState.SYSTEM_PACKAGE_NAME);
3083
3084 currentVersion = 120;
3085 }
3086
Svetoslav7e0683b2015-08-03 16:02:52 -07003087 if (currentVersion == 120) {
3088 // Before 121, we used a different string encoding logic. We just bump the
3089 // version here; SettingsState knows how to handle pre-version 120 files.
3090 currentVersion = 121;
3091 }
Makoto Onuki3a2c35782015-06-18 11:21:58 -07003092
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003093 if (currentVersion == 121) {
3094 // Version 122: allow OEMs to set a default payment component in resources.
3095 // Note that we only write the default if no default has been set;
3096 // if there is, we just leave the default at whatever it currently is.
3097 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3098 String defaultComponent = (getContext().getResources().getString(
3099 R.string.def_nfc_payment_component));
3100 Setting currentSetting = secureSettings.getSettingLocked(
3101 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT);
3102 if (defaultComponent != null && !defaultComponent.isEmpty() &&
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003103 currentSetting.isNull()) {
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003104 secureSettings.insertSettingLocked(
3105 Settings.Secure.NFC_PAYMENT_DEFAULT_COMPONENT,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003106 defaultComponent, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Martijn Coenen7ab4b7f2015-07-27 15:58:32 +02003107 }
3108 currentVersion = 122;
3109 }
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003110
3111 if (currentVersion == 122) {
3112 // Version 123: Adding a default value for the ability to add a user from
3113 // the lock screen.
3114 if (userId == UserHandle.USER_SYSTEM) {
3115 final SettingsState globalSettings = getGlobalSettingsLocked();
3116 Setting currentSetting = globalSettings.getSettingLocked(
3117 Settings.Global.ADD_USERS_WHEN_LOCKED);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003118 if (currentSetting.isNull()) {
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003119 globalSettings.insertSettingLocked(
3120 Settings.Global.ADD_USERS_WHEN_LOCKED,
3121 getContext().getResources().getBoolean(
3122 R.bool.def_add_users_from_lockscreen) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003123 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla269c11e2015-12-02 16:51:16 -08003124 }
3125 }
3126 currentVersion = 123;
3127 }
Bryce Leebd179282015-12-17 19:01:37 -08003128
3129 if (currentVersion == 123) {
Bryce Leeec85f342015-12-16 13:32:28 -08003130 final SettingsState globalSettings = getGlobalSettingsLocked();
3131 String defaultDisabledProfiles = (getContext().getResources().getString(
3132 R.string.def_bluetooth_disabled_profiles));
3133 globalSettings.insertSettingLocked(Settings.Global.BLUETOOTH_DISABLED_PROFILES,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003134 defaultDisabledProfiles, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Bryce Leebd179282015-12-17 19:01:37 -08003135 currentVersion = 124;
Bryce Leeec85f342015-12-16 13:32:28 -08003136 }
3137
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003138 if (currentVersion == 124) {
3139 // Version 124: allow OEMs to set a default value for whether IME should be
3140 // shown when a physical keyboard is connected.
3141 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3142 Setting currentSetting = secureSettings.getSettingLocked(
3143 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003144 if (currentSetting.isNull()) {
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003145 secureSettings.insertSettingLocked(
3146 Settings.Secure.SHOW_IME_WITH_HARD_KEYBOARD,
3147 getContext().getResources().getBoolean(
3148 R.bool.def_show_ime_with_hard_keyboard) ? "1" : "0",
Svetoslav Ganove080da92016-12-21 17:10:35 -08003149 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Prathmesh Prabhude16b862016-03-04 15:22:24 -08003150 }
3151 currentVersion = 125;
3152 }
3153
Ruben Brunk98576cf2016-03-07 18:54:28 -08003154 if (currentVersion == 125) {
3155 // Version 125: Allow OEMs to set the default VR service.
3156 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3157
3158 Setting currentSetting = secureSettings.getSettingLocked(
3159 Settings.Secure.ENABLED_VR_LISTENERS);
Svetoslav Ganovfedb2302016-04-26 18:36:42 -07003160 if (currentSetting.isNull()) {
Ruben Brunk98576cf2016-03-07 18:54:28 -08003161 ArraySet<ComponentName> l =
3162 SystemConfig.getInstance().getDefaultVrComponents();
3163
3164 if (l != null && !l.isEmpty()) {
3165 StringBuilder b = new StringBuilder();
3166 boolean start = true;
3167 for (ComponentName c : l) {
3168 if (!start) {
3169 b.append(':');
3170 }
3171 b.append(c.flattenToString());
3172 start = false;
3173 }
3174 secureSettings.insertSettingLocked(
3175 Settings.Secure.ENABLED_VR_LISTENERS, b.toString(),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003176 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Ruben Brunk98576cf2016-03-07 18:54:28 -08003177 }
3178
3179 }
3180 currentVersion = 126;
3181 }
3182
Daniel U02ba6122016-04-01 18:41:42 +01003183 if (currentVersion == 126) {
3184 // Version 126: copy the primary values of LOCK_SCREEN_SHOW_NOTIFICATIONS and
3185 // LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS into managed profile.
3186 if (mUserManager.isManagedProfile(userId)) {
3187 final SettingsState systemSecureSettings =
3188 getSecureSettingsLocked(UserHandle.USER_SYSTEM);
3189
3190 final Setting showNotifications = systemSecureSettings.getSettingLocked(
3191 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003192 if (!showNotifications.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003193 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3194 secureSettings.insertSettingLocked(
3195 Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003196 showNotifications.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003197 SettingsState.SYSTEM_PACKAGE_NAME);
3198 }
3199
3200 final Setting allowPrivate = systemSecureSettings.getSettingLocked(
3201 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS);
Seigo Nonaka6e5b6022016-04-27 16:32:44 +09003202 if (!allowPrivate.isNull()) {
Daniel U02ba6122016-04-01 18:41:42 +01003203 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3204 secureSettings.insertSettingLocked(
3205 Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003206 allowPrivate.getValue(), null, true,
Daniel U02ba6122016-04-01 18:41:42 +01003207 SettingsState.SYSTEM_PACKAGE_NAME);
3208 }
3209 }
3210 currentVersion = 127;
3211 }
3212
Steven Ngdc20ba62016-04-26 18:19:04 +01003213 if (currentVersion == 127) {
Mahaver Chopra3d9805d2016-07-07 16:25:05 +01003214 // version 127 is no longer used.
Steven Ngdc20ba62016-04-26 18:19:04 +01003215 currentVersion = 128;
3216 }
3217
Julia Reynolds1f721e12016-07-11 08:50:58 -04003218 if (currentVersion == 128) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003219 // Version 128: Removed
Julia Reynolds1f721e12016-07-11 08:50:58 -04003220 currentVersion = 129;
3221 }
3222
Dan Sandler71f85e92016-07-20 13:46:05 -04003223 if (currentVersion == 129) {
3224 // default longpress timeout changed from 500 to 400. If unchanged from the old
3225 // default, update to the new default.
3226 final SettingsState systemSecureSettings =
3227 getSecureSettingsLocked(userId);
3228 final String oldValue = systemSecureSettings.getSettingLocked(
3229 Settings.Secure.LONG_PRESS_TIMEOUT).getValue();
3230 if (TextUtils.equals("500", oldValue)) {
3231 systemSecureSettings.insertSettingLocked(
3232 Settings.Secure.LONG_PRESS_TIMEOUT,
3233 String.valueOf(getContext().getResources().getInteger(
3234 R.integer.def_long_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003235 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Dan Sandler71f85e92016-07-20 13:46:05 -04003236 }
3237 currentVersion = 130;
3238 }
3239
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003240 if (currentVersion == 130) {
Adrian Roos69741a22016-10-21 14:49:17 -07003241 // Split Ambient settings
3242 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3243 boolean dozeExplicitlyDisabled = "0".equals(secureSettings.
3244 getSettingLocked(Settings.Secure.DOZE_ENABLED).getValue());
3245
3246 if (dozeExplicitlyDisabled) {
3247 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_PICK_UP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003248 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003249 secureSettings.insertSettingLocked(Settings.Secure.DOZE_PULSE_ON_DOUBLE_TAP,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003250 "0", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003251 }
3252 currentVersion = 131;
3253 }
3254
3255 if (currentVersion == 131) {
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003256 // Initialize new multi-press timeout to default value
3257 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3258 final String oldValue = systemSecureSettings.getSettingLocked(
3259 Settings.Secure.MULTI_PRESS_TIMEOUT).getValue();
3260 if (TextUtils.equals(null, oldValue)) {
3261 systemSecureSettings.insertSettingLocked(
3262 Settings.Secure.MULTI_PRESS_TIMEOUT,
3263 String.valueOf(getContext().getResources().getInteger(
3264 R.integer.def_multi_press_timeout_millis)),
Svetoslav Ganove080da92016-12-21 17:10:35 -08003265 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003266 }
3267
Adrian Roos69741a22016-10-21 14:49:17 -07003268 currentVersion = 132;
Anthony Hugh96e9cc52016-07-12 15:17:24 -07003269 }
3270
Adrian Roos69741a22016-10-21 14:49:17 -07003271 if (currentVersion == 132) {
3272 // Version 132: Allow managed profile to optionally use the parent's ringtones
Andre Lagoea35e072016-08-04 13:41:13 +01003273 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3274 String defaultSyncParentSounds = (getContext().getResources()
3275 .getBoolean(R.bool.def_sync_parent_sounds) ? "1" : "0");
3276 systemSecureSettings.insertSettingLocked(
Svetoslav Ganove080da92016-12-21 17:10:35 -08003277 Settings.Secure.SYNC_PARENT_SOUNDS, defaultSyncParentSounds,
3278 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Adrian Roos69741a22016-10-21 14:49:17 -07003279 currentVersion = 133;
Andre Lagoea35e072016-08-04 13:41:13 +01003280 }
3281
Adrian Roos69741a22016-10-21 14:49:17 -07003282 if (currentVersion == 133) {
3283 // Version 133: Add default end button behavior
Keun-young Parkec7a1182016-10-18 11:52:38 -07003284 final SettingsState systemSettings = getSystemSettingsLocked(userId);
3285 if (systemSettings.getSettingLocked(Settings.System.END_BUTTON_BEHAVIOR) ==
3286 null) {
3287 String defaultEndButtonBehavior = Integer.toString(getContext()
3288 .getResources().getInteger(R.integer.def_end_button_behavior));
3289 systemSettings.insertSettingLocked(Settings.System.END_BUTTON_BEHAVIOR,
Svetoslav Ganove080da92016-12-21 17:10:35 -08003290 defaultEndButtonBehavior, null, true,
3291 SettingsState.SYSTEM_PACKAGE_NAME);
Keun-young Parkec7a1182016-10-18 11:52:38 -07003292 }
Adrian Roos69741a22016-10-21 14:49:17 -07003293 currentVersion = 134;
Keun-young Parkec7a1182016-10-18 11:52:38 -07003294 }
3295
Phil Weaver89e3ffc2016-09-19 13:51:10 -07003296 if (currentVersion == 134) {
3297 // Remove setting that specifies if magnification values should be preserved.
3298 // This setting defaulted to true and never has a UI.
3299 getSecureSettingsLocked(userId).deleteSettingLocked(
3300 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_AUTO_UPDATE);
3301 currentVersion = 135;
3302 }
3303
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003304 if (currentVersion == 135) {
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003305 // Version 135 no longer used.
Jeremy Joslin8bdad342016-12-14 11:46:47 -08003306 currentVersion = 136;
3307 }
3308
Mark Rathjend891f012017-01-19 04:10:37 +00003309 if (currentVersion == 136) {
3310 // Version 136: Store legacy SSAID for all apps currently installed on the
3311 // device as first step in migrating SSAID to be unique per application.
3312
3313 final boolean isUpgrade;
3314 try {
3315 isUpgrade = mPackageManager.isUpgrade();
3316 } catch (RemoteException e) {
3317 throw new IllegalStateException("Package manager not available");
3318 }
3319 // Only retain legacy ssaid if the device is performing an OTA. After wiping
3320 // user data or first boot on a new device should use new ssaid generation.
3321 if (isUpgrade) {
3322 // Retrieve the legacy ssaid from the secure settings table.
Mark Rathjenea617592017-01-18 23:03:41 -08003323 final Setting legacySsaidSetting = getSettingLocked(SETTINGS_TYPE_SECURE,
3324 userId, Settings.Secure.ANDROID_ID);
3325 if (legacySsaidSetting == null || legacySsaidSetting.isNull()
3326 || legacySsaidSetting.getValue() == null) {
3327 throw new IllegalStateException("Legacy ssaid not accessible");
3328 }
3329 final String legacySsaid = legacySsaidSetting.getValue();
Mark Rathjend891f012017-01-19 04:10:37 +00003330
3331 // Fill each uid with the legacy ssaid to be backwards compatible.
3332 final List<PackageInfo> packages;
3333 try {
3334 packages = mPackageManager.getInstalledPackages(0, userId).getList();
3335 } catch (RemoteException e) {
3336 throw new IllegalStateException("Package manager not available");
3337 }
3338
3339 final SettingsState ssaidSettings = getSsaidSettingsLocked(userId);
3340 for (PackageInfo info : packages) {
3341 // Check if the UID already has an entry in the table.
3342 final String uid = Integer.toString(info.applicationInfo.uid);
3343 final Setting ssaid = ssaidSettings.getSettingLocked(uid);
3344
3345 if (ssaid.isNull() || ssaid.getValue() == null) {
3346 // Android Id doesn't exist for this package so create it.
3347 ssaidSettings.insertSettingLocked(uid, legacySsaid, null, true,
3348 info.packageName);
3349 }
3350 }
3351 }
3352
3353 currentVersion = 137;
3354 }
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003355 if (currentVersion == 137) {
3356 // Version 138: Settings.Secure#INSTALL_NON_MARKET_APPS is deprecated and its
3357 // default value set to 1. The user can no longer change the value of this
3358 // setting through the UI.
3359 final SettingsState secureSetting = getSecureSettingsLocked(userId);
3360 if (!mUserManager.hasUserRestriction(
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003361 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, UserHandle.of(userId))
3362 && secureSetting.getSettingLocked(
3363 Settings.Secure.INSTALL_NON_MARKET_APPS).getValue().equals("0")) {
3364
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003365 secureSetting.insertSettingLocked(Settings.Secure.INSTALL_NON_MARKET_APPS,
3366 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shukla0b1356f2017-02-21 14:33:50 -08003367 // For managed profiles with profile owners, DevicePolicyManagerService
3368 // may want to set the user restriction in this case
3369 secureSetting.insertSettingLocked(
3370 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, "1", null, true,
3371 SettingsState.SYSTEM_PACKAGE_NAME);
Suprabh Shuklae3745ee2017-02-02 20:01:11 -08003372 }
3373 currentVersion = 138;
3374 }
Mark Rathjend891f012017-01-19 04:10:37 +00003375
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003376 if (currentVersion == 138) {
Jeremy Joslin27d14c42017-02-15 12:02:03 -08003377 // Version 139: Removed.
Jeremy Joslinc9eb3c42017-02-08 10:45:30 -08003378 currentVersion = 139;
3379 }
3380
Phil Weaver385912e2017-02-10 10:06:56 -08003381 if (currentVersion == 139) {
3382 // Version 140: Settings.Secure#ACCESSIBILITY_SPEAK_PASSWORD is deprecated and
3383 // the user can no longer change the value of this setting through the UI.
3384 // Force to true.
3385 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3386 secureSettings.updateSettingLocked(Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
3387 "1", null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3388 currentVersion = 140;
3389 }
3390
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003391 if (currentVersion == 140) {
Julia Reynoldsb852e562017-06-06 16:14:18 -04003392 // Version 141: Removed
Julia Reynoldsad0d9e02017-02-15 08:41:48 -05003393 currentVersion = 141;
3394 }
3395
Svet Ganov13701552017-02-23 12:45:17 -08003396 if (currentVersion == 141) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003397 // This implementation was incorrectly setting the current value of
3398 // settings changed by non-system packages as the default which default
3399 // is set by the system. We add a new upgrade step at the end to properly
3400 // handle this case which would also fix incorrect changes made by the
3401 // old implementation of this step.
Svet Ganov13701552017-02-23 12:45:17 -08003402 currentVersion = 142;
3403 }
3404
Stephen Chen5d0922f2017-03-27 10:28:04 -07003405 if (currentVersion == 142) {
Felipe Lemeff355092017-04-03 12:55:02 -07003406 // Version 143: Set a default value for Wi-Fi wakeup feature.
Stephen Chen5d0922f2017-03-27 10:28:04 -07003407 if (userId == UserHandle.USER_SYSTEM) {
3408 final SettingsState globalSettings = getGlobalSettingsLocked();
3409 Setting currentSetting = globalSettings.getSettingLocked(
3410 Settings.Global.WIFI_WAKEUP_ENABLED);
3411 if (currentSetting.isNull()) {
3412 globalSettings.insertSettingLocked(
3413 Settings.Global.WIFI_WAKEUP_ENABLED,
3414 getContext().getResources().getBoolean(
3415 R.bool.def_wifi_wakeup_enabled) ? "1" : "0",
3416 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3417 }
3418 }
3419
3420 currentVersion = 143;
3421 }
3422
Felipe Lemeff355092017-04-03 12:55:02 -07003423 if (currentVersion == 143) {
3424 // Version 144: Set a default value for Autofill service.
3425 final SettingsState secureSettings = getSecureSettingsLocked(userId);
3426 final Setting currentSetting = secureSettings
3427 .getSettingLocked(Settings.Secure.AUTOFILL_SERVICE);
3428 if (currentSetting.isNull()) {
3429 final String defaultValue = getContext().getResources().getString(
3430 com.android.internal.R.string.config_defaultAutofillService);
3431 if (defaultValue != null) {
3432 Slog.d(LOG_TAG, "Setting [" + defaultValue + "] as Autofill Service "
3433 + "for user " + userId);
3434 secureSettings.insertSettingLocked(Settings.Secure.AUTOFILL_SERVICE,
3435 defaultValue, null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3436 }
3437 }
3438
3439 currentVersion = 144;
3440 }
3441
Jeremy Joslin45caa252017-05-04 11:22:46 -07003442 if (currentVersion == 144) {
Amin Shaikh86367962017-06-07 08:58:22 -07003443 // Version 145: Removed
3444 currentVersion = 145;
3445 }
3446
3447 if (currentVersion == 145) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003448 // Version 146: In step 142 we had a bug where incorrectly
3449 // some settings were considered system set and as a result
3450 // made the default and marked as the default being set by
3451 // the system. Here reevaluate the default and default system
3452 // set flags. This would both fix corruption by the old impl
3453 // of step 142 and also properly handle devices which never
3454 // run 142.
Jeremy Joslin45caa252017-05-04 11:22:46 -07003455 if (userId == UserHandle.USER_SYSTEM) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003456 SettingsState globalSettings = getGlobalSettingsLocked();
3457 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(globalSettings, userId);
3458 globalSettings.persistSyncLocked();
Jeremy Joslin45caa252017-05-04 11:22:46 -07003459 }
3460
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003461 SettingsState secureSettings = getSecureSettingsLocked(mUserId);
3462 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(secureSettings, userId);
3463 secureSettings.persistSyncLocked();
3464
3465 SettingsState systemSettings = getSystemSettingsLocked(mUserId);
3466 ensureLegacyDefaultValueAndSystemSetUpdatedLocked(systemSettings, userId);
3467 systemSettings.persistSyncLocked();
3468
Amin Shaikh86367962017-06-07 08:58:22 -07003469 currentVersion = 146;
Jeremy Joslin45caa252017-05-04 11:22:46 -07003470 }
3471
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003472 if (currentVersion == 146) {
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003473 // Version 147: Set the default value for WIFI_WAKEUP_AVAILABLE.
3474 if (userId == UserHandle.USER_SYSTEM) {
3475 final SettingsState globalSettings = getGlobalSettingsLocked();
3476 final Setting currentSetting = globalSettings.getSettingLocked(
3477 Settings.Global.WIFI_WAKEUP_AVAILABLE);
3478 if (currentSetting.getValue() == null) {
3479 final int defaultValue = getContext().getResources().getInteger(
3480 com.android.internal.R.integer.config_wifi_wakeup_available);
3481 globalSettings.insertSettingLocked(
3482 Settings.Global.WIFI_WAKEUP_AVAILABLE,
3483 String.valueOf(defaultValue),
3484 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3485 }
3486 }
3487
3488 currentVersion = 147;
3489 }
3490
3491 if (currentVersion == 147) {
3492 // Version 148: Set the default value for DEFAULT_RESTRICT_BACKGROUND_DATA.
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003493 if (userId == UserHandle.USER_SYSTEM) {
3494 final SettingsState globalSettings = getGlobalSettingsLocked();
3495 final Setting currentSetting = globalSettings.getSettingLocked(
3496 Global.DEFAULT_RESTRICT_BACKGROUND_DATA);
3497 if (currentSetting.isNull()) {
3498 globalSettings.insertSettingLocked(
3499 Global.DEFAULT_RESTRICT_BACKGROUND_DATA,
3500 getContext().getResources().getBoolean(
3501 R.bool.def_restrict_background_data) ? "1" : "0",
3502 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3503 }
3504 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003505 currentVersion = 148;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01003506 }
3507
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003508 if (currentVersion == 148) {
3509 // Version 149: Set the default value for BACKUP_MANAGER_CONSTANTS.
3510 final SettingsState systemSecureSettings = getSecureSettingsLocked(userId);
3511 final String oldValue = systemSecureSettings.getSettingLocked(
3512 Settings.Secure.BACKUP_MANAGER_CONSTANTS).getValue();
3513 if (TextUtils.equals(null, oldValue)) {
3514 final String defaultValue = getContext().getResources().getString(
3515 R.string.def_backup_manager_constants);
3516 if (!TextUtils.isEmpty(defaultValue)) {
3517 systemSecureSettings.insertSettingLocked(
3518 Settings.Secure.BACKUP_MANAGER_CONSTANTS, defaultValue, null,
3519 true, SettingsState.SYSTEM_PACKAGE_NAME);
3520 }
3521 }
Tim Zhengcc1e76a2017-08-30 17:46:19 -07003522 currentVersion = 149;
3523 }
Jacky Cheung7076a312017-10-02 10:40:48 -07003524
3525 if (currentVersion == 149) {
3526 // Version 150: Set a default value for mobile data always on
3527 final SettingsState globalSettings = getGlobalSettingsLocked();
3528 final Setting currentSetting = globalSettings.getSettingLocked(
3529 Settings.Global.MOBILE_DATA_ALWAYS_ON);
3530 if (currentSetting.isNull()) {
3531 globalSettings.insertSettingLocked(
3532 Settings.Global.MOBILE_DATA_ALWAYS_ON,
3533 getContext().getResources().getBoolean(
3534 R.bool.def_mobile_data_always_on) ? "1" : "0",
3535 null, true, SettingsState.SYSTEM_PACKAGE_NAME);
3536 }
3537
3538 currentVersion = 150;
3539 }
3540
Felipe Lemeff355092017-04-03 12:55:02 -07003541 // vXXX: Add new settings above this point.
3542
Dan Sandler71f85e92016-07-20 13:46:05 -04003543 if (currentVersion != newVersion) {
Svetoslav Ganov264c7a92016-08-24 17:31:14 -07003544 Slog.wtf("SettingsProvider", "warning: upgrading settings database to version "
Dan Sandler71f85e92016-07-20 13:46:05 -04003545 + newVersion + " left it at "
Stephen Chen5d0922f2017-03-27 10:28:04 -07003546 + currentVersion +
3547 " instead; this is probably a bug. Did you update SETTINGS_VERSION?",
3548 new Throwable());
Dan Sandler71f85e92016-07-20 13:46:05 -04003549 if (DEBUG) {
3550 throw new RuntimeException("db upgrade error");
3551 }
3552 }
3553
Jeff Brown503cffc2015-03-26 18:08:51 -07003554 // Return the current version.
3555 return currentVersion;
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08003556 }
3557 }
Svet Ganov13701552017-02-23 12:45:17 -08003558
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003559 private void ensureLegacyDefaultValueAndSystemSetUpdatedLocked(SettingsState settings,
3560 int userId) {
Svet Ganov13701552017-02-23 12:45:17 -08003561 List<String> names = settings.getSettingNamesLocked();
3562 final int nameCount = names.size();
3563 for (int i = 0; i < nameCount; i++) {
3564 String name = names.get(i);
3565 Setting setting = settings.getSettingLocked(name);
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003566
3567 // In the upgrade case we pretend the call is made from the app
3568 // that made the last change to the setting to properly determine
3569 // whether the call has been made by a system component.
3570 int callingUid = -1;
3571 try {
3572 callingUid = mPackageManager.getPackageUid(setting.getPackageName(), 0, userId);
3573 } catch (RemoteException e) {
3574 /* ignore - handled below */
3575 }
3576 if (callingUid < 0) {
3577 Slog.e(LOG_TAG, "Unknown package: " + setting.getPackageName());
3578 continue;
3579 }
3580 try {
3581 final boolean systemSet = SettingsState.isSystemPackage(getContext(),
3582 setting.getPackageName(), callingUid);
Svet Ganov13701552017-02-23 12:45:17 -08003583 if (systemSet) {
3584 settings.insertSettingLocked(name, setting.getValue(),
3585 setting.getTag(), true, setting.getPackageName());
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003586 } else if (setting.getDefaultValue() != null && setting.isDefaultFromSystem()) {
3587 // We had a bug where changes by non-system packages were marked
3588 // as system made and as a result set as the default. Therefore, if
3589 // the package changed the setting last is not a system one but the
3590 // setting is marked as its default coming from the system we clear
3591 // the default and clear the system set flag.
3592 settings.resetSettingDefaultValueLocked(name);
Svet Ganov13701552017-02-23 12:45:17 -08003593 }
Svetoslav Ganovf7654c52017-08-16 17:33:22 -07003594 } catch (IllegalStateException e) {
3595 // If the package goes over its quota during the upgrade, don't
3596 // crash but just log the error as the system does the upgrade.
3597 Slog.e(LOG_TAG, "Error upgrading setting: " + setting.getName(), e);
3598
Svet Ganov13701552017-02-23 12:45:17 -08003599 }
3600 }
3601 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08003602 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003603}