blob: f0b8812937103e90d4e56bb244031886d9f43a50 [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)) {
318 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700319 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700320 } else if (table.equals(TABLE_SECURE)) {
321 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
322 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);
450
451 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
452 SystemProperties.set(property, "");
453 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
454 SystemProperties.set(property, "");
455 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700456 }
457
Christopher Tate78d2a662012-09-13 16:19:44 -0700458 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700459 if (LOCAL_LOGV) {
460 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
461 }
462
Christopher Tate78d2a662012-09-13 16:19:44 -0700463 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700464
Christopher Tate78d2a662012-09-13 16:19:44 -0700465 synchronized (this) {
466 dbhelper = mOpenHelpers.get(userHandle);
467 if (dbhelper == null) {
468 dbhelper = new DatabaseHelper(getContext(), userHandle);
469 mOpenHelpers.append(userHandle, dbhelper);
470
471 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
472 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
473 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
474 }
475 }
476
477 // Initialization of the db *outside* the locks. It's possible that racing
478 // threads might wind up here, the second having read the cache entries
479 // written by the first, but that's benign: the SQLite helper implementation
480 // manages concurrency itself, and it's important that we not run the db
481 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700482 SQLiteDatabase db = dbhelper.getWritableDatabase();
483
Christopher Tate78d2a662012-09-13 16:19:44 -0700484 // Watch for external modifications to the database files,
485 // keeping our caches in sync. We synchronize the observer set
486 // separately, and of course it has to run after the db file
487 // itself was set up by the DatabaseHelper.
488 synchronized (sObserverInstances) {
489 if (sObserverInstances.get(userHandle) == null) {
490 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
491 sObserverInstances.append(userHandle, observer);
492 observer.startWatching();
493 }
494 }
Christopher Tate06efb532012-08-24 15:29:27 -0700495
Christopher Tate4dc7a682012-09-11 12:15:49 -0700496 ensureAndroidIdIsSet(userHandle);
497
Christopher Tate06efb532012-08-24 15:29:27 -0700498 startAsyncCachePopulation(userHandle);
499 }
500
501 class CachePrefetchThread extends Thread {
502 private int mUserHandle;
503
504 CachePrefetchThread(int userHandle) {
505 super("populate-settings-caches");
506 mUserHandle = userHandle;
507 }
508
509 @Override
510 public void run() {
511 fullyPopulateCaches(mUserHandle);
512 }
513 }
514
515 private void startAsyncCachePopulation(int userHandle) {
516 new CachePrefetchThread(userHandle).start();
517 }
518
519 private void fullyPopulateCaches(final int userHandle) {
520 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
521 // Only populate the globals cache once, for the owning user
522 if (userHandle == UserHandle.USER_OWNER) {
523 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
524 }
525 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
526 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700527 }
528
529 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700530 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
531 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700532 Cursor c = db.query(
533 table,
534 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
535 null, null, null, null, null,
536 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
537 try {
538 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800539 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700540 cache.setFullyMatchesDisk(true); // optimistic
541 int rows = 0;
542 while (c.moveToNext()) {
543 rows++;
544 String name = c.getString(0);
545 String value = c.getString(1);
546 cache.populate(name, value);
547 }
548 if (rows > MAX_CACHE_ENTRIES) {
549 // Somewhat redundant, as removeEldestEntry() will
550 // have already done this, but to be explicit:
551 cache.setFullyMatchesDisk(false);
552 Log.d(TAG, "row count exceeds max cache entries for table " + table);
553 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700554 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700555 cache.fullyMatchesDisk());
556 }
557 } finally {
558 c.close();
559 }
560 }
561
Christopher Tate4dc7a682012-09-11 12:15:49 -0700562 private boolean ensureAndroidIdIsSet(int userHandle) {
563 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800564 new String[] { Settings.NameValueTable.VALUE },
565 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700566 new String[] { Settings.Secure.ANDROID_ID }, null,
567 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800568 try {
569 final String value = c.moveToNext() ? c.getString(0) : null;
570 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700571 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800572 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800573 final ContentValues values = new ContentValues();
574 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
575 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700576 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800577 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700578 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800579 return false;
580 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700581 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
582 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800583 }
584 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800585 } finally {
586 c.close();
587 }
588 }
589
Christopher Tate06efb532012-08-24 15:29:27 -0700590 // Lazy-initialize the settings caches for non-primary users
591 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700592 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
593 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700594 }
595
596 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700597 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700598 long oldId = Binder.clearCallingIdentity();
599 try {
600 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
601 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700602 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700603 dbHelper = mOpenHelpers.get(callingUser);
604 }
605 return dbHelper;
606 } finally {
607 Binder.restoreCallingIdentity(oldId);
608 }
609 }
610
611 public SettingsCache cacheForTable(final int callingUser, String tableName) {
612 if (TABLE_SYSTEM.equals(tableName)) {
613 return getOrConstructCache(callingUser, sSystemCaches);
614 }
615 if (TABLE_SECURE.equals(tableName)) {
616 return getOrConstructCache(callingUser, sSecureCaches);
617 }
618 if (TABLE_GLOBAL.equals(tableName)) {
619 return sGlobalCache;
620 }
621 return null;
622 }
623
624 /**
625 * Used for wiping a whole cache on deletes when we're not
626 * sure what exactly was deleted or changed.
627 */
628 public void invalidateCache(final int callingUser, String tableName) {
629 SettingsCache cache = cacheForTable(callingUser, tableName);
630 if (cache == null) {
631 return;
632 }
633 synchronized (cache) {
634 cache.evictAll();
635 cache.mCacheFullyMatchesDisk = false;
636 }
637 }
638
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800639 /**
640 * Fast path that avoids the use of chatty remoted Cursors.
641 */
642 @Override
643 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700644 int callingUser = UserHandle.getCallingUserId();
645 if (args != null) {
646 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
647 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700648 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
649 Binder.getCallingUid(), reqUser, false, true,
650 "get/set setting for user", null);
651 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700652 }
653 }
654
Christopher Tateb7564452012-09-19 16:21:18 -0700655 // Okay, permission checks have cleared. Reset to our own identity so we can
656 // manipulate all users' data with impunity.
657 long oldId = Binder.clearCallingIdentity();
658 try {
659 // Note: we assume that get/put operations for moved-to-global names have already
660 // been directed to the new location on the caller side (otherwise we'd fix them
661 // up here).
662 DatabaseHelper dbHelper;
663 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700664
Christopher Tateb7564452012-09-19 16:21:18 -0700665 // Get methods
666 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
667 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
668 dbHelper = getOrEstablishDatabase(callingUser);
669 cache = sSystemCaches.get(callingUser);
670 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
671 }
672 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
673 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
674 dbHelper = getOrEstablishDatabase(callingUser);
675 cache = sSecureCaches.get(callingUser);
676 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
677 }
678 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
679 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
680 // fast path: owner db & cache are immutable after onCreate() so we need not
681 // guard on the attempt to look them up
682 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
683 sGlobalCache, request);
684 }
Christopher Tate06efb532012-08-24 15:29:27 -0700685
Christopher Tateb7564452012-09-19 16:21:18 -0700686 // Put methods - new value is in the args bundle under the key named by
687 // the Settings.NameValueTable.VALUE static.
688 final String newValue = (args == null)
689 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700690
Christopher Tateb7564452012-09-19 16:21:18 -0700691 final ContentValues values = new ContentValues();
692 values.put(Settings.NameValueTable.NAME, request);
693 values.put(Settings.NameValueTable.VALUE, newValue);
694 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
695 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
696 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
697 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
698 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
699 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
700 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
701 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
702 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
703 } else {
704 Slog.w(TAG, "call() with invalid method: " + method);
705 }
706 } finally {
707 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700708 }
709
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800710 return null;
711 }
712
713 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
714 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700715 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
716 final SettingsCache cache, String key) {
717 if (cache == null) {
718 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
719 return null;
720 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800721 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800722 Bundle value = cache.get(key);
723 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700724 if (value != TOO_LARGE_TO_CACHE_MARKER) {
725 return value;
726 }
727 // else we fall through and read the value from disk
728 } else if (cache.fullyMatchesDisk()) {
729 // Fast path (very common). Don't even try touch disk
730 // if we know we've slurped it all in. Trying to
731 // touch the disk would mean waiting for yaffs2 to
732 // give us access, which could takes hundreds of
733 // milliseconds. And we're very likely being called
734 // from somebody's UI thread...
735 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800736 }
737 }
738
Christopher Tate06efb532012-08-24 15:29:27 -0700739 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800740 Cursor cursor = null;
741 try {
742 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
743 null, null, null, null);
744 if (cursor != null && cursor.getCount() == 1) {
745 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800746 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800747 }
748 } catch (SQLiteException e) {
749 Log.w(TAG, "settings lookup error", e);
750 return null;
751 } finally {
752 if (cursor != null) cursor.close();
753 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800754 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800755 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800756 }
757
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700758 @Override
759 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700760 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
761 }
762
Christopher Tateb7564452012-09-19 16:21:18 -0700763 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700764 String sort, int forUser) {
765 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700766 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700767 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700768 dbH = getOrEstablishDatabase(
769 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700770 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800772 // The favorites table was moved from this provider to a provider inside Home
773 // Home still need to query this table to upgrade from pre-cupcake builds
774 // However, a cupcake+ build with no data does not contain this table which will
775 // cause an exception in the SQL stack. The following line is a special case to
776 // 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 -0800777 if (TABLE_FAVORITES.equals(args.table)) {
778 return null;
779 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
780 args.table = TABLE_FAVORITES;
781 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
782 if (cursor != null) {
783 boolean exists = cursor.getCount() > 0;
784 cursor.close();
785 if (!exists) return null;
786 } else {
787 return null;
788 }
789 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800790
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700791 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
792 qb.setTables(args.table);
793
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700794 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
795 ret.setNotificationUri(getContext().getContentResolver(), url);
796 return ret;
797 }
798
799 @Override
800 public String getType(Uri url) {
801 // If SqlArguments supplies a where clause, then it must be an item
802 // (because we aren't supplying our own where clause).
803 SqlArguments args = new SqlArguments(url, null, null);
804 if (TextUtils.isEmpty(args.where)) {
805 return "vnd.android.cursor.dir/" + args.table;
806 } else {
807 return "vnd.android.cursor.item/" + args.table;
808 }
809 }
810
811 @Override
812 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700813 final int callingUser = UserHandle.getCallingUserId();
814 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700815 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (TABLE_FAVORITES.equals(args.table)) {
817 return 0;
818 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700819 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700820 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700821
Christopher Tate06efb532012-08-24 15:29:27 -0700822 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
823 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700824 DatabaseHelper dbH = getOrEstablishDatabase(
825 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700826 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700827 db.beginTransaction();
828 try {
829 int numValues = values.length;
830 for (int i = 0; i < numValues; i++) {
831 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800832 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700833 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
834 }
835 db.setTransactionSuccessful();
836 } finally {
837 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700838 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700839 }
840
Christopher Tate06efb532012-08-24 15:29:27 -0700841 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700842 return values.length;
843 }
844
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700845 /*
846 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
847 * This setting contains a list of the currently enabled location providers.
848 * But helper functions in android.providers.Settings can enable or disable
849 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800850 *
851 * @returns whether the database needs to be updated or not, also modifying
852 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700853 */
854 private boolean parseProviderList(Uri url, ContentValues initialValues) {
855 String value = initialValues.getAsString(Settings.Secure.VALUE);
856 String newProviders = null;
857 if (value != null && value.length() > 1) {
858 char prefix = value.charAt(0);
859 if (prefix == '+' || prefix == '-') {
860 // skip prefix
861 value = value.substring(1);
862
863 // read list of enabled providers into "providers"
864 String providers = "";
865 String[] columns = {Settings.Secure.VALUE};
866 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
867 Cursor cursor = query(url, columns, where, null, null);
868 if (cursor != null && cursor.getCount() == 1) {
869 try {
870 cursor.moveToFirst();
871 providers = cursor.getString(0);
872 } finally {
873 cursor.close();
874 }
875 }
876
877 int index = providers.indexOf(value);
878 int end = index + value.length();
879 // check for commas to avoid matching on partial string
880 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
881 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
882
883 if (prefix == '+' && index < 0) {
884 // append the provider to the list if not present
885 if (providers.length() == 0) {
886 newProviders = value;
887 } else {
888 newProviders = providers + ',' + value;
889 }
890 } else if (prefix == '-' && index >= 0) {
891 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400892 // remove leading or trailing comma
893 if (index > 0) {
894 index--;
895 } else if (end < providers.length()) {
896 end++;
897 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700898
899 newProviders = providers.substring(0, index);
900 if (end < providers.length()) {
901 newProviders += providers.substring(end);
902 }
903 } else {
904 // nothing changed, so no need to update the database
905 return false;
906 }
907
908 if (newProviders != null) {
909 initialValues.put(Settings.Secure.VALUE, newProviders);
910 }
911 }
912 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800913
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700914 return true;
915 }
916
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700917 @Override
918 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700919 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
920 }
921
922 // Settings.put*ForUser() always winds up here, so this is where we apply
923 // policy around permission to write settings for other users.
924 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
925 final int callingUser = UserHandle.getCallingUserId();
926 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700927 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700928 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
929 "Not permitted to access settings for other users");
930 }
931
932 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
933 + " by " + callingUser);
934
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700935 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 if (TABLE_FAVORITES.equals(args.table)) {
937 return null;
938 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700939 checkWritePermissions(args);
940
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700941 // Special case LOCATION_PROVIDERS_ALLOWED.
942 // Support enabling/disabling a single provider (using "+" or "-" prefix)
943 String name = initialValues.getAsString(Settings.Secure.NAME);
944 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
945 if (!parseProviderList(url, initialValues)) return null;
946 }
947
Christopher Tate06efb532012-08-24 15:29:27 -0700948 // The global table is stored under the owner, always
949 if (TABLE_GLOBAL.equals(args.table)) {
950 desiredUserHandle = UserHandle.USER_OWNER;
951 }
952
953 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800954 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
955 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
956 return Uri.withAppendedPath(url, name);
957 }
958
Christopher Tate06efb532012-08-24 15:29:27 -0700959 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
960 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700961 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700964 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 if (rowId <= 0) return null;
966
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800967 SettingsCache.populate(cache, initialValues); // before we notify
968
Christopher Tate78d2a662012-09-13 16:19:44 -0700969 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
970 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700971 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700973 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700974 return url;
975 }
976
977 @Override
978 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700979 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700980 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700981 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (TABLE_FAVORITES.equals(args.table)) {
983 return 0;
984 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
985 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700986 } else if (TABLE_GLOBAL.equals(args.table)) {
987 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700989 checkWritePermissions(args);
990
Christopher Tate06efb532012-08-24 15:29:27 -0700991 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
992 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700993 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700994 SQLiteDatabase db = dbH.getWritableDatabase();
995 int count = db.delete(args.table, args.where, args.args);
996 mutationCount.decrementAndGet();
997 if (count > 0) {
998 invalidateCache(callingUser, args.table); // before we notify
999 sendNotify(url, callingUser);
1000 }
1001 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001002 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1003 return count;
1004 }
1005
1006 @Override
1007 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001008 // NOTE: update() is never called by the front-end Settings API, and updates that
1009 // wind up affecting rows in Secure that are globally shared will not have the
1010 // intended effect (the update will be invisible to the rest of the system).
1011 // This should have no practical effect, since writes to the Secure db can only
1012 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001013 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001014 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001015 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 if (TABLE_FAVORITES.equals(args.table)) {
1017 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001018 } else if (TABLE_GLOBAL.equals(args.table)) {
1019 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001021 checkWritePermissions(args);
1022
Christopher Tate06efb532012-08-24 15:29:27 -07001023 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1024 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001025 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001026 SQLiteDatabase db = dbH.getWritableDatabase();
1027 int count = db.update(args.table, initialValues, args.where, args.args);
1028 mutationCount.decrementAndGet();
1029 if (count > 0) {
1030 invalidateCache(callingUser, args.table); // before we notify
1031 sendNotify(url, callingUser);
1032 }
1033 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001034 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1035 return count;
1036 }
1037
1038 @Override
1039 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1040
1041 /*
1042 * When a client attempts to openFile the default ringtone or
1043 * notification setting Uri, we will proxy the call to the current
1044 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001045 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001046 int ringtoneType = RingtoneManager.getDefaultType(uri);
1047 // Above call returns -1 if the Uri doesn't match a default type
1048 if (ringtoneType != -1) {
1049 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001050
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001051 // Get the current value for the default sound
1052 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001053
Marco Nelissen69f593c2009-07-28 09:55:04 -07001054 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001055 // Only proxy the openFile call to drm or media providers
1056 String authority = soundUri.getAuthority();
1057 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1058 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1059
1060 if (isDrmAuthority) {
1061 try {
1062 // Check DRM access permission here, since once we
1063 // do the below call the DRM will be checking our
1064 // permission, not our caller's permission
1065 DrmStore.enforceAccessDrmPermission(context);
1066 } catch (SecurityException e) {
1067 throw new FileNotFoundException(e.getMessage());
1068 }
1069 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001070
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001071 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1072 }
1073 }
1074 }
1075
1076 return super.openFile(uri, mode);
1077 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001078
1079 @Override
1080 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1081
1082 /*
1083 * When a client attempts to openFile the default ringtone or
1084 * notification setting Uri, we will proxy the call to the current
1085 * default ringtone's Uri (if it is in the DRM or media provider).
1086 */
1087 int ringtoneType = RingtoneManager.getDefaultType(uri);
1088 // Above call returns -1 if the Uri doesn't match a default type
1089 if (ringtoneType != -1) {
1090 Context context = getContext();
1091
1092 // Get the current value for the default sound
1093 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1094
1095 if (soundUri != null) {
1096 // Only proxy the openFile call to drm or media providers
1097 String authority = soundUri.getAuthority();
1098 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1099 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1100
1101 if (isDrmAuthority) {
1102 try {
1103 // Check DRM access permission here, since once we
1104 // do the below call the DRM will be checking our
1105 // permission, not our caller's permission
1106 DrmStore.enforceAccessDrmPermission(context);
1107 } catch (SecurityException e) {
1108 throw new FileNotFoundException(e.getMessage());
1109 }
1110 }
1111
1112 ParcelFileDescriptor pfd = null;
1113 try {
1114 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1115 return new AssetFileDescriptor(pfd, 0, -1);
1116 } catch (FileNotFoundException ex) {
1117 // fall through and open the fallback ringtone below
1118 }
1119 }
1120
1121 try {
1122 return super.openAssetFile(soundUri, mode);
1123 } catch (FileNotFoundException ex) {
1124 // Since a non-null Uri was specified, but couldn't be opened,
1125 // fall back to the built-in ringtone.
1126 return context.getResources().openRawResourceFd(
1127 com.android.internal.R.raw.fallbackring);
1128 }
1129 }
1130 // no need to fall through and have openFile() try again, since we
1131 // already know that will fail.
1132 throw new FileNotFoundException(); // or return null ?
1133 }
1134
1135 // Note that this will end up calling openFile() above.
1136 return super.openAssetFile(uri, mode);
1137 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001138
1139 /**
1140 * In-memory LRU Cache of system and secure settings, along with
1141 * associated helper functions to keep cache coherent with the
1142 * database.
1143 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001144 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001145
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001146 private final String mCacheName;
1147 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1148
1149 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001150 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001151 mCacheName = name;
1152 }
1153
1154 /**
1155 * Is the whole database table slurped into this cache?
1156 */
1157 public boolean fullyMatchesDisk() {
1158 synchronized (this) {
1159 return mCacheFullyMatchesDisk;
1160 }
1161 }
1162
1163 public void setFullyMatchesDisk(boolean value) {
1164 synchronized (this) {
1165 mCacheFullyMatchesDisk = value;
1166 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001167 }
1168
1169 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001170 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1171 if (evicted) {
1172 mCacheFullyMatchesDisk = false;
1173 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001174 }
1175
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001176 /**
1177 * Atomic cache population, conditional on size of value and if
1178 * we lost a race.
1179 *
1180 * @returns a Bundle to send back to the client from call(), even
1181 * if we lost the race.
1182 */
1183 public Bundle putIfAbsent(String key, String value) {
1184 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1185 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1186 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001187 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001188 put(key, bundle);
1189 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001190 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001191 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001192 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001193 }
1194
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001195 /**
1196 * Populates a key in a given (possibly-null) cache.
1197 */
1198 public static void populate(SettingsCache cache, ContentValues contentValues) {
1199 if (cache == null) {
1200 return;
1201 }
1202 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1203 if (name == null) {
1204 Log.w(TAG, "null name populating settings cache.");
1205 return;
1206 }
1207 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001208 cache.populate(name, value);
1209 }
1210
1211 public void populate(String name, String value) {
1212 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001213 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001214 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001215 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001216 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001217 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001218 }
1219 }
1220
1221 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001222 * For suppressing duplicate/redundant settings inserts early,
1223 * checking our cache first (but without faulting it in),
1224 * before going to sqlite with the mutation.
1225 */
1226 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1227 if (cache == null) return false;
1228 synchronized (cache) {
1229 Bundle bundle = cache.get(name);
1230 if (bundle == null) return false;
1231 String oldValue = bundle.getPairValue();
1232 if (oldValue == null && value == null) return true;
1233 if ((oldValue == null) != (value == null)) return false;
1234 return oldValue.equals(value);
1235 }
1236 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001237 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001238}