blob: 2c0bf75d5f77c1b412cd51c023f099efc61c2f2a [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>();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -0700113 sSecureGlobalKeys.add(Settings.Global.ADB_ENABLED);
114 sSecureGlobalKeys.add(Settings.Global.ASSISTED_GPS_ENABLED);
115 sSecureGlobalKeys.add(Settings.Global.BLUETOOTH_ON);
116 sSecureGlobalKeys.add(Settings.Global.CDMA_CELL_BROADCAST_SMS);
117 sSecureGlobalKeys.add(Settings.Global.CDMA_ROAMING_MODE);
118 sSecureGlobalKeys.add(Settings.Global.CDMA_SUBSCRIPTION_MODE);
119 sSecureGlobalKeys.add(Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE);
120 sSecureGlobalKeys.add(Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI);
121 sSecureGlobalKeys.add(Settings.Global.DATA_ROAMING);
122 sSecureGlobalKeys.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
123 sSecureGlobalKeys.add(Settings.Global.DEVICE_PROVISIONED);
124 sSecureGlobalKeys.add(Settings.Global.DISPLAY_DENSITY_FORCED);
125 sSecureGlobalKeys.add(Settings.Global.DISPLAY_SIZE_FORCED);
126 sSecureGlobalKeys.add(Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
127 sSecureGlobalKeys.add(Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
128 sSecureGlobalKeys.add(Settings.Global.INSTALL_NON_MARKET_APPS);
129 sSecureGlobalKeys.add(Settings.Global.MOBILE_DATA);
130 sSecureGlobalKeys.add(Settings.Global.NETSTATS_DEV_BUCKET_DURATION);
131 sSecureGlobalKeys.add(Settings.Global.NETSTATS_DEV_DELETE_AGE);
132 sSecureGlobalKeys.add(Settings.Global.NETSTATS_DEV_PERSIST_BYTES);
133 sSecureGlobalKeys.add(Settings.Global.NETSTATS_DEV_ROTATE_AGE);
134 sSecureGlobalKeys.add(Settings.Global.NETSTATS_ENABLED);
135 sSecureGlobalKeys.add(Settings.Global.NETSTATS_GLOBAL_ALERT_BYTES);
136 sSecureGlobalKeys.add(Settings.Global.NETSTATS_POLL_INTERVAL);
137 sSecureGlobalKeys.add(Settings.Global.NETSTATS_REPORT_XT_OVER_DEV);
138 sSecureGlobalKeys.add(Settings.Global.NETSTATS_SAMPLE_ENABLED);
139 sSecureGlobalKeys.add(Settings.Global.NETSTATS_TIME_CACHE_MAX_AGE);
140 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_BUCKET_DURATION);
141 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_DELETE_AGE);
142 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_PERSIST_BYTES);
143 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_ROTATE_AGE);
144 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_TAG_BUCKET_DURATION);
145 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_TAG_DELETE_AGE);
146 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_TAG_PERSIST_BYTES);
147 sSecureGlobalKeys.add(Settings.Global.NETSTATS_UID_TAG_ROTATE_AGE);
148 sSecureGlobalKeys.add(Settings.Global.NETWORK_PREFERENCE);
149 sSecureGlobalKeys.add(Settings.Global.NITZ_UPDATE_DIFF);
150 sSecureGlobalKeys.add(Settings.Global.NITZ_UPDATE_SPACING);
151 sSecureGlobalKeys.add(Settings.Global.NTP_SERVER);
152 sSecureGlobalKeys.add(Settings.Global.NTP_TIMEOUT);
153 sSecureGlobalKeys.add(Settings.Global.PDP_WATCHDOG_ERROR_POLL_COUNT);
154 sSecureGlobalKeys.add(Settings.Global.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
155 sSecureGlobalKeys.add(Settings.Global.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
156 sSecureGlobalKeys.add(Settings.Global.PDP_WATCHDOG_POLL_INTERVAL_MS);
157 sSecureGlobalKeys.add(Settings.Global.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
158 sSecureGlobalKeys.add(Settings.Global.SAMPLING_PROFILER_MS);
159 sSecureGlobalKeys.add(Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL);
160 sSecureGlobalKeys.add(Settings.Global.SETUP_PREPAID_DETECTION_REDIR_HOST);
161 sSecureGlobalKeys.add(Settings.Global.SETUP_PREPAID_DETECTION_TARGET_URL);
162 sSecureGlobalKeys.add(Settings.Global.TETHER_DUN_APN);
163 sSecureGlobalKeys.add(Settings.Global.TETHER_DUN_REQUIRED);
164 sSecureGlobalKeys.add(Settings.Global.TETHER_SUPPORTED);
165 sSecureGlobalKeys.add(Settings.Global.THROTTLE_HELP_URI);
166 sSecureGlobalKeys.add(Settings.Global.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
167 sSecureGlobalKeys.add(Settings.Global.THROTTLE_NOTIFICATION_TYPE);
168 sSecureGlobalKeys.add(Settings.Global.THROTTLE_POLLING_SEC);
169 sSecureGlobalKeys.add(Settings.Global.THROTTLE_RESET_DAY);
170 sSecureGlobalKeys.add(Settings.Global.THROTTLE_THRESHOLD_BYTES);
171 sSecureGlobalKeys.add(Settings.Global.THROTTLE_VALUE_KBITSPS);
172 sSecureGlobalKeys.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
173 sSecureGlobalKeys.add(Settings.Global.USE_GOOGLE_MAIL);
174 sSecureGlobalKeys.add(Settings.Global.WEB_AUTOFILL_QUERY_URL);
175 sSecureGlobalKeys.add(Settings.Global.WIFI_COUNTRY_CODE);
176 sSecureGlobalKeys.add(Settings.Global.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
177 sSecureGlobalKeys.add(Settings.Global.WIFI_FREQUENCY_BAND);
178 sSecureGlobalKeys.add(Settings.Global.WIFI_IDLE_MS);
179 sSecureGlobalKeys.add(Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT);
180 sSecureGlobalKeys.add(Settings.Global.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
181 sSecureGlobalKeys.add(Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
182 sSecureGlobalKeys.add(Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
183 sSecureGlobalKeys.add(Settings.Global.WIFI_NUM_OPEN_NETWORKS_KEPT);
184 sSecureGlobalKeys.add(Settings.Global.WIFI_ON);
185 sSecureGlobalKeys.add(Settings.Global.WIFI_P2P_DEVICE_NAME);
186 sSecureGlobalKeys.add(Settings.Global.WIFI_SAVED_STATE);
187 sSecureGlobalKeys.add(Settings.Global.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
188 sSecureGlobalKeys.add(Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
189 sSecureGlobalKeys.add(Settings.Global.WIFI_WATCHDOG_NUM_ARP_PINGS);
190 sSecureGlobalKeys.add(Settings.Global.WIFI_WATCHDOG_ON);
191 sSecureGlobalKeys.add(Settings.Global.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
192 sSecureGlobalKeys.add(Settings.Global.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
193 sSecureGlobalKeys.add(Settings.Global.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
194 sSecureGlobalKeys.add(Settings.Global.PACKAGE_VERIFIER_ENABLE);
195 sSecureGlobalKeys.add(Settings.Global.PACKAGE_VERIFIER_TIMEOUT);
196 sSecureGlobalKeys.add(Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE);
197 sSecureGlobalKeys.add(Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS);
198 sSecureGlobalKeys.add(Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS);
199 sSecureGlobalKeys.add(Settings.Global.GPRS_REGISTER_CHECK_PERIOD_MS);
200 sSecureGlobalKeys.add(Settings.Global.WTF_IS_FATAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700201
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)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700319 property = Settings.System.SYS_PROP_SETTING_VERSION;
Amith Yamasanid1582142009-07-08 20:04:55 -0700320 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700321 } else if (table.equals(TABLE_SECURE)) {
Dianne Hackborn139748f2012-09-24 11:36:57 -0700322 property = Settings.Secure.SYS_PROP_SETTING_VERSION;
Christopher Tate06efb532012-08-24 15:29:27 -0700323 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);
Christopher Tate06efb532012-08-24 15:29:27 -0700451 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700452 }
453
Christopher Tate78d2a662012-09-13 16:19:44 -0700454 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700455 if (LOCAL_LOGV) {
456 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
457 }
458
Christopher Tate78d2a662012-09-13 16:19:44 -0700459 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700460
Christopher Tate78d2a662012-09-13 16:19:44 -0700461 synchronized (this) {
462 dbhelper = mOpenHelpers.get(userHandle);
463 if (dbhelper == null) {
464 dbhelper = new DatabaseHelper(getContext(), userHandle);
465 mOpenHelpers.append(userHandle, dbhelper);
466
467 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
468 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
469 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
470 }
471 }
472
473 // Initialization of the db *outside* the locks. It's possible that racing
474 // threads might wind up here, the second having read the cache entries
475 // written by the first, but that's benign: the SQLite helper implementation
476 // manages concurrency itself, and it's important that we not run the db
477 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700478 SQLiteDatabase db = dbhelper.getWritableDatabase();
479
Christopher Tate78d2a662012-09-13 16:19:44 -0700480 // Watch for external modifications to the database files,
481 // keeping our caches in sync. We synchronize the observer set
482 // separately, and of course it has to run after the db file
483 // itself was set up by the DatabaseHelper.
484 synchronized (sObserverInstances) {
485 if (sObserverInstances.get(userHandle) == null) {
486 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
487 sObserverInstances.append(userHandle, observer);
488 observer.startWatching();
489 }
490 }
Christopher Tate06efb532012-08-24 15:29:27 -0700491
Christopher Tate4dc7a682012-09-11 12:15:49 -0700492 ensureAndroidIdIsSet(userHandle);
493
Christopher Tate06efb532012-08-24 15:29:27 -0700494 startAsyncCachePopulation(userHandle);
495 }
496
497 class CachePrefetchThread extends Thread {
498 private int mUserHandle;
499
500 CachePrefetchThread(int userHandle) {
501 super("populate-settings-caches");
502 mUserHandle = userHandle;
503 }
504
505 @Override
506 public void run() {
507 fullyPopulateCaches(mUserHandle);
508 }
509 }
510
511 private void startAsyncCachePopulation(int userHandle) {
512 new CachePrefetchThread(userHandle).start();
513 }
514
515 private void fullyPopulateCaches(final int userHandle) {
516 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
517 // Only populate the globals cache once, for the owning user
518 if (userHandle == UserHandle.USER_OWNER) {
519 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
520 }
521 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
522 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700523 }
524
525 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700526 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
527 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700528 Cursor c = db.query(
529 table,
530 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
531 null, null, null, null, null,
532 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
533 try {
534 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800535 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700536 cache.setFullyMatchesDisk(true); // optimistic
537 int rows = 0;
538 while (c.moveToNext()) {
539 rows++;
540 String name = c.getString(0);
541 String value = c.getString(1);
542 cache.populate(name, value);
543 }
544 if (rows > MAX_CACHE_ENTRIES) {
545 // Somewhat redundant, as removeEldestEntry() will
546 // have already done this, but to be explicit:
547 cache.setFullyMatchesDisk(false);
548 Log.d(TAG, "row count exceeds max cache entries for table " + table);
549 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700550 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700551 cache.fullyMatchesDisk());
552 }
553 } finally {
554 c.close();
555 }
556 }
557
Christopher Tate4dc7a682012-09-11 12:15:49 -0700558 private boolean ensureAndroidIdIsSet(int userHandle) {
559 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800560 new String[] { Settings.NameValueTable.VALUE },
561 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700562 new String[] { Settings.Secure.ANDROID_ID }, null,
563 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800564 try {
565 final String value = c.moveToNext() ? c.getString(0) : null;
566 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700567 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800568 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800569 final ContentValues values = new ContentValues();
570 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
571 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700572 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800573 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700574 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800575 return false;
576 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700577 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
578 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800579 }
580 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800581 } finally {
582 c.close();
583 }
584 }
585
Christopher Tate06efb532012-08-24 15:29:27 -0700586 // Lazy-initialize the settings caches for non-primary users
587 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700588 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
589 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700590 }
591
592 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700593 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700594 long oldId = Binder.clearCallingIdentity();
595 try {
596 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
597 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700598 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700599 dbHelper = mOpenHelpers.get(callingUser);
600 }
601 return dbHelper;
602 } finally {
603 Binder.restoreCallingIdentity(oldId);
604 }
605 }
606
607 public SettingsCache cacheForTable(final int callingUser, String tableName) {
608 if (TABLE_SYSTEM.equals(tableName)) {
609 return getOrConstructCache(callingUser, sSystemCaches);
610 }
611 if (TABLE_SECURE.equals(tableName)) {
612 return getOrConstructCache(callingUser, sSecureCaches);
613 }
614 if (TABLE_GLOBAL.equals(tableName)) {
615 return sGlobalCache;
616 }
617 return null;
618 }
619
620 /**
621 * Used for wiping a whole cache on deletes when we're not
622 * sure what exactly was deleted or changed.
623 */
624 public void invalidateCache(final int callingUser, String tableName) {
625 SettingsCache cache = cacheForTable(callingUser, tableName);
626 if (cache == null) {
627 return;
628 }
629 synchronized (cache) {
630 cache.evictAll();
631 cache.mCacheFullyMatchesDisk = false;
632 }
633 }
634
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800635 /**
636 * Fast path that avoids the use of chatty remoted Cursors.
637 */
638 @Override
639 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700640 int callingUser = UserHandle.getCallingUserId();
641 if (args != null) {
642 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
643 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700644 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
645 Binder.getCallingUid(), reqUser, false, true,
646 "get/set setting for user", null);
647 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700648 }
649 }
650
Christopher Tateb7564452012-09-19 16:21:18 -0700651 // Okay, permission checks have cleared. Reset to our own identity so we can
652 // manipulate all users' data with impunity.
653 long oldId = Binder.clearCallingIdentity();
654 try {
655 // Note: we assume that get/put operations for moved-to-global names have already
656 // been directed to the new location on the caller side (otherwise we'd fix them
657 // up here).
658 DatabaseHelper dbHelper;
659 SettingsCache cache;
Christopher Tate06efb532012-08-24 15:29:27 -0700660
Christopher Tateb7564452012-09-19 16:21:18 -0700661 // Get methods
662 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
663 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
664 dbHelper = getOrEstablishDatabase(callingUser);
665 cache = sSystemCaches.get(callingUser);
666 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
667 }
668 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
669 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
670 dbHelper = getOrEstablishDatabase(callingUser);
671 cache = sSecureCaches.get(callingUser);
672 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
673 }
674 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
675 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
676 // fast path: owner db & cache are immutable after onCreate() so we need not
677 // guard on the attempt to look them up
678 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
679 sGlobalCache, request);
680 }
Christopher Tate06efb532012-08-24 15:29:27 -0700681
Christopher Tateb7564452012-09-19 16:21:18 -0700682 // Put methods - new value is in the args bundle under the key named by
683 // the Settings.NameValueTable.VALUE static.
684 final String newValue = (args == null)
685 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700686
Christopher Tateb7564452012-09-19 16:21:18 -0700687 final ContentValues values = new ContentValues();
688 values.put(Settings.NameValueTable.NAME, request);
689 values.put(Settings.NameValueTable.VALUE, newValue);
690 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
691 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
692 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
693 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
694 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
695 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
696 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
697 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
698 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
699 } else {
700 Slog.w(TAG, "call() with invalid method: " + method);
701 }
702 } finally {
703 Binder.restoreCallingIdentity(oldId);
Christopher Tate06efb532012-08-24 15:29:27 -0700704 }
705
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800706 return null;
707 }
708
709 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
710 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700711 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
712 final SettingsCache cache, String key) {
713 if (cache == null) {
714 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
715 return null;
716 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800717 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800718 Bundle value = cache.get(key);
719 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700720 if (value != TOO_LARGE_TO_CACHE_MARKER) {
721 return value;
722 }
723 // else we fall through and read the value from disk
724 } else if (cache.fullyMatchesDisk()) {
725 // Fast path (very common). Don't even try touch disk
726 // if we know we've slurped it all in. Trying to
727 // touch the disk would mean waiting for yaffs2 to
728 // give us access, which could takes hundreds of
729 // milliseconds. And we're very likely being called
730 // from somebody's UI thread...
731 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800732 }
733 }
734
Christopher Tate06efb532012-08-24 15:29:27 -0700735 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800736 Cursor cursor = null;
737 try {
738 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
739 null, null, null, null);
740 if (cursor != null && cursor.getCount() == 1) {
741 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800742 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800743 }
744 } catch (SQLiteException e) {
745 Log.w(TAG, "settings lookup error", e);
746 return null;
747 } finally {
748 if (cursor != null) cursor.close();
749 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800750 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800751 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800752 }
753
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700754 @Override
755 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700756 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
757 }
758
Christopher Tateb7564452012-09-19 16:21:18 -0700759 private Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
Christopher Tate4dc7a682012-09-11 12:15:49 -0700760 String sort, int forUser) {
761 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700762 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700763 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700764 dbH = getOrEstablishDatabase(
765 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700766 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800768 // The favorites table was moved from this provider to a provider inside Home
769 // Home still need to query this table to upgrade from pre-cupcake builds
770 // However, a cupcake+ build with no data does not contain this table which will
771 // cause an exception in the SQL stack. The following line is a special case to
772 // 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 -0800773 if (TABLE_FAVORITES.equals(args.table)) {
774 return null;
775 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
776 args.table = TABLE_FAVORITES;
777 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
778 if (cursor != null) {
779 boolean exists = cursor.getCount() > 0;
780 cursor.close();
781 if (!exists) return null;
782 } else {
783 return null;
784 }
785 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800786
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700787 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
788 qb.setTables(args.table);
789
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700790 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
791 ret.setNotificationUri(getContext().getContentResolver(), url);
792 return ret;
793 }
794
795 @Override
796 public String getType(Uri url) {
797 // If SqlArguments supplies a where clause, then it must be an item
798 // (because we aren't supplying our own where clause).
799 SqlArguments args = new SqlArguments(url, null, null);
800 if (TextUtils.isEmpty(args.where)) {
801 return "vnd.android.cursor.dir/" + args.table;
802 } else {
803 return "vnd.android.cursor.item/" + args.table;
804 }
805 }
806
807 @Override
808 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700809 final int callingUser = UserHandle.getCallingUserId();
810 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700811 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 if (TABLE_FAVORITES.equals(args.table)) {
813 return 0;
814 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700815 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700816 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700817
Christopher Tate06efb532012-08-24 15:29:27 -0700818 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
819 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700820 DatabaseHelper dbH = getOrEstablishDatabase(
821 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700822 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700823 db.beginTransaction();
824 try {
825 int numValues = values.length;
826 for (int i = 0; i < numValues; i++) {
827 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800828 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700829 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
830 }
831 db.setTransactionSuccessful();
832 } finally {
833 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700834 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700835 }
836
Christopher Tate06efb532012-08-24 15:29:27 -0700837 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700838 return values.length;
839 }
840
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700841 /*
842 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
843 * This setting contains a list of the currently enabled location providers.
844 * But helper functions in android.providers.Settings can enable or disable
845 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800846 *
847 * @returns whether the database needs to be updated or not, also modifying
848 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700849 */
850 private boolean parseProviderList(Uri url, ContentValues initialValues) {
851 String value = initialValues.getAsString(Settings.Secure.VALUE);
852 String newProviders = null;
853 if (value != null && value.length() > 1) {
854 char prefix = value.charAt(0);
855 if (prefix == '+' || prefix == '-') {
856 // skip prefix
857 value = value.substring(1);
858
859 // read list of enabled providers into "providers"
860 String providers = "";
861 String[] columns = {Settings.Secure.VALUE};
862 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
863 Cursor cursor = query(url, columns, where, null, null);
864 if (cursor != null && cursor.getCount() == 1) {
865 try {
866 cursor.moveToFirst();
867 providers = cursor.getString(0);
868 } finally {
869 cursor.close();
870 }
871 }
872
873 int index = providers.indexOf(value);
874 int end = index + value.length();
875 // check for commas to avoid matching on partial string
876 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
877 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
878
879 if (prefix == '+' && index < 0) {
880 // append the provider to the list if not present
881 if (providers.length() == 0) {
882 newProviders = value;
883 } else {
884 newProviders = providers + ',' + value;
885 }
886 } else if (prefix == '-' && index >= 0) {
887 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400888 // remove leading or trailing comma
889 if (index > 0) {
890 index--;
891 } else if (end < providers.length()) {
892 end++;
893 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700894
895 newProviders = providers.substring(0, index);
896 if (end < providers.length()) {
897 newProviders += providers.substring(end);
898 }
899 } else {
900 // nothing changed, so no need to update the database
901 return false;
902 }
903
904 if (newProviders != null) {
905 initialValues.put(Settings.Secure.VALUE, newProviders);
906 }
907 }
908 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800909
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700910 return true;
911 }
912
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700913 @Override
914 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700915 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
916 }
917
918 // Settings.put*ForUser() always winds up here, so this is where we apply
919 // policy around permission to write settings for other users.
920 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
921 final int callingUser = UserHandle.getCallingUserId();
922 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700923 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700924 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
925 "Not permitted to access settings for other users");
926 }
927
928 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
929 + " by " + callingUser);
930
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700931 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 if (TABLE_FAVORITES.equals(args.table)) {
933 return null;
934 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700935 checkWritePermissions(args);
936
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700937 // Special case LOCATION_PROVIDERS_ALLOWED.
938 // Support enabling/disabling a single provider (using "+" or "-" prefix)
939 String name = initialValues.getAsString(Settings.Secure.NAME);
940 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
941 if (!parseProviderList(url, initialValues)) return null;
942 }
943
Christopher Tate06efb532012-08-24 15:29:27 -0700944 // The global table is stored under the owner, always
945 if (TABLE_GLOBAL.equals(args.table)) {
946 desiredUserHandle = UserHandle.USER_OWNER;
947 }
948
949 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800950 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
951 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
952 return Uri.withAppendedPath(url, name);
953 }
954
Christopher Tate06efb532012-08-24 15:29:27 -0700955 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
956 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700957 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700958 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700959 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700960 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700961 if (rowId <= 0) return null;
962
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800963 SettingsCache.populate(cache, initialValues); // before we notify
964
Christopher Tate78d2a662012-09-13 16:19:44 -0700965 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
966 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700967 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700968 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700969 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700970 return url;
971 }
972
973 @Override
974 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700975 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700976 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700977 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 if (TABLE_FAVORITES.equals(args.table)) {
979 return 0;
980 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
981 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700982 } else if (TABLE_GLOBAL.equals(args.table)) {
983 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700985 checkWritePermissions(args);
986
Christopher Tate06efb532012-08-24 15:29:27 -0700987 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
988 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700989 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700990 SQLiteDatabase db = dbH.getWritableDatabase();
991 int count = db.delete(args.table, args.where, args.args);
992 mutationCount.decrementAndGet();
993 if (count > 0) {
994 invalidateCache(callingUser, args.table); // before we notify
995 sendNotify(url, callingUser);
996 }
997 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700998 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
999 return count;
1000 }
1001
1002 @Override
1003 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001004 // NOTE: update() is never called by the front-end Settings API, and updates that
1005 // wind up affecting rows in Secure that are globally shared will not have the
1006 // intended effect (the update will be invisible to the rest of the system).
1007 // This should have no practical effect, since writes to the Secure db can only
1008 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001009 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001010 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001011 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 if (TABLE_FAVORITES.equals(args.table)) {
1013 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001014 } else if (TABLE_GLOBAL.equals(args.table)) {
1015 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001017 checkWritePermissions(args);
1018
Christopher Tate06efb532012-08-24 15:29:27 -07001019 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1020 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001021 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001022 SQLiteDatabase db = dbH.getWritableDatabase();
1023 int count = db.update(args.table, initialValues, args.where, args.args);
1024 mutationCount.decrementAndGet();
1025 if (count > 0) {
1026 invalidateCache(callingUser, args.table); // before we notify
1027 sendNotify(url, callingUser);
1028 }
1029 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001030 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1031 return count;
1032 }
1033
1034 @Override
1035 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1036
1037 /*
1038 * When a client attempts to openFile the default ringtone or
1039 * notification setting Uri, we will proxy the call to the current
1040 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001041 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001042 int ringtoneType = RingtoneManager.getDefaultType(uri);
1043 // Above call returns -1 if the Uri doesn't match a default type
1044 if (ringtoneType != -1) {
1045 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001046
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001047 // Get the current value for the default sound
1048 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001049
Marco Nelissen69f593c2009-07-28 09:55:04 -07001050 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001051 // Only proxy the openFile call to drm or media providers
1052 String authority = soundUri.getAuthority();
1053 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1054 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1055
1056 if (isDrmAuthority) {
1057 try {
1058 // Check DRM access permission here, since once we
1059 // do the below call the DRM will be checking our
1060 // permission, not our caller's permission
1061 DrmStore.enforceAccessDrmPermission(context);
1062 } catch (SecurityException e) {
1063 throw new FileNotFoundException(e.getMessage());
1064 }
1065 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001066
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001067 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1068 }
1069 }
1070 }
1071
1072 return super.openFile(uri, mode);
1073 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001074
1075 @Override
1076 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1077
1078 /*
1079 * When a client attempts to openFile the default ringtone or
1080 * notification setting Uri, we will proxy the call to the current
1081 * default ringtone's Uri (if it is in the DRM or media provider).
1082 */
1083 int ringtoneType = RingtoneManager.getDefaultType(uri);
1084 // Above call returns -1 if the Uri doesn't match a default type
1085 if (ringtoneType != -1) {
1086 Context context = getContext();
1087
1088 // Get the current value for the default sound
1089 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1090
1091 if (soundUri != null) {
1092 // Only proxy the openFile call to drm or media providers
1093 String authority = soundUri.getAuthority();
1094 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1095 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1096
1097 if (isDrmAuthority) {
1098 try {
1099 // Check DRM access permission here, since once we
1100 // do the below call the DRM will be checking our
1101 // permission, not our caller's permission
1102 DrmStore.enforceAccessDrmPermission(context);
1103 } catch (SecurityException e) {
1104 throw new FileNotFoundException(e.getMessage());
1105 }
1106 }
1107
1108 ParcelFileDescriptor pfd = null;
1109 try {
1110 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1111 return new AssetFileDescriptor(pfd, 0, -1);
1112 } catch (FileNotFoundException ex) {
1113 // fall through and open the fallback ringtone below
1114 }
1115 }
1116
1117 try {
1118 return super.openAssetFile(soundUri, mode);
1119 } catch (FileNotFoundException ex) {
1120 // Since a non-null Uri was specified, but couldn't be opened,
1121 // fall back to the built-in ringtone.
1122 return context.getResources().openRawResourceFd(
1123 com.android.internal.R.raw.fallbackring);
1124 }
1125 }
1126 // no need to fall through and have openFile() try again, since we
1127 // already know that will fail.
1128 throw new FileNotFoundException(); // or return null ?
1129 }
1130
1131 // Note that this will end up calling openFile() above.
1132 return super.openAssetFile(uri, mode);
1133 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001134
1135 /**
1136 * In-memory LRU Cache of system and secure settings, along with
1137 * associated helper functions to keep cache coherent with the
1138 * database.
1139 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001140 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001141
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001142 private final String mCacheName;
1143 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1144
1145 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001146 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001147 mCacheName = name;
1148 }
1149
1150 /**
1151 * Is the whole database table slurped into this cache?
1152 */
1153 public boolean fullyMatchesDisk() {
1154 synchronized (this) {
1155 return mCacheFullyMatchesDisk;
1156 }
1157 }
1158
1159 public void setFullyMatchesDisk(boolean value) {
1160 synchronized (this) {
1161 mCacheFullyMatchesDisk = value;
1162 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001163 }
1164
1165 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001166 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1167 if (evicted) {
1168 mCacheFullyMatchesDisk = false;
1169 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001170 }
1171
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001172 /**
1173 * Atomic cache population, conditional on size of value and if
1174 * we lost a race.
1175 *
1176 * @returns a Bundle to send back to the client from call(), even
1177 * if we lost the race.
1178 */
1179 public Bundle putIfAbsent(String key, String value) {
1180 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1181 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1182 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001183 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001184 put(key, bundle);
1185 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001186 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001187 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001188 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001189 }
1190
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001191 /**
1192 * Populates a key in a given (possibly-null) cache.
1193 */
1194 public static void populate(SettingsCache cache, ContentValues contentValues) {
1195 if (cache == null) {
1196 return;
1197 }
1198 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1199 if (name == null) {
1200 Log.w(TAG, "null name populating settings cache.");
1201 return;
1202 }
1203 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001204 cache.populate(name, value);
1205 }
1206
1207 public void populate(String name, String value) {
1208 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001209 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001210 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001211 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001212 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001213 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001214 }
1215 }
1216
1217 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001218 * For suppressing duplicate/redundant settings inserts early,
1219 * checking our cache first (but without faulting it in),
1220 * before going to sqlite with the mutation.
1221 */
1222 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1223 if (cache == null) return false;
1224 synchronized (cache) {
1225 Bundle bundle = cache.get(name);
1226 if (bundle == null) return false;
1227 String oldValue = bundle.getPairValue();
1228 if (oldValue == null && value == null) return true;
1229 if ((oldValue == null) != (value == null)) return false;
1230 return oldValue.equals(value);
1231 }
1232 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001233 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001234}