blob: b444eb15d3f7c05b9553a688af7dfb6c1d6831b5 [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
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tate06efb532012-08-24 15:29:27 -070025import android.app.ActivityManagerNative;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentProvider;
29import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070032import android.content.Intent;
33import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Christopher Tate06efb532012-08-24 15:29:27 -070035import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070036import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080039import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteQueryBuilder;
Christopher Tate06efb532012-08-24 15:29:27 -070041import android.database.sqlite.SQLiteStatement;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.media.RingtoneManager;
43import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070044import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070046import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047import android.os.ParcelFileDescriptor;
Christopher Tate06efb532012-08-24 15:29:27 -070048import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070050import android.os.UserHandle;
51import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.provider.DrmStore;
53import android.provider.MediaStore;
54import android.provider.Settings;
55import android.text.TextUtils;
56import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080057import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070058import android.util.Slog;
59import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061public class SettingsProvider extends ContentProvider {
62 private static final String TAG = "SettingsProvider";
63 private static final boolean LOCAL_LOGV = false;
64
Christopher Tate06efb532012-08-24 15:29:27 -070065 private static final String TABLE_SYSTEM = "system";
66 private static final String TABLE_SECURE = "secure";
67 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TABLE_FAVORITES = "favorites";
69 private static final String TABLE_OLD_FAVORITES = "old_favorites";
70
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080071 private static final String[] COLUMN_VALUE = new String[] { "value" };
72
Christopher Tate06efb532012-08-24 15:29:27 -070073 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080074 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070075 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070076 private static final SparseArray<SettingsCache> sSystemCaches
77 = new SparseArray<SettingsCache>();
78 private static final SparseArray<SettingsCache> sSecureCaches
79 = new SparseArray<SettingsCache>();
80 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070081
82 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070083 // database mutations are currently being handled for this user.
84 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070085 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070086 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
87 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080088
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080089 // Over this size we don't reject loading or saving settings but
90 // we do consider them broken/malicious and don't keep them in
91 // memory at least:
92 private static final int MAX_CACHE_ENTRY_SIZE = 500;
93
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080094 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
95
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070096 // Used as a sentinel value in an instance equality test when we
97 // want to cache the existence of a key, but not store its value.
98 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
99
Christopher Tate06efb532012-08-24 15:29:27 -0700100 // Each defined user has their own settings
101 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
102 //protected DatabaseHelper mOpenHelper;
103 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700104 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105
106 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700107 * Settings which need to be treated as global/shared in multi-user environments.
108 */
109 static final HashSet<String> sSecureGlobalKeys;
110 static final HashSet<String> sSystemGlobalKeys;
111 static {
112 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
113 // table, shared across all users
114 // These must match Settings.Secure.MOVED_TO_GLOBAL
115 sSecureGlobalKeys = new HashSet<String>();
116 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
117 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
118 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
119 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
120 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
121 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
122 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
123 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
124 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
125 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
126 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
127 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
128 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
129 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
130 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
131 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
132 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
133 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
146 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
147 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
148 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
149 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
150 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
151 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
152 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
153 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
154 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
155 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
156 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
157 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
158 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
159 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
160 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
161 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
162 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
163 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
164 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
165 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
166 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
167 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
168 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
170 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
171 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
172 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
173 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
174 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
175 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
176 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
177 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
178 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
190 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
191 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
192
193 // Keys from the 'system' table now moved to 'global'
194 // These must match Settings.System.MOVED_TO_GLOBAL
195 sSystemGlobalKeys = new HashSet<String>();
196 sSystemGlobalKeys.add(Settings.Secure.ADB_ENABLED);
197 sSystemGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
198 sSystemGlobalKeys.add(Settings.Secure.DATA_ROAMING);
199 sSystemGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
200 sSystemGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
201 sSystemGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
202
203 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
204 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
205 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
206 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
207 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
208 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
209 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
210 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
211 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
212 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
213 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
214 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
215 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
216 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
217 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
218 }
219
220 private boolean settingMovedToGlobal(final String name) {
221 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
222 }
223
224 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700225 * Decode a content URL into the table, projection, and arguments
226 * used to access the corresponding database rows.
227 */
228 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700230 public final String where;
231 public final String[] args;
232
233 /** Operate on existing rows. */
234 SqlArguments(Uri url, String where, String[] args) {
235 if (url.getPathSegments().size() == 1) {
236 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700237 if (!DatabaseHelper.isValidTable(this.table)) {
238 throw new IllegalArgumentException("Bad root path: " + this.table);
239 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700240 this.where = where;
241 this.args = args;
242 } else if (url.getPathSegments().size() != 2) {
243 throw new IllegalArgumentException("Invalid URI: " + url);
244 } else if (!TextUtils.isEmpty(where)) {
245 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
246 } else {
247 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700248 if (!DatabaseHelper.isValidTable(this.table)) {
249 throw new IllegalArgumentException("Bad root path: " + this.table);
250 }
Christopher Tate06efb532012-08-24 15:29:27 -0700251 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252 this.where = Settings.NameValueTable.NAME + "=?";
253 this.args = new String[] { url.getPathSegments().get(1) };
254 } else {
255 this.where = "_id=" + ContentUris.parseId(url);
256 this.args = null;
257 }
258 }
259 }
260
261 /** Insert new rows (no where clause allowed). */
262 SqlArguments(Uri url) {
263 if (url.getPathSegments().size() == 1) {
264 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700265 if (!DatabaseHelper.isValidTable(this.table)) {
266 throw new IllegalArgumentException("Bad root path: " + this.table);
267 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700268 this.where = null;
269 this.args = null;
270 } else {
271 throw new IllegalArgumentException("Invalid URI: " + url);
272 }
273 }
274 }
275
276 /**
277 * Get the content URI of a row added to a table.
278 * @param tableUri of the entire table
279 * @param values found in the row
280 * @param rowId of the row
281 * @return the content URI for this particular row
282 */
283 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
284 if (tableUri.getPathSegments().size() != 1) {
285 throw new IllegalArgumentException("Invalid URI: " + tableUri);
286 }
287 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700288 if (TABLE_SYSTEM.equals(table) ||
289 TABLE_SECURE.equals(table) ||
290 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291 String name = values.getAsString(Settings.NameValueTable.NAME);
292 return Uri.withAppendedPath(tableUri, name);
293 } else {
294 return ContentUris.withAppendedId(tableUri, rowId);
295 }
296 }
297
298 /**
299 * Send a notification when a particular content URI changes.
300 * Modify the system property used to communicate the version of
301 * this table, for tables which have such a property. (The Settings
302 * contract class uses these to provide client-side caches.)
303 * @param uri to send notifications for
304 */
Christopher Tate06efb532012-08-24 15:29:27 -0700305 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700306 // Update the system property *first*, so if someone is listening for
307 // a notification and then using the contract class to get their data,
308 // the system property will be updated and they'll get the new data.
309
Amith Yamasanid1582142009-07-08 20:04:55 -0700310 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700312 if (table.equals(TABLE_SYSTEM)) {
313 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700314 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700315 } else if (table.equals(TABLE_SECURE)) {
316 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
317 backedUpDataChanged = true;
318 } else if (table.equals(TABLE_GLOBAL)) {
319 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700320 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700321 }
322
323 if (property != null) {
324 long version = SystemProperties.getLong(property, 0) + 1;
325 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
326 SystemProperties.set(property, Long.toString(version));
327 }
328
-b master501eec92009-07-06 13:53:11 -0700329 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700330 if (backedUpDataChanged) {
331 mBackupManager.dataChanged();
332 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700333 // Now send the notification through the content framework.
334
335 String notify = uri.getQueryParameter("notify");
336 if (notify == null || "true".equals(notify)) {
337 getContext().getContentResolver().notifyChange(uri, null);
338 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
339 } else {
340 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
341 }
342 }
343
344 /**
345 * Make sure the caller has permission to write this data.
346 * @param args supplied by the caller
347 * @throws SecurityException if the caller is forbidden to write.
348 */
349 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700350 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800351 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800352 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
353 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700354 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800355 String.format("Permission denial: writing to secure settings requires %1$s",
356 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700357 }
358 }
359
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700360 // FileObserver for external modifications to the database file.
361 // Note that this is for platform developers only with
362 // userdebug/eng builds who should be able to tinker with the
363 // sqlite database out from under the SettingsProvider, which is
364 // normally the exclusive owner of the database. But we keep this
365 // enabled all the time to minimize development-vs-user
366 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700367 private static SparseArray<SettingsFileObserver> sObserverInstances
368 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700369 private class SettingsFileObserver extends FileObserver {
370 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700371 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700372 private final String mPath;
373
Christopher Tate06efb532012-08-24 15:29:27 -0700374 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700375 super(path, FileObserver.CLOSE_WRITE |
376 FileObserver.CREATE | FileObserver.DELETE |
377 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700378 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700379 mPath = path;
380 }
381
382 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700383 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700384 if (modsInFlight > 0) {
385 // our own modification.
386 return;
387 }
Christopher Tate06efb532012-08-24 15:29:27 -0700388 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
389 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700390 if (!mIsDirty.compareAndSet(false, true)) {
391 // already handled. (we get a few update events
392 // during an sqlite write)
393 return;
394 }
Christopher Tate06efb532012-08-24 15:29:27 -0700395 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
396 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700397 mIsDirty.set(false);
398 }
399 }
400
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 @Override
402 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700403 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700404 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800405
Christopher Tate06efb532012-08-24 15:29:27 -0700406 synchronized (this) {
407 establishDbTrackingLocked(UserHandle.USER_OWNER);
408
409 IntentFilter userFilter = new IntentFilter();
410 userFilter.addAction(Intent.ACTION_USER_REMOVED);
411 getContext().registerReceiver(new BroadcastReceiver() {
412 @Override
413 public void onReceive(Context context, Intent intent) {
414 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
415 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
416 UserHandle.USER_OWNER);
417 if (userHandle != UserHandle.USER_OWNER) {
418 onUserRemoved(userHandle);
419 }
420 }
421 }
422 }, userFilter);
423
424 if (!ensureAndroidIdIsSet()) {
425 return false;
426 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800427 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700428 return true;
429 }
430
Christopher Tate06efb532012-08-24 15:29:27 -0700431 void onUserRemoved(int userHandle) {
432 // the db file itself will be deleted automatically, but we need to tear down
433 // our caches and other internal bookkeeping. Creation/deletion of a user's
434 // settings db infrastructure is synchronized on 'this'
435 synchronized (this) {
436 FileObserver observer = sObserverInstances.get(userHandle);
437 if (observer != null) {
438 observer.stopWatching();
439 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700440 }
Christopher Tate06efb532012-08-24 15:29:27 -0700441
442 mOpenHelpers.delete(userHandle);
443 sSystemCaches.delete(userHandle);
444 sSecureCaches.delete(userHandle);
445 sKnownMutationsInFlight.delete(userHandle);
446
447 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
448 SystemProperties.set(property, "");
449 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
450 SystemProperties.set(property, "");
451 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700452 }
453
Christopher Tate06efb532012-08-24 15:29:27 -0700454 private void establishDbTrackingLocked(int userHandle) {
455 if (LOCAL_LOGV) {
456 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
457 }
458
459 DatabaseHelper dbhelper = new DatabaseHelper(getContext(), userHandle);
460 mOpenHelpers.append(userHandle, dbhelper);
461
462 // Watch for external modifications to the database files,
463 // keeping our caches in sync.
464 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
465 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
466 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
467 SQLiteDatabase db = dbhelper.getWritableDatabase();
468
469 // Now we can start observing it for changes
470 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
471 sObserverInstances.append(userHandle, observer);
472 observer.startWatching();
473
474 startAsyncCachePopulation(userHandle);
475 }
476
477 class CachePrefetchThread extends Thread {
478 private int mUserHandle;
479
480 CachePrefetchThread(int userHandle) {
481 super("populate-settings-caches");
482 mUserHandle = userHandle;
483 }
484
485 @Override
486 public void run() {
487 fullyPopulateCaches(mUserHandle);
488 }
489 }
490
491 private void startAsyncCachePopulation(int userHandle) {
492 new CachePrefetchThread(userHandle).start();
493 }
494
495 private void fullyPopulateCaches(final int userHandle) {
496 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
497 // Only populate the globals cache once, for the owning user
498 if (userHandle == UserHandle.USER_OWNER) {
499 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
500 }
501 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
502 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700503 }
504
505 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700506 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
507 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700508 Cursor c = db.query(
509 table,
510 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
511 null, null, null, null, null,
512 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
513 try {
514 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800515 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700516 cache.setFullyMatchesDisk(true); // optimistic
517 int rows = 0;
518 while (c.moveToNext()) {
519 rows++;
520 String name = c.getString(0);
521 String value = c.getString(1);
522 cache.populate(name, value);
523 }
524 if (rows > MAX_CACHE_ENTRIES) {
525 // Somewhat redundant, as removeEldestEntry() will
526 // have already done this, but to be explicit:
527 cache.setFullyMatchesDisk(false);
528 Log.d(TAG, "row count exceeds max cache entries for table " + table);
529 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700530 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700531 cache.fullyMatchesDisk());
532 }
533 } finally {
534 c.close();
535 }
536 }
537
Fred Quintanac70239e2009-12-17 10:28:33 -0800538 private boolean ensureAndroidIdIsSet() {
539 final Cursor c = query(Settings.Secure.CONTENT_URI,
540 new String[] { Settings.NameValueTable.VALUE },
541 Settings.NameValueTable.NAME + "=?",
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800542 new String[] { Settings.Secure.ANDROID_ID }, null);
Fred Quintanac70239e2009-12-17 10:28:33 -0800543 try {
544 final String value = c.moveToNext() ? c.getString(0) : null;
545 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700546 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800547 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Doug Zongker0fe27cf2010-08-19 13:38:26 -0700548 Log.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue + "]");
Fred Quintanac70239e2009-12-17 10:28:33 -0800549 final ContentValues values = new ContentValues();
550 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
551 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
552 final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
553 if (uri == null) {
554 return false;
555 }
556 }
557 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800558 } finally {
559 c.close();
560 }
561 }
562
Christopher Tate06efb532012-08-24 15:29:27 -0700563 // Lazy-initialize the settings caches for non-primary users
564 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
565 synchronized (this) {
566 getOrEstablishDatabaseLocked(callingUser); // ignore return value; we don't need it
567 return which.get(callingUser);
568 }
569 }
570
571 // Lazy initialize the database helper and caches for this user, if necessary
572 private DatabaseHelper getOrEstablishDatabaseLocked(int callingUser) {
573 long oldId = Binder.clearCallingIdentity();
574 try {
575 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
576 if (null == dbHelper) {
577 establishDbTrackingLocked(callingUser);
578 dbHelper = mOpenHelpers.get(callingUser);
579 }
580 return dbHelper;
581 } finally {
582 Binder.restoreCallingIdentity(oldId);
583 }
584 }
585
586 public SettingsCache cacheForTable(final int callingUser, String tableName) {
587 if (TABLE_SYSTEM.equals(tableName)) {
588 return getOrConstructCache(callingUser, sSystemCaches);
589 }
590 if (TABLE_SECURE.equals(tableName)) {
591 return getOrConstructCache(callingUser, sSecureCaches);
592 }
593 if (TABLE_GLOBAL.equals(tableName)) {
594 return sGlobalCache;
595 }
596 return null;
597 }
598
599 /**
600 * Used for wiping a whole cache on deletes when we're not
601 * sure what exactly was deleted or changed.
602 */
603 public void invalidateCache(final int callingUser, String tableName) {
604 SettingsCache cache = cacheForTable(callingUser, tableName);
605 if (cache == null) {
606 return;
607 }
608 synchronized (cache) {
609 cache.evictAll();
610 cache.mCacheFullyMatchesDisk = false;
611 }
612 }
613
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800614 /**
615 * Fast path that avoids the use of chatty remoted Cursors.
616 */
617 @Override
618 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700619 int callingUser = UserHandle.getCallingUserId();
620 if (args != null) {
621 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
622 if (reqUser != callingUser) {
623 getContext().enforceCallingPermission(
624 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
625 "Not permitted to access settings for other users");
626 if (reqUser == UserHandle.USER_CURRENT) {
627 try {
628 reqUser = ActivityManagerNative.getDefault().getCurrentUser().id;
629 } catch (RemoteException e) {
630 // can't happen
631 }
632 if (LOCAL_LOGV) {
633 Slog.v(TAG, " USER_CURRENT resolved to " + reqUser);
634 }
635 }
636 if (reqUser < 0) {
637 throw new IllegalArgumentException("Bad user handle " + reqUser);
638 }
639 callingUser = reqUser;
640 if (LOCAL_LOGV) Slog.v(TAG, " fetching setting for user " + callingUser);
641 }
642 }
643
644 // Note: we assume that get/put operations for moved-to-global names have already
645 // been directed to the new location on the caller side (otherwise we'd fix them
646 // up here).
647
648 DatabaseHelper dbHelper;
649 SettingsCache cache;
650
651 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800652 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700653 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
654 synchronized (this) {
655 dbHelper = getOrEstablishDatabaseLocked(callingUser);
656 cache = sSystemCaches.get(callingUser);
657 }
658 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800659 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800660 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700661 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
662 synchronized (this) {
663 dbHelper = getOrEstablishDatabaseLocked(callingUser);
664 cache = sSecureCaches.get(callingUser);
665 }
666 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800667 }
Christopher Tate06efb532012-08-24 15:29:27 -0700668 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
669 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
670 // fast path: owner db & cache are immutable after onCreate() so we need not
671 // guard on the attempt to look them up
672 return lookupValue(getOrEstablishDatabaseLocked(UserHandle.USER_OWNER), TABLE_GLOBAL,
673 sGlobalCache, request);
674 }
675
676 // Put methods - new value is in the args bundle under the key named by
677 // the Settings.NameValueTable.VALUE static.
678 final String newValue = (args == null)
679 ? null : args.getString(Settings.NameValueTable.VALUE);
680 if (newValue == null) {
681 throw new IllegalArgumentException("Bad value for " + method);
682 }
683
684 final ContentValues values = new ContentValues();
685 values.put(Settings.NameValueTable.NAME, request);
686 values.put(Settings.NameValueTable.VALUE, newValue);
687 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
688 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
689 insert(Settings.System.CONTENT_URI, values);
690 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
691 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
692 insert(Settings.Secure.CONTENT_URI, values);
693 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
694 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
695 insert(Settings.Global.CONTENT_URI, values);
696 } else {
697 Slog.w(TAG, "call() with invalid method: " + method);
698 }
699
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800700 return null;
701 }
702
703 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
704 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700705 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
706 final SettingsCache cache, String key) {
707 if (cache == null) {
708 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
709 return null;
710 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800711 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800712 Bundle value = cache.get(key);
713 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700714 if (value != TOO_LARGE_TO_CACHE_MARKER) {
715 return value;
716 }
717 // else we fall through and read the value from disk
718 } else if (cache.fullyMatchesDisk()) {
719 // Fast path (very common). Don't even try touch disk
720 // if we know we've slurped it all in. Trying to
721 // touch the disk would mean waiting for yaffs2 to
722 // give us access, which could takes hundreds of
723 // milliseconds. And we're very likely being called
724 // from somebody's UI thread...
725 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800726 }
727 }
728
Christopher Tate06efb532012-08-24 15:29:27 -0700729 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800730 Cursor cursor = null;
731 try {
732 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
733 null, null, null, null);
734 if (cursor != null && cursor.getCount() == 1) {
735 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800736 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800737 }
738 } catch (SQLiteException e) {
739 Log.w(TAG, "settings lookup error", e);
740 return null;
741 } finally {
742 if (cursor != null) cursor.close();
743 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800744 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800745 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800746 }
747
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700748 @Override
749 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate06efb532012-08-24 15:29:27 -0700750 final int callingUser = UserHandle.getCallingUserId();
751 if (LOCAL_LOGV) Slog.v(TAG, "query() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700752 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700753 DatabaseHelper dbH;
754 synchronized (this) {
755 dbH = getOrEstablishDatabaseLocked(callingUser);
756 }
757 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800759 // The favorites table was moved from this provider to a provider inside Home
760 // Home still need to query this table to upgrade from pre-cupcake builds
761 // However, a cupcake+ build with no data does not contain this table which will
762 // cause an exception in the SQL stack. The following line is a special case to
763 // let the caller of the query have a chance to recover and avoid the exception
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 if (TABLE_FAVORITES.equals(args.table)) {
765 return null;
766 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
767 args.table = TABLE_FAVORITES;
768 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
769 if (cursor != null) {
770 boolean exists = cursor.getCount() > 0;
771 cursor.close();
772 if (!exists) return null;
773 } else {
774 return null;
775 }
776 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800777
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700778 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
779 qb.setTables(args.table);
780
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700781 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
782 ret.setNotificationUri(getContext().getContentResolver(), url);
783 return ret;
784 }
785
786 @Override
787 public String getType(Uri url) {
788 // If SqlArguments supplies a where clause, then it must be an item
789 // (because we aren't supplying our own where clause).
790 SqlArguments args = new SqlArguments(url, null, null);
791 if (TextUtils.isEmpty(args.where)) {
792 return "vnd.android.cursor.dir/" + args.table;
793 } else {
794 return "vnd.android.cursor.item/" + args.table;
795 }
796 }
797
798 @Override
799 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700800 final int callingUser = UserHandle.getCallingUserId();
801 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700802 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 if (TABLE_FAVORITES.equals(args.table)) {
804 return 0;
805 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700806 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700807 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700808
Christopher Tate06efb532012-08-24 15:29:27 -0700809 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
810 mutationCount.incrementAndGet();
811 DatabaseHelper dbH;
812 synchronized (this) {
813 dbH = getOrEstablishDatabaseLocked(callingUser);
814 }
815 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700816 db.beginTransaction();
817 try {
818 int numValues = values.length;
819 for (int i = 0; i < numValues; i++) {
820 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800821 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700822 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
823 }
824 db.setTransactionSuccessful();
825 } finally {
826 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700827 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700828 }
829
Christopher Tate06efb532012-08-24 15:29:27 -0700830 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700831 return values.length;
832 }
833
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700834 /*
835 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
836 * This setting contains a list of the currently enabled location providers.
837 * But helper functions in android.providers.Settings can enable or disable
838 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800839 *
840 * @returns whether the database needs to be updated or not, also modifying
841 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700842 */
843 private boolean parseProviderList(Uri url, ContentValues initialValues) {
844 String value = initialValues.getAsString(Settings.Secure.VALUE);
845 String newProviders = null;
846 if (value != null && value.length() > 1) {
847 char prefix = value.charAt(0);
848 if (prefix == '+' || prefix == '-') {
849 // skip prefix
850 value = value.substring(1);
851
852 // read list of enabled providers into "providers"
853 String providers = "";
854 String[] columns = {Settings.Secure.VALUE};
855 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
856 Cursor cursor = query(url, columns, where, null, null);
857 if (cursor != null && cursor.getCount() == 1) {
858 try {
859 cursor.moveToFirst();
860 providers = cursor.getString(0);
861 } finally {
862 cursor.close();
863 }
864 }
865
866 int index = providers.indexOf(value);
867 int end = index + value.length();
868 // check for commas to avoid matching on partial string
869 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
870 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
871
872 if (prefix == '+' && index < 0) {
873 // append the provider to the list if not present
874 if (providers.length() == 0) {
875 newProviders = value;
876 } else {
877 newProviders = providers + ',' + value;
878 }
879 } else if (prefix == '-' && index >= 0) {
880 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400881 // remove leading or trailing comma
882 if (index > 0) {
883 index--;
884 } else if (end < providers.length()) {
885 end++;
886 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700887
888 newProviders = providers.substring(0, index);
889 if (end < providers.length()) {
890 newProviders += providers.substring(end);
891 }
892 } else {
893 // nothing changed, so no need to update the database
894 return false;
895 }
896
897 if (newProviders != null) {
898 initialValues.put(Settings.Secure.VALUE, newProviders);
899 }
900 }
901 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800902
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700903 return true;
904 }
905
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700906 @Override
907 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700908 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
909 }
910
911 // Settings.put*ForUser() always winds up here, so this is where we apply
912 // policy around permission to write settings for other users.
913 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
914 final int callingUser = UserHandle.getCallingUserId();
915 if (callingUser != desiredUserHandle) {
916 getContext().enforceCallingPermission(
917 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
918 "Not permitted to access settings for other users");
919 }
920
921 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
922 + " by " + callingUser);
923
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700924 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 if (TABLE_FAVORITES.equals(args.table)) {
926 return null;
927 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700928 checkWritePermissions(args);
929
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700930 // Special case LOCATION_PROVIDERS_ALLOWED.
931 // Support enabling/disabling a single provider (using "+" or "-" prefix)
932 String name = initialValues.getAsString(Settings.Secure.NAME);
933 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
934 if (!parseProviderList(url, initialValues)) return null;
935 }
936
Christopher Tate06efb532012-08-24 15:29:27 -0700937 // The global table is stored under the owner, always
938 if (TABLE_GLOBAL.equals(args.table)) {
939 desiredUserHandle = UserHandle.USER_OWNER;
940 }
941
942 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800943 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
944 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
945 return Uri.withAppendedPath(url, name);
946 }
947
Christopher Tate06efb532012-08-24 15:29:27 -0700948 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
949 mutationCount.incrementAndGet();
950 DatabaseHelper dbH;
951 synchronized (this) {
952 dbH = getOrEstablishDatabaseLocked(callingUser);
953 }
954 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700955 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700956 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700957 if (rowId <= 0) return null;
958
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800959 SettingsCache.populate(cache, initialValues); // before we notify
960
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700961 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700964 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 return url;
966 }
967
968 @Override
969 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700970 final int callingUser = UserHandle.getCallingUserId();
971 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 if (TABLE_FAVORITES.equals(args.table)) {
974 return 0;
975 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
976 args.table = TABLE_FAVORITES;
977 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978 checkWritePermissions(args);
979
Christopher Tate06efb532012-08-24 15:29:27 -0700980 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
981 mutationCount.incrementAndGet();
982 DatabaseHelper dbH;
983 synchronized (this) {
984 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800985 }
Christopher Tate06efb532012-08-24 15:29:27 -0700986 SQLiteDatabase db = dbH.getWritableDatabase();
987 int count = db.delete(args.table, args.where, args.args);
988 mutationCount.decrementAndGet();
989 if (count > 0) {
990 invalidateCache(callingUser, args.table); // before we notify
991 sendNotify(url, callingUser);
992 }
993 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700994 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
995 return count;
996 }
997
998 @Override
999 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001000 // NOTE: update() is never called by the front-end Settings API, and updates that
1001 // wind up affecting rows in Secure that are globally shared will not have the
1002 // intended effect (the update will be invisible to the rest of the system).
1003 // This should have no practical effect, since writes to the Secure db can only
1004 // be done by system code, and that code should be using the correct API up front.
1005 final int callingUser = UserHandle.getCallingUserId();
1006 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001007 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 if (TABLE_FAVORITES.equals(args.table)) {
1009 return 0;
1010 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001011 checkWritePermissions(args);
1012
Christopher Tate06efb532012-08-24 15:29:27 -07001013 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1014 mutationCount.incrementAndGet();
1015 DatabaseHelper dbH;
1016 synchronized (this) {
1017 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001018 }
Christopher Tate06efb532012-08-24 15:29:27 -07001019 SQLiteDatabase db = dbH.getWritableDatabase();
1020 int count = db.update(args.table, initialValues, args.where, args.args);
1021 mutationCount.decrementAndGet();
1022 if (count > 0) {
1023 invalidateCache(callingUser, args.table); // before we notify
1024 sendNotify(url, callingUser);
1025 }
1026 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001027 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1028 return count;
1029 }
1030
1031 @Override
1032 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1033
1034 /*
1035 * When a client attempts to openFile the default ringtone or
1036 * notification setting Uri, we will proxy the call to the current
1037 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001038 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001039 int ringtoneType = RingtoneManager.getDefaultType(uri);
1040 // Above call returns -1 if the Uri doesn't match a default type
1041 if (ringtoneType != -1) {
1042 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001043
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001044 // Get the current value for the default sound
1045 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001046
Marco Nelissen69f593c2009-07-28 09:55:04 -07001047 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001048 // Only proxy the openFile call to drm or media providers
1049 String authority = soundUri.getAuthority();
1050 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1051 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1052
1053 if (isDrmAuthority) {
1054 try {
1055 // Check DRM access permission here, since once we
1056 // do the below call the DRM will be checking our
1057 // permission, not our caller's permission
1058 DrmStore.enforceAccessDrmPermission(context);
1059 } catch (SecurityException e) {
1060 throw new FileNotFoundException(e.getMessage());
1061 }
1062 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001063
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001064 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1065 }
1066 }
1067 }
1068
1069 return super.openFile(uri, mode);
1070 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001071
1072 @Override
1073 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1074
1075 /*
1076 * When a client attempts to openFile the default ringtone or
1077 * notification setting Uri, we will proxy the call to the current
1078 * default ringtone's Uri (if it is in the DRM or media provider).
1079 */
1080 int ringtoneType = RingtoneManager.getDefaultType(uri);
1081 // Above call returns -1 if the Uri doesn't match a default type
1082 if (ringtoneType != -1) {
1083 Context context = getContext();
1084
1085 // Get the current value for the default sound
1086 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1087
1088 if (soundUri != null) {
1089 // Only proxy the openFile call to drm or media providers
1090 String authority = soundUri.getAuthority();
1091 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1092 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1093
1094 if (isDrmAuthority) {
1095 try {
1096 // Check DRM access permission here, since once we
1097 // do the below call the DRM will be checking our
1098 // permission, not our caller's permission
1099 DrmStore.enforceAccessDrmPermission(context);
1100 } catch (SecurityException e) {
1101 throw new FileNotFoundException(e.getMessage());
1102 }
1103 }
1104
1105 ParcelFileDescriptor pfd = null;
1106 try {
1107 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1108 return new AssetFileDescriptor(pfd, 0, -1);
1109 } catch (FileNotFoundException ex) {
1110 // fall through and open the fallback ringtone below
1111 }
1112 }
1113
1114 try {
1115 return super.openAssetFile(soundUri, mode);
1116 } catch (FileNotFoundException ex) {
1117 // Since a non-null Uri was specified, but couldn't be opened,
1118 // fall back to the built-in ringtone.
1119 return context.getResources().openRawResourceFd(
1120 com.android.internal.R.raw.fallbackring);
1121 }
1122 }
1123 // no need to fall through and have openFile() try again, since we
1124 // already know that will fail.
1125 throw new FileNotFoundException(); // or return null ?
1126 }
1127
1128 // Note that this will end up calling openFile() above.
1129 return super.openAssetFile(uri, mode);
1130 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001131
1132 /**
1133 * In-memory LRU Cache of system and secure settings, along with
1134 * associated helper functions to keep cache coherent with the
1135 * database.
1136 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001137 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001138
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001139 private final String mCacheName;
1140 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1141
1142 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001143 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001144 mCacheName = name;
1145 }
1146
1147 /**
1148 * Is the whole database table slurped into this cache?
1149 */
1150 public boolean fullyMatchesDisk() {
1151 synchronized (this) {
1152 return mCacheFullyMatchesDisk;
1153 }
1154 }
1155
1156 public void setFullyMatchesDisk(boolean value) {
1157 synchronized (this) {
1158 mCacheFullyMatchesDisk = value;
1159 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001160 }
1161
1162 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001163 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1164 if (evicted) {
1165 mCacheFullyMatchesDisk = false;
1166 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001167 }
1168
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001169 /**
1170 * Atomic cache population, conditional on size of value and if
1171 * we lost a race.
1172 *
1173 * @returns a Bundle to send back to the client from call(), even
1174 * if we lost the race.
1175 */
1176 public Bundle putIfAbsent(String key, String value) {
1177 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1178 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1179 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001180 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001181 put(key, bundle);
1182 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001183 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001184 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001185 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001186 }
1187
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001188 /**
1189 * Populates a key in a given (possibly-null) cache.
1190 */
1191 public static void populate(SettingsCache cache, ContentValues contentValues) {
1192 if (cache == null) {
1193 return;
1194 }
1195 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1196 if (name == null) {
1197 Log.w(TAG, "null name populating settings cache.");
1198 return;
1199 }
1200 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001201 cache.populate(name, value);
1202 }
1203
1204 public void populate(String name, String value) {
1205 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001206 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001207 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001208 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001209 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001210 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001211 }
1212 }
1213
1214 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001215 * For suppressing duplicate/redundant settings inserts early,
1216 * checking our cache first (but without faulting it in),
1217 * before going to sqlite with the mutation.
1218 */
1219 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1220 if (cache == null) return false;
1221 synchronized (cache) {
1222 Bundle bundle = cache.get(name);
1223 if (bundle == null) return false;
1224 String oldValue = bundle.getPairValue();
1225 if (oldValue == null && value == null) return true;
1226 if ((oldValue == null) != (value == null)) return false;
1227 return oldValue.equals(value);
1228 }
1229 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001230 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001231}