blob: 3a9b068a4f786a221bfab18ac98415fc4374f010 [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 Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
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;
Marco Nelissen69f593c2009-07-28 09:55:04 -070035import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036import android.database.Cursor;
37import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080038import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070039import android.database.sqlite.SQLiteQueryBuilder;
40import android.media.RingtoneManager;
41import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080043import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070044import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070045import android.os.ParcelFileDescriptor;
46import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070047import android.os.UserHandle;
48import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.provider.DrmStore;
50import android.provider.MediaStore;
51import android.provider.Settings;
52import android.text.TextUtils;
53import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080054import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070055import android.util.Slog;
56import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070057
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070058public class SettingsProvider extends ContentProvider {
59 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070060 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
Christopher Tate06efb532012-08-24 15:29:27 -070062 private static final String TABLE_SYSTEM = "system";
63 private static final String TABLE_SECURE = "secure";
64 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 private static final String TABLE_FAVORITES = "favorites";
66 private static final String TABLE_OLD_FAVORITES = "old_favorites";
67
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080068 private static final String[] COLUMN_VALUE = new String[] { "value" };
69
Christopher Tate06efb532012-08-24 15:29:27 -070070 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080071 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070072 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070073 private static final SparseArray<SettingsCache> sSystemCaches
74 = new SparseArray<SettingsCache>();
75 private static final SparseArray<SettingsCache> sSecureCaches
76 = new SparseArray<SettingsCache>();
77 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070078
79 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070080 // database mutations are currently being handled for this user.
81 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070083 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
84 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080085
Christopher Tate78d2a662012-09-13 16:19:44 -070086 // Each defined user has their own settings
87 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
88
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 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700101 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700102
103 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700104 * Settings which need to be treated as global/shared in multi-user environments.
105 */
106 static final HashSet<String> sSecureGlobalKeys;
107 static final HashSet<String> sSystemGlobalKeys;
108 static {
109 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
110 // table, shared across all users
111 // These must match Settings.Secure.MOVED_TO_GLOBAL
112 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate92198742012-09-07 12:00:13 -0700113 sSecureGlobalKeys.add(Settings.Secure.ADB_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700114 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700115 sSecureGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
Christopher Tate06efb532012-08-24 15:29:27 -0700116 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
117 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
118 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
119 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
120 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
Christopher Tate92198742012-09-07 12:00:13 -0700121 sSecureGlobalKeys.add(Settings.Secure.DATA_ROAMING);
Christopher Tate06efb532012-08-24 15:29:27 -0700122 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700123 sSecureGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
Christopher Tate06efb532012-08-24 15:29:27 -0700124 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
125 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
126 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
127 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Christopher Tate92198742012-09-07 12:00:13 -0700128 sSecureGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
Christopher Tate06efb532012-08-24 15:29:27 -0700129 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
130 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
131 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
132 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
133 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
146 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
147 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
148 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
149 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
150 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
151 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
152 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
153 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
154 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
155 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
156 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
157 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
158 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
159 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
160 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
161 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
162 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
163 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
164 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
165 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
166 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
167 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
168 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
170 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
171 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
Christopher Tate92198742012-09-07 12:00:13 -0700172 sSecureGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700173 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
174 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
175 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
176 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
177 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
178 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
190 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
191 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
192 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
193 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
Christopher Tatec868b642012-09-12 17:41:04 -0700194 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_ENABLE);
195 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_TIMEOUT);
196 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE);
197 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS);
198 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS);
199 sSecureGlobalKeys.add(Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS);
Christopher Tate06efb532012-08-24 15:29:27 -0700200 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
201
202 // Keys from the 'system' table now moved to 'global'
203 // These must match Settings.System.MOVED_TO_GLOBAL
204 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700205
206 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
207 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
208 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
209 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
210 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
211 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
212 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
213 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
214 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
215 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
216 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
217 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
218 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
219 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700220 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700221 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
222 }
223
224 private boolean settingMovedToGlobal(final String name) {
225 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
226 }
227
228 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700229 * Decode a content URL into the table, projection, and arguments
230 * used to access the corresponding database rows.
231 */
232 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700234 public final String where;
235 public final String[] args;
236
237 /** Operate on existing rows. */
238 SqlArguments(Uri url, String where, String[] args) {
239 if (url.getPathSegments().size() == 1) {
240 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700241 if (!DatabaseHelper.isValidTable(this.table)) {
242 throw new IllegalArgumentException("Bad root path: " + this.table);
243 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700244 this.where = where;
245 this.args = args;
246 } else if (url.getPathSegments().size() != 2) {
247 throw new IllegalArgumentException("Invalid URI: " + url);
248 } else if (!TextUtils.isEmpty(where)) {
249 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
250 } else {
251 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700252 if (!DatabaseHelper.isValidTable(this.table)) {
253 throw new IllegalArgumentException("Bad root path: " + this.table);
254 }
Christopher Tate06efb532012-08-24 15:29:27 -0700255 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700256 this.where = Settings.NameValueTable.NAME + "=?";
257 this.args = new String[] { url.getPathSegments().get(1) };
258 } else {
259 this.where = "_id=" + ContentUris.parseId(url);
260 this.args = null;
261 }
262 }
263 }
264
265 /** Insert new rows (no where clause allowed). */
266 SqlArguments(Uri url) {
267 if (url.getPathSegments().size() == 1) {
268 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700269 if (!DatabaseHelper.isValidTable(this.table)) {
270 throw new IllegalArgumentException("Bad root path: " + this.table);
271 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700272 this.where = null;
273 this.args = null;
274 } else {
275 throw new IllegalArgumentException("Invalid URI: " + url);
276 }
277 }
278 }
279
280 /**
281 * Get the content URI of a row added to a table.
282 * @param tableUri of the entire table
283 * @param values found in the row
284 * @param rowId of the row
285 * @return the content URI for this particular row
286 */
287 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
288 if (tableUri.getPathSegments().size() != 1) {
289 throw new IllegalArgumentException("Invalid URI: " + tableUri);
290 }
291 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700292 if (TABLE_SYSTEM.equals(table) ||
293 TABLE_SECURE.equals(table) ||
294 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700295 String name = values.getAsString(Settings.NameValueTable.NAME);
296 return Uri.withAppendedPath(tableUri, name);
297 } else {
298 return ContentUris.withAppendedId(tableUri, rowId);
299 }
300 }
301
302 /**
303 * Send a notification when a particular content URI changes.
304 * Modify the system property used to communicate the version of
305 * this table, for tables which have such a property. (The Settings
306 * contract class uses these to provide client-side caches.)
307 * @param uri to send notifications for
308 */
Christopher Tate06efb532012-08-24 15:29:27 -0700309 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700310 // Update the system property *first*, so if someone is listening for
311 // a notification and then using the contract class to get their data,
312 // the system property will be updated and they'll get the new data.
313
Amith Yamasanid1582142009-07-08 20:04:55 -0700314 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700315 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700316 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700317 if (table.equals(TABLE_SYSTEM)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700318 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700319 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700320 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700321 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700322 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700323 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700324 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700325 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700326 }
327
328 if (property != null) {
329 long version = SystemProperties.getLong(property, 0) + 1;
330 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
331 SystemProperties.set(property, Long.toString(version));
332 }
333
-b master501eec92009-07-06 13:53:11 -0700334 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700335 if (backedUpDataChanged) {
336 mBackupManager.dataChanged();
337 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700338 // Now send the notification through the content framework.
339
340 String notify = uri.getQueryParameter("notify");
341 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700342 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700343 final long oldId = Binder.clearCallingIdentity();
344 try {
345 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
346 } finally {
347 Binder.restoreCallingIdentity(oldId);
348 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700349 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700350 } else {
351 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
352 }
353 }
354
355 /**
356 * Make sure the caller has permission to write this data.
357 * @param args supplied by the caller
358 * @throws SecurityException if the caller is forbidden to write.
359 */
360 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700361 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800362 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800363 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
364 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700365 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800366 String.format("Permission denial: writing to secure settings requires %1$s",
367 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368 }
369 }
370
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700371 // FileObserver for external modifications to the database file.
372 // Note that this is for platform developers only with
373 // userdebug/eng builds who should be able to tinker with the
374 // sqlite database out from under the SettingsProvider, which is
375 // normally the exclusive owner of the database. But we keep this
376 // enabled all the time to minimize development-vs-user
377 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700378 private static SparseArray<SettingsFileObserver> sObserverInstances
379 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700380 private class SettingsFileObserver extends FileObserver {
381 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700382 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700383 private final String mPath;
384
Christopher Tate06efb532012-08-24 15:29:27 -0700385 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700386 super(path, FileObserver.CLOSE_WRITE |
387 FileObserver.CREATE | FileObserver.DELETE |
388 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700389 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700390 mPath = path;
391 }
392
393 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700394 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700395 if (modsInFlight > 0) {
396 // our own modification.
397 return;
398 }
Christopher Tate06efb532012-08-24 15:29:27 -0700399 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
400 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700401 if (!mIsDirty.compareAndSet(false, true)) {
402 // already handled. (we get a few update events
403 // during an sqlite write)
404 return;
405 }
Christopher Tate06efb532012-08-24 15:29:27 -0700406 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
407 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700408 mIsDirty.set(false);
409 }
410 }
411
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700412 @Override
413 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700414 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700415 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800416
Christopher Tate78d2a662012-09-13 16:19:44 -0700417 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700418
Christopher Tate78d2a662012-09-13 16:19:44 -0700419 IntentFilter userFilter = new IntentFilter();
420 userFilter.addAction(Intent.ACTION_USER_REMOVED);
421 getContext().registerReceiver(new BroadcastReceiver() {
422 @Override
423 public void onReceive(Context context, Intent intent) {
424 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
425 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
426 UserHandle.USER_OWNER);
427 if (userHandle != UserHandle.USER_OWNER) {
428 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700429 }
430 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700431 }
432 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700433 return true;
434 }
435
Christopher Tate06efb532012-08-24 15:29:27 -0700436 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700437 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700438 // the db file itself will be deleted automatically, but we need to tear down
439 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700440 FileObserver observer = sObserverInstances.get(userHandle);
441 if (observer != null) {
442 observer.stopWatching();
443 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700444 }
Christopher Tate06efb532012-08-24 15:29:27 -0700445
446 mOpenHelpers.delete(userHandle);
447 sSystemCaches.delete(userHandle);
448 sSecureCaches.delete(userHandle);
449 sKnownMutationsInFlight.delete(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700450 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700451 }
452
Christopher Tate78d2a662012-09-13 16:19:44 -0700453 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700454 if (LOCAL_LOGV) {
455 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
456 }
457
Christopher Tate78d2a662012-09-13 16:19:44 -0700458 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700459
Christopher Tate78d2a662012-09-13 16:19:44 -0700460 synchronized (this) {
461 dbhelper = mOpenHelpers.get(userHandle);
462 if (dbhelper == null) {
463 dbhelper = new DatabaseHelper(getContext(), userHandle);
464 mOpenHelpers.append(userHandle, dbhelper);
465
466 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
467 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
468 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
469 }
470 }
471
472 // Initialization of the db *outside* the locks. It's possible that racing
473 // threads might wind up here, the second having read the cache entries
474 // written by the first, but that's benign: the SQLite helper implementation
475 // manages concurrency itself, and it's important that we not run the db
476 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700477 SQLiteDatabase db = dbhelper.getWritableDatabase();
478
Christopher Tate78d2a662012-09-13 16:19:44 -0700479 // Watch for external modifications to the database files,
480 // keeping our caches in sync. We synchronize the observer set
481 // separately, and of course it has to run after the db file
482 // itself was set up by the DatabaseHelper.
483 synchronized (sObserverInstances) {
484 if (sObserverInstances.get(userHandle) == null) {
485 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
486 sObserverInstances.append(userHandle, observer);
487 observer.startWatching();
488 }
489 }
Christopher Tate06efb532012-08-24 15:29:27 -0700490
Christopher Tate4dc7a682012-09-11 12:15:49 -0700491 ensureAndroidIdIsSet(userHandle);
492
Christopher Tate06efb532012-08-24 15:29:27 -0700493 startAsyncCachePopulation(userHandle);
494 }
495
496 class CachePrefetchThread extends Thread {
497 private int mUserHandle;
498
499 CachePrefetchThread(int userHandle) {
500 super("populate-settings-caches");
501 mUserHandle = userHandle;
502 }
503
504 @Override
505 public void run() {
506 fullyPopulateCaches(mUserHandle);
507 }
508 }
509
510 private void startAsyncCachePopulation(int userHandle) {
511 new CachePrefetchThread(userHandle).start();
512 }
513
514 private void fullyPopulateCaches(final int userHandle) {
515 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
516 // Only populate the globals cache once, for the owning user
517 if (userHandle == UserHandle.USER_OWNER) {
518 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
519 }
520 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
521 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700522 }
523
524 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700525 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
526 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700527 Cursor c = db.query(
528 table,
529 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
530 null, null, null, null, null,
531 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
532 try {
533 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800534 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700535 cache.setFullyMatchesDisk(true); // optimistic
536 int rows = 0;
537 while (c.moveToNext()) {
538 rows++;
539 String name = c.getString(0);
540 String value = c.getString(1);
541 cache.populate(name, value);
542 }
543 if (rows > MAX_CACHE_ENTRIES) {
544 // Somewhat redundant, as removeEldestEntry() will
545 // have already done this, but to be explicit:
546 cache.setFullyMatchesDisk(false);
547 Log.d(TAG, "row count exceeds max cache entries for table " + table);
548 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700549 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700550 cache.fullyMatchesDisk());
551 }
552 } finally {
553 c.close();
554 }
555 }
556
Christopher Tate4dc7a682012-09-11 12:15:49 -0700557 private boolean ensureAndroidIdIsSet(int userHandle) {
558 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800559 new String[] { Settings.NameValueTable.VALUE },
560 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700561 new String[] { Settings.Secure.ANDROID_ID }, null,
562 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800563 try {
564 final String value = c.moveToNext() ? c.getString(0) : null;
565 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700566 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800567 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800568 final ContentValues values = new ContentValues();
569 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
570 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700571 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800572 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700573 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800574 return false;
575 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700576 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
577 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800578 }
579 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800580 } finally {
581 c.close();
582 }
583 }
584
Christopher Tate06efb532012-08-24 15:29:27 -0700585 // Lazy-initialize the settings caches for non-primary users
586 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700587 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
588 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700589 }
590
591 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700592 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700593 long oldId = Binder.clearCallingIdentity();
594 try {
595 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
596 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700597 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700598 dbHelper = mOpenHelpers.get(callingUser);
599 }
600 return dbHelper;
601 } finally {
602 Binder.restoreCallingIdentity(oldId);
603 }
604 }
605
606 public SettingsCache cacheForTable(final int callingUser, String tableName) {
607 if (TABLE_SYSTEM.equals(tableName)) {
608 return getOrConstructCache(callingUser, sSystemCaches);
609 }
610 if (TABLE_SECURE.equals(tableName)) {
611 return getOrConstructCache(callingUser, sSecureCaches);
612 }
613 if (TABLE_GLOBAL.equals(tableName)) {
614 return sGlobalCache;
615 }
616 return null;
617 }
618
619 /**
620 * Used for wiping a whole cache on deletes when we're not
621 * sure what exactly was deleted or changed.
622 */
623 public void invalidateCache(final int callingUser, String tableName) {
624 SettingsCache cache = cacheForTable(callingUser, tableName);
625 if (cache == null) {
626 return;
627 }
628 synchronized (cache) {
629 cache.evictAll();
630 cache.mCacheFullyMatchesDisk = false;
631 }
632 }
633
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800634 /**
635 * Fast path that avoids the use of chatty remoted Cursors.
636 */
637 @Override
638 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700639 int callingUser = UserHandle.getCallingUserId();
640 if (args != null) {
641 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
642 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700643 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
644 Binder.getCallingUid(), reqUser, false, true,
645 "get/set setting for user", null);
646 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700647 }
648 }
649
Christopher Tateb7564452012-09-19 16:21:18 -0700650 // Okay, permission checks have cleared. Reset to our own identity so we can
651 // manipulate all users' data with impunity.
652 long oldId = Binder.clearCallingIdentity();
653 try {
654 // Note: we assume that get/put operations for moved-to-global names have already
655 // been directed to the new location on the caller side (otherwise we'd fix them
656 // up here).
657 DatabaseHelper dbHelper;
658 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700659
Christopher Tateb7564452012-09-19 16:21:18 -0700660 // Get methods
661 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
662 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
663 dbHelper = getOrEstablishDatabase(callingUser);
664 cache = sSystemCaches.get(callingUser);
665 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
666 }
667 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
668 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
669 dbHelper = getOrEstablishDatabase(callingUser);
670 cache = sSecureCaches.get(callingUser);
671 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
672 }
673 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
674 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
675 // fast path: owner db & cache are immutable after onCreate() so we need not
676 // guard on the attempt to look them up
677 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
678 sGlobalCache, request);
679 }
Christopher Tate06efb532012-08-24 15:29:27 -0700680
Christopher Tateb7564452012-09-19 16:21:18 -0700681 // Put methods - new value is in the args bundle under the key named by
682 // the Settings.NameValueTable.VALUE static.
683 final String newValue = (args == null)
684 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700685
Christopher Tateb7564452012-09-19 16:21:18 -0700686 final ContentValues values = new ContentValues();
687 values.put(Settings.NameValueTable.NAME, request);
688 values.put(Settings.NameValueTable.VALUE, newValue);
689 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
690 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
691 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
692 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
693 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
694 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
695 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
696 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
697 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
698 } else {
699 Slog.w(TAG, "call() with invalid method: " + method);
700 }
701 } finally {
702 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700703 }
704
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800705 return null;
706 }
707
708 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
709 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700710 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
711 final SettingsCache cache, String key) {
712 if (cache == null) {
713 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
714 return null;
715 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800716 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800717 Bundle value = cache.get(key);
718 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700719 if (value != TOO_LARGE_TO_CACHE_MARKER) {
720 return value;
721 }
722 // else we fall through and read the value from disk
723 } else if (cache.fullyMatchesDisk()) {
724 // Fast path (very common). Don't even try touch disk
725 // if we know we've slurped it all in. Trying to
726 // touch the disk would mean waiting for yaffs2 to
727 // give us access, which could takes hundreds of
728 // milliseconds. And we're very likely being called
729 // from somebody's UI thread...
730 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800731 }
732 }
733
Christopher Tate06efb532012-08-24 15:29:27 -0700734 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800735 Cursor cursor = null;
736 try {
737 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
738 null, null, null, null);
739 if (cursor != null && cursor.getCount() == 1) {
740 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800741 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800742 }
743 } catch (SQLiteException e) {
744 Log.w(TAG, "settings lookup error", e);
745 return null;
746 } finally {
747 if (cursor != null) cursor.close();
748 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800749 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800750 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800751 }
752
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700753 @Override
754 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700755 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
756 }
757
Christopher Tateb7564452012-09-19 16:21:18 -0700758 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700759 String sort, int forUser) {
760 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700761 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700762 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700763 dbH = getOrEstablishDatabase(
764 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700765 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800767 // The favorites table was moved from this provider to a provider inside Home
768 // Home still need to query this table to upgrade from pre-cupcake builds
769 // However, a cupcake+ build with no data does not contain this table which will
770 // cause an exception in the SQL stack. The following line is a special case to
771 // 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 -0800772 if (TABLE_FAVORITES.equals(args.table)) {
773 return null;
774 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
775 args.table = TABLE_FAVORITES;
776 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
777 if (cursor != null) {
778 boolean exists = cursor.getCount() > 0;
779 cursor.close();
780 if (!exists) return null;
781 } else {
782 return null;
783 }
784 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800785
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700786 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
787 qb.setTables(args.table);
788
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700789 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
790 ret.setNotificationUri(getContext().getContentResolver(), url);
791 return ret;
792 }
793
794 @Override
795 public String getType(Uri url) {
796 // If SqlArguments supplies a where clause, then it must be an item
797 // (because we aren't supplying our own where clause).
798 SqlArguments args = new SqlArguments(url, null, null);
799 if (TextUtils.isEmpty(args.where)) {
800 return "vnd.android.cursor.dir/" + args.table;
801 } else {
802 return "vnd.android.cursor.item/" + args.table;
803 }
804 }
805
806 @Override
807 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700808 final int callingUser = UserHandle.getCallingUserId();
809 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700810 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (TABLE_FAVORITES.equals(args.table)) {
812 return 0;
813 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700814 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700815 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700816
Christopher Tate06efb532012-08-24 15:29:27 -0700817 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
818 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700819 DatabaseHelper dbH = getOrEstablishDatabase(
820 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700821 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700822 db.beginTransaction();
823 try {
824 int numValues = values.length;
825 for (int i = 0; i < numValues; i++) {
826 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800827 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700828 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
829 }
830 db.setTransactionSuccessful();
831 } finally {
832 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700833 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700834 }
835
Christopher Tate06efb532012-08-24 15:29:27 -0700836 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700837 return values.length;
838 }
839
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700840 /*
841 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
842 * This setting contains a list of the currently enabled location providers.
843 * But helper functions in android.providers.Settings can enable or disable
844 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800845 *
846 * @returns whether the database needs to be updated or not, also modifying
847 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700848 */
849 private boolean parseProviderList(Uri url, ContentValues initialValues) {
850 String value = initialValues.getAsString(Settings.Secure.VALUE);
851 String newProviders = null;
852 if (value != null && value.length() > 1) {
853 char prefix = value.charAt(0);
854 if (prefix == '+' || prefix == '-') {
855 // skip prefix
856 value = value.substring(1);
857
858 // read list of enabled providers into "providers"
859 String providers = "";
860 String[] columns = {Settings.Secure.VALUE};
861 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
862 Cursor cursor = query(url, columns, where, null, null);
863 if (cursor != null && cursor.getCount() == 1) {
864 try {
865 cursor.moveToFirst();
866 providers = cursor.getString(0);
867 } finally {
868 cursor.close();
869 }
870 }
871
872 int index = providers.indexOf(value);
873 int end = index + value.length();
874 // check for commas to avoid matching on partial string
875 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
876 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
877
878 if (prefix == '+' && index < 0) {
879 // append the provider to the list if not present
880 if (providers.length() == 0) {
881 newProviders = value;
882 } else {
883 newProviders = providers + ',' + value;
884 }
885 } else if (prefix == '-' && index >= 0) {
886 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400887 // remove leading or trailing comma
888 if (index > 0) {
889 index--;
890 } else if (end < providers.length()) {
891 end++;
892 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700893
894 newProviders = providers.substring(0, index);
895 if (end < providers.length()) {
896 newProviders += providers.substring(end);
897 }
898 } else {
899 // nothing changed, so no need to update the database
900 return false;
901 }
902
903 if (newProviders != null) {
904 initialValues.put(Settings.Secure.VALUE, newProviders);
905 }
906 }
907 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800908
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700909 return true;
910 }
911
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700912 @Override
913 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700914 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
915 }
916
917 // Settings.put*ForUser() always winds up here, so this is where we apply
918 // policy around permission to write settings for other users.
919 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
920 final int callingUser = UserHandle.getCallingUserId();
921 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700922 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700923 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
924 "Not permitted to access settings for other users");
925 }
926
927 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
928 + " by " + callingUser);
929
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700930 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 if (TABLE_FAVORITES.equals(args.table)) {
932 return null;
933 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700934 checkWritePermissions(args);
935
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700936 // Special case LOCATION_PROVIDERS_ALLOWED.
937 // Support enabling/disabling a single provider (using "+" or "-" prefix)
938 String name = initialValues.getAsString(Settings.Secure.NAME);
939 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
940 if (!parseProviderList(url, initialValues)) return null;
941 }
942
Christopher Tate06efb532012-08-24 15:29:27 -0700943 // The global table is stored under the owner, always
944 if (TABLE_GLOBAL.equals(args.table)) {
945 desiredUserHandle = UserHandle.USER_OWNER;
946 }
947
948 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800949 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
950 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
951 return Uri.withAppendedPath(url, name);
952 }
953
Christopher Tate06efb532012-08-24 15:29:27 -0700954 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
955 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700956 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700957 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700958 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700959 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700960 if (rowId <= 0) return null;
961
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800962 SettingsCache.populate(cache, initialValues); // before we notify
963
Christopher Tate78d2a662012-09-13 16:19:44 -0700964 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
965 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700966 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700967 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700968 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700969 return url;
970 }
971
972 @Override
973 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700974 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700975 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700976 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 if (TABLE_FAVORITES.equals(args.table)) {
978 return 0;
979 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
980 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700981 } else if (TABLE_GLOBAL.equals(args.table)) {
982 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700984 checkWritePermissions(args);
985
Christopher Tate06efb532012-08-24 15:29:27 -0700986 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
987 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700988 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700989 SQLiteDatabase db = dbH.getWritableDatabase();
990 int count = db.delete(args.table, args.where, args.args);
991 mutationCount.decrementAndGet();
992 if (count > 0) {
993 invalidateCache(callingUser, args.table); // before we notify
994 sendNotify(url, callingUser);
995 }
996 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700997 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
998 return count;
999 }
1000
1001 @Override
1002 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001003 // NOTE: update() is never called by the front-end Settings API, and updates that
1004 // wind up affecting rows in Secure that are globally shared will not have the
1005 // intended effect (the update will be invisible to the rest of the system).
1006 // This should have no practical effect, since writes to the Secure db can only
1007 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001008 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001009 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001010 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 if (TABLE_FAVORITES.equals(args.table)) {
1012 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001013 } else if (TABLE_GLOBAL.equals(args.table)) {
1014 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001016 checkWritePermissions(args);
1017
Christopher Tate06efb532012-08-24 15:29:27 -07001018 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1019 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001020 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001021 SQLiteDatabase db = dbH.getWritableDatabase();
1022 int count = db.update(args.table, initialValues, args.where, args.args);
1023 mutationCount.decrementAndGet();
1024 if (count > 0) {
1025 invalidateCache(callingUser, args.table); // before we notify
1026 sendNotify(url, callingUser);
1027 }
1028 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001029 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1030 return count;
1031 }
1032
1033 @Override
1034 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1035
1036 /*
1037 * When a client attempts to openFile the default ringtone or
1038 * notification setting Uri, we will proxy the call to the current
1039 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001040 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001041 int ringtoneType = RingtoneManager.getDefaultType(uri);
1042 // Above call returns -1 if the Uri doesn't match a default type
1043 if (ringtoneType != -1) {
1044 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001045
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001046 // Get the current value for the default sound
1047 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001048
Marco Nelissen69f593c2009-07-28 09:55:04 -07001049 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001050 // Only proxy the openFile call to drm or media providers
1051 String authority = soundUri.getAuthority();
1052 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1053 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1054
1055 if (isDrmAuthority) {
1056 try {
1057 // Check DRM access permission here, since once we
1058 // do the below call the DRM will be checking our
1059 // permission, not our caller's permission
1060 DrmStore.enforceAccessDrmPermission(context);
1061 } catch (SecurityException e) {
1062 throw new FileNotFoundException(e.getMessage());
1063 }
1064 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001066 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1067 }
1068 }
1069 }
1070
1071 return super.openFile(uri, mode);
1072 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001073
1074 @Override
1075 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1076
1077 /*
1078 * When a client attempts to openFile the default ringtone or
1079 * notification setting Uri, we will proxy the call to the current
1080 * default ringtone's Uri (if it is in the DRM or media provider).
1081 */
1082 int ringtoneType = RingtoneManager.getDefaultType(uri);
1083 // Above call returns -1 if the Uri doesn't match a default type
1084 if (ringtoneType != -1) {
1085 Context context = getContext();
1086
1087 // Get the current value for the default sound
1088 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1089
1090 if (soundUri != null) {
1091 // Only proxy the openFile call to drm or media providers
1092 String authority = soundUri.getAuthority();
1093 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1094 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1095
1096 if (isDrmAuthority) {
1097 try {
1098 // Check DRM access permission here, since once we
1099 // do the below call the DRM will be checking our
1100 // permission, not our caller's permission
1101 DrmStore.enforceAccessDrmPermission(context);
1102 } catch (SecurityException e) {
1103 throw new FileNotFoundException(e.getMessage());
1104 }
1105 }
1106
1107 ParcelFileDescriptor pfd = null;
1108 try {
1109 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1110 return new AssetFileDescriptor(pfd, 0, -1);
1111 } catch (FileNotFoundException ex) {
1112 // fall through and open the fallback ringtone below
1113 }
1114 }
1115
1116 try {
1117 return super.openAssetFile(soundUri, mode);
1118 } catch (FileNotFoundException ex) {
1119 // Since a non-null Uri was specified, but couldn't be opened,
1120 // fall back to the built-in ringtone.
1121 return context.getResources().openRawResourceFd(
1122 com.android.internal.R.raw.fallbackring);
1123 }
1124 }
1125 // no need to fall through and have openFile() try again, since we
1126 // already know that will fail.
1127 throw new FileNotFoundException(); // or return null ?
1128 }
1129
1130 // Note that this will end up calling openFile() above.
1131 return super.openAssetFile(uri, mode);
1132 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001133
1134 /**
1135 * In-memory LRU Cache of system and secure settings, along with
1136 * associated helper functions to keep cache coherent with the
1137 * database.
1138 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001139 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001140
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001141 private final String mCacheName;
1142 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1143
1144 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001145 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001146 mCacheName = name;
1147 }
1148
1149 /**
1150 * Is the whole database table slurped into this cache?
1151 */
1152 public boolean fullyMatchesDisk() {
1153 synchronized (this) {
1154 return mCacheFullyMatchesDisk;
1155 }
1156 }
1157
1158 public void setFullyMatchesDisk(boolean value) {
1159 synchronized (this) {
1160 mCacheFullyMatchesDisk = value;
1161 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001162 }
1163
1164 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001165 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1166 if (evicted) {
1167 mCacheFullyMatchesDisk = false;
1168 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001169 }
1170
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001171 /**
1172 * Atomic cache population, conditional on size of value and if
1173 * we lost a race.
1174 *
1175 * @returns a Bundle to send back to the client from call(), even
1176 * if we lost the race.
1177 */
1178 public Bundle putIfAbsent(String key, String value) {
1179 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1180 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1181 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001182 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001183 put(key, bundle);
1184 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001185 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001186 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001187 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001188 }
1189
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001190 /**
1191 * Populates a key in a given (possibly-null) cache.
1192 */
1193 public static void populate(SettingsCache cache, ContentValues contentValues) {
1194 if (cache == null) {
1195 return;
1196 }
1197 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1198 if (name == null) {
1199 Log.w(TAG, "null name populating settings cache.");
1200 return;
1201 }
1202 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001203 cache.populate(name, value);
1204 }
1205
1206 public void populate(String name, String value) {
1207 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001208 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001209 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001210 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001211 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001212 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001213 }
1214 }
1215
1216 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001217 * For suppressing duplicate/redundant settings inserts early,
1218 * checking our cache first (but without faulting it in),
1219 * before going to sqlite with the mutation.
1220 */
1221 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1222 if (cache == null) return false;
1223 synchronized (cache) {
1224 Bundle bundle = cache.get(name);
1225 if (bundle == null) return false;
1226 String oldValue = bundle.getPairValue();
1227 if (oldValue == null && value == null) return true;
1228 if ((oldValue == null) != (value == null)) return false;
1229 return oldValue.equals(value);
1230 }
1231 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001232 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001233}