blob: 7cc5decdd7ae555ef3b7c8a33c26e2bd79b81f07 [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 Tate06efb532012-08-24 15:29:27 -070026import android.app.ActivityManagerNative;
Christopher Tate45281862010-03-05 15:46:30 -080027import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029import android.content.ContentProvider;
30import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070033import android.content.Intent;
34import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070037import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteQueryBuilder;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.database.sqlite.SQLiteStatement;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043import android.media.RingtoneManager;
44import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070047import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070051import android.os.UserHandle;
52import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053import android.provider.DrmStore;
54import android.provider.MediaStore;
55import android.provider.Settings;
56import android.text.TextUtils;
57import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080058import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.util.Slog;
60import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062public class SettingsProvider extends ContentProvider {
63 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070064 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065
Christopher Tate06efb532012-08-24 15:29:27 -070066 private static final String TABLE_SYSTEM = "system";
67 private static final String TABLE_SECURE = "secure";
68 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 private static final String TABLE_FAVORITES = "favorites";
70 private static final String TABLE_OLD_FAVORITES = "old_favorites";
71
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080072 private static final String[] COLUMN_VALUE = new String[] { "value" };
73
Christopher Tate06efb532012-08-24 15:29:27 -070074 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080075 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070076 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070077 private static final SparseArray<SettingsCache> sSystemCaches
78 = new SparseArray<SettingsCache>();
79 private static final SparseArray<SettingsCache> sSecureCaches
80 = new SparseArray<SettingsCache>();
81 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082
83 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070084 // database mutations are currently being handled for this user.
85 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070086 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070087 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
88 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080089
Christopher Tate78d2a662012-09-13 16:19:44 -070090 // Each defined user has their own settings
91 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
92
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080093 // Over this size we don't reject loading or saving settings but
94 // we do consider them broken/malicious and don't keep them in
95 // memory at least:
96 private static final int MAX_CACHE_ENTRY_SIZE = 500;
97
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080098 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
99
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700100 // Used as a sentinel value in an instance equality test when we
101 // want to cache the existence of a key, but not store its value.
102 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
103
Christopher Tate06efb532012-08-24 15:29:27 -0700104 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700105 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
107 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700108 * Settings which need to be treated as global/shared in multi-user environments.
109 */
110 static final HashSet<String> sSecureGlobalKeys;
111 static final HashSet<String> sSystemGlobalKeys;
112 static {
113 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
114 // table, shared across all users
115 // These must match Settings.Secure.MOVED_TO_GLOBAL
116 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate92198742012-09-07 12:00:13 -0700117 sSecureGlobalKeys.add(Settings.Secure.ADB_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700118 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700119 sSecureGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
Christopher Tate06efb532012-08-24 15:29:27 -0700120 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
121 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
122 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
123 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
124 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
Christopher Tate92198742012-09-07 12:00:13 -0700125 sSecureGlobalKeys.add(Settings.Secure.DATA_ROAMING);
Christopher Tate06efb532012-08-24 15:29:27 -0700126 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700127 sSecureGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
Christopher Tate06efb532012-08-24 15:29:27 -0700128 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
129 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
130 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
131 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Christopher Tate92198742012-09-07 12:00:13 -0700132 sSecureGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
Christopher Tate06efb532012-08-24 15:29:27 -0700133 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
146 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
147 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
148 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
149 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
150 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
151 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
152 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
153 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
154 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
155 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
156 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
157 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
158 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
159 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
160 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
161 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
162 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
163 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
164 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
165 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
166 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
167 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
168 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
170 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
171 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
172 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
173 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
174 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
175 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
Christopher Tate92198742012-09-07 12:00:13 -0700176 sSecureGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700177 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
178 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
190 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
191 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
192 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
193 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
194 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
195 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
196 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
197 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
Christopher Tatec868b642012-09-12 17:41:04 -0700198 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_ENABLE);
199 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_TIMEOUT);
200 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE);
201 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS);
202 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS);
203 sSecureGlobalKeys.add(Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS);
Christopher Tate06efb532012-08-24 15:29:27 -0700204 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
205
206 // Keys from the 'system' table now moved to 'global'
207 // These must match Settings.System.MOVED_TO_GLOBAL
208 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700209
210 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
211 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
212 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
213 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
214 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
215 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
216 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
217 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
218 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
219 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
220 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
221 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
222 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
223 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700224 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700225 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
226 }
227
228 private boolean settingMovedToGlobal(final String name) {
229 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
230 }
231
232 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700233 * Decode a content URL into the table, projection, and arguments
234 * used to access the corresponding database rows.
235 */
236 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700238 public final String where;
239 public final String[] args;
240
241 /** Operate on existing rows. */
242 SqlArguments(Uri url, String where, String[] args) {
243 if (url.getPathSegments().size() == 1) {
244 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700245 if (!DatabaseHelper.isValidTable(this.table)) {
246 throw new IllegalArgumentException("Bad root path: " + this.table);
247 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 this.where = where;
249 this.args = args;
250 } else if (url.getPathSegments().size() != 2) {
251 throw new IllegalArgumentException("Invalid URI: " + url);
252 } else if (!TextUtils.isEmpty(where)) {
253 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
254 } else {
255 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700256 if (!DatabaseHelper.isValidTable(this.table)) {
257 throw new IllegalArgumentException("Bad root path: " + this.table);
258 }
Christopher Tate06efb532012-08-24 15:29:27 -0700259 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 this.where = Settings.NameValueTable.NAME + "=?";
261 this.args = new String[] { url.getPathSegments().get(1) };
262 } else {
263 this.where = "_id=" + ContentUris.parseId(url);
264 this.args = null;
265 }
266 }
267 }
268
269 /** Insert new rows (no where clause allowed). */
270 SqlArguments(Uri url) {
271 if (url.getPathSegments().size() == 1) {
272 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700273 if (!DatabaseHelper.isValidTable(this.table)) {
274 throw new IllegalArgumentException("Bad root path: " + this.table);
275 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 this.where = null;
277 this.args = null;
278 } else {
279 throw new IllegalArgumentException("Invalid URI: " + url);
280 }
281 }
282 }
283
284 /**
285 * Get the content URI of a row added to a table.
286 * @param tableUri of the entire table
287 * @param values found in the row
288 * @param rowId of the row
289 * @return the content URI for this particular row
290 */
291 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
292 if (tableUri.getPathSegments().size() != 1) {
293 throw new IllegalArgumentException("Invalid URI: " + tableUri);
294 }
295 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700296 if (TABLE_SYSTEM.equals(table) ||
297 TABLE_SECURE.equals(table) ||
298 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700299 String name = values.getAsString(Settings.NameValueTable.NAME);
300 return Uri.withAppendedPath(tableUri, name);
301 } else {
302 return ContentUris.withAppendedId(tableUri, rowId);
303 }
304 }
305
306 /**
307 * Send a notification when a particular content URI changes.
308 * Modify the system property used to communicate the version of
309 * this table, for tables which have such a property. (The Settings
310 * contract class uses these to provide client-side caches.)
311 * @param uri to send notifications for
312 */
Christopher Tate06efb532012-08-24 15:29:27 -0700313 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 // Update the system property *first*, so if someone is listening for
315 // a notification and then using the contract class to get their data,
316 // the system property will be updated and they'll get the new data.
317
Amith Yamasanid1582142009-07-08 20:04:55 -0700318 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700320 if (table.equals(TABLE_SYSTEM)) {
321 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700322 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700323 } else if (table.equals(TABLE_SECURE)) {
324 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
325 backedUpDataChanged = true;
326 } else if (table.equals(TABLE_GLOBAL)) {
327 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700328 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700329 }
330
331 if (property != null) {
332 long version = SystemProperties.getLong(property, 0) + 1;
333 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
334 SystemProperties.set(property, Long.toString(version));
335 }
336
-b master501eec92009-07-06 13:53:11 -0700337 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700338 if (backedUpDataChanged) {
339 mBackupManager.dataChanged();
340 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700341 // Now send the notification through the content framework.
342
343 String notify = uri.getQueryParameter("notify");
344 if (notify == null || "true".equals(notify)) {
345 getContext().getContentResolver().notifyChange(uri, null);
346 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
347 } else {
348 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
349 }
350 }
351
352 /**
353 * Make sure the caller has permission to write this data.
354 * @param args supplied by the caller
355 * @throws SecurityException if the caller is forbidden to write.
356 */
357 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700358 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800359 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800360 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
361 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700362 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800363 String.format("Permission denial: writing to secure settings requires %1$s",
364 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365 }
366 }
367
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700368 // FileObserver for external modifications to the database file.
369 // Note that this is for platform developers only with
370 // userdebug/eng builds who should be able to tinker with the
371 // sqlite database out from under the SettingsProvider, which is
372 // normally the exclusive owner of the database. But we keep this
373 // enabled all the time to minimize development-vs-user
374 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700375 private static SparseArray<SettingsFileObserver> sObserverInstances
376 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700377 private class SettingsFileObserver extends FileObserver {
378 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700379 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700380 private final String mPath;
381
Christopher Tate06efb532012-08-24 15:29:27 -0700382 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700383 super(path, FileObserver.CLOSE_WRITE |
384 FileObserver.CREATE | FileObserver.DELETE |
385 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700386 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700387 mPath = path;
388 }
389
390 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700391 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700392 if (modsInFlight > 0) {
393 // our own modification.
394 return;
395 }
Christopher Tate06efb532012-08-24 15:29:27 -0700396 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
397 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700398 if (!mIsDirty.compareAndSet(false, true)) {
399 // already handled. (we get a few update events
400 // during an sqlite write)
401 return;
402 }
Christopher Tate06efb532012-08-24 15:29:27 -0700403 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
404 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700405 mIsDirty.set(false);
406 }
407 }
408
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700409 @Override
410 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700411 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700412 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800413
Christopher Tate78d2a662012-09-13 16:19:44 -0700414 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700415
Christopher Tate78d2a662012-09-13 16:19:44 -0700416 IntentFilter userFilter = new IntentFilter();
417 userFilter.addAction(Intent.ACTION_USER_REMOVED);
418 getContext().registerReceiver(new BroadcastReceiver() {
419 @Override
420 public void onReceive(Context context, Intent intent) {
421 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
422 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
423 UserHandle.USER_OWNER);
424 if (userHandle != UserHandle.USER_OWNER) {
425 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700426 }
427 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700428 }
429 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 return true;
431 }
432
Christopher Tate06efb532012-08-24 15:29:27 -0700433 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700434 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700435 // the db file itself will be deleted automatically, but we need to tear down
436 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700437 FileObserver observer = sObserverInstances.get(userHandle);
438 if (observer != null) {
439 observer.stopWatching();
440 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700441 }
Christopher Tate06efb532012-08-24 15:29:27 -0700442
443 mOpenHelpers.delete(userHandle);
444 sSystemCaches.delete(userHandle);
445 sSecureCaches.delete(userHandle);
446 sKnownMutationsInFlight.delete(userHandle);
447
448 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
449 SystemProperties.set(property, "");
450 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
451 SystemProperties.set(property, "");
452 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700453 }
454
Christopher Tate78d2a662012-09-13 16:19:44 -0700455 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700456 if (LOCAL_LOGV) {
457 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
458 }
459
Christopher Tate78d2a662012-09-13 16:19:44 -0700460 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700461
Christopher Tate78d2a662012-09-13 16:19:44 -0700462 synchronized (this) {
463 dbhelper = mOpenHelpers.get(userHandle);
464 if (dbhelper == null) {
465 dbhelper = new DatabaseHelper(getContext(), userHandle);
466 mOpenHelpers.append(userHandle, dbhelper);
467
468 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
469 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
470 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
471 }
472 }
473
474 // Initialization of the db *outside* the locks. It's possible that racing
475 // threads might wind up here, the second having read the cache entries
476 // written by the first, but that's benign: the SQLite helper implementation
477 // manages concurrency itself, and it's important that we not run the db
478 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700479 SQLiteDatabase db = dbhelper.getWritableDatabase();
480
Christopher Tate78d2a662012-09-13 16:19:44 -0700481 // Watch for external modifications to the database files,
482 // keeping our caches in sync. We synchronize the observer set
483 // separately, and of course it has to run after the db file
484 // itself was set up by the DatabaseHelper.
485 synchronized (sObserverInstances) {
486 if (sObserverInstances.get(userHandle) == null) {
487 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
488 sObserverInstances.append(userHandle, observer);
489 observer.startWatching();
490 }
491 }
Christopher Tate06efb532012-08-24 15:29:27 -0700492
Christopher Tate4dc7a682012-09-11 12:15:49 -0700493 ensureAndroidIdIsSet(userHandle);
494
Christopher Tate06efb532012-08-24 15:29:27 -0700495 startAsyncCachePopulation(userHandle);
496 }
497
498 class CachePrefetchThread extends Thread {
499 private int mUserHandle;
500
501 CachePrefetchThread(int userHandle) {
502 super("populate-settings-caches");
503 mUserHandle = userHandle;
504 }
505
506 @Override
507 public void run() {
508 fullyPopulateCaches(mUserHandle);
509 }
510 }
511
512 private void startAsyncCachePopulation(int userHandle) {
513 new CachePrefetchThread(userHandle).start();
514 }
515
516 private void fullyPopulateCaches(final int userHandle) {
517 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
518 // Only populate the globals cache once, for the owning user
519 if (userHandle == UserHandle.USER_OWNER) {
520 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
521 }
522 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
523 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700524 }
525
526 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700527 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
528 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700529 Cursor c = db.query(
530 table,
531 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
532 null, null, null, null, null,
533 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
534 try {
535 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800536 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700537 cache.setFullyMatchesDisk(true); // optimistic
538 int rows = 0;
539 while (c.moveToNext()) {
540 rows++;
541 String name = c.getString(0);
542 String value = c.getString(1);
543 cache.populate(name, value);
544 }
545 if (rows > MAX_CACHE_ENTRIES) {
546 // Somewhat redundant, as removeEldestEntry() will
547 // have already done this, but to be explicit:
548 cache.setFullyMatchesDisk(false);
549 Log.d(TAG, "row count exceeds max cache entries for table " + table);
550 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700551 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700552 cache.fullyMatchesDisk());
553 }
554 } finally {
555 c.close();
556 }
557 }
558
Christopher Tate4dc7a682012-09-11 12:15:49 -0700559 private boolean ensureAndroidIdIsSet(int userHandle) {
560 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800561 new String[] { Settings.NameValueTable.VALUE },
562 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700563 new String[] { Settings.Secure.ANDROID_ID }, null,
564 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800565 try {
566 final String value = c.moveToNext() ? c.getString(0) : null;
567 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700568 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800569 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800570 final ContentValues values = new ContentValues();
571 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
572 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700573 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800574 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700575 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800576 return false;
577 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700578 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
579 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800580 }
581 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800582 } finally {
583 c.close();
584 }
585 }
586
Christopher Tate06efb532012-08-24 15:29:27 -0700587 // Lazy-initialize the settings caches for non-primary users
588 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700589 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
590 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700591 }
592
593 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700594 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700595 long oldId = Binder.clearCallingIdentity();
596 try {
597 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
598 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700599 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700600 dbHelper = mOpenHelpers.get(callingUser);
601 }
602 return dbHelper;
603 } finally {
604 Binder.restoreCallingIdentity(oldId);
605 }
606 }
607
608 public SettingsCache cacheForTable(final int callingUser, String tableName) {
609 if (TABLE_SYSTEM.equals(tableName)) {
610 return getOrConstructCache(callingUser, sSystemCaches);
611 }
612 if (TABLE_SECURE.equals(tableName)) {
613 return getOrConstructCache(callingUser, sSecureCaches);
614 }
615 if (TABLE_GLOBAL.equals(tableName)) {
616 return sGlobalCache;
617 }
618 return null;
619 }
620
621 /**
622 * Used for wiping a whole cache on deletes when we're not
623 * sure what exactly was deleted or changed.
624 */
625 public void invalidateCache(final int callingUser, String tableName) {
626 SettingsCache cache = cacheForTable(callingUser, tableName);
627 if (cache == null) {
628 return;
629 }
630 synchronized (cache) {
631 cache.evictAll();
632 cache.mCacheFullyMatchesDisk = false;
633 }
634 }
635
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800636 /**
637 * Fast path that avoids the use of chatty remoted Cursors.
638 */
639 @Override
640 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700641 int callingUser = UserHandle.getCallingUserId();
642 if (args != null) {
643 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
644 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700645 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
646 Binder.getCallingUid(), reqUser, false, true,
647 "get/set setting for user", null);
648 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700649 }
650 }
651
652 // Note: we assume that get/put operations for moved-to-global names have already
653 // been directed to the new location on the caller side (otherwise we'd fix them
654 // up here).
655
656 DatabaseHelper dbHelper;
657 SettingsCache cache;
658
659 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800660 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700661 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700662 dbHelper = getOrEstablishDatabase(callingUser);
663 cache = sSystemCaches.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700664 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800665 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800666 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700667 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700668 dbHelper = getOrEstablishDatabase(callingUser);
669 cache = sSecureCaches.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700670 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800671 }
Christopher Tate06efb532012-08-24 15:29:27 -0700672 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
673 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
674 // fast path: owner db & cache are immutable after onCreate() so we need not
675 // guard on the attempt to look them up
Christopher Tate78d2a662012-09-13 16:19:44 -0700676 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
Christopher Tate06efb532012-08-24 15:29:27 -0700677 sGlobalCache, request);
678 }
679
680 // Put methods - new value is in the args bundle under the key named by
681 // the Settings.NameValueTable.VALUE static.
682 final String newValue = (args == null)
683 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700684
685 final ContentValues values = new ContentValues();
686 values.put(Settings.NameValueTable.NAME, request);
687 values.put(Settings.NameValueTable.VALUE, newValue);
688 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
689 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700690 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700691 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
692 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700693 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700694 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
695 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700696 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700697 } else {
698 Slog.w(TAG, "call() with invalid method: " + method);
699 }
700
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800701 return null;
702 }
703
704 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
705 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700706 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
707 final SettingsCache cache, String key) {
708 if (cache == null) {
709 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
710 return null;
711 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800712 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800713 Bundle value = cache.get(key);
714 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700715 if (value != TOO_LARGE_TO_CACHE_MARKER) {
716 return value;
717 }
718 // else we fall through and read the value from disk
719 } else if (cache.fullyMatchesDisk()) {
720 // Fast path (very common). Don't even try touch disk
721 // if we know we've slurped it all in. Trying to
722 // touch the disk would mean waiting for yaffs2 to
723 // give us access, which could takes hundreds of
724 // milliseconds. And we're very likely being called
725 // from somebody's UI thread...
726 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800727 }
728 }
729
Christopher Tate06efb532012-08-24 15:29:27 -0700730 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800731 Cursor cursor = null;
732 try {
733 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
734 null, null, null, null);
735 if (cursor != null && cursor.getCount() == 1) {
736 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800737 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800738 }
739 } catch (SQLiteException e) {
740 Log.w(TAG, "settings lookup error", e);
741 return null;
742 } finally {
743 if (cursor != null) cursor.close();
744 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800745 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800746 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800747 }
748
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700749 @Override
750 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700751 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
752 }
753
754 public Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
755 String sort, int forUser) {
756 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700757 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700758 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700759 dbH = getOrEstablishDatabase(
760 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700761 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800763 // The favorites table was moved from this provider to a provider inside Home
764 // Home still need to query this table to upgrade from pre-cupcake builds
765 // However, a cupcake+ build with no data does not contain this table which will
766 // cause an exception in the SQL stack. The following line is a special case to
767 // 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 -0800768 if (TABLE_FAVORITES.equals(args.table)) {
769 return null;
770 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
771 args.table = TABLE_FAVORITES;
772 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
773 if (cursor != null) {
774 boolean exists = cursor.getCount() > 0;
775 cursor.close();
776 if (!exists) return null;
777 } else {
778 return null;
779 }
780 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800781
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700782 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
783 qb.setTables(args.table);
784
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700785 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
786 ret.setNotificationUri(getContext().getContentResolver(), url);
787 return ret;
788 }
789
790 @Override
791 public String getType(Uri url) {
792 // If SqlArguments supplies a where clause, then it must be an item
793 // (because we aren't supplying our own where clause).
794 SqlArguments args = new SqlArguments(url, null, null);
795 if (TextUtils.isEmpty(args.where)) {
796 return "vnd.android.cursor.dir/" + args.table;
797 } else {
798 return "vnd.android.cursor.item/" + args.table;
799 }
800 }
801
802 @Override
803 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700804 final int callingUser = UserHandle.getCallingUserId();
805 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700806 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 if (TABLE_FAVORITES.equals(args.table)) {
808 return 0;
809 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700810 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700811 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700812
Christopher Tate06efb532012-08-24 15:29:27 -0700813 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
814 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700815 DatabaseHelper dbH = getOrEstablishDatabase(
816 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700817 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700818 db.beginTransaction();
819 try {
820 int numValues = values.length;
821 for (int i = 0; i < numValues; i++) {
822 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800823 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700824 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
825 }
826 db.setTransactionSuccessful();
827 } finally {
828 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700829 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700830 }
831
Christopher Tate06efb532012-08-24 15:29:27 -0700832 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700833 return values.length;
834 }
835
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700836 /*
837 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
838 * This setting contains a list of the currently enabled location providers.
839 * But helper functions in android.providers.Settings can enable or disable
840 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800841 *
842 * @returns whether the database needs to be updated or not, also modifying
843 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700844 */
845 private boolean parseProviderList(Uri url, ContentValues initialValues) {
846 String value = initialValues.getAsString(Settings.Secure.VALUE);
847 String newProviders = null;
848 if (value != null && value.length() > 1) {
849 char prefix = value.charAt(0);
850 if (prefix == '+' || prefix == '-') {
851 // skip prefix
852 value = value.substring(1);
853
854 // read list of enabled providers into "providers"
855 String providers = "";
856 String[] columns = {Settings.Secure.VALUE};
857 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
858 Cursor cursor = query(url, columns, where, null, null);
859 if (cursor != null && cursor.getCount() == 1) {
860 try {
861 cursor.moveToFirst();
862 providers = cursor.getString(0);
863 } finally {
864 cursor.close();
865 }
866 }
867
868 int index = providers.indexOf(value);
869 int end = index + value.length();
870 // check for commas to avoid matching on partial string
871 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
872 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
873
874 if (prefix == '+' && index < 0) {
875 // append the provider to the list if not present
876 if (providers.length() == 0) {
877 newProviders = value;
878 } else {
879 newProviders = providers + ',' + value;
880 }
881 } else if (prefix == '-' && index >= 0) {
882 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400883 // remove leading or trailing comma
884 if (index > 0) {
885 index--;
886 } else if (end < providers.length()) {
887 end++;
888 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700889
890 newProviders = providers.substring(0, index);
891 if (end < providers.length()) {
892 newProviders += providers.substring(end);
893 }
894 } else {
895 // nothing changed, so no need to update the database
896 return false;
897 }
898
899 if (newProviders != null) {
900 initialValues.put(Settings.Secure.VALUE, newProviders);
901 }
902 }
903 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800904
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700905 return true;
906 }
907
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700908 @Override
909 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700910 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
911 }
912
913 // Settings.put*ForUser() always winds up here, so this is where we apply
914 // policy around permission to write settings for other users.
915 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
916 final int callingUser = UserHandle.getCallingUserId();
917 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700918 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700919 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
920 "Not permitted to access settings for other users");
921 }
922
923 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
924 + " by " + callingUser);
925
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700926 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 if (TABLE_FAVORITES.equals(args.table)) {
928 return null;
929 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700930 checkWritePermissions(args);
931
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700932 // Special case LOCATION_PROVIDERS_ALLOWED.
933 // Support enabling/disabling a single provider (using "+" or "-" prefix)
934 String name = initialValues.getAsString(Settings.Secure.NAME);
935 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
936 if (!parseProviderList(url, initialValues)) return null;
937 }
938
Christopher Tate06efb532012-08-24 15:29:27 -0700939 // The global table is stored under the owner, always
940 if (TABLE_GLOBAL.equals(args.table)) {
941 desiredUserHandle = UserHandle.USER_OWNER;
942 }
943
944 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800945 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
946 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
947 return Uri.withAppendedPath(url, name);
948 }
949
Christopher Tate06efb532012-08-24 15:29:27 -0700950 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
951 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700952 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700953 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700954 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700955 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700956 if (rowId <= 0) return null;
957
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800958 SettingsCache.populate(cache, initialValues); // before we notify
959
Christopher Tate78d2a662012-09-13 16:19:44 -0700960 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
961 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700964 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700965 return url;
966 }
967
968 @Override
969 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700970 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700971 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 if (TABLE_FAVORITES.equals(args.table)) {
974 return 0;
975 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
976 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700977 } else if (TABLE_GLOBAL.equals(args.table)) {
978 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700980 checkWritePermissions(args);
981
Christopher Tate06efb532012-08-24 15:29:27 -0700982 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
983 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700984 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700985 SQLiteDatabase db = dbH.getWritableDatabase();
986 int count = db.delete(args.table, args.where, args.args);
987 mutationCount.decrementAndGet();
988 if (count > 0) {
989 invalidateCache(callingUser, args.table); // before we notify
990 sendNotify(url, callingUser);
991 }
992 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700993 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
994 return count;
995 }
996
997 @Override
998 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700999 // NOTE: update() is never called by the front-end Settings API, and updates that
1000 // wind up affecting rows in Secure that are globally shared will not have the
1001 // intended effect (the update will be invisible to the rest of the system).
1002 // This should have no practical effect, since writes to the Secure db can only
1003 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001004 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001005 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001006 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 if (TABLE_FAVORITES.equals(args.table)) {
1008 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001009 } else if (TABLE_GLOBAL.equals(args.table)) {
1010 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001012 checkWritePermissions(args);
1013
Christopher Tate06efb532012-08-24 15:29:27 -07001014 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1015 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001016 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001017 SQLiteDatabase db = dbH.getWritableDatabase();
1018 int count = db.update(args.table, initialValues, args.where, args.args);
1019 mutationCount.decrementAndGet();
1020 if (count > 0) {
1021 invalidateCache(callingUser, args.table); // before we notify
1022 sendNotify(url, callingUser);
1023 }
1024 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001025 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1026 return count;
1027 }
1028
1029 @Override
1030 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1031
1032 /*
1033 * When a client attempts to openFile the default ringtone or
1034 * notification setting Uri, we will proxy the call to the current
1035 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001036 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001037 int ringtoneType = RingtoneManager.getDefaultType(uri);
1038 // Above call returns -1 if the Uri doesn't match a default type
1039 if (ringtoneType != -1) {
1040 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001041
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001042 // Get the current value for the default sound
1043 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001044
Marco Nelissen69f593c2009-07-28 09:55:04 -07001045 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001046 // Only proxy the openFile call to drm or media providers
1047 String authority = soundUri.getAuthority();
1048 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1049 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1050
1051 if (isDrmAuthority) {
1052 try {
1053 // Check DRM access permission here, since once we
1054 // do the below call the DRM will be checking our
1055 // permission, not our caller's permission
1056 DrmStore.enforceAccessDrmPermission(context);
1057 } catch (SecurityException e) {
1058 throw new FileNotFoundException(e.getMessage());
1059 }
1060 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001061
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001062 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1063 }
1064 }
1065 }
1066
1067 return super.openFile(uri, mode);
1068 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001069
1070 @Override
1071 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1072
1073 /*
1074 * When a client attempts to openFile the default ringtone or
1075 * notification setting Uri, we will proxy the call to the current
1076 * default ringtone's Uri (if it is in the DRM or media provider).
1077 */
1078 int ringtoneType = RingtoneManager.getDefaultType(uri);
1079 // Above call returns -1 if the Uri doesn't match a default type
1080 if (ringtoneType != -1) {
1081 Context context = getContext();
1082
1083 // Get the current value for the default sound
1084 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1085
1086 if (soundUri != null) {
1087 // Only proxy the openFile call to drm or media providers
1088 String authority = soundUri.getAuthority();
1089 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1090 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1091
1092 if (isDrmAuthority) {
1093 try {
1094 // Check DRM access permission here, since once we
1095 // do the below call the DRM will be checking our
1096 // permission, not our caller's permission
1097 DrmStore.enforceAccessDrmPermission(context);
1098 } catch (SecurityException e) {
1099 throw new FileNotFoundException(e.getMessage());
1100 }
1101 }
1102
1103 ParcelFileDescriptor pfd = null;
1104 try {
1105 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1106 return new AssetFileDescriptor(pfd, 0, -1);
1107 } catch (FileNotFoundException ex) {
1108 // fall through and open the fallback ringtone below
1109 }
1110 }
1111
1112 try {
1113 return super.openAssetFile(soundUri, mode);
1114 } catch (FileNotFoundException ex) {
1115 // Since a non-null Uri was specified, but couldn't be opened,
1116 // fall back to the built-in ringtone.
1117 return context.getResources().openRawResourceFd(
1118 com.android.internal.R.raw.fallbackring);
1119 }
1120 }
1121 // no need to fall through and have openFile() try again, since we
1122 // already know that will fail.
1123 throw new FileNotFoundException(); // or return null ?
1124 }
1125
1126 // Note that this will end up calling openFile() above.
1127 return super.openAssetFile(uri, mode);
1128 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001129
1130 /**
1131 * In-memory LRU Cache of system and secure settings, along with
1132 * associated helper functions to keep cache coherent with the
1133 * database.
1134 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001135 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001136
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001137 private final String mCacheName;
1138 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1139
1140 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001141 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001142 mCacheName = name;
1143 }
1144
1145 /**
1146 * Is the whole database table slurped into this cache?
1147 */
1148 public boolean fullyMatchesDisk() {
1149 synchronized (this) {
1150 return mCacheFullyMatchesDisk;
1151 }
1152 }
1153
1154 public void setFullyMatchesDisk(boolean value) {
1155 synchronized (this) {
1156 mCacheFullyMatchesDisk = value;
1157 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001158 }
1159
1160 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001161 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1162 if (evicted) {
1163 mCacheFullyMatchesDisk = false;
1164 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001165 }
1166
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001167 /**
1168 * Atomic cache population, conditional on size of value and if
1169 * we lost a race.
1170 *
1171 * @returns a Bundle to send back to the client from call(), even
1172 * if we lost the race.
1173 */
1174 public Bundle putIfAbsent(String key, String value) {
1175 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1176 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1177 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001178 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001179 put(key, bundle);
1180 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001181 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001182 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001183 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001184 }
1185
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001186 /**
1187 * Populates a key in a given (possibly-null) cache.
1188 */
1189 public static void populate(SettingsCache cache, ContentValues contentValues) {
1190 if (cache == null) {
1191 return;
1192 }
1193 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1194 if (name == null) {
1195 Log.w(TAG, "null name populating settings cache.");
1196 return;
1197 }
1198 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001199 cache.populate(name, value);
1200 }
1201
1202 public void populate(String name, String value) {
1203 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001204 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001205 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001206 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001207 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001208 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001209 }
1210 }
1211
1212 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001213 * For suppressing duplicate/redundant settings inserts early,
1214 * checking our cache first (but without faulting it in),
1215 * before going to sqlite with the mutation.
1216 */
1217 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1218 if (cache == null) return false;
1219 synchronized (cache) {
1220 Bundle bundle = cache.get(name);
1221 if (bundle == null) return false;
1222 String oldValue = bundle.getPairValue();
1223 if (oldValue == null && value == null) return true;
1224 if ((oldValue == null) != (value == null)) return false;
1225 return oldValue.equals(value);
1226 }
1227 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001228 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001229}