blob: 9839c16569fb839735226d2f2082f325692ae222 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.settings;
18
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
Christopher Tate06efb532012-08-24 15:29:27 -070026import android.app.ActivityManagerNative;
Christopher Tate45281862010-03-05 15:46:30 -080027import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029import android.content.ContentProvider;
30import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070033import android.content.Intent;
34import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070037import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteQueryBuilder;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.database.sqlite.SQLiteStatement;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043import android.media.RingtoneManager;
44import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070047import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070051import android.os.UserHandle;
52import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053import android.provider.DrmStore;
54import android.provider.MediaStore;
55import android.provider.Settings;
56import android.text.TextUtils;
57import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080058import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.util.Slog;
60import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062public class SettingsProvider extends ContentProvider {
63 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070064 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065
Christopher Tate06efb532012-08-24 15:29:27 -070066 private static final String TABLE_SYSTEM = "system";
67 private static final String TABLE_SECURE = "secure";
68 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 private static final String TABLE_FAVORITES = "favorites";
70 private static final String TABLE_OLD_FAVORITES = "old_favorites";
71
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080072 private static final String[] COLUMN_VALUE = new String[] { "value" };
73
Christopher Tate06efb532012-08-24 15:29:27 -070074 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080075 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070076 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070077 private static final SparseArray<SettingsCache> sSystemCaches
78 = new SparseArray<SettingsCache>();
79 private static final SparseArray<SettingsCache> sSecureCaches
80 = new SparseArray<SettingsCache>();
81 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082
83 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070084 // database mutations are currently being handled for this user.
85 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070086 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070087 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
88 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080089
Christopher Tate78d2a662012-09-13 16:19:44 -070090 // Each defined user has their own settings
91 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
92
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080093 // Over this size we don't reject loading or saving settings but
94 // we do consider them broken/malicious and don't keep them in
95 // memory at least:
96 private static final int MAX_CACHE_ENTRY_SIZE = 500;
97
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080098 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
99
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700100 // Used as a sentinel value in an instance equality test when we
101 // want to cache the existence of a key, but not store its value.
102 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
103
Christopher Tate06efb532012-08-24 15:29:27 -0700104 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700105 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
107 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700108 * Settings which need to be treated as global/shared in multi-user environments.
109 */
110 static final HashSet<String> sSecureGlobalKeys;
111 static final HashSet<String> sSystemGlobalKeys;
112 static {
113 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
114 // table, shared across all users
115 // These must match Settings.Secure.MOVED_TO_GLOBAL
116 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate92198742012-09-07 12:00:13 -0700117 sSecureGlobalKeys.add(Settings.Secure.ADB_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700118 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700119 sSecureGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
Christopher Tate06efb532012-08-24 15:29:27 -0700120 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
121 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
122 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
123 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
124 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
Christopher Tate92198742012-09-07 12:00:13 -0700125 sSecureGlobalKeys.add(Settings.Secure.DATA_ROAMING);
Christopher Tate06efb532012-08-24 15:29:27 -0700126 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700127 sSecureGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
Christopher Tate06efb532012-08-24 15:29:27 -0700128 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
129 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
130 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
131 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Christopher Tate92198742012-09-07 12:00:13 -0700132 sSecureGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
Christopher Tate06efb532012-08-24 15:29:27 -0700133 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
146 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
147 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
148 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
149 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
150 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
151 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
152 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
153 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
154 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
155 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
156 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
157 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
158 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
159 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
160 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
161 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
162 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
163 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
164 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
165 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
166 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
167 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
168 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
170 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
171 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
172 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
173 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
174 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
175 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
Christopher Tate92198742012-09-07 12:00:13 -0700176 sSecureGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700177 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
178 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
190 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
191 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
192 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
193 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
194 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
195 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
196 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
197 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
Christopher Tatec868b642012-09-12 17:41:04 -0700198 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_ENABLE);
199 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_TIMEOUT);
200 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE);
201 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS);
202 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS);
203 sSecureGlobalKeys.add(Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS);
Christopher Tate06efb532012-08-24 15:29:27 -0700204 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
205
206 // Keys from the 'system' table now moved to 'global'
207 // These must match Settings.System.MOVED_TO_GLOBAL
208 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700209
210 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
211 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
212 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
213 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
214 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
215 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
216 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
217 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
218 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
219 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
220 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
221 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
222 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
223 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700224 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700225 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
226 }
227
228 private boolean settingMovedToGlobal(final String name) {
229 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
230 }
231
232 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700233 * Decode a content URL into the table, projection, and arguments
234 * used to access the corresponding database rows.
235 */
236 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700238 public final String where;
239 public final String[] args;
240
241 /** Operate on existing rows. */
242 SqlArguments(Uri url, String where, String[] args) {
243 if (url.getPathSegments().size() == 1) {
244 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700245 if (!DatabaseHelper.isValidTable(this.table)) {
246 throw new IllegalArgumentException("Bad root path: " + this.table);
247 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 this.where = where;
249 this.args = args;
250 } else if (url.getPathSegments().size() != 2) {
251 throw new IllegalArgumentException("Invalid URI: " + url);
252 } else if (!TextUtils.isEmpty(where)) {
253 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
254 } else {
255 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700256 if (!DatabaseHelper.isValidTable(this.table)) {
257 throw new IllegalArgumentException("Bad root path: " + this.table);
258 }
Christopher Tate06efb532012-08-24 15:29:27 -0700259 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 this.where = Settings.NameValueTable.NAME + "=?";
261 this.args = new String[] { url.getPathSegments().get(1) };
262 } else {
263 this.where = "_id=" + ContentUris.parseId(url);
264 this.args = null;
265 }
266 }
267 }
268
269 /** Insert new rows (no where clause allowed). */
270 SqlArguments(Uri url) {
271 if (url.getPathSegments().size() == 1) {
272 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700273 if (!DatabaseHelper.isValidTable(this.table)) {
274 throw new IllegalArgumentException("Bad root path: " + this.table);
275 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 this.where = null;
277 this.args = null;
278 } else {
279 throw new IllegalArgumentException("Invalid URI: " + url);
280 }
281 }
282 }
283
284 /**
285 * Get the content URI of a row added to a table.
286 * @param tableUri of the entire table
287 * @param values found in the row
288 * @param rowId of the row
289 * @return the content URI for this particular row
290 */
291 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
292 if (tableUri.getPathSegments().size() != 1) {
293 throw new IllegalArgumentException("Invalid URI: " + tableUri);
294 }
295 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700296 if (TABLE_SYSTEM.equals(table) ||
297 TABLE_SECURE.equals(table) ||
298 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700299 String name = values.getAsString(Settings.NameValueTable.NAME);
300 return Uri.withAppendedPath(tableUri, name);
301 } else {
302 return ContentUris.withAppendedId(tableUri, rowId);
303 }
304 }
305
306 /**
307 * Send a notification when a particular content URI changes.
308 * Modify the system property used to communicate the version of
309 * this table, for tables which have such a property. (The Settings
310 * contract class uses these to provide client-side caches.)
311 * @param uri to send notifications for
312 */
Christopher Tate06efb532012-08-24 15:29:27 -0700313 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 // Update the system property *first*, so if someone is listening for
315 // a notification and then using the contract class to get their data,
316 // the system property will be updated and they'll get the new data.
317
Amith Yamasanid1582142009-07-08 20:04:55 -0700318 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate16aa9732012-09-17 16:23:44 -0700320 final boolean isGlobal = table.equals(TABLE_GLOBAL);
Christopher Tate06efb532012-08-24 15:29:27 -0700321 if (table.equals(TABLE_SYSTEM)) {
322 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700323 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700324 } else if (table.equals(TABLE_SECURE)) {
325 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
326 backedUpDataChanged = true;
Christopher Tate16aa9732012-09-17 16:23:44 -0700327 } else if (isGlobal) {
Christopher Tate06efb532012-08-24 15:29:27 -0700328 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700329 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700330 }
331
332 if (property != null) {
333 long version = SystemProperties.getLong(property, 0) + 1;
334 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
335 SystemProperties.set(property, Long.toString(version));
336 }
337
-b master501eec92009-07-06 13:53:11 -0700338 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700339 if (backedUpDataChanged) {
340 mBackupManager.dataChanged();
341 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700342 // Now send the notification through the content framework.
343
344 String notify = uri.getQueryParameter("notify");
345 if (notify == null || "true".equals(notify)) {
Christopher Tate16aa9732012-09-17 16:23:44 -0700346 final int notifyTarget = isGlobal ? UserHandle.USER_ALL : userHandle;
Christopher Tatec8459dc82012-09-18 13:27:36 -0700347 final long oldId = Binder.clearCallingIdentity();
348 try {
349 getContext().getContentResolver().notifyChange(uri, null, true, notifyTarget);
350 } finally {
351 Binder.restoreCallingIdentity(oldId);
352 }
Christopher Tate16aa9732012-09-17 16:23:44 -0700353 if (LOCAL_LOGV) Log.v(TAG, "notifying for " + notifyTarget + ": " + uri);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700354 } else {
355 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
356 }
357 }
358
359 /**
360 * Make sure the caller has permission to write this data.
361 * @param args supplied by the caller
362 * @throws SecurityException if the caller is forbidden to write.
363 */
364 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700365 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800366 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800367 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
368 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700369 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800370 String.format("Permission denial: writing to secure settings requires %1$s",
371 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700372 }
373 }
374
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700375 // FileObserver for external modifications to the database file.
376 // Note that this is for platform developers only with
377 // userdebug/eng builds who should be able to tinker with the
378 // sqlite database out from under the SettingsProvider, which is
379 // normally the exclusive owner of the database. But we keep this
380 // enabled all the time to minimize development-vs-user
381 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700382 private static SparseArray<SettingsFileObserver> sObserverInstances
383 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700384 private class SettingsFileObserver extends FileObserver {
385 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700386 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700387 private final String mPath;
388
Christopher Tate06efb532012-08-24 15:29:27 -0700389 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700390 super(path, FileObserver.CLOSE_WRITE |
391 FileObserver.CREATE | FileObserver.DELETE |
392 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700393 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700394 mPath = path;
395 }
396
397 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700398 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700399 if (modsInFlight > 0) {
400 // our own modification.
401 return;
402 }
Christopher Tate06efb532012-08-24 15:29:27 -0700403 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
404 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700405 if (!mIsDirty.compareAndSet(false, true)) {
406 // already handled. (we get a few update events
407 // during an sqlite write)
408 return;
409 }
Christopher Tate06efb532012-08-24 15:29:27 -0700410 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
411 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700412 mIsDirty.set(false);
413 }
414 }
415
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700416 @Override
417 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700418 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700419 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800420
Christopher Tate78d2a662012-09-13 16:19:44 -0700421 establishDbTracking(UserHandle.USER_OWNER);
Christopher Tate06efb532012-08-24 15:29:27 -0700422
Christopher Tate78d2a662012-09-13 16:19:44 -0700423 IntentFilter userFilter = new IntentFilter();
424 userFilter.addAction(Intent.ACTION_USER_REMOVED);
425 getContext().registerReceiver(new BroadcastReceiver() {
426 @Override
427 public void onReceive(Context context, Intent intent) {
428 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
429 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
430 UserHandle.USER_OWNER);
431 if (userHandle != UserHandle.USER_OWNER) {
432 onUserRemoved(userHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700433 }
434 }
Christopher Tate78d2a662012-09-13 16:19:44 -0700435 }
436 }, userFilter);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700437 return true;
438 }
439
Christopher Tate06efb532012-08-24 15:29:27 -0700440 void onUserRemoved(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700441 synchronized (this) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700442 // the db file itself will be deleted automatically, but we need to tear down
443 // our caches and other internal bookkeeping.
Christopher Tate06efb532012-08-24 15:29:27 -0700444 FileObserver observer = sObserverInstances.get(userHandle);
445 if (observer != null) {
446 observer.stopWatching();
447 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700448 }
Christopher Tate06efb532012-08-24 15:29:27 -0700449
450 mOpenHelpers.delete(userHandle);
451 sSystemCaches.delete(userHandle);
452 sSecureCaches.delete(userHandle);
453 sKnownMutationsInFlight.delete(userHandle);
454
455 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
456 SystemProperties.set(property, "");
457 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
458 SystemProperties.set(property, "");
459 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700460 }
461
Christopher Tate78d2a662012-09-13 16:19:44 -0700462 private void establishDbTracking(int userHandle) {
Christopher Tate06efb532012-08-24 15:29:27 -0700463 if (LOCAL_LOGV) {
464 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
465 }
466
Christopher Tate78d2a662012-09-13 16:19:44 -0700467 DatabaseHelper dbhelper;
Christopher Tate06efb532012-08-24 15:29:27 -0700468
Christopher Tate78d2a662012-09-13 16:19:44 -0700469 synchronized (this) {
470 dbhelper = mOpenHelpers.get(userHandle);
471 if (dbhelper == null) {
472 dbhelper = new DatabaseHelper(getContext(), userHandle);
473 mOpenHelpers.append(userHandle, dbhelper);
474
475 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
476 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
477 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
478 }
479 }
480
481 // Initialization of the db *outside* the locks. It's possible that racing
482 // threads might wind up here, the second having read the cache entries
483 // written by the first, but that's benign: the SQLite helper implementation
484 // manages concurrency itself, and it's important that we not run the db
485 // initialization with any of our own locks held, so we're fine.
Christopher Tate06efb532012-08-24 15:29:27 -0700486 SQLiteDatabase db = dbhelper.getWritableDatabase();
487
Christopher Tate78d2a662012-09-13 16:19:44 -0700488 // Watch for external modifications to the database files,
489 // keeping our caches in sync. We synchronize the observer set
490 // separately, and of course it has to run after the db file
491 // itself was set up by the DatabaseHelper.
492 synchronized (sObserverInstances) {
493 if (sObserverInstances.get(userHandle) == null) {
494 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
495 sObserverInstances.append(userHandle, observer);
496 observer.startWatching();
497 }
498 }
Christopher Tate06efb532012-08-24 15:29:27 -0700499
Christopher Tate4dc7a682012-09-11 12:15:49 -0700500 ensureAndroidIdIsSet(userHandle);
501
Christopher Tate06efb532012-08-24 15:29:27 -0700502 startAsyncCachePopulation(userHandle);
503 }
504
505 class CachePrefetchThread extends Thread {
506 private int mUserHandle;
507
508 CachePrefetchThread(int userHandle) {
509 super("populate-settings-caches");
510 mUserHandle = userHandle;
511 }
512
513 @Override
514 public void run() {
515 fullyPopulateCaches(mUserHandle);
516 }
517 }
518
519 private void startAsyncCachePopulation(int userHandle) {
520 new CachePrefetchThread(userHandle).start();
521 }
522
523 private void fullyPopulateCaches(final int userHandle) {
524 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
525 // Only populate the globals cache once, for the owning user
526 if (userHandle == UserHandle.USER_OWNER) {
527 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
528 }
529 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
530 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700531 }
532
533 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700534 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
535 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700536 Cursor c = db.query(
537 table,
538 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
539 null, null, null, null, null,
540 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
541 try {
542 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800543 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700544 cache.setFullyMatchesDisk(true); // optimistic
545 int rows = 0;
546 while (c.moveToNext()) {
547 rows++;
548 String name = c.getString(0);
549 String value = c.getString(1);
550 cache.populate(name, value);
551 }
552 if (rows > MAX_CACHE_ENTRIES) {
553 // Somewhat redundant, as removeEldestEntry() will
554 // have already done this, but to be explicit:
555 cache.setFullyMatchesDisk(false);
556 Log.d(TAG, "row count exceeds max cache entries for table " + table);
557 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700558 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700559 cache.fullyMatchesDisk());
560 }
561 } finally {
562 c.close();
563 }
564 }
565
Christopher Tate4dc7a682012-09-11 12:15:49 -0700566 private boolean ensureAndroidIdIsSet(int userHandle) {
567 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800568 new String[] { Settings.NameValueTable.VALUE },
569 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700570 new String[] { Settings.Secure.ANDROID_ID }, null,
571 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800572 try {
573 final String value = c.moveToNext() ? c.getString(0) : null;
574 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700575 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800576 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800577 final ContentValues values = new ContentValues();
578 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
579 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700580 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800581 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700582 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800583 return false;
584 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700585 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
586 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800587 }
588 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800589 } finally {
590 c.close();
591 }
592 }
593
Christopher Tate06efb532012-08-24 15:29:27 -0700594 // Lazy-initialize the settings caches for non-primary users
595 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700596 getOrEstablishDatabase(callingUser); // ignore return value; we don't need it
597 return which.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700598 }
599
600 // Lazy initialize the database helper and caches for this user, if necessary
Christopher Tate78d2a662012-09-13 16:19:44 -0700601 private DatabaseHelper getOrEstablishDatabase(int callingUser) {
Christopher Tate06efb532012-08-24 15:29:27 -0700602 long oldId = Binder.clearCallingIdentity();
603 try {
604 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
605 if (null == dbHelper) {
Christopher Tate78d2a662012-09-13 16:19:44 -0700606 establishDbTracking(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700607 dbHelper = mOpenHelpers.get(callingUser);
608 }
609 return dbHelper;
610 } finally {
611 Binder.restoreCallingIdentity(oldId);
612 }
613 }
614
615 public SettingsCache cacheForTable(final int callingUser, String tableName) {
616 if (TABLE_SYSTEM.equals(tableName)) {
617 return getOrConstructCache(callingUser, sSystemCaches);
618 }
619 if (TABLE_SECURE.equals(tableName)) {
620 return getOrConstructCache(callingUser, sSecureCaches);
621 }
622 if (TABLE_GLOBAL.equals(tableName)) {
623 return sGlobalCache;
624 }
625 return null;
626 }
627
628 /**
629 * Used for wiping a whole cache on deletes when we're not
630 * sure what exactly was deleted or changed.
631 */
632 public void invalidateCache(final int callingUser, String tableName) {
633 SettingsCache cache = cacheForTable(callingUser, tableName);
634 if (cache == null) {
635 return;
636 }
637 synchronized (cache) {
638 cache.evictAll();
639 cache.mCacheFullyMatchesDisk = false;
640 }
641 }
642
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800643 /**
644 * Fast path that avoids the use of chatty remoted Cursors.
645 */
646 @Override
647 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700648 int callingUser = UserHandle.getCallingUserId();
649 if (args != null) {
650 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
651 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700652 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
653 Binder.getCallingUid(), reqUser, false, true,
654 "get/set setting for user", null);
655 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700656 }
657 }
658
659 // Note: we assume that get/put operations for moved-to-global names have already
660 // been directed to the new location on the caller side (otherwise we'd fix them
661 // up here).
662
663 DatabaseHelper dbHelper;
664 SettingsCache cache;
665
666 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800667 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700668 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700669 dbHelper = getOrEstablishDatabase(callingUser);
670 cache = sSystemCaches.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700671 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800672 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800673 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700674 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700675 dbHelper = getOrEstablishDatabase(callingUser);
676 cache = sSecureCaches.get(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700677 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800678 }
Christopher Tate06efb532012-08-24 15:29:27 -0700679 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
Christopher Tate78d2a662012-09-13 16:19:44 -0700683 return lookupValue(getOrEstablishDatabase(UserHandle.USER_OWNER), TABLE_GLOBAL,
Christopher Tate06efb532012-08-24 15:29:27 -0700684 sGlobalCache, request);
685 }
686
687 // 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
692 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);
Christopher Tate78d2a662012-09-13 16:19:44 -0700697 insertForUser(Settings.System.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700698 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
699 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700700 insertForUser(Settings.Secure.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700701 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
702 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
Christopher Tate78d2a662012-09-13 16:19:44 -0700703 insertForUser(Settings.Global.CONTENT_URI, values, callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700704 } else {
705 Slog.w(TAG, "call() with invalid method: " + method);
706 }
707
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800708 return null;
709 }
710
711 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
712 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700713 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
714 final SettingsCache cache, String key) {
715 if (cache == null) {
716 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
717 return null;
718 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800719 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800720 Bundle value = cache.get(key);
721 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700722 if (value != TOO_LARGE_TO_CACHE_MARKER) {
723 return value;
724 }
725 // else we fall through and read the value from disk
726 } else if (cache.fullyMatchesDisk()) {
727 // Fast path (very common). Don't even try touch disk
728 // if we know we've slurped it all in. Trying to
729 // touch the disk would mean waiting for yaffs2 to
730 // give us access, which could takes hundreds of
731 // milliseconds. And we're very likely being called
732 // from somebody's UI thread...
733 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800734 }
735 }
736
Christopher Tate06efb532012-08-24 15:29:27 -0700737 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800738 Cursor cursor = null;
739 try {
740 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
741 null, null, null, null);
742 if (cursor != null && cursor.getCount() == 1) {
743 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800744 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800745 }
746 } catch (SQLiteException e) {
747 Log.w(TAG, "settings lookup error", e);
748 return null;
749 } finally {
750 if (cursor != null) cursor.close();
751 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800752 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800753 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800754 }
755
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700756 @Override
757 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700758 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
759 }
760
761 public Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
762 String sort, int forUser) {
763 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700764 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700765 DatabaseHelper dbH;
Christopher Tate78d2a662012-09-13 16:19:44 -0700766 dbH = getOrEstablishDatabase(
767 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700768 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800770 // The favorites table was moved from this provider to a provider inside Home
771 // Home still need to query this table to upgrade from pre-cupcake builds
772 // However, a cupcake+ build with no data does not contain this table which will
773 // cause an exception in the SQL stack. The following line is a special case to
774 // 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 -0800775 if (TABLE_FAVORITES.equals(args.table)) {
776 return null;
777 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
778 args.table = TABLE_FAVORITES;
779 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
780 if (cursor != null) {
781 boolean exists = cursor.getCount() > 0;
782 cursor.close();
783 if (!exists) return null;
784 } else {
785 return null;
786 }
787 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800788
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700789 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
790 qb.setTables(args.table);
791
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700792 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
793 ret.setNotificationUri(getContext().getContentResolver(), url);
794 return ret;
795 }
796
797 @Override
798 public String getType(Uri url) {
799 // If SqlArguments supplies a where clause, then it must be an item
800 // (because we aren't supplying our own where clause).
801 SqlArguments args = new SqlArguments(url, null, null);
802 if (TextUtils.isEmpty(args.where)) {
803 return "vnd.android.cursor.dir/" + args.table;
804 } else {
805 return "vnd.android.cursor.item/" + args.table;
806 }
807 }
808
809 @Override
810 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700811 final int callingUser = UserHandle.getCallingUserId();
812 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700813 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 if (TABLE_FAVORITES.equals(args.table)) {
815 return 0;
816 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700817 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700818 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700819
Christopher Tate06efb532012-08-24 15:29:27 -0700820 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
821 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700822 DatabaseHelper dbH = getOrEstablishDatabase(
823 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700824 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700825 db.beginTransaction();
826 try {
827 int numValues = values.length;
828 for (int i = 0; i < numValues; i++) {
829 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800830 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700831 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
832 }
833 db.setTransactionSuccessful();
834 } finally {
835 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700836 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700837 }
838
Christopher Tate06efb532012-08-24 15:29:27 -0700839 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700840 return values.length;
841 }
842
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700843 /*
844 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
845 * This setting contains a list of the currently enabled location providers.
846 * But helper functions in android.providers.Settings can enable or disable
847 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800848 *
849 * @returns whether the database needs to be updated or not, also modifying
850 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700851 */
852 private boolean parseProviderList(Uri url, ContentValues initialValues) {
853 String value = initialValues.getAsString(Settings.Secure.VALUE);
854 String newProviders = null;
855 if (value != null && value.length() > 1) {
856 char prefix = value.charAt(0);
857 if (prefix == '+' || prefix == '-') {
858 // skip prefix
859 value = value.substring(1);
860
861 // read list of enabled providers into "providers"
862 String providers = "";
863 String[] columns = {Settings.Secure.VALUE};
864 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
865 Cursor cursor = query(url, columns, where, null, null);
866 if (cursor != null && cursor.getCount() == 1) {
867 try {
868 cursor.moveToFirst();
869 providers = cursor.getString(0);
870 } finally {
871 cursor.close();
872 }
873 }
874
875 int index = providers.indexOf(value);
876 int end = index + value.length();
877 // check for commas to avoid matching on partial string
878 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
879 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
880
881 if (prefix == '+' && index < 0) {
882 // append the provider to the list if not present
883 if (providers.length() == 0) {
884 newProviders = value;
885 } else {
886 newProviders = providers + ',' + value;
887 }
888 } else if (prefix == '-' && index >= 0) {
889 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400890 // remove leading or trailing comma
891 if (index > 0) {
892 index--;
893 } else if (end < providers.length()) {
894 end++;
895 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700896
897 newProviders = providers.substring(0, index);
898 if (end < providers.length()) {
899 newProviders += providers.substring(end);
900 }
901 } else {
902 // nothing changed, so no need to update the database
903 return false;
904 }
905
906 if (newProviders != null) {
907 initialValues.put(Settings.Secure.VALUE, newProviders);
908 }
909 }
910 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800911
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700912 return true;
913 }
914
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700915 @Override
916 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700917 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
918 }
919
920 // Settings.put*ForUser() always winds up here, so this is where we apply
921 // policy around permission to write settings for other users.
922 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
923 final int callingUser = UserHandle.getCallingUserId();
924 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700925 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700926 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
927 "Not permitted to access settings for other users");
928 }
929
930 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
931 + " by " + callingUser);
932
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700933 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 if (TABLE_FAVORITES.equals(args.table)) {
935 return null;
936 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700937 checkWritePermissions(args);
938
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700939 // Special case LOCATION_PROVIDERS_ALLOWED.
940 // Support enabling/disabling a single provider (using "+" or "-" prefix)
941 String name = initialValues.getAsString(Settings.Secure.NAME);
942 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
943 if (!parseProviderList(url, initialValues)) return null;
944 }
945
Christopher Tate06efb532012-08-24 15:29:27 -0700946 // The global table is stored under the owner, always
947 if (TABLE_GLOBAL.equals(args.table)) {
948 desiredUserHandle = UserHandle.USER_OWNER;
949 }
950
951 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800952 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
953 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
954 return Uri.withAppendedPath(url, name);
955 }
956
Christopher Tate06efb532012-08-24 15:29:27 -0700957 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
958 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700959 DatabaseHelper dbH = getOrEstablishDatabase(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700960 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700961 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 if (rowId <= 0) return null;
964
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800965 SettingsCache.populate(cache, initialValues); // before we notify
966
Christopher Tate78d2a662012-09-13 16:19:44 -0700967 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues
968 + " for user " + desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700969 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700970 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700971 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700972 return url;
973 }
974
975 @Override
976 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700977 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700978 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 if (TABLE_FAVORITES.equals(args.table)) {
981 return 0;
982 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
983 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700984 } else if (TABLE_GLOBAL.equals(args.table)) {
985 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700987 checkWritePermissions(args);
988
Christopher Tate06efb532012-08-24 15:29:27 -0700989 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
990 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -0700991 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700992 SQLiteDatabase db = dbH.getWritableDatabase();
993 int count = db.delete(args.table, args.where, args.args);
994 mutationCount.decrementAndGet();
995 if (count > 0) {
996 invalidateCache(callingUser, args.table); // before we notify
997 sendNotify(url, callingUser);
998 }
999 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001000 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
1001 return count;
1002 }
1003
1004 @Override
1005 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001006 // NOTE: update() is never called by the front-end Settings API, and updates that
1007 // wind up affecting rows in Secure that are globally shared will not have the
1008 // intended effect (the update will be invisible to the rest of the system).
1009 // This should have no practical effect, since writes to the Secure db can only
1010 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001011 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001012 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001013 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 if (TABLE_FAVORITES.equals(args.table)) {
1015 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001016 } else if (TABLE_GLOBAL.equals(args.table)) {
1017 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001019 checkWritePermissions(args);
1020
Christopher Tate06efb532012-08-24 15:29:27 -07001021 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1022 mutationCount.incrementAndGet();
Christopher Tate78d2a662012-09-13 16:19:44 -07001023 DatabaseHelper dbH = getOrEstablishDatabase(callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -07001024 SQLiteDatabase db = dbH.getWritableDatabase();
1025 int count = db.update(args.table, initialValues, args.where, args.args);
1026 mutationCount.decrementAndGet();
1027 if (count > 0) {
1028 invalidateCache(callingUser, args.table); // before we notify
1029 sendNotify(url, callingUser);
1030 }
1031 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001032 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1033 return count;
1034 }
1035
1036 @Override
1037 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1038
1039 /*
1040 * When a client attempts to openFile the default ringtone or
1041 * notification setting Uri, we will proxy the call to the current
1042 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001043 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001044 int ringtoneType = RingtoneManager.getDefaultType(uri);
1045 // Above call returns -1 if the Uri doesn't match a default type
1046 if (ringtoneType != -1) {
1047 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001048
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001049 // Get the current value for the default sound
1050 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001051
Marco Nelissen69f593c2009-07-28 09:55:04 -07001052 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001053 // Only proxy the openFile call to drm or media providers
1054 String authority = soundUri.getAuthority();
1055 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1056 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1057
1058 if (isDrmAuthority) {
1059 try {
1060 // Check DRM access permission here, since once we
1061 // do the below call the DRM will be checking our
1062 // permission, not our caller's permission
1063 DrmStore.enforceAccessDrmPermission(context);
1064 } catch (SecurityException e) {
1065 throw new FileNotFoundException(e.getMessage());
1066 }
1067 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001068
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001069 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1070 }
1071 }
1072 }
1073
1074 return super.openFile(uri, mode);
1075 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001076
1077 @Override
1078 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1079
1080 /*
1081 * When a client attempts to openFile the default ringtone or
1082 * notification setting Uri, we will proxy the call to the current
1083 * default ringtone's Uri (if it is in the DRM or media provider).
1084 */
1085 int ringtoneType = RingtoneManager.getDefaultType(uri);
1086 // Above call returns -1 if the Uri doesn't match a default type
1087 if (ringtoneType != -1) {
1088 Context context = getContext();
1089
1090 // Get the current value for the default sound
1091 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1092
1093 if (soundUri != null) {
1094 // Only proxy the openFile call to drm or media providers
1095 String authority = soundUri.getAuthority();
1096 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1097 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1098
1099 if (isDrmAuthority) {
1100 try {
1101 // Check DRM access permission here, since once we
1102 // do the below call the DRM will be checking our
1103 // permission, not our caller's permission
1104 DrmStore.enforceAccessDrmPermission(context);
1105 } catch (SecurityException e) {
1106 throw new FileNotFoundException(e.getMessage());
1107 }
1108 }
1109
1110 ParcelFileDescriptor pfd = null;
1111 try {
1112 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1113 return new AssetFileDescriptor(pfd, 0, -1);
1114 } catch (FileNotFoundException ex) {
1115 // fall through and open the fallback ringtone below
1116 }
1117 }
1118
1119 try {
1120 return super.openAssetFile(soundUri, mode);
1121 } catch (FileNotFoundException ex) {
1122 // Since a non-null Uri was specified, but couldn't be opened,
1123 // fall back to the built-in ringtone.
1124 return context.getResources().openRawResourceFd(
1125 com.android.internal.R.raw.fallbackring);
1126 }
1127 }
1128 // no need to fall through and have openFile() try again, since we
1129 // already know that will fail.
1130 throw new FileNotFoundException(); // or return null ?
1131 }
1132
1133 // Note that this will end up calling openFile() above.
1134 return super.openAssetFile(uri, mode);
1135 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001136
1137 /**
1138 * In-memory LRU Cache of system and secure settings, along with
1139 * associated helper functions to keep cache coherent with the
1140 * database.
1141 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001142 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001143
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001144 private final String mCacheName;
1145 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1146
1147 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001148 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001149 mCacheName = name;
1150 }
1151
1152 /**
1153 * Is the whole database table slurped into this cache?
1154 */
1155 public boolean fullyMatchesDisk() {
1156 synchronized (this) {
1157 return mCacheFullyMatchesDisk;
1158 }
1159 }
1160
1161 public void setFullyMatchesDisk(boolean value) {
1162 synchronized (this) {
1163 mCacheFullyMatchesDisk = value;
1164 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001165 }
1166
1167 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001168 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1169 if (evicted) {
1170 mCacheFullyMatchesDisk = false;
1171 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001172 }
1173
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001174 /**
1175 * Atomic cache population, conditional on size of value and if
1176 * we lost a race.
1177 *
1178 * @returns a Bundle to send back to the client from call(), even
1179 * if we lost the race.
1180 */
1181 public Bundle putIfAbsent(String key, String value) {
1182 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1183 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1184 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001185 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001186 put(key, bundle);
1187 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001188 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001189 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001190 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001191 }
1192
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001193 /**
1194 * Populates a key in a given (possibly-null) cache.
1195 */
1196 public static void populate(SettingsCache cache, ContentValues contentValues) {
1197 if (cache == null) {
1198 return;
1199 }
1200 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1201 if (name == null) {
1202 Log.w(TAG, "null name populating settings cache.");
1203 return;
1204 }
1205 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001206 cache.populate(name, value);
1207 }
1208
1209 public void populate(String name, String value) {
1210 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001211 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001212 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001213 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001214 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001215 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001216 }
1217 }
1218
1219 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001220 * For suppressing duplicate/redundant settings inserts early,
1221 * checking our cache first (but without faulting it in),
1222 * before going to sqlite with the mutation.
1223 */
1224 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1225 if (cache == null) return false;
1226 synchronized (cache) {
1227 Bundle bundle = cache.get(name);
1228 if (bundle == null) return false;
1229 String oldValue = bundle.getPairValue();
1230 if (oldValue == null && value == null) return true;
1231 if ((oldValue == null) != (value == null)) return false;
1232 return oldValue.equals(value);
1233 }
1234 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001235 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001236}