blob: b04475a1126e2af4eee2942a00395c2edeeb908a [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 }
Doug Zongker5bcb5512012-09-24 12:24:54 -0700255 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table) ||
256 TABLE_GLOBAL.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700257 this.where = Settings.NameValueTable.NAME + "=?";
258 this.args = new String[] { url.getPathSegments().get(1) };
259 } else {
260 this.where = "_id=" + ContentUris.parseId(url);
261 this.args = null;
262 }
263 }
264 }
265
266 /** Insert new rows (no where clause allowed). */
267 SqlArguments(Uri url) {
268 if (url.getPathSegments().size() == 1) {
269 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700270 if (!DatabaseHelper.isValidTable(this.table)) {
271 throw new IllegalArgumentException("Bad root path: " + this.table);
272 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700273 this.where = null;
274 this.args = null;
275 } else {
276 throw new IllegalArgumentException("Invalid URI: " + url);
277 }
278 }
279 }
280
281 /**
282 * Get the content URI of a row added to a table.
283 * @param tableUri of the entire table
284 * @param values found in the row
285 * @param rowId of the row
286 * @return the content URI for this particular row
287 */
288 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
289 if (tableUri.getPathSegments().size() != 1) {
290 throw new IllegalArgumentException("Invalid URI: " + tableUri);
291 }
292 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700293 if (TABLE_SYSTEM.equals(table) ||
294 TABLE_SECURE.equals(table) ||
295 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 String name = values.getAsString(Settings.NameValueTable.NAME);
297 return Uri.withAppendedPath(tableUri, name);
298 } else {
299 return ContentUris.withAppendedId(tableUri, rowId);
300 }
301 }
302
303 /**
304 * Send a notification when a particular content URI changes.
305 * Modify the system property used to communicate the version of
306 * this table, for tables which have such a property. (The Settings
307 * contract class uses these to provide client-side caches.)
308 * @param uri to send notifications for
309 */
Christopher Tate06efb532012-08-24 15:29:27 -0700310 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700311 // Update the system property *first*, so if someone is listening for
312 // a notification and then using the contract class to get their data,
313 // the system property will be updated and they'll get the new data.
314
Amith Yamasanid1582142009-07-08 20:04:55 -0700315 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700316 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700317 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700318 if (table.equals(TABLE_SYSTEM)) {
319 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700320 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700321 } else if (table.equals(TABLE_SECURE)) {
322 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
323 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700324 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700325 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700326 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700327 }
328
329 if (property != null) {
330 long version = SystemProperties.getLong(property, 0) + 1;
331 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
332 SystemProperties.set(property, Long.toString(version));
333 }
334
-b master501eec92009-07-06 13:53:11 -0700335 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700336 if (backedUpDataChanged) {
337 mBackupManager.dataChanged();
338 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700339 // Now send the notification through the content framework.
340
341 String notify = uri.getQueryParameter("notify");
342 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700343 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700344 final long oldId = Binder.clearCallingIdentity();
345 try {
346 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
347 } finally {
348 Binder.restoreCallingIdentity(oldId);
349 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700350 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700351 } else {
352 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
353 }
354 }
355
356 /**
357 * Make sure the caller has permission to write this data.
358 * @param args supplied by the caller
359 * @throws SecurityException if the caller is forbidden to write.
360 */
361 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700362 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800363 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800364 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
365 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700366 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800367 String.format("Permission denial: writing to secure settings requires %1$s",
368 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700369 }
370 }
371
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700372 // FileObserver for external modifications to the database file.
373 // Note that this is for platform developers only with
374 // userdebug/eng builds who should be able to tinker with the
375 // sqlite database out from under the SettingsProvider, which is
376 // normally the exclusive owner of the database. But we keep this
377 // enabled all the time to minimize development-vs-user
378 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700379 private static SparseArray<SettingsFileObserver> sObserverInstances
380 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700381 private class SettingsFileObserver extends FileObserver {
382 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700383 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700384 private final String mPath;
385
Christopher Tate06efb532012-08-24 15:29:27 -0700386 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700387 super(path, FileObserver.CLOSE_WRITE |
388 FileObserver.CREATE | FileObserver.DELETE |
389 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700390 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700391 mPath = path;
392 }
393
394 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700395 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700396 if (modsInFlight > 0) {
397 // our own modification.
398 return;
399 }
Christopher Tate06efb532012-08-24 15:29:27 -0700400 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
401 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700402 if (!mIsDirty.compareAndSet(false, true)) {
403 // already handled. (we get a few update events
404 // during an sqlite write)
405 return;
406 }
Christopher Tate06efb532012-08-24 15:29:27 -0700407 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
408 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700409 mIsDirty.set(false);
410 }
411 }
412
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700413 @Override
414 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700415 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700416 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800417
Christopher Tate78d2a662012-09-13 16:19:44 -0700418 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700419
Christopher Tate78d2a662012-09-13 16:19:44 -0700420 IntentFilter userFilter = new IntentFilter();
421 userFilter.addAction(Intent.ACTION_USER_REMOVED);
422 getContext().registerReceiver(new BroadcastReceiver() {
423 @Override
424 public void onReceive(Context context, Intent intent) {
425 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
426 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
427 UserHandle.USER_OWNER);
428 if (userHandle != UserHandle.USER_OWNER) {
429 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700430 }
431 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700432 }
433 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434 return true;
435 }
436
Christopher Tate06efb532012-08-24 15:29:27 -0700437 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700438 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700439 // the db file itself will be deleted automatically, but we need to tear down
440 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700441 FileObserver observer = sObserverInstances.get(userHandle);
442 if (observer != null) {
443 observer.stopWatching();
444 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700445 }
Christopher Tate06efb532012-08-24 15:29:27 -0700446
447 mOpenHelpers.delete(userHandle);
448 sSystemCaches.delete(userHandle);
449 sSecureCaches.delete(userHandle);
450 sKnownMutationsInFlight.delete(userHandle);
451
452 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
453 SystemProperties.set(property, "");
454 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
455 SystemProperties.set(property, "");
456 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700457 }
458
Christopher Tate78d2a662012-09-13 16:19:44 -0700459 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700460 if (LOCAL_LOGV) {
461 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
462 }
463
Christopher Tate78d2a662012-09-13 16:19:44 -0700464 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700465
Christopher Tate78d2a662012-09-13 16:19:44 -0700466 synchronized (this) {
467 dbhelper = mOpenHelpers.get(userHandle);
468 if (dbhelper == null) {
469 dbhelper = new DatabaseHelper(getContext(), userHandle);
470 mOpenHelpers.append(userHandle, dbhelper);
471
472 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
473 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
474 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
475 }
476 }
477
478 // Initialization of the db *outside* the locks. It's possible that racing
479 // threads might wind up here, the second having read the cache entries
480 // written by the first, but that's benign: the SQLite helper implementation
481 // manages concurrency itself, and it's important that we not run the db
482 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700483 SQLiteDatabase db = dbhelper.getWritableDatabase();
484
Christopher Tate78d2a662012-09-13 16:19:44 -0700485 // Watch for external modifications to the database files,
486 // keeping our caches in sync. We synchronize the observer set
487 // separately, and of course it has to run after the db file
488 // itself was set up by the DatabaseHelper.
489 synchronized (sObserverInstances) {
490 if (sObserverInstances.get(userHandle) == null) {
491 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
492 sObserverInstances.append(userHandle, observer);
493 observer.startWatching();
494 }
495 }
Christopher Tate06efb532012-08-24 15:29:27 -0700496
Christopher Tate4dc7a682012-09-11 12:15:49 -0700497 ensureAndroidIdIsSet(userHandle);
498
Christopher Tate06efb532012-08-24 15:29:27 -0700499 startAsyncCachePopulation(userHandle);
500 }
501
502 class CachePrefetchThread extends Thread {
503 private int mUserHandle;
504
505 CachePrefetchThread(int userHandle) {
506 super("populate-settings-caches");
507 mUserHandle = userHandle;
508 }
509
510 @Override
511 public void run() {
512 fullyPopulateCaches(mUserHandle);
513 }
514 }
515
516 private void startAsyncCachePopulation(int userHandle) {
517 new CachePrefetchThread(userHandle).start();
518 }
519
520 private void fullyPopulateCaches(final int userHandle) {
521 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
522 // Only populate the globals cache once, for the owning user
523 if (userHandle == UserHandle.USER_OWNER) {
524 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
525 }
526 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
527 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700528 }
529
530 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700531 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
532 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700533 Cursor c = db.query(
534 table,
535 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
536 null, null, null, null, null,
537 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
538 try {
539 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800540 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700541 cache.setFullyMatchesDisk(true); // optimistic
542 int rows = 0;
543 while (c.moveToNext()) {
544 rows++;
545 String name = c.getString(0);
546 String value = c.getString(1);
547 cache.populate(name, value);
548 }
549 if (rows > MAX_CACHE_ENTRIES) {
550 // Somewhat redundant, as removeEldestEntry() will
551 // have already done this, but to be explicit:
552 cache.setFullyMatchesDisk(false);
553 Log.d(TAG, "row count exceeds max cache entries for table " + table);
554 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700555 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700556 cache.fullyMatchesDisk());
557 }
558 } finally {
559 c.close();
560 }
561 }
562
Christopher Tate4dc7a682012-09-11 12:15:49 -0700563 private boolean ensureAndroidIdIsSet(int userHandle) {
564 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800565 new String[] { Settings.NameValueTable.VALUE },
566 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700567 new String[] { Settings.Secure.ANDROID_ID }, null,
568 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800569 try {
570 final String value = c.moveToNext() ? c.getString(0) : null;
571 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700572 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800573 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800574 final ContentValues values = new ContentValues();
575 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
576 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700577 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800578 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700579 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800580 return false;
581 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700582 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
583 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800584 }
585 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800586 } finally {
587 c.close();
588 }
589 }
590
Christopher Tate06efb532012-08-24 15:29:27 -0700591 // Lazy-initialize the settings caches for non-primary users
592 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700593 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
594 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700595 }
596
597 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700598 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700599 long oldId = Binder.clearCallingIdentity();
600 try {
601 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
602 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700603 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700604 dbHelper = mOpenHelpers.get(callingUser);
605 }
606 return dbHelper;
607 } finally {
608 Binder.restoreCallingIdentity(oldId);
609 }
610 }
611
612 public SettingsCache cacheForTable(final int callingUser, String tableName) {
613 if (TABLE_SYSTEM.equals(tableName)) {
614 return getOrConstructCache(callingUser, sSystemCaches);
615 }
616 if (TABLE_SECURE.equals(tableName)) {
617 return getOrConstructCache(callingUser, sSecureCaches);
618 }
619 if (TABLE_GLOBAL.equals(tableName)) {
620 return sGlobalCache;
621 }
622 return null;
623 }
624
625 /**
626 * Used for wiping a whole cache on deletes when we're not
627 * sure what exactly was deleted or changed.
628 */
629 public void invalidateCache(final int callingUser, String tableName) {
630 SettingsCache cache = cacheForTable(callingUser, tableName);
631 if (cache == null) {
632 return;
633 }
634 synchronized (cache) {
635 cache.evictAll();
636 cache.mCacheFullyMatchesDisk = false;
637 }
638 }
639
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800640 /**
641 * Fast path that avoids the use of chatty remoted Cursors.
642 */
643 @Override
644 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700645 int callingUser = UserHandle.getCallingUserId();
646 if (args != null) {
647 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
648 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700649 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
650 Binder.getCallingUid(), reqUser, false, true,
651 "get/set setting for user", null);
652 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700653 }
654 }
655
Christopher Tateb7564452012-09-19 16:21:18 -0700656 // Okay, permission checks have cleared. Reset to our own identity so we can
657 // manipulate all users' data with impunity.
658 long oldId = Binder.clearCallingIdentity();
659 try {
660 // Note: we assume that get/put operations for moved-to-global names have already
661 // been directed to the new location on the caller side (otherwise we'd fix them
662 // up here).
663 DatabaseHelper dbHelper;
664 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700665
Christopher Tateb7564452012-09-19 16:21:18 -0700666 // Get methods
667 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
668 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
669 dbHelper = getOrEstablishDatabase(callingUser);
670 cache = sSystemCaches.get(callingUser);
671 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
672 }
673 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
674 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
675 dbHelper = getOrEstablishDatabase(callingUser);
676 cache = sSecureCaches.get(callingUser);
677 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
678 }
679 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
680 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
681 // fast path: owner db & cache are immutable after onCreate() so we need not
682 // guard on the attempt to look them up
683 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
684 sGlobalCache, request);
685 }
Christopher Tate06efb532012-08-24 15:29:27 -0700686
Christopher Tateb7564452012-09-19 16:21:18 -0700687 // Put methods - new value is in the args bundle under the key named by
688 // the Settings.NameValueTable.VALUE static.
689 final String newValue = (args == null)
690 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700691
Christopher Tateb7564452012-09-19 16:21:18 -0700692 final ContentValues values = new ContentValues();
693 values.put(Settings.NameValueTable.NAME, request);
694 values.put(Settings.NameValueTable.VALUE, newValue);
695 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
696 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
697 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
698 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
699 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
700 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
701 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
702 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
703 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
704 } else {
705 Slog.w(TAG, "call() with invalid method: " + method);
706 }
707 } finally {
708 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700709 }
710
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800711 return null;
712 }
713
714 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
715 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700716 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
717 final SettingsCache cache, String key) {
718 if (cache == null) {
719 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
720 return null;
721 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800722 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800723 Bundle value = cache.get(key);
724 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700725 if (value != TOO_LARGE_TO_CACHE_MARKER) {
726 return value;
727 }
728 // else we fall through and read the value from disk
729 } else if (cache.fullyMatchesDisk()) {
730 // Fast path (very common). Don't even try touch disk
731 // if we know we've slurped it all in. Trying to
732 // touch the disk would mean waiting for yaffs2 to
733 // give us access, which could takes hundreds of
734 // milliseconds. And we're very likely being called
735 // from somebody's UI thread...
736 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800737 }
738 }
739
Christopher Tate06efb532012-08-24 15:29:27 -0700740 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800741 Cursor cursor = null;
742 try {
743 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
744 null, null, null, null);
745 if (cursor != null && cursor.getCount() == 1) {
746 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800747 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800748 }
749 } catch (SQLiteException e) {
750 Log.w(TAG, "settings lookup error", e);
751 return null;
752 } finally {
753 if (cursor != null) cursor.close();
754 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800755 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800756 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800757 }
758
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700759 @Override
760 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700761 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
762 }
763
Christopher Tateb7564452012-09-19 16:21:18 -0700764 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700765 String sort, int forUser) {
766 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700767 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700768 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700769 dbH = getOrEstablishDatabase(
770 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700771 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800773 // The favorites table was moved from this provider to a provider inside Home
774 // Home still need to query this table to upgrade from pre-cupcake builds
775 // However, a cupcake+ build with no data does not contain this table which will
776 // cause an exception in the SQL stack. The following line is a special case to
777 // 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 -0800778 if (TABLE_FAVORITES.equals(args.table)) {
779 return null;
780 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
781 args.table = TABLE_FAVORITES;
782 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
783 if (cursor != null) {
784 boolean exists = cursor.getCount() > 0;
785 cursor.close();
786 if (!exists) return null;
787 } else {
788 return null;
789 }
790 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800791
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700792 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
793 qb.setTables(args.table);
794
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700795 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
796 ret.setNotificationUri(getContext().getContentResolver(), url);
797 return ret;
798 }
799
800 @Override
801 public String getType(Uri url) {
802 // If SqlArguments supplies a where clause, then it must be an item
803 // (because we aren't supplying our own where clause).
804 SqlArguments args = new SqlArguments(url, null, null);
805 if (TextUtils.isEmpty(args.where)) {
806 return "vnd.android.cursor.dir/" + args.table;
807 } else {
808 return "vnd.android.cursor.item/" + args.table;
809 }
810 }
811
812 @Override
813 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700814 final int callingUser = UserHandle.getCallingUserId();
815 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700816 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 if (TABLE_FAVORITES.equals(args.table)) {
818 return 0;
819 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700820 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700821 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700822
Christopher Tate06efb532012-08-24 15:29:27 -0700823 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
824 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700825 DatabaseHelper dbH = getOrEstablishDatabase(
826 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700827 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700828 db.beginTransaction();
829 try {
830 int numValues = values.length;
831 for (int i = 0; i < numValues; i++) {
832 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800833 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700834 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
835 }
836 db.setTransactionSuccessful();
837 } finally {
838 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700839 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700840 }
841
Christopher Tate06efb532012-08-24 15:29:27 -0700842 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700843 return values.length;
844 }
845
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700846 /*
847 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
848 * This setting contains a list of the currently enabled location providers.
849 * But helper functions in android.providers.Settings can enable or disable
850 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800851 *
852 * @returns whether the database needs to be updated or not, also modifying
853 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700854 */
855 private boolean parseProviderList(Uri url, ContentValues initialValues) {
856 String value = initialValues.getAsString(Settings.Secure.VALUE);
857 String newProviders = null;
858 if (value != null && value.length() > 1) {
859 char prefix = value.charAt(0);
860 if (prefix == '+' || prefix == '-') {
861 // skip prefix
862 value = value.substring(1);
863
864 // read list of enabled providers into "providers"
865 String providers = "";
866 String[] columns = {Settings.Secure.VALUE};
867 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
868 Cursor cursor = query(url, columns, where, null, null);
869 if (cursor != null && cursor.getCount() == 1) {
870 try {
871 cursor.moveToFirst();
872 providers = cursor.getString(0);
873 } finally {
874 cursor.close();
875 }
876 }
877
878 int index = providers.indexOf(value);
879 int end = index + value.length();
880 // check for commas to avoid matching on partial string
881 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
882 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
883
884 if (prefix == '+' && index < 0) {
885 // append the provider to the list if not present
886 if (providers.length() == 0) {
887 newProviders = value;
888 } else {
889 newProviders = providers + ',' + value;
890 }
891 } else if (prefix == '-' && index >= 0) {
892 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400893 // remove leading or trailing comma
894 if (index > 0) {
895 index--;
896 } else if (end < providers.length()) {
897 end++;
898 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700899
900 newProviders = providers.substring(0, index);
901 if (end < providers.length()) {
902 newProviders += providers.substring(end);
903 }
904 } else {
905 // nothing changed, so no need to update the database
906 return false;
907 }
908
909 if (newProviders != null) {
910 initialValues.put(Settings.Secure.VALUE, newProviders);
911 }
912 }
913 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800914
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700915 return true;
916 }
917
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700918 @Override
919 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700920 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
921 }
922
923 // Settings.put*ForUser() always winds up here, so this is where we apply
924 // policy around permission to write settings for other users.
925 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
926 final int callingUser = UserHandle.getCallingUserId();
927 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700928 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700929 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
930 "Not permitted to access settings for other users");
931 }
932
933 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
934 + " by " + callingUser);
935
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700936 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (TABLE_FAVORITES.equals(args.table)) {
938 return null;
939 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700940 checkWritePermissions(args);
941
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700942 // Special case LOCATION_PROVIDERS_ALLOWED.
943 // Support enabling/disabling a single provider (using "+" or "-" prefix)
944 String name = initialValues.getAsString(Settings.Secure.NAME);
945 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
946 if (!parseProviderList(url, initialValues)) return null;
947 }
948
Christopher Tate06efb532012-08-24 15:29:27 -0700949 // The global table is stored under the owner, always
950 if (TABLE_GLOBAL.equals(args.table)) {
951 desiredUserHandle = UserHandle.USER_OWNER;
952 }
953
954 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800955 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
956 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
957 return Uri.withAppendedPath(url, name);
958 }
959
Christopher Tate06efb532012-08-24 15:29:27 -0700960 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
961 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700962 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700963 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700964 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700965 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700966 if (rowId <= 0) return null;
967
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800968 SettingsCache.populate(cache, initialValues); // before we notify
969
Christopher Tate78d2a662012-09-13 16:19:44 -0700970 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
971 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700972 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700973 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700974 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700975 return url;
976 }
977
978 @Override
979 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700980 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700981 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700982 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 if (TABLE_FAVORITES.equals(args.table)) {
984 return 0;
985 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
986 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700987 } else if (TABLE_GLOBAL.equals(args.table)) {
988 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700990 checkWritePermissions(args);
991
Christopher Tate06efb532012-08-24 15:29:27 -0700992 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
993 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700994 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700995 SQLiteDatabase db = dbH.getWritableDatabase();
996 int count = db.delete(args.table, args.where, args.args);
997 mutationCount.decrementAndGet();
998 if (count > 0) {
999 invalidateCache(callingUser, args.table); // before we notify
1000 sendNotify(url, callingUser);
1001 }
1002 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001003 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1004 return count;
1005 }
1006
1007 @Override
1008 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001009 // NOTE: update() is never called by the front-end Settings API, and updates that
1010 // wind up affecting rows in Secure that are globally shared will not have the
1011 // intended effect (the update will be invisible to the rest of the system).
1012 // This should have no practical effect, since writes to the Secure db can only
1013 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001014 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001015 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001016 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 if (TABLE_FAVORITES.equals(args.table)) {
1018 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001019 } else if (TABLE_GLOBAL.equals(args.table)) {
1020 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001022 checkWritePermissions(args);
1023
Christopher Tate06efb532012-08-24 15:29:27 -07001024 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1025 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001026 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001027 SQLiteDatabase db = dbH.getWritableDatabase();
1028 int count = db.update(args.table, initialValues, args.where, args.args);
1029 mutationCount.decrementAndGet();
1030 if (count > 0) {
1031 invalidateCache(callingUser, args.table); // before we notify
1032 sendNotify(url, callingUser);
1033 }
1034 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001035 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1036 return count;
1037 }
1038
1039 @Override
1040 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1041
1042 /*
1043 * When a client attempts to openFile the default ringtone or
1044 * notification setting Uri, we will proxy the call to the current
1045 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001046 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001047 int ringtoneType = RingtoneManager.getDefaultType(uri);
1048 // Above call returns -1 if the Uri doesn't match a default type
1049 if (ringtoneType != -1) {
1050 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001051
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001052 // Get the current value for the default sound
1053 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001054
Marco Nelissen69f593c2009-07-28 09:55:04 -07001055 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001056 // Only proxy the openFile call to drm or media providers
1057 String authority = soundUri.getAuthority();
1058 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1059 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1060
1061 if (isDrmAuthority) {
1062 try {
1063 // Check DRM access permission here, since once we
1064 // do the below call the DRM will be checking our
1065 // permission, not our caller's permission
1066 DrmStore.enforceAccessDrmPermission(context);
1067 } catch (SecurityException e) {
1068 throw new FileNotFoundException(e.getMessage());
1069 }
1070 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001071
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001072 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1073 }
1074 }
1075 }
1076
1077 return super.openFile(uri, mode);
1078 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001079
1080 @Override
1081 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1082
1083 /*
1084 * When a client attempts to openFile the default ringtone or
1085 * notification setting Uri, we will proxy the call to the current
1086 * default ringtone's Uri (if it is in the DRM or media provider).
1087 */
1088 int ringtoneType = RingtoneManager.getDefaultType(uri);
1089 // Above call returns -1 if the Uri doesn't match a default type
1090 if (ringtoneType != -1) {
1091 Context context = getContext();
1092
1093 // Get the current value for the default sound
1094 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1095
1096 if (soundUri != null) {
1097 // Only proxy the openFile call to drm or media providers
1098 String authority = soundUri.getAuthority();
1099 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1100 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1101
1102 if (isDrmAuthority) {
1103 try {
1104 // Check DRM access permission here, since once we
1105 // do the below call the DRM will be checking our
1106 // permission, not our caller's permission
1107 DrmStore.enforceAccessDrmPermission(context);
1108 } catch (SecurityException e) {
1109 throw new FileNotFoundException(e.getMessage());
1110 }
1111 }
1112
1113 ParcelFileDescriptor pfd = null;
1114 try {
1115 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1116 return new AssetFileDescriptor(pfd, 0, -1);
1117 } catch (FileNotFoundException ex) {
1118 // fall through and open the fallback ringtone below
1119 }
1120 }
1121
1122 try {
1123 return super.openAssetFile(soundUri, mode);
1124 } catch (FileNotFoundException ex) {
1125 // Since a non-null Uri was specified, but couldn't be opened,
1126 // fall back to the built-in ringtone.
1127 return context.getResources().openRawResourceFd(
1128 com.android.internal.R.raw.fallbackring);
1129 }
1130 }
1131 // no need to fall through and have openFile() try again, since we
1132 // already know that will fail.
1133 throw new FileNotFoundException(); // or return null ?
1134 }
1135
1136 // Note that this will end up calling openFile() above.
1137 return super.openAssetFile(uri, mode);
1138 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001139
1140 /**
1141 * In-memory LRU Cache of system and secure settings, along with
1142 * associated helper functions to keep cache coherent with the
1143 * database.
1144 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001145 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001146
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001147 private final String mCacheName;
1148 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1149
1150 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001151 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001152 mCacheName = name;
1153 }
1154
1155 /**
1156 * Is the whole database table slurped into this cache?
1157 */
1158 public boolean fullyMatchesDisk() {
1159 synchronized (this) {
1160 return mCacheFullyMatchesDisk;
1161 }
1162 }
1163
1164 public void setFullyMatchesDisk(boolean value) {
1165 synchronized (this) {
1166 mCacheFullyMatchesDisk = value;
1167 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001168 }
1169
1170 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001171 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1172 if (evicted) {
1173 mCacheFullyMatchesDisk = false;
1174 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001175 }
1176
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001177 /**
1178 * Atomic cache population, conditional on size of value and if
1179 * we lost a race.
1180 *
1181 * @returns a Bundle to send back to the client from call(), even
1182 * if we lost the race.
1183 */
1184 public Bundle putIfAbsent(String key, String value) {
1185 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1186 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1187 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001188 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001189 put(key, bundle);
1190 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001191 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001192 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001193 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001194 }
1195
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001196 /**
1197 * Populates a key in a given (possibly-null) cache.
1198 */
1199 public static void populate(SettingsCache cache, ContentValues contentValues) {
1200 if (cache == null) {
1201 return;
1202 }
1203 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1204 if (name == null) {
1205 Log.w(TAG, "null name populating settings cache.");
1206 return;
1207 }
1208 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001209 cache.populate(name, value);
1210 }
1211
1212 public void populate(String name, String value) {
1213 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001214 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001215 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001216 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001217 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001218 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001219 }
1220 }
1221
1222 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001223 * For suppressing duplicate/redundant settings inserts early,
1224 * checking our cache first (but without faulting it in),
1225 * before going to sqlite with the mutation.
1226 */
1227 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1228 if (cache == null) return false;
1229 synchronized (cache) {
1230 Bundle bundle = cache.get(name);
1231 if (bundle == null) return false;
1232 String oldValue = bundle.getPairValue();
1233 if (oldValue == null && value == null) return true;
1234 if ((oldValue == null) != (value == null)) return false;
1235 return oldValue.equals(value);
1236 }
1237 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001238 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001239}