blob: f859f4197ad10b0396059e6ed066b5bf5e13a0ff [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 Tate06efb532012-08-24 15:29:27 -070025import android.app.ActivityManagerNative;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070027import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028import android.content.ContentProvider;
29import android.content.ContentUris;
30import android.content.ContentValues;
31import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070032import android.content.Intent;
33import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070034import android.content.pm.PackageManager;
Christopher Tate06efb532012-08-24 15:29:27 -070035import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070036import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070037import android.database.Cursor;
38import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080039import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070040import android.database.sqlite.SQLiteQueryBuilder;
Christopher Tate06efb532012-08-24 15:29:27 -070041import android.database.sqlite.SQLiteStatement;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042import android.media.RingtoneManager;
43import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070044import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080045import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070046import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070047import android.os.ParcelFileDescriptor;
Christopher Tate06efb532012-08-24 15:29:27 -070048import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070049import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070050import android.os.UserHandle;
51import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070052import android.provider.DrmStore;
53import android.provider.MediaStore;
54import android.provider.Settings;
55import android.text.TextUtils;
56import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080057import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070058import android.util.Slog;
59import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070060
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061public class SettingsProvider extends ContentProvider {
62 private static final String TAG = "SettingsProvider";
63 private static final boolean LOCAL_LOGV = false;
64
Christopher Tate06efb532012-08-24 15:29:27 -070065 private static final String TABLE_SYSTEM = "system";
66 private static final String TABLE_SECURE = "secure";
67 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 private static final String TABLE_FAVORITES = "favorites";
69 private static final String TABLE_OLD_FAVORITES = "old_favorites";
70
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080071 private static final String[] COLUMN_VALUE = new String[] { "value" };
72
Christopher Tate06efb532012-08-24 15:29:27 -070073 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080074 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070075 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070076 private static final SparseArray<SettingsCache> sSystemCaches
77 = new SparseArray<SettingsCache>();
78 private static final SparseArray<SettingsCache> sSecureCaches
79 = new SparseArray<SettingsCache>();
80 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070081
82 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070083 // database mutations are currently being handled for this user.
84 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070085 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070086 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
87 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080088
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080089 // Over this size we don't reject loading or saving settings but
90 // we do consider them broken/malicious and don't keep them in
91 // memory at least:
92 private static final int MAX_CACHE_ENTRY_SIZE = 500;
93
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080094 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
95
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070096 // Used as a sentinel value in an instance equality test when we
97 // want to cache the existence of a key, but not store its value.
98 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
99
Christopher Tate06efb532012-08-24 15:29:27 -0700100 // Each defined user has their own settings
101 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
102 //protected DatabaseHelper mOpenHelper;
103 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700104 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700105
106 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700107 * Settings which need to be treated as global/shared in multi-user environments.
108 */
109 static final HashSet<String> sSecureGlobalKeys;
110 static final HashSet<String> sSystemGlobalKeys;
111 static {
112 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
113 // table, shared across all users
114 // These must match Settings.Secure.MOVED_TO_GLOBAL
115 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate92198742012-09-07 12:00:13 -0700116 sSecureGlobalKeys.add(Settings.Secure.ADB_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700117 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700118 sSecureGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
Christopher Tate06efb532012-08-24 15:29:27 -0700119 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
120 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
121 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
122 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
123 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
Christopher Tate92198742012-09-07 12:00:13 -0700124 sSecureGlobalKeys.add(Settings.Secure.DATA_ROAMING);
Christopher Tate06efb532012-08-24 15:29:27 -0700125 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700126 sSecureGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
Christopher Tate06efb532012-08-24 15:29:27 -0700127 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
128 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
129 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
130 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Christopher Tate92198742012-09-07 12:00:13 -0700131 sSecureGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
Christopher Tate06efb532012-08-24 15:29:27 -0700132 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
133 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
146 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
147 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
148 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
149 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
150 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
151 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
152 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
153 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
154 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
155 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
156 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
157 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
158 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
159 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
160 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
161 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
162 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
163 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
164 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
165 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
166 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
167 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
168 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
170 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
171 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
172 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
173 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
174 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
Christopher Tate92198742012-09-07 12:00:13 -0700175 sSecureGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700176 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
177 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
178 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
190 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
191 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
192 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
193 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
194 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
195 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
196 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
197 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
198
199 // Keys from the 'system' table now moved to 'global'
200 // These must match Settings.System.MOVED_TO_GLOBAL
201 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700202
203 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
204 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
205 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
206 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
207 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
208 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
209 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
210 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
211 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
212 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
213 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
214 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
215 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
216 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700217 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700218 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
219 }
220
221 private boolean settingMovedToGlobal(final String name) {
222 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
223 }
224
225 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700226 * Decode a content URL into the table, projection, and arguments
227 * used to access the corresponding database rows.
228 */
229 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231 public final String where;
232 public final String[] args;
233
234 /** Operate on existing rows. */
235 SqlArguments(Uri url, String where, String[] args) {
236 if (url.getPathSegments().size() == 1) {
237 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700238 if (!DatabaseHelper.isValidTable(this.table)) {
239 throw new IllegalArgumentException("Bad root path: " + this.table);
240 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700241 this.where = where;
242 this.args = args;
243 } else if (url.getPathSegments().size() != 2) {
244 throw new IllegalArgumentException("Invalid URI: " + url);
245 } else if (!TextUtils.isEmpty(where)) {
246 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
247 } else {
248 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700249 if (!DatabaseHelper.isValidTable(this.table)) {
250 throw new IllegalArgumentException("Bad root path: " + this.table);
251 }
Christopher Tate06efb532012-08-24 15:29:27 -0700252 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700253 this.where = Settings.NameValueTable.NAME + "=?";
254 this.args = new String[] { url.getPathSegments().get(1) };
255 } else {
256 this.where = "_id=" + ContentUris.parseId(url);
257 this.args = null;
258 }
259 }
260 }
261
262 /** Insert new rows (no where clause allowed). */
263 SqlArguments(Uri url) {
264 if (url.getPathSegments().size() == 1) {
265 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700266 if (!DatabaseHelper.isValidTable(this.table)) {
267 throw new IllegalArgumentException("Bad root path: " + this.table);
268 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700269 this.where = null;
270 this.args = null;
271 } else {
272 throw new IllegalArgumentException("Invalid URI: " + url);
273 }
274 }
275 }
276
277 /**
278 * Get the content URI of a row added to a table.
279 * @param tableUri of the entire table
280 * @param values found in the row
281 * @param rowId of the row
282 * @return the content URI for this particular row
283 */
284 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
285 if (tableUri.getPathSegments().size() != 1) {
286 throw new IllegalArgumentException("Invalid URI: " + tableUri);
287 }
288 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700289 if (TABLE_SYSTEM.equals(table) ||
290 TABLE_SECURE.equals(table) ||
291 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292 String name = values.getAsString(Settings.NameValueTable.NAME);
293 return Uri.withAppendedPath(tableUri, name);
294 } else {
295 return ContentUris.withAppendedId(tableUri, rowId);
296 }
297 }
298
299 /**
300 * Send a notification when a particular content URI changes.
301 * Modify the system property used to communicate the version of
302 * this table, for tables which have such a property. (The Settings
303 * contract class uses these to provide client-side caches.)
304 * @param uri to send notifications for
305 */
Christopher Tate06efb532012-08-24 15:29:27 -0700306 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700307 // Update the system property *first*, so if someone is listening for
308 // a notification and then using the contract class to get their data,
309 // the system property will be updated and they'll get the new data.
310
Amith Yamasanid1582142009-07-08 20:04:55 -0700311 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700312 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700313 if (table.equals(TABLE_SYSTEM)) {
314 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700315 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700316 } else if (table.equals(TABLE_SECURE)) {
317 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
318 backedUpDataChanged = true;
319 } else if (table.equals(TABLE_GLOBAL)) {
320 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700321 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700322 }
323
324 if (property != null) {
325 long version = SystemProperties.getLong(property, 0) + 1;
326 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
327 SystemProperties.set(property, Long.toString(version));
328 }
329
-b master501eec92009-07-06 13:53:11 -0700330 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700331 if (backedUpDataChanged) {
332 mBackupManager.dataChanged();
333 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700334 // Now send the notification through the content framework.
335
336 String notify = uri.getQueryParameter("notify");
337 if (notify == null || "true".equals(notify)) {
338 getContext().getContentResolver().notifyChange(uri, null);
339 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
340 } else {
341 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
342 }
343 }
344
345 /**
346 * Make sure the caller has permission to write this data.
347 * @param args supplied by the caller
348 * @throws SecurityException if the caller is forbidden to write.
349 */
350 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700351 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800352 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800353 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
354 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700355 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800356 String.format("Permission denial: writing to secure settings requires %1$s",
357 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700358 }
359 }
360
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700361 // FileObserver for external modifications to the database file.
362 // Note that this is for platform developers only with
363 // userdebug/eng builds who should be able to tinker with the
364 // sqlite database out from under the SettingsProvider, which is
365 // normally the exclusive owner of the database. But we keep this
366 // enabled all the time to minimize development-vs-user
367 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700368 private static SparseArray<SettingsFileObserver> sObserverInstances
369 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700370 private class SettingsFileObserver extends FileObserver {
371 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700372 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700373 private final String mPath;
374
Christopher Tate06efb532012-08-24 15:29:27 -0700375 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700376 super(path, FileObserver.CLOSE_WRITE |
377 FileObserver.CREATE | FileObserver.DELETE |
378 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700379 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700380 mPath = path;
381 }
382
383 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700384 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700385 if (modsInFlight > 0) {
386 // our own modification.
387 return;
388 }
Christopher Tate06efb532012-08-24 15:29:27 -0700389 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
390 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700391 if (!mIsDirty.compareAndSet(false, true)) {
392 // already handled. (we get a few update events
393 // during an sqlite write)
394 return;
395 }
Christopher Tate06efb532012-08-24 15:29:27 -0700396 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
397 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700398 mIsDirty.set(false);
399 }
400 }
401
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700402 @Override
403 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700404 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700405 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800406
Christopher Tate06efb532012-08-24 15:29:27 -0700407 synchronized (this) {
408 establishDbTrackingLocked(UserHandle.USER_OWNER);
409
410 IntentFilter userFilter = new IntentFilter();
411 userFilter.addAction(Intent.ACTION_USER_REMOVED);
412 getContext().registerReceiver(new BroadcastReceiver() {
413 @Override
414 public void onReceive(Context context, Intent intent) {
415 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
416 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
417 UserHandle.USER_OWNER);
418 if (userHandle != UserHandle.USER_OWNER) {
419 onUserRemoved(userHandle);
420 }
421 }
422 }
423 }, userFilter);
424
425 if (!ensureAndroidIdIsSet()) {
426 return false;
427 }
Fred Quintanac70239e2009-12-17 10:28:33 -0800428 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700429 return true;
430 }
431
Christopher Tate06efb532012-08-24 15:29:27 -0700432 void onUserRemoved(int userHandle) {
433 // the db file itself will be deleted automatically, but we need to tear down
434 // our caches and other internal bookkeeping. Creation/deletion of a user's
435 // settings db infrastructure is synchronized on 'this'
436 synchronized (this) {
437 FileObserver observer = sObserverInstances.get(userHandle);
438 if (observer != null) {
439 observer.stopWatching();
440 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700441 }
Christopher Tate06efb532012-08-24 15:29:27 -0700442
443 mOpenHelpers.delete(userHandle);
444 sSystemCaches.delete(userHandle);
445 sSecureCaches.delete(userHandle);
446 sKnownMutationsInFlight.delete(userHandle);
447
448 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
449 SystemProperties.set(property, "");
450 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
451 SystemProperties.set(property, "");
452 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700453 }
454
Christopher Tate06efb532012-08-24 15:29:27 -0700455 private void establishDbTrackingLocked(int userHandle) {
456 if (LOCAL_LOGV) {
457 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
458 }
459
460 DatabaseHelper dbhelper = new DatabaseHelper(getContext(), userHandle);
461 mOpenHelpers.append(userHandle, dbhelper);
462
463 // Watch for external modifications to the database files,
464 // keeping our caches in sync.
465 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
466 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
467 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
468 SQLiteDatabase db = dbhelper.getWritableDatabase();
469
470 // Now we can start observing it for changes
471 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
472 sObserverInstances.append(userHandle, observer);
473 observer.startWatching();
474
475 startAsyncCachePopulation(userHandle);
476 }
477
478 class CachePrefetchThread extends Thread {
479 private int mUserHandle;
480
481 CachePrefetchThread(int userHandle) {
482 super("populate-settings-caches");
483 mUserHandle = userHandle;
484 }
485
486 @Override
487 public void run() {
488 fullyPopulateCaches(mUserHandle);
489 }
490 }
491
492 private void startAsyncCachePopulation(int userHandle) {
493 new CachePrefetchThread(userHandle).start();
494 }
495
496 private void fullyPopulateCaches(final int userHandle) {
497 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
498 // Only populate the globals cache once, for the owning user
499 if (userHandle == UserHandle.USER_OWNER) {
500 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
501 }
502 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
503 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700504 }
505
506 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700507 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
508 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700509 Cursor c = db.query(
510 table,
511 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
512 null, null, null, null, null,
513 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
514 try {
515 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800516 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700517 cache.setFullyMatchesDisk(true); // optimistic
518 int rows = 0;
519 while (c.moveToNext()) {
520 rows++;
521 String name = c.getString(0);
522 String value = c.getString(1);
523 cache.populate(name, value);
524 }
525 if (rows > MAX_CACHE_ENTRIES) {
526 // Somewhat redundant, as removeEldestEntry() will
527 // have already done this, but to be explicit:
528 cache.setFullyMatchesDisk(false);
529 Log.d(TAG, "row count exceeds max cache entries for table " + table);
530 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700531 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700532 cache.fullyMatchesDisk());
533 }
534 } finally {
535 c.close();
536 }
537 }
538
Fred Quintanac70239e2009-12-17 10:28:33 -0800539 private boolean ensureAndroidIdIsSet() {
540 final Cursor c = query(Settings.Secure.CONTENT_URI,
541 new String[] { Settings.NameValueTable.VALUE },
542 Settings.NameValueTable.NAME + "=?",
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800543 new String[] { Settings.Secure.ANDROID_ID }, null);
Fred Quintanac70239e2009-12-17 10:28:33 -0800544 try {
545 final String value = c.moveToNext() ? c.getString(0) : null;
546 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700547 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800548 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Doug Zongker0fe27cf2010-08-19 13:38:26 -0700549 Log.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue + "]");
Fred Quintanac70239e2009-12-17 10:28:33 -0800550 final ContentValues values = new ContentValues();
551 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
552 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
553 final Uri uri = insert(Settings.Secure.CONTENT_URI, values);
554 if (uri == null) {
555 return false;
556 }
557 }
558 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800559 } finally {
560 c.close();
561 }
562 }
563
Christopher Tate06efb532012-08-24 15:29:27 -0700564 // Lazy-initialize the settings caches for non-primary users
565 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
566 synchronized (this) {
567 getOrEstablishDatabaseLocked(callingUser); // ignore return value; we don't need it
568 return which.get(callingUser);
569 }
570 }
571
572 // Lazy initialize the database helper and caches for this user, if necessary
573 private DatabaseHelper getOrEstablishDatabaseLocked(int callingUser) {
574 long oldId = Binder.clearCallingIdentity();
575 try {
576 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
577 if (null == dbHelper) {
578 establishDbTrackingLocked(callingUser);
579 dbHelper = mOpenHelpers.get(callingUser);
580 }
581 return dbHelper;
582 } finally {
583 Binder.restoreCallingIdentity(oldId);
584 }
585 }
586
587 public SettingsCache cacheForTable(final int callingUser, String tableName) {
588 if (TABLE_SYSTEM.equals(tableName)) {
589 return getOrConstructCache(callingUser, sSystemCaches);
590 }
591 if (TABLE_SECURE.equals(tableName)) {
592 return getOrConstructCache(callingUser, sSecureCaches);
593 }
594 if (TABLE_GLOBAL.equals(tableName)) {
595 return sGlobalCache;
596 }
597 return null;
598 }
599
600 /**
601 * Used for wiping a whole cache on deletes when we're not
602 * sure what exactly was deleted or changed.
603 */
604 public void invalidateCache(final int callingUser, String tableName) {
605 SettingsCache cache = cacheForTable(callingUser, tableName);
606 if (cache == null) {
607 return;
608 }
609 synchronized (cache) {
610 cache.evictAll();
611 cache.mCacheFullyMatchesDisk = false;
612 }
613 }
614
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800615 /**
616 * Fast path that avoids the use of chatty remoted Cursors.
617 */
618 @Override
619 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700620 int callingUser = UserHandle.getCallingUserId();
621 if (args != null) {
622 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
623 if (reqUser != callingUser) {
624 getContext().enforceCallingPermission(
625 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
626 "Not permitted to access settings for other users");
627 if (reqUser == UserHandle.USER_CURRENT) {
628 try {
629 reqUser = ActivityManagerNative.getDefault().getCurrentUser().id;
630 } catch (RemoteException e) {
631 // can't happen
632 }
633 if (LOCAL_LOGV) {
634 Slog.v(TAG, " USER_CURRENT resolved to " + reqUser);
635 }
636 }
637 if (reqUser < 0) {
638 throw new IllegalArgumentException("Bad user handle " + reqUser);
639 }
640 callingUser = reqUser;
641 if (LOCAL_LOGV) Slog.v(TAG, " fetching setting for user " + callingUser);
642 }
643 }
644
645 // Note: we assume that get/put operations for moved-to-global names have already
646 // been directed to the new location on the caller side (otherwise we'd fix them
647 // up here).
648
649 DatabaseHelper dbHelper;
650 SettingsCache cache;
651
652 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800653 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700654 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
655 synchronized (this) {
656 dbHelper = getOrEstablishDatabaseLocked(callingUser);
657 cache = sSystemCaches.get(callingUser);
658 }
659 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800660 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800661 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700662 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
663 synchronized (this) {
664 dbHelper = getOrEstablishDatabaseLocked(callingUser);
665 cache = sSecureCaches.get(callingUser);
666 }
667 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800668 }
Christopher Tate06efb532012-08-24 15:29:27 -0700669 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
670 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
671 // fast path: owner db & cache are immutable after onCreate() so we need not
672 // guard on the attempt to look them up
673 return lookupValue(getOrEstablishDatabaseLocked(UserHandle.USER_OWNER), TABLE_GLOBAL,
674 sGlobalCache, request);
675 }
676
677 // Put methods - new value is in the args bundle under the key named by
678 // the Settings.NameValueTable.VALUE static.
679 final String newValue = (args == null)
680 ? null : args.getString(Settings.NameValueTable.VALUE);
681 if (newValue == null) {
682 throw new IllegalArgumentException("Bad value for " + method);
683 }
684
685 final ContentValues values = new ContentValues();
686 values.put(Settings.NameValueTable.NAME, request);
687 values.put(Settings.NameValueTable.VALUE, newValue);
688 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
689 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
690 insert(Settings.System.CONTENT_URI, values);
691 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
692 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
693 insert(Settings.Secure.CONTENT_URI, values);
694 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
695 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
696 insert(Settings.Global.CONTENT_URI, values);
697 } else {
698 Slog.w(TAG, "call() with invalid method: " + method);
699 }
700
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800701 return null;
702 }
703
704 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
705 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700706 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
707 final SettingsCache cache, String key) {
708 if (cache == null) {
709 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
710 return null;
711 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800712 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800713 Bundle value = cache.get(key);
714 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700715 if (value != TOO_LARGE_TO_CACHE_MARKER) {
716 return value;
717 }
718 // else we fall through and read the value from disk
719 } else if (cache.fullyMatchesDisk()) {
720 // Fast path (very common). Don't even try touch disk
721 // if we know we've slurped it all in. Trying to
722 // touch the disk would mean waiting for yaffs2 to
723 // give us access, which could takes hundreds of
724 // milliseconds. And we're very likely being called
725 // from somebody's UI thread...
726 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800727 }
728 }
729
Christopher Tate06efb532012-08-24 15:29:27 -0700730 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800731 Cursor cursor = null;
732 try {
733 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
734 null, null, null, null);
735 if (cursor != null && cursor.getCount() == 1) {
736 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800737 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800738 }
739 } catch (SQLiteException e) {
740 Log.w(TAG, "settings lookup error", e);
741 return null;
742 } finally {
743 if (cursor != null) cursor.close();
744 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800745 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800746 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800747 }
748
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700749 @Override
750 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate06efb532012-08-24 15:29:27 -0700751 final int callingUser = UserHandle.getCallingUserId();
752 if (LOCAL_LOGV) Slog.v(TAG, "query() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700753 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700754 DatabaseHelper dbH;
755 synchronized (this) {
756 dbH = getOrEstablishDatabaseLocked(callingUser);
757 }
758 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800760 // The favorites table was moved from this provider to a provider inside Home
761 // Home still need to query this table to upgrade from pre-cupcake builds
762 // However, a cupcake+ build with no data does not contain this table which will
763 // cause an exception in the SQL stack. The following line is a special case to
764 // 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 -0800765 if (TABLE_FAVORITES.equals(args.table)) {
766 return null;
767 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
768 args.table = TABLE_FAVORITES;
769 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
770 if (cursor != null) {
771 boolean exists = cursor.getCount() > 0;
772 cursor.close();
773 if (!exists) return null;
774 } else {
775 return null;
776 }
777 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800778
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700779 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
780 qb.setTables(args.table);
781
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700782 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
783 ret.setNotificationUri(getContext().getContentResolver(), url);
784 return ret;
785 }
786
787 @Override
788 public String getType(Uri url) {
789 // If SqlArguments supplies a where clause, then it must be an item
790 // (because we aren't supplying our own where clause).
791 SqlArguments args = new SqlArguments(url, null, null);
792 if (TextUtils.isEmpty(args.where)) {
793 return "vnd.android.cursor.dir/" + args.table;
794 } else {
795 return "vnd.android.cursor.item/" + args.table;
796 }
797 }
798
799 @Override
800 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700801 final int callingUser = UserHandle.getCallingUserId();
802 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700803 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 if (TABLE_FAVORITES.equals(args.table)) {
805 return 0;
806 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700807 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700808 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700809
Christopher Tate06efb532012-08-24 15:29:27 -0700810 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
811 mutationCount.incrementAndGet();
812 DatabaseHelper dbH;
813 synchronized (this) {
814 dbH = getOrEstablishDatabaseLocked(callingUser);
815 }
816 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700817 db.beginTransaction();
818 try {
819 int numValues = values.length;
820 for (int i = 0; i < numValues; i++) {
821 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800822 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700823 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
824 }
825 db.setTransactionSuccessful();
826 } finally {
827 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700828 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700829 }
830
Christopher Tate06efb532012-08-24 15:29:27 -0700831 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700832 return values.length;
833 }
834
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700835 /*
836 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
837 * This setting contains a list of the currently enabled location providers.
838 * But helper functions in android.providers.Settings can enable or disable
839 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800840 *
841 * @returns whether the database needs to be updated or not, also modifying
842 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700843 */
844 private boolean parseProviderList(Uri url, ContentValues initialValues) {
845 String value = initialValues.getAsString(Settings.Secure.VALUE);
846 String newProviders = null;
847 if (value != null && value.length() > 1) {
848 char prefix = value.charAt(0);
849 if (prefix == '+' || prefix == '-') {
850 // skip prefix
851 value = value.substring(1);
852
853 // read list of enabled providers into "providers"
854 String providers = "";
855 String[] columns = {Settings.Secure.VALUE};
856 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
857 Cursor cursor = query(url, columns, where, null, null);
858 if (cursor != null && cursor.getCount() == 1) {
859 try {
860 cursor.moveToFirst();
861 providers = cursor.getString(0);
862 } finally {
863 cursor.close();
864 }
865 }
866
867 int index = providers.indexOf(value);
868 int end = index + value.length();
869 // check for commas to avoid matching on partial string
870 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
871 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
872
873 if (prefix == '+' && index < 0) {
874 // append the provider to the list if not present
875 if (providers.length() == 0) {
876 newProviders = value;
877 } else {
878 newProviders = providers + ',' + value;
879 }
880 } else if (prefix == '-' && index >= 0) {
881 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400882 // remove leading or trailing comma
883 if (index > 0) {
884 index--;
885 } else if (end < providers.length()) {
886 end++;
887 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700888
889 newProviders = providers.substring(0, index);
890 if (end < providers.length()) {
891 newProviders += providers.substring(end);
892 }
893 } else {
894 // nothing changed, so no need to update the database
895 return false;
896 }
897
898 if (newProviders != null) {
899 initialValues.put(Settings.Secure.VALUE, newProviders);
900 }
901 }
902 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800903
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700904 return true;
905 }
906
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700907 @Override
908 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700909 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
910 }
911
912 // Settings.put*ForUser() always winds up here, so this is where we apply
913 // policy around permission to write settings for other users.
914 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
915 final int callingUser = UserHandle.getCallingUserId();
916 if (callingUser != desiredUserHandle) {
917 getContext().enforceCallingPermission(
918 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
919 "Not permitted to access settings for other users");
920 }
921
922 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
923 + " by " + callingUser);
924
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700925 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 if (TABLE_FAVORITES.equals(args.table)) {
927 return null;
928 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700929 checkWritePermissions(args);
930
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700931 // Special case LOCATION_PROVIDERS_ALLOWED.
932 // Support enabling/disabling a single provider (using "+" or "-" prefix)
933 String name = initialValues.getAsString(Settings.Secure.NAME);
934 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
935 if (!parseProviderList(url, initialValues)) return null;
936 }
937
Christopher Tate06efb532012-08-24 15:29:27 -0700938 // The global table is stored under the owner, always
939 if (TABLE_GLOBAL.equals(args.table)) {
940 desiredUserHandle = UserHandle.USER_OWNER;
941 }
942
943 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800944 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
945 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
946 return Uri.withAppendedPath(url, name);
947 }
948
Christopher Tate06efb532012-08-24 15:29:27 -0700949 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
950 mutationCount.incrementAndGet();
951 DatabaseHelper dbH;
952 synchronized (this) {
953 dbH = getOrEstablishDatabaseLocked(callingUser);
954 }
955 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700956 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700957 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700958 if (rowId <= 0) return null;
959
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800960 SettingsCache.populate(cache, initialValues); // before we notify
961
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700962 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700963 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700964 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700965 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700966 return url;
967 }
968
969 @Override
970 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -0700971 final int callingUser = UserHandle.getCallingUserId();
972 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700973 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 if (TABLE_FAVORITES.equals(args.table)) {
975 return 0;
976 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
977 args.table = TABLE_FAVORITES;
978 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700979 checkWritePermissions(args);
980
Christopher Tate06efb532012-08-24 15:29:27 -0700981 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
982 mutationCount.incrementAndGet();
983 DatabaseHelper dbH;
984 synchronized (this) {
985 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800986 }
Christopher Tate06efb532012-08-24 15:29:27 -0700987 SQLiteDatabase db = dbH.getWritableDatabase();
988 int count = db.delete(args.table, args.where, args.args);
989 mutationCount.decrementAndGet();
990 if (count > 0) {
991 invalidateCache(callingUser, args.table); // before we notify
992 sendNotify(url, callingUser);
993 }
994 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700995 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
996 return count;
997 }
998
999 @Override
1000 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001001 // NOTE: update() is never called by the front-end Settings API, and updates that
1002 // wind up affecting rows in Secure that are globally shared will not have the
1003 // intended effect (the update will be invisible to the rest of the system).
1004 // This should have no practical effect, since writes to the Secure db can only
1005 // be done by system code, and that code should be using the correct API up front.
1006 final int callingUser = UserHandle.getCallingUserId();
1007 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001008 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 if (TABLE_FAVORITES.equals(args.table)) {
1010 return 0;
1011 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001012 checkWritePermissions(args);
1013
Christopher Tate06efb532012-08-24 15:29:27 -07001014 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1015 mutationCount.incrementAndGet();
1016 DatabaseHelper dbH;
1017 synchronized (this) {
1018 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001019 }
Christopher Tate06efb532012-08-24 15:29:27 -07001020 SQLiteDatabase db = dbH.getWritableDatabase();
1021 int count = db.update(args.table, initialValues, args.where, args.args);
1022 mutationCount.decrementAndGet();
1023 if (count > 0) {
1024 invalidateCache(callingUser, args.table); // before we notify
1025 sendNotify(url, callingUser);
1026 }
1027 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001028 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1029 return count;
1030 }
1031
1032 @Override
1033 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1034
1035 /*
1036 * When a client attempts to openFile the default ringtone or
1037 * notification setting Uri, we will proxy the call to the current
1038 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001039 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001040 int ringtoneType = RingtoneManager.getDefaultType(uri);
1041 // Above call returns -1 if the Uri doesn't match a default type
1042 if (ringtoneType != -1) {
1043 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001044
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001045 // Get the current value for the default sound
1046 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001047
Marco Nelissen69f593c2009-07-28 09:55:04 -07001048 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001049 // Only proxy the openFile call to drm or media providers
1050 String authority = soundUri.getAuthority();
1051 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1052 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1053
1054 if (isDrmAuthority) {
1055 try {
1056 // Check DRM access permission here, since once we
1057 // do the below call the DRM will be checking our
1058 // permission, not our caller's permission
1059 DrmStore.enforceAccessDrmPermission(context);
1060 } catch (SecurityException e) {
1061 throw new FileNotFoundException(e.getMessage());
1062 }
1063 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001064
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001065 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1066 }
1067 }
1068 }
1069
1070 return super.openFile(uri, mode);
1071 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001072
1073 @Override
1074 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1075
1076 /*
1077 * When a client attempts to openFile the default ringtone or
1078 * notification setting Uri, we will proxy the call to the current
1079 * default ringtone's Uri (if it is in the DRM or media provider).
1080 */
1081 int ringtoneType = RingtoneManager.getDefaultType(uri);
1082 // Above call returns -1 if the Uri doesn't match a default type
1083 if (ringtoneType != -1) {
1084 Context context = getContext();
1085
1086 // Get the current value for the default sound
1087 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1088
1089 if (soundUri != null) {
1090 // Only proxy the openFile call to drm or media providers
1091 String authority = soundUri.getAuthority();
1092 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1093 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1094
1095 if (isDrmAuthority) {
1096 try {
1097 // Check DRM access permission here, since once we
1098 // do the below call the DRM will be checking our
1099 // permission, not our caller's permission
1100 DrmStore.enforceAccessDrmPermission(context);
1101 } catch (SecurityException e) {
1102 throw new FileNotFoundException(e.getMessage());
1103 }
1104 }
1105
1106 ParcelFileDescriptor pfd = null;
1107 try {
1108 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1109 return new AssetFileDescriptor(pfd, 0, -1);
1110 } catch (FileNotFoundException ex) {
1111 // fall through and open the fallback ringtone below
1112 }
1113 }
1114
1115 try {
1116 return super.openAssetFile(soundUri, mode);
1117 } catch (FileNotFoundException ex) {
1118 // Since a non-null Uri was specified, but couldn't be opened,
1119 // fall back to the built-in ringtone.
1120 return context.getResources().openRawResourceFd(
1121 com.android.internal.R.raw.fallbackring);
1122 }
1123 }
1124 // no need to fall through and have openFile() try again, since we
1125 // already know that will fail.
1126 throw new FileNotFoundException(); // or return null ?
1127 }
1128
1129 // Note that this will end up calling openFile() above.
1130 return super.openAssetFile(uri, mode);
1131 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001132
1133 /**
1134 * In-memory LRU Cache of system and secure settings, along with
1135 * associated helper functions to keep cache coherent with the
1136 * database.
1137 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001138 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001139
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001140 private final String mCacheName;
1141 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1142
1143 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001144 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001145 mCacheName = name;
1146 }
1147
1148 /**
1149 * Is the whole database table slurped into this cache?
1150 */
1151 public boolean fullyMatchesDisk() {
1152 synchronized (this) {
1153 return mCacheFullyMatchesDisk;
1154 }
1155 }
1156
1157 public void setFullyMatchesDisk(boolean value) {
1158 synchronized (this) {
1159 mCacheFullyMatchesDisk = value;
1160 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001161 }
1162
1163 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001164 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1165 if (evicted) {
1166 mCacheFullyMatchesDisk = false;
1167 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001168 }
1169
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001170 /**
1171 * Atomic cache population, conditional on size of value and if
1172 * we lost a race.
1173 *
1174 * @returns a Bundle to send back to the client from call(), even
1175 * if we lost the race.
1176 */
1177 public Bundle putIfAbsent(String key, String value) {
1178 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1179 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1180 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001181 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001182 put(key, bundle);
1183 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001184 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001185 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001186 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001187 }
1188
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001189 /**
1190 * Populates a key in a given (possibly-null) cache.
1191 */
1192 public static void populate(SettingsCache cache, ContentValues contentValues) {
1193 if (cache == null) {
1194 return;
1195 }
1196 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1197 if (name == null) {
1198 Log.w(TAG, "null name populating settings cache.");
1199 return;
1200 }
1201 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001202 cache.populate(name, value);
1203 }
1204
1205 public void populate(String name, String value) {
1206 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001207 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001208 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001209 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001210 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001211 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001212 }
1213 }
1214
1215 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001216 * For suppressing duplicate/redundant settings inserts early,
1217 * checking our cache first (but without faulting it in),
1218 * before going to sqlite with the mutation.
1219 */
1220 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1221 if (cache == null) return false;
1222 synchronized (cache) {
1223 Bundle bundle = cache.get(name);
1224 if (bundle == null) return false;
1225 String oldValue = bundle.getPairValue();
1226 if (oldValue == null && value == null) return true;
1227 if ((oldValue == null) != (value == null)) return false;
1228 return oldValue.equals(value);
1229 }
1230 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001231 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001232}