blob: 6773482bd54dea692bc2970c78c1ba1eb72ca9f3 [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 Tated5fe1472012-09-10 15:48:38 -070064 private static final boolean LOCAL_LOGV = true;
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
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080090 // Over this size we don't reject loading or saving settings but
91 // we do consider them broken/malicious and don't keep them in
92 // memory at least:
93 private static final int MAX_CACHE_ENTRY_SIZE = 500;
94
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080095 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
96
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070097 // Used as a sentinel value in an instance equality test when we
98 // want to cache the existence of a key, but not store its value.
99 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
100
Christopher Tate06efb532012-08-24 15:29:27 -0700101 // Each defined user has their own settings
102 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
103 //protected DatabaseHelper mOpenHelper;
104 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);
198 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
199
200 // Keys from the 'system' table now moved to 'global'
201 // These must match Settings.System.MOVED_TO_GLOBAL
202 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700203
204 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
205 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
206 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
207 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
208 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
209 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
210 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
211 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
212 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
213 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
214 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
215 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
216 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
217 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700218 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700219 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
220 }
221
222 private boolean settingMovedToGlobal(final String name) {
223 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
224 }
225
226 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700227 * Decode a content URL into the table, projection, and arguments
228 * used to access the corresponding database rows.
229 */
230 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700232 public final String where;
233 public final String[] args;
234
235 /** Operate on existing rows. */
236 SqlArguments(Uri url, String where, String[] args) {
237 if (url.getPathSegments().size() == 1) {
238 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700239 if (!DatabaseHelper.isValidTable(this.table)) {
240 throw new IllegalArgumentException("Bad root path: " + this.table);
241 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 this.where = where;
243 this.args = args;
244 } else if (url.getPathSegments().size() != 2) {
245 throw new IllegalArgumentException("Invalid URI: " + url);
246 } else if (!TextUtils.isEmpty(where)) {
247 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
248 } else {
249 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700250 if (!DatabaseHelper.isValidTable(this.table)) {
251 throw new IllegalArgumentException("Bad root path: " + this.table);
252 }
Christopher Tate06efb532012-08-24 15:29:27 -0700253 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 this.where = Settings.NameValueTable.NAME + "=?";
255 this.args = new String[] { url.getPathSegments().get(1) };
256 } else {
257 this.where = "_id=" + ContentUris.parseId(url);
258 this.args = null;
259 }
260 }
261 }
262
263 /** Insert new rows (no where clause allowed). */
264 SqlArguments(Uri url) {
265 if (url.getPathSegments().size() == 1) {
266 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700267 if (!DatabaseHelper.isValidTable(this.table)) {
268 throw new IllegalArgumentException("Bad root path: " + this.table);
269 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700270 this.where = null;
271 this.args = null;
272 } else {
273 throw new IllegalArgumentException("Invalid URI: " + url);
274 }
275 }
276 }
277
278 /**
279 * Get the content URI of a row added to a table.
280 * @param tableUri of the entire table
281 * @param values found in the row
282 * @param rowId of the row
283 * @return the content URI for this particular row
284 */
285 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
286 if (tableUri.getPathSegments().size() != 1) {
287 throw new IllegalArgumentException("Invalid URI: " + tableUri);
288 }
289 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700290 if (TABLE_SYSTEM.equals(table) ||
291 TABLE_SECURE.equals(table) ||
292 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293 String name = values.getAsString(Settings.NameValueTable.NAME);
294 return Uri.withAppendedPath(tableUri, name);
295 } else {
296 return ContentUris.withAppendedId(tableUri, rowId);
297 }
298 }
299
300 /**
301 * Send a notification when a particular content URI changes.
302 * Modify the system property used to communicate the version of
303 * this table, for tables which have such a property. (The Settings
304 * contract class uses these to provide client-side caches.)
305 * @param uri to send notifications for
306 */
Christopher Tate06efb532012-08-24 15:29:27 -0700307 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 // Update the system property *first*, so if someone is listening for
309 // a notification and then using the contract class to get their data,
310 // the system property will be updated and they'll get the new data.
311
Amith Yamasanid1582142009-07-08 20:04:55 -0700312 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700313 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700314 if (table.equals(TABLE_SYSTEM)) {
315 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700316 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700317 } else if (table.equals(TABLE_SECURE)) {
318 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
319 backedUpDataChanged = true;
320 } else if (table.equals(TABLE_GLOBAL)) {
321 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700322 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700323 }
324
325 if (property != null) {
326 long version = SystemProperties.getLong(property, 0) + 1;
327 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
328 SystemProperties.set(property, Long.toString(version));
329 }
330
-b master501eec92009-07-06 13:53:11 -0700331 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700332 if (backedUpDataChanged) {
333 mBackupManager.dataChanged();
334 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335 // Now send the notification through the content framework.
336
337 String notify = uri.getQueryParameter("notify");
338 if (notify == null || "true".equals(notify)) {
339 getContext().getContentResolver().notifyChange(uri, null);
340 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
341 } else {
342 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
343 }
344 }
345
346 /**
347 * Make sure the caller has permission to write this data.
348 * @param args supplied by the caller
349 * @throws SecurityException if the caller is forbidden to write.
350 */
351 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700352 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800353 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800354 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
355 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700356 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800357 String.format("Permission denial: writing to secure settings requires %1$s",
358 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700359 }
360 }
361
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700362 // FileObserver for external modifications to the database file.
363 // Note that this is for platform developers only with
364 // userdebug/eng builds who should be able to tinker with the
365 // sqlite database out from under the SettingsProvider, which is
366 // normally the exclusive owner of the database. But we keep this
367 // enabled all the time to minimize development-vs-user
368 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700369 private static SparseArray<SettingsFileObserver> sObserverInstances
370 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700371 private class SettingsFileObserver extends FileObserver {
372 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700373 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700374 private final String mPath;
375
Christopher Tate06efb532012-08-24 15:29:27 -0700376 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700377 super(path, FileObserver.CLOSE_WRITE |
378 FileObserver.CREATE | FileObserver.DELETE |
379 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700380 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700381 mPath = path;
382 }
383
384 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700385 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700386 if (modsInFlight > 0) {
387 // our own modification.
388 return;
389 }
Christopher Tate06efb532012-08-24 15:29:27 -0700390 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
391 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700392 if (!mIsDirty.compareAndSet(false, true)) {
393 // already handled. (we get a few update events
394 // during an sqlite write)
395 return;
396 }
Christopher Tate06efb532012-08-24 15:29:27 -0700397 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
398 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700399 mIsDirty.set(false);
400 }
401 }
402
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700403 @Override
404 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700405 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700406 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800407
Christopher Tate06efb532012-08-24 15:29:27 -0700408 synchronized (this) {
409 establishDbTrackingLocked(UserHandle.USER_OWNER);
410
411 IntentFilter userFilter = new IntentFilter();
412 userFilter.addAction(Intent.ACTION_USER_REMOVED);
413 getContext().registerReceiver(new BroadcastReceiver() {
414 @Override
415 public void onReceive(Context context, Intent intent) {
416 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
417 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
418 UserHandle.USER_OWNER);
419 if (userHandle != UserHandle.USER_OWNER) {
420 onUserRemoved(userHandle);
421 }
422 }
423 }
424 }, userFilter);
425
426 if (!ensureAndroidIdIsSet()) {
427 return false;
428 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800429 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 return true;
431 }
432
Christopher Tate06efb532012-08-24 15:29:27 -0700433 void onUserRemoved(int userHandle) {
434 // the db file itself will be deleted automatically, but we need to tear down
435 // our caches and other internal bookkeeping. Creation/deletion of a user's
436 // settings db infrastructure is synchronized on 'this'
437 synchronized (this) {
438 FileObserver observer = sObserverInstances.get(userHandle);
439 if (observer != null) {
440 observer.stopWatching();
441 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700442 }
Christopher Tate06efb532012-08-24 15:29:27 -0700443
444 mOpenHelpers.delete(userHandle);
445 sSystemCaches.delete(userHandle);
446 sSecureCaches.delete(userHandle);
447 sKnownMutationsInFlight.delete(userHandle);
448
449 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
450 SystemProperties.set(property, "");
451 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
452 SystemProperties.set(property, "");
453 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700454 }
455
Christopher Tate06efb532012-08-24 15:29:27 -0700456 private void establishDbTrackingLocked(int userHandle) {
457 if (LOCAL_LOGV) {
458 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
459 }
460
461 DatabaseHelper dbhelper = new DatabaseHelper(getContext(), userHandle);
462 mOpenHelpers.append(userHandle, dbhelper);
463
464 // Watch for external modifications to the database files,
465 // keeping our caches in sync.
466 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
467 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
468 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
469 SQLiteDatabase db = dbhelper.getWritableDatabase();
470
471 // Now we can start observing it for changes
472 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
473 sObserverInstances.append(userHandle, observer);
474 observer.startWatching();
475
476 startAsyncCachePopulation(userHandle);
477 }
478
479 class CachePrefetchThread extends Thread {
480 private int mUserHandle;
481
482 CachePrefetchThread(int userHandle) {
483 super("populate-settings-caches");
484 mUserHandle = userHandle;
485 }
486
487 @Override
488 public void run() {
489 fullyPopulateCaches(mUserHandle);
490 }
491 }
492
493 private void startAsyncCachePopulation(int userHandle) {
494 new CachePrefetchThread(userHandle).start();
495 }
496
497 private void fullyPopulateCaches(final int userHandle) {
498 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
499 // Only populate the globals cache once, for the owning user
500 if (userHandle == UserHandle.USER_OWNER) {
501 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
502 }
503 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
504 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700505 }
506
507 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700508 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
509 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700510 Cursor c = db.query(
511 table,
512 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
513 null, null, null, null, null,
514 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
515 try {
516 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800517 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700518 cache.setFullyMatchesDisk(true); // optimistic
519 int rows = 0;
520 while (c.moveToNext()) {
521 rows++;
522 String name = c.getString(0);
523 String value = c.getString(1);
524 cache.populate(name, value);
525 }
526 if (rows > MAX_CACHE_ENTRIES) {
527 // Somewhat redundant, as removeEldestEntry() will
528 // have already done this, but to be explicit:
529 cache.setFullyMatchesDisk(false);
530 Log.d(TAG, "row count exceeds max cache entries for table " + table);
531 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700532 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700533 cache.fullyMatchesDisk());
534 }
535 } finally {
536 c.close();
537 }
538 }
539
Fred Quintanac70239e2009-12-17 10:28:33 -0800540 private boolean ensureAndroidIdIsSet() {
541 final Cursor c = query(Settings.Secure.CONTENT_URI,
542 new String[] { Settings.NameValueTable.VALUE },
543 Settings.NameValueTable.NAME + "=?",
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800544 new String[] { Settings.Secure.ANDROID_ID }, null);
Fred Quintanac70239e2009-12-17 10:28:33 -0800545 try {
546 final String value = c.moveToNext() ? c.getString(0) : null;
547 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700548 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800549 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Doug Zongker0fe27cf2010-08-19 13:38:26 -0700550 Log.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue + "]");
Fred Quintanac70239e2009-12-17 10:28:33 -0800551 final ContentValues values = new ContentValues();
552 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
553 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
554 final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
555 if (uri == null) {
556 return false;
557 }
558 }
559 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800560 } finally {
561 c.close();
562 }
563 }
564
Christopher Tate06efb532012-08-24 15:29:27 -0700565 // Lazy-initialize the settings caches for non-primary users
566 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
567 synchronized (this) {
568 getOrEstablishDatabaseLocked(callingUser); // ignore return value; we don't need it
569 return which.get(callingUser);
570 }
571 }
572
573 // Lazy initialize the database helper and caches for this user, if necessary
574 private DatabaseHelper getOrEstablishDatabaseLocked(int callingUser) {
575 long oldId = Binder.clearCallingIdentity();
576 try {
577 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
578 if (null == dbHelper) {
579 establishDbTrackingLocked(callingUser);
580 dbHelper = mOpenHelpers.get(callingUser);
581 }
582 return dbHelper;
583 } finally {
584 Binder.restoreCallingIdentity(oldId);
585 }
586 }
587
588 public SettingsCache cacheForTable(final int callingUser, String tableName) {
589 if (TABLE_SYSTEM.equals(tableName)) {
590 return getOrConstructCache(callingUser, sSystemCaches);
591 }
592 if (TABLE_SECURE.equals(tableName)) {
593 return getOrConstructCache(callingUser, sSecureCaches);
594 }
595 if (TABLE_GLOBAL.equals(tableName)) {
596 return sGlobalCache;
597 }
598 return null;
599 }
600
601 /**
602 * Used for wiping a whole cache on deletes when we're not
603 * sure what exactly was deleted or changed.
604 */
605 public void invalidateCache(final int callingUser, String tableName) {
606 SettingsCache cache = cacheForTable(callingUser, tableName);
607 if (cache == null) {
608 return;
609 }
610 synchronized (cache) {
611 cache.evictAll();
612 cache.mCacheFullyMatchesDisk = false;
613 }
614 }
615
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800616 /**
617 * Fast path that avoids the use of chatty remoted Cursors.
618 */
619 @Override
620 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700621 int callingUser = UserHandle.getCallingUserId();
622 if (args != null) {
623 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
624 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700625 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
626 Binder.getCallingUid(), reqUser, false, true,
627 "get/set setting for user", null);
628 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700629 }
630 }
631
632 // Note: we assume that get/put operations for moved-to-global names have already
633 // been directed to the new location on the caller side (otherwise we'd fix them
634 // up here).
635
636 DatabaseHelper dbHelper;
637 SettingsCache cache;
638
639 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800640 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700641 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
642 synchronized (this) {
643 dbHelper = getOrEstablishDatabaseLocked(callingUser);
644 cache = sSystemCaches.get(callingUser);
645 }
646 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800647 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800648 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700649 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
650 synchronized (this) {
651 dbHelper = getOrEstablishDatabaseLocked(callingUser);
652 cache = sSecureCaches.get(callingUser);
653 }
654 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800655 }
Christopher Tate06efb532012-08-24 15:29:27 -0700656 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
657 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
658 // fast path: owner db & cache are immutable after onCreate() so we need not
659 // guard on the attempt to look them up
660 return lookupValue(getOrEstablishDatabaseLocked(UserHandle.USER_OWNER), TABLE_GLOBAL,
661 sGlobalCache, request);
662 }
663
664 // Put methods - new value is in the args bundle under the key named by
665 // the Settings.NameValueTable.VALUE static.
666 final String newValue = (args == null)
667 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700668
669 final ContentValues values = new ContentValues();
670 values.put(Settings.NameValueTable.NAME, request);
671 values.put(Settings.NameValueTable.VALUE, newValue);
672 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
673 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
674 insert(Settings.System.CONTENT_URI, values);
675 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
676 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
677 insert(Settings.Secure.CONTENT_URI, values);
678 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
679 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
680 insert(Settings.Global.CONTENT_URI, values);
681 } else {
682 Slog.w(TAG, "call() with invalid method: " + method);
683 }
684
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800685 return null;
686 }
687
688 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
689 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700690 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
691 final SettingsCache cache, String key) {
692 if (cache == null) {
693 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
694 return null;
695 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800696 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800697 Bundle value = cache.get(key);
698 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700699 if (value != TOO_LARGE_TO_CACHE_MARKER) {
700 return value;
701 }
702 // else we fall through and read the value from disk
703 } else if (cache.fullyMatchesDisk()) {
704 // Fast path (very common). Don't even try touch disk
705 // if we know we've slurped it all in. Trying to
706 // touch the disk would mean waiting for yaffs2 to
707 // give us access, which could takes hundreds of
708 // milliseconds. And we're very likely being called
709 // from somebody's UI thread...
710 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800711 }
712 }
713
Christopher Tate06efb532012-08-24 15:29:27 -0700714 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800715 Cursor cursor = null;
716 try {
717 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
718 null, null, null, null);
719 if (cursor != null && cursor.getCount() == 1) {
720 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800721 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800722 }
723 } catch (SQLiteException e) {
724 Log.w(TAG, "settings lookup error", e);
725 return null;
726 } finally {
727 if (cursor != null) cursor.close();
728 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800729 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800730 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800731 }
732
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700733 @Override
734 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate06efb532012-08-24 15:29:27 -0700735 final int callingUser = UserHandle.getCallingUserId();
736 if (LOCAL_LOGV) Slog.v(TAG, "query() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700737 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700738 DatabaseHelper dbH;
739 synchronized (this) {
740 dbH = getOrEstablishDatabaseLocked(callingUser);
741 }
742 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800744 // The favorites table was moved from this provider to a provider inside Home
745 // Home still need to query this table to upgrade from pre-cupcake builds
746 // However, a cupcake+ build with no data does not contain this table which will
747 // cause an exception in the SQL stack. The following line is a special case to
748 // 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 -0800749 if (TABLE_FAVORITES.equals(args.table)) {
750 return null;
751 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
752 args.table = TABLE_FAVORITES;
753 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
754 if (cursor != null) {
755 boolean exists = cursor.getCount() > 0;
756 cursor.close();
757 if (!exists) return null;
758 } else {
759 return null;
760 }
761 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800762
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700763 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
764 qb.setTables(args.table);
765
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700766 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
767 ret.setNotificationUri(getContext().getContentResolver(), url);
768 return ret;
769 }
770
771 @Override
772 public String getType(Uri url) {
773 // If SqlArguments supplies a where clause, then it must be an item
774 // (because we aren't supplying our own where clause).
775 SqlArguments args = new SqlArguments(url, null, null);
776 if (TextUtils.isEmpty(args.where)) {
777 return "vnd.android.cursor.dir/" + args.table;
778 } else {
779 return "vnd.android.cursor.item/" + args.table;
780 }
781 }
782
783 @Override
784 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700785 final int callingUser = UserHandle.getCallingUserId();
786 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700787 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 if (TABLE_FAVORITES.equals(args.table)) {
789 return 0;
790 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700791 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700792 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700793
Christopher Tate06efb532012-08-24 15:29:27 -0700794 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
795 mutationCount.incrementAndGet();
796 DatabaseHelper dbH;
797 synchronized (this) {
798 dbH = getOrEstablishDatabaseLocked(callingUser);
799 }
800 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700801 db.beginTransaction();
802 try {
803 int numValues = values.length;
804 for (int i = 0; i < numValues; i++) {
805 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800806 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700807 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
808 }
809 db.setTransactionSuccessful();
810 } finally {
811 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700812 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700813 }
814
Christopher Tate06efb532012-08-24 15:29:27 -0700815 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700816 return values.length;
817 }
818
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700819 /*
820 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
821 * This setting contains a list of the currently enabled location providers.
822 * But helper functions in android.providers.Settings can enable or disable
823 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800824 *
825 * @returns whether the database needs to be updated or not, also modifying
826 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700827 */
828 private boolean parseProviderList(Uri url, ContentValues initialValues) {
829 String value = initialValues.getAsString(Settings.Secure.VALUE);
830 String newProviders = null;
831 if (value != null && value.length() > 1) {
832 char prefix = value.charAt(0);
833 if (prefix == '+' || prefix == '-') {
834 // skip prefix
835 value = value.substring(1);
836
837 // read list of enabled providers into "providers"
838 String providers = "";
839 String[] columns = {Settings.Secure.VALUE};
840 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
841 Cursor cursor = query(url, columns, where, null, null);
842 if (cursor != null && cursor.getCount() == 1) {
843 try {
844 cursor.moveToFirst();
845 providers = cursor.getString(0);
846 } finally {
847 cursor.close();
848 }
849 }
850
851 int index = providers.indexOf(value);
852 int end = index + value.length();
853 // check for commas to avoid matching on partial string
854 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
855 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
856
857 if (prefix == '+' && index < 0) {
858 // append the provider to the list if not present
859 if (providers.length() == 0) {
860 newProviders = value;
861 } else {
862 newProviders = providers + ',' + value;
863 }
864 } else if (prefix == '-' && index >= 0) {
865 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400866 // remove leading or trailing comma
867 if (index > 0) {
868 index--;
869 } else if (end < providers.length()) {
870 end++;
871 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700872
873 newProviders = providers.substring(0, index);
874 if (end < providers.length()) {
875 newProviders += providers.substring(end);
876 }
877 } else {
878 // nothing changed, so no need to update the database
879 return false;
880 }
881
882 if (newProviders != null) {
883 initialValues.put(Settings.Secure.VALUE, newProviders);
884 }
885 }
886 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800887
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700888 return true;
889 }
890
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700891 @Override
892 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700893 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
894 }
895
896 // Settings.put*ForUser() always winds up here, so this is where we apply
897 // policy around permission to write settings for other users.
898 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
899 final int callingUser = UserHandle.getCallingUserId();
900 if (callingUser != desiredUserHandle) {
901 getContext().enforceCallingPermission(
902 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
903 "Not permitted to access settings for other users");
904 }
905
906 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
907 + " by " + callingUser);
908
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700909 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 if (TABLE_FAVORITES.equals(args.table)) {
911 return null;
912 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700913 checkWritePermissions(args);
914
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700915 // Special case LOCATION_PROVIDERS_ALLOWED.
916 // Support enabling/disabling a single provider (using "+" or "-" prefix)
917 String name = initialValues.getAsString(Settings.Secure.NAME);
918 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
919 if (!parseProviderList(url, initialValues)) return null;
920 }
921
Christopher Tate06efb532012-08-24 15:29:27 -0700922 // The global table is stored under the owner, always
923 if (TABLE_GLOBAL.equals(args.table)) {
924 desiredUserHandle = UserHandle.USER_OWNER;
925 }
926
927 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800928 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
929 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
930 return Uri.withAppendedPath(url, name);
931 }
932
Christopher Tate06efb532012-08-24 15:29:27 -0700933 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
934 mutationCount.incrementAndGet();
935 DatabaseHelper dbH;
936 synchronized (this) {
937 dbH = getOrEstablishDatabaseLocked(callingUser);
938 }
939 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700940 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700941 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700942 if (rowId <= 0) return null;
943
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800944 SettingsCache.populate(cache, initialValues); // before we notify
945
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700946 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700947 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700948 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700949 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700950 return url;
951 }
952
953 @Override
954 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700955 final int callingUser = UserHandle.getCallingUserId();
956 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700957 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 if (TABLE_FAVORITES.equals(args.table)) {
959 return 0;
960 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
961 args.table = TABLE_FAVORITES;
962 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 checkWritePermissions(args);
964
Christopher Tate06efb532012-08-24 15:29:27 -0700965 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
966 mutationCount.incrementAndGet();
967 DatabaseHelper dbH;
968 synchronized (this) {
969 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800970 }
Christopher Tate06efb532012-08-24 15:29:27 -0700971 SQLiteDatabase db = dbH.getWritableDatabase();
972 int count = db.delete(args.table, args.where, args.args);
973 mutationCount.decrementAndGet();
974 if (count > 0) {
975 invalidateCache(callingUser, args.table); // before we notify
976 sendNotify(url, callingUser);
977 }
978 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
980 return count;
981 }
982
983 @Override
984 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700985 // NOTE: update() is never called by the front-end Settings API, and updates that
986 // wind up affecting rows in Secure that are globally shared will not have the
987 // intended effect (the update will be invisible to the rest of the system).
988 // This should have no practical effect, since writes to the Secure db can only
989 // be done by system code, and that code should be using the correct API up front.
990 final int callingUser = UserHandle.getCallingUserId();
991 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700992 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 if (TABLE_FAVORITES.equals(args.table)) {
994 return 0;
995 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700996 checkWritePermissions(args);
997
Christopher Tate06efb532012-08-24 15:29:27 -0700998 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
999 mutationCount.incrementAndGet();
1000 DatabaseHelper dbH;
1001 synchronized (this) {
1002 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001003 }
Christopher Tate06efb532012-08-24 15:29:27 -07001004 SQLiteDatabase db = dbH.getWritableDatabase();
1005 int count = db.update(args.table, initialValues, args.where, args.args);
1006 mutationCount.decrementAndGet();
1007 if (count > 0) {
1008 invalidateCache(callingUser, args.table); // before we notify
1009 sendNotify(url, callingUser);
1010 }
1011 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001012 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1013 return count;
1014 }
1015
1016 @Override
1017 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1018
1019 /*
1020 * When a client attempts to openFile the default ringtone or
1021 * notification setting Uri, we will proxy the call to the current
1022 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001023 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001024 int ringtoneType = RingtoneManager.getDefaultType(uri);
1025 // Above call returns -1 if the Uri doesn't match a default type
1026 if (ringtoneType != -1) {
1027 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001028
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001029 // Get the current value for the default sound
1030 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001031
Marco Nelissen69f593c2009-07-28 09:55:04 -07001032 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001033 // Only proxy the openFile call to drm or media providers
1034 String authority = soundUri.getAuthority();
1035 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1036 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1037
1038 if (isDrmAuthority) {
1039 try {
1040 // Check DRM access permission here, since once we
1041 // do the below call the DRM will be checking our
1042 // permission, not our caller's permission
1043 DrmStore.enforceAccessDrmPermission(context);
1044 } catch (SecurityException e) {
1045 throw new FileNotFoundException(e.getMessage());
1046 }
1047 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001048
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001049 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1050 }
1051 }
1052 }
1053
1054 return super.openFile(uri, mode);
1055 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001056
1057 @Override
1058 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1059
1060 /*
1061 * When a client attempts to openFile the default ringtone or
1062 * notification setting Uri, we will proxy the call to the current
1063 * default ringtone's Uri (if it is in the DRM or media provider).
1064 */
1065 int ringtoneType = RingtoneManager.getDefaultType(uri);
1066 // Above call returns -1 if the Uri doesn't match a default type
1067 if (ringtoneType != -1) {
1068 Context context = getContext();
1069
1070 // Get the current value for the default sound
1071 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1072
1073 if (soundUri != null) {
1074 // Only proxy the openFile call to drm or media providers
1075 String authority = soundUri.getAuthority();
1076 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1077 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1078
1079 if (isDrmAuthority) {
1080 try {
1081 // Check DRM access permission here, since once we
1082 // do the below call the DRM will be checking our
1083 // permission, not our caller's permission
1084 DrmStore.enforceAccessDrmPermission(context);
1085 } catch (SecurityException e) {
1086 throw new FileNotFoundException(e.getMessage());
1087 }
1088 }
1089
1090 ParcelFileDescriptor pfd = null;
1091 try {
1092 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1093 return new AssetFileDescriptor(pfd, 0, -1);
1094 } catch (FileNotFoundException ex) {
1095 // fall through and open the fallback ringtone below
1096 }
1097 }
1098
1099 try {
1100 return super.openAssetFile(soundUri, mode);
1101 } catch (FileNotFoundException ex) {
1102 // Since a non-null Uri was specified, but couldn't be opened,
1103 // fall back to the built-in ringtone.
1104 return context.getResources().openRawResourceFd(
1105 com.android.internal.R.raw.fallbackring);
1106 }
1107 }
1108 // no need to fall through and have openFile() try again, since we
1109 // already know that will fail.
1110 throw new FileNotFoundException(); // or return null ?
1111 }
1112
1113 // Note that this will end up calling openFile() above.
1114 return super.openAssetFile(uri, mode);
1115 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001116
1117 /**
1118 * In-memory LRU Cache of system and secure settings, along with
1119 * associated helper functions to keep cache coherent with the
1120 * database.
1121 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001122 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001123
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001124 private final String mCacheName;
1125 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1126
1127 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001128 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001129 mCacheName = name;
1130 }
1131
1132 /**
1133 * Is the whole database table slurped into this cache?
1134 */
1135 public boolean fullyMatchesDisk() {
1136 synchronized (this) {
1137 return mCacheFullyMatchesDisk;
1138 }
1139 }
1140
1141 public void setFullyMatchesDisk(boolean value) {
1142 synchronized (this) {
1143 mCacheFullyMatchesDisk = value;
1144 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001145 }
1146
1147 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001148 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1149 if (evicted) {
1150 mCacheFullyMatchesDisk = false;
1151 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001152 }
1153
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001154 /**
1155 * Atomic cache population, conditional on size of value and if
1156 * we lost a race.
1157 *
1158 * @returns a Bundle to send back to the client from call(), even
1159 * if we lost the race.
1160 */
1161 public Bundle putIfAbsent(String key, String value) {
1162 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1163 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1164 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001165 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001166 put(key, bundle);
1167 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001168 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001169 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001170 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001171 }
1172
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001173 /**
1174 * Populates a key in a given (possibly-null) cache.
1175 */
1176 public static void populate(SettingsCache cache, ContentValues contentValues) {
1177 if (cache == null) {
1178 return;
1179 }
1180 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1181 if (name == null) {
1182 Log.w(TAG, "null name populating settings cache.");
1183 return;
1184 }
1185 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001186 cache.populate(name, value);
1187 }
1188
1189 public void populate(String name, String value) {
1190 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001191 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001192 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001193 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001194 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001195 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001196 }
1197 }
1198
1199 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001200 * For suppressing duplicate/redundant settings inserts early,
1201 * checking our cache first (but without faulting it in),
1202 * before going to sqlite with the mutation.
1203 */
1204 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1205 if (cache == null) return false;
1206 synchronized (cache) {
1207 Bundle bundle = cache.get(name);
1208 if (bundle == null) return false;
1209 String oldValue = bundle.getPairValue();
1210 if (oldValue == null && value == null) return true;
1211 if ((oldValue == null) != (value == null)) return false;
1212 return oldValue.equals(value);
1213 }
1214 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001215 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001216}