blob: ba7501b896cd78efab3b2de81cf5df36ad2a982c [file] [log] [blame]
Amith Yamasani220f4d62009-07-02 02:34:14 -07001/*
2 * Copyright (C) 2008 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
Svetoslav Ganova571a582011-09-20 18:32:20 -070019import android.app.backup.BackupAgentHelper;
20import android.app.backup.BackupDataInput;
21import android.app.backup.BackupDataOutput;
22import android.app.backup.FullBackupDataOutput;
23import android.content.ContentValues;
24import android.content.Context;
25import android.database.Cursor;
26import android.net.Uri;
27import android.net.wifi.WifiManager;
28import android.os.FileUtils;
29import android.os.ParcelFileDescriptor;
30import android.os.Process;
31import android.provider.Settings;
32import android.util.Log;
33
Brad Fitzpatrick70787892010-11-17 11:31:12 -080034import java.io.BufferedOutputStream;
Amith Yamasani2cfab842009-09-09 18:27:31 -070035import java.io.BufferedReader;
36import java.io.BufferedWriter;
Christopher Tate8dfe2b92012-05-15 15:05:04 -070037import java.io.CharArrayReader;
Amith Yamasanid1582142009-07-08 20:04:55 -070038import java.io.DataInputStream;
39import java.io.DataOutputStream;
Amith Yamasani2cfab842009-09-09 18:27:31 -070040import java.io.EOFException;
Amith Yamasani220f4d62009-07-02 02:34:14 -070041import java.io.File;
42import java.io.FileInputStream;
43import java.io.FileOutputStream;
Amith Yamasani2cfab842009-09-09 18:27:31 -070044import java.io.FileReader;
45import java.io.FileWriter;
Amith Yamasani220f4d62009-07-02 02:34:14 -070046import java.io.IOException;
Svetoslav Ganova571a582011-09-20 18:32:20 -070047import java.io.InputStream;
Brad Fitzpatrick70787892010-11-17 11:31:12 -080048import java.io.OutputStream;
Christopher Tate8dfe2b92012-05-15 15:05:04 -070049import java.io.Writer;
50import java.util.ArrayList;
Svetoslav Ganova571a582011-09-20 18:32:20 -070051import java.util.HashMap;
Christopher Tate8dfe2b92012-05-15 15:05:04 -070052import java.util.HashSet;
Svetoslav Ganova571a582011-09-20 18:32:20 -070053import java.util.Map;
Amith Yamasanid1582142009-07-08 20:04:55 -070054import java.util.zip.CRC32;
Amith Yamasani220f4d62009-07-02 02:34:14 -070055
Amith Yamasani220f4d62009-07-02 02:34:14 -070056/**
57 * Performs backup and restore of the System and Secure settings.
58 * List of settings that are backed up are stored in the Settings.java file
59 */
Christopher Tatecc84c692010-03-29 14:54:02 -070060public class SettingsBackupAgent extends BackupAgentHelper {
Christopher Tate436344a2009-09-30 16:17:37 -070061 private static final boolean DEBUG = false;
Christopher Tate8dfe2b92012-05-15 15:05:04 -070062 private static final boolean DEBUG_BACKUP = DEBUG || false;
Amith Yamasani220f4d62009-07-02 02:34:14 -070063
64 private static final String KEY_SYSTEM = "system";
65 private static final String KEY_SECURE = "secure";
Christopher Tate66488d62012-10-02 11:58:01 -070066 private static final String KEY_GLOBAL = "global";
Amith Yamasani8823c0a82009-07-07 14:30:17 -070067 private static final String KEY_LOCALE = "locale";
Amith Yamasani220f4d62009-07-02 02:34:14 -070068
Christopher Tatea286f412009-09-18 15:51:15 -070069 // Versioning of the state file. Increment this version
70 // number any time the set of state items is altered.
Christopher Tate66488d62012-10-02 11:58:01 -070071 private static final int STATE_VERSION = 3;
Christopher Tatea286f412009-09-18 15:51:15 -070072
Christopher Tate66488d62012-10-02 11:58:01 -070073 // Slots in the checksum array. Never insert new items in the middle
74 // of this array; new slots must be appended.
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -080075 private static final int STATE_SYSTEM = 0;
76 private static final int STATE_SECURE = 1;
77 private static final int STATE_LOCALE = 2;
78 private static final int STATE_WIFI_SUPPLICANT = 3;
79 private static final int STATE_WIFI_CONFIG = 4;
Christopher Tate66488d62012-10-02 11:58:01 -070080 private static final int STATE_GLOBAL = 5;
81
82 private static final int STATE_SIZE = 6; // The current number of state items
83
84 // Number of entries in the checksum array at various version numbers
85 private static final int STATE_SIZES[] = {
86 0,
87 4, // version 1
88 5, // version 2 added STATE_WIFI_CONFIG
89 STATE_SIZE // version 3 added STATE_GLOBAL
90 };
Amith Yamasanid1582142009-07-08 20:04:55 -070091
Christopher Tate75a99702011-05-18 16:28:19 -070092 // Versioning of the 'full backup' format
Christopher Tate66488d62012-10-02 11:58:01 -070093 private static final int FULL_BACKUP_VERSION = 2;
94 private static final int FULL_BACKUP_ADDED_GLOBAL = 2; // added the "global" entry
Christopher Tate75a99702011-05-18 16:28:19 -070095
Svetoslav Ganova571a582011-09-20 18:32:20 -070096 private static final int INTEGER_BYTE_COUNT = Integer.SIZE / Byte.SIZE;
Amith Yamasani220f4d62009-07-02 02:34:14 -070097
98 private static final byte[] EMPTY_DATA = new byte[0];
99
100 private static final String TAG = "SettingsBackupAgent";
101
Amith Yamasani220f4d62009-07-02 02:34:14 -0700102 private static final int COLUMN_NAME = 1;
103 private static final int COLUMN_VALUE = 2;
104
105 private static final String[] PROJECTION = {
106 Settings.NameValueTable._ID,
107 Settings.NameValueTable.NAME,
108 Settings.NameValueTable.VALUE
109 };
110
111 private static final String FILE_WIFI_SUPPLICANT = "/data/misc/wifi/wpa_supplicant.conf";
Amith Yamasani2cfab842009-09-09 18:27:31 -0700112 private static final String FILE_WIFI_SUPPLICANT_TEMPLATE =
113 "/system/etc/wifi/wpa_supplicant.conf";
Christian Sonntag92c17522009-08-07 15:16:17 -0700114
115 // the key to store the WIFI data under, should be sorted as last, so restore happens last.
116 // use very late unicode character to quasi-guarantee last sort position.
Amith Yamasani2cfab842009-09-09 18:27:31 -0700117 private static final String KEY_WIFI_SUPPLICANT = "\uffedWIFI";
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800118 private static final String KEY_WIFI_CONFIG = "\uffedCONFIG_WIFI";
Amith Yamasani220f4d62009-07-02 02:34:14 -0700119
Christopher Tate4a627c72011-04-01 14:43:32 -0700120 // Name of the temporary file we use during full backup/restore. This is
121 // stored in the full-backup tarfile as well, so should not be changed.
122 private static final String STAGE_FILE = "flattened-data";
123
Amith Yamasani220f4d62009-07-02 02:34:14 -0700124 private SettingsHelper mSettingsHelper;
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800125 private WifiManager mWfm;
126 private static String mWifiConfigFile;
Amith Yamasani220f4d62009-07-02 02:34:14 -0700127
Christopher Tate8dfe2b92012-05-15 15:05:04 -0700128 // Class for capturing a network definition from the wifi supplicant config file
129 static class Network {
130 String ssid = ""; // equals() and hashCode() need these to be non-null
131 String key_mgmt = "";
132 final ArrayList<String> rawLines = new ArrayList<String>();
133
134 public static Network readFromStream(BufferedReader in) {
135 final Network n = new Network();
136 String line;
137 try {
138 while (in.ready()) {
139 line = in.readLine();
140 if (line == null || line.startsWith("}")) {
141 break;
142 }
143 n.rememberLine(line);
144 }
145 } catch (IOException e) {
146 return null;
147 }
148 return n;
149 }
150
151 void rememberLine(String line) {
152 // can't rely on particular whitespace patterns so strip leading/trailing
153 line = line.trim();
154 if (line.isEmpty()) return; // only whitespace; drop the line
155 rawLines.add(line);
156
157 // remember the ssid and key_mgmt lines for duplicate culling
158 if (line.startsWith("ssid")) {
159 ssid = line;
160 } else if (line.startsWith("key_mgmt")) {
161 key_mgmt = line;
162 }
163 }
164
165 public void write(Writer w) throws IOException {
166 w.write("\nnetwork={\n");
167 for (String line : rawLines) {
168 w.write("\t" + line + "\n");
169 }
170 w.write("}\n");
171 }
172
173 public void dump() {
174 Log.v(TAG, "network={");
175 for (String line : rawLines) {
176 Log.v(TAG, " " + line);
177 }
178 Log.v(TAG, "}");
179 }
180
181 // Same approach as Pair.equals() and Pair.hashCode()
182 @Override
183 public boolean equals(Object o) {
184 if (o == this) return true;
185 if (!(o instanceof Network)) return false;
186 final Network other;
187 try {
188 other = (Network) o;
189 } catch (ClassCastException e) {
190 return false;
191 }
192 return ssid.equals(other.ssid) && key_mgmt.equals(other.key_mgmt);
193 }
194
195 @Override
196 public int hashCode() {
197 int result = 17;
198 result = 31 * result + ssid.hashCode();
199 result = 31 * result + key_mgmt.hashCode();
200 return result;
201 }
202 }
203
204 // Ingest multiple wifi config file fragments, looking for network={} blocks
205 // and eliminating duplicates
206 class WifiNetworkSettings {
207 // One for fast lookup, one for maintaining ordering
208 final HashSet<Network> mKnownNetworks = new HashSet<Network>();
209 final ArrayList<Network> mNetworks = new ArrayList<Network>(8);
210
211 public void readNetworks(BufferedReader in) {
212 try {
213 String line;
214 while (in.ready()) {
215 line = in.readLine();
216 if (line != null) {
217 // Parse out 'network=' decls so we can ignore duplicates
218 if (line.startsWith("network")) {
219 Network net = Network.readFromStream(in);
220 if (! mKnownNetworks.contains(net)) {
221 if (DEBUG_BACKUP) {
222 Log.v(TAG, "Adding " + net.ssid + " / " + net.key_mgmt);
223 }
224 mKnownNetworks.add(net);
225 mNetworks.add(net);
226 } else {
227 if (DEBUG_BACKUP) {
228 Log.v(TAG, "Dupe; skipped " + net.ssid + " / " + net.key_mgmt);
229 }
230 }
231 }
232 }
233 }
234 } catch (IOException e) {
235 // whatever happened, we're done now
236 }
237 }
238
239 public void write(Writer w) throws IOException {
240 for (Network net : mNetworks) {
241 net.write(w);
242 }
243 }
244
245 public void dump() {
246 for (Network net : mNetworks) {
247 net.dump();
248 }
249 }
250 }
251
Svetoslav Ganova571a582011-09-20 18:32:20 -0700252 @Override
Amith Yamasani220f4d62009-07-02 02:34:14 -0700253 public void onCreate() {
Christopher Tate75a99702011-05-18 16:28:19 -0700254 if (DEBUG_BACKUP) Log.d(TAG, "onCreate() invoked");
255
Amith Yamasani220f4d62009-07-02 02:34:14 -0700256 mSettingsHelper = new SettingsHelper(this);
257 super.onCreate();
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800258
259 WifiManager mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
260 if (mWfm != null) mWifiConfigFile = mWfm.getConfigFile();
Amith Yamasani220f4d62009-07-02 02:34:14 -0700261 }
262
263 @Override
264 public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
265 ParcelFileDescriptor newState) throws IOException {
266
267 byte[] systemSettingsData = getSystemSettings();
268 byte[] secureSettingsData = getSecureSettings();
Christopher Tate66488d62012-10-02 11:58:01 -0700269 byte[] globalSettingsData = getGlobalSettings();
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700270 byte[] locale = mSettingsHelper.getLocaleData();
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800271 byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
272 byte[] wifiConfigData = getFileData(mWifiConfigFile);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700273
Christopher Tate79ec80d2011-06-24 14:58:49 -0700274 long[] stateChecksums = readOldChecksums(oldState);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700275
Christopher Tate79ec80d2011-06-24 14:58:49 -0700276 stateChecksums[STATE_SYSTEM] =
277 writeIfChanged(stateChecksums[STATE_SYSTEM], KEY_SYSTEM, systemSettingsData, data);
278 stateChecksums[STATE_SECURE] =
279 writeIfChanged(stateChecksums[STATE_SECURE], KEY_SECURE, secureSettingsData, data);
Christopher Tate66488d62012-10-02 11:58:01 -0700280 stateChecksums[STATE_GLOBAL] =
281 writeIfChanged(stateChecksums[STATE_GLOBAL], KEY_GLOBAL, secureSettingsData, data);
Christopher Tate79ec80d2011-06-24 14:58:49 -0700282 stateChecksums[STATE_LOCALE] =
283 writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
284 stateChecksums[STATE_WIFI_SUPPLICANT] =
285 writeIfChanged(stateChecksums[STATE_WIFI_SUPPLICANT], KEY_WIFI_SUPPLICANT,
286 wifiSupplicantData, data);
287 stateChecksums[STATE_WIFI_CONFIG] =
288 writeIfChanged(stateChecksums[STATE_WIFI_CONFIG], KEY_WIFI_CONFIG, wifiConfigData,
289 data);
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700290
Christopher Tate79ec80d2011-06-24 14:58:49 -0700291 writeNewChecksums(stateChecksums, newState);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700292 }
293
294 @Override
295 public void onRestore(BackupDataInput data, int appVersionCode,
296 ParcelFileDescriptor newState) throws IOException {
297
Christopher Tate66488d62012-10-02 11:58:01 -0700298 HashSet<String> movedToGlobal = new HashSet<String>();
299 Settings.System.getMovedKeys(movedToGlobal);
300 Settings.Secure.getMovedKeys(movedToGlobal);
301
Amith Yamasani220f4d62009-07-02 02:34:14 -0700302 while (data.readNextHeader()) {
303 final String key = data.getKey();
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700304 final int size = data.getDataSize();
Amith Yamasani220f4d62009-07-02 02:34:14 -0700305 if (KEY_SYSTEM.equals(key)) {
Christopher Tate66488d62012-10-02 11:58:01 -0700306 restoreSettings(data, Settings.System.CONTENT_URI, movedToGlobal);
Amith Yamasanid1582142009-07-08 20:04:55 -0700307 mSettingsHelper.applyAudioSettings();
Amith Yamasani220f4d62009-07-02 02:34:14 -0700308 } else if (KEY_SECURE.equals(key)) {
Christopher Tate66488d62012-10-02 11:58:01 -0700309 restoreSettings(data, Settings.Secure.CONTENT_URI, movedToGlobal);
Christian Sonntag92c17522009-08-07 15:16:17 -0700310 } else if (KEY_WIFI_SUPPLICANT.equals(key)) {
Christian Sonntagc5b5b0f2009-08-07 10:00:21 -0700311 int retainedWifiState = enableWifi(false);
Amith Yamasani2cfab842009-09-09 18:27:31 -0700312 restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, data);
Amith Yamasanid1582142009-07-08 20:04:55 -0700313 FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
314 FileUtils.S_IRUSR | FileUtils.S_IWUSR |
315 FileUtils.S_IRGRP | FileUtils.S_IWGRP,
316 Process.myUid(), Process.WIFI_UID);
Christian Sonntagc5b5b0f2009-08-07 10:00:21 -0700317 // retain the previous WIFI state.
318 enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
319 retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700320 } else if (KEY_LOCALE.equals(key)) {
321 byte[] localeData = new byte[size];
322 data.readEntityData(localeData, 0, size);
Christopher Tate75a99702011-05-18 16:28:19 -0700323 mSettingsHelper.setLocaleData(localeData, size);
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800324 } else if (KEY_WIFI_CONFIG.equals(key)) {
325 restoreFileData(mWifiConfigFile, data);
326 } else {
Amith Yamasani220f4d62009-07-02 02:34:14 -0700327 data.skipEntityData();
328 }
329 }
330 }
331
Christopher Tate75a99702011-05-18 16:28:19 -0700332 @Override
Christopher Tate79ec80d2011-06-24 14:58:49 -0700333 public void onFullBackup(FullBackupDataOutput data) throws IOException {
334 byte[] systemSettingsData = getSystemSettings();
335 byte[] secureSettingsData = getSecureSettings();
Christopher Tate66488d62012-10-02 11:58:01 -0700336 byte[] globalSettingsData = getGlobalSettings();
Christopher Tate79ec80d2011-06-24 14:58:49 -0700337 byte[] locale = mSettingsHelper.getLocaleData();
338 byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
339 byte[] wifiConfigData = getFileData(mWifiConfigFile);
340
341 // Write the data to the staging file, then emit that as our tarfile
342 // representation of the backed-up settings.
343 String root = getFilesDir().getAbsolutePath();
344 File stage = new File(root, STAGE_FILE);
345 try {
346 FileOutputStream filestream = new FileOutputStream(stage);
347 BufferedOutputStream bufstream = new BufferedOutputStream(filestream);
348 DataOutputStream out = new DataOutputStream(bufstream);
349
Christopher Tate2efd2db2011-07-19 16:32:49 -0700350 if (DEBUG_BACKUP) Log.d(TAG, "Writing flattened data version " + FULL_BACKUP_VERSION);
Christopher Tate79ec80d2011-06-24 14:58:49 -0700351 out.writeInt(FULL_BACKUP_VERSION);
352
Christopher Tate2efd2db2011-07-19 16:32:49 -0700353 if (DEBUG_BACKUP) Log.d(TAG, systemSettingsData.length + " bytes of settings data");
Christopher Tate79ec80d2011-06-24 14:58:49 -0700354 out.writeInt(systemSettingsData.length);
355 out.write(systemSettingsData);
Christopher Tate2efd2db2011-07-19 16:32:49 -0700356 if (DEBUG_BACKUP) Log.d(TAG, secureSettingsData.length + " bytes of secure settings data");
Christopher Tate79ec80d2011-06-24 14:58:49 -0700357 out.writeInt(secureSettingsData.length);
358 out.write(secureSettingsData);
Christopher Tate66488d62012-10-02 11:58:01 -0700359 if (DEBUG_BACKUP) Log.d(TAG, globalSettingsData.length + " bytes of global settings data");
360 out.writeInt(globalSettingsData.length);
361 out.write(globalSettingsData);
Christopher Tate2efd2db2011-07-19 16:32:49 -0700362 if (DEBUG_BACKUP) Log.d(TAG, locale.length + " bytes of locale data");
Christopher Tate79ec80d2011-06-24 14:58:49 -0700363 out.writeInt(locale.length);
364 out.write(locale);
Christopher Tate2efd2db2011-07-19 16:32:49 -0700365 if (DEBUG_BACKUP) Log.d(TAG, wifiSupplicantData.length + " bytes of wifi supplicant data");
Christopher Tate79ec80d2011-06-24 14:58:49 -0700366 out.writeInt(wifiSupplicantData.length);
367 out.write(wifiSupplicantData);
Christopher Tate2efd2db2011-07-19 16:32:49 -0700368 if (DEBUG_BACKUP) Log.d(TAG, wifiConfigData.length + " bytes of wifi config data");
Christopher Tate79ec80d2011-06-24 14:58:49 -0700369 out.writeInt(wifiConfigData.length);
370 out.write(wifiConfigData);
371
372 out.flush(); // also flushes downstream
373
374 // now we're set to emit the tar stream
375 fullBackupFile(stage, data);
376 } finally {
377 stage.delete();
378 }
379 }
380
381 @Override
Christopher Tate75a99702011-05-18 16:28:19 -0700382 public void onRestoreFile(ParcelFileDescriptor data, long size,
383 int type, String domain, String relpath, long mode, long mtime)
384 throws IOException {
385 if (DEBUG_BACKUP) Log.d(TAG, "onRestoreFile() invoked");
386 // Our data is actually a blob of flattened settings data identical to that
387 // produced during incremental backups. Just unpack and apply it all in
388 // turn.
389 FileInputStream instream = new FileInputStream(data.getFileDescriptor());
390 DataInputStream in = new DataInputStream(instream);
391
392 int version = in.readInt();
393 if (DEBUG_BACKUP) Log.d(TAG, "Flattened data version " + version);
Christopher Tate66488d62012-10-02 11:58:01 -0700394 if (version <= FULL_BACKUP_VERSION) {
395 // Generate the moved-to-global lookup table
396 HashSet<String> movedToGlobal = new HashSet<String>();
397 Settings.System.getMovedKeys(movedToGlobal);
398 Settings.Secure.getMovedKeys(movedToGlobal);
399
Christopher Tate75a99702011-05-18 16:28:19 -0700400 // system settings data first
401 int nBytes = in.readInt();
402 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of settings data");
403 byte[] buffer = new byte[nBytes];
Christopher Tate2efd2db2011-07-19 16:32:49 -0700404 in.readFully(buffer, 0, nBytes);
Christopher Tate66488d62012-10-02 11:58:01 -0700405 restoreSettings(buffer, nBytes, Settings.System.CONTENT_URI, movedToGlobal);
Christopher Tate75a99702011-05-18 16:28:19 -0700406
407 // secure settings
408 nBytes = in.readInt();
409 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of secure settings data");
410 if (nBytes > buffer.length) buffer = new byte[nBytes];
Christopher Tate2efd2db2011-07-19 16:32:49 -0700411 in.readFully(buffer, 0, nBytes);
Christopher Tate66488d62012-10-02 11:58:01 -0700412 restoreSettings(buffer, nBytes, Settings.Secure.CONTENT_URI, movedToGlobal);
413
414 // Global only if sufficiently new
415 if (version >= FULL_BACKUP_ADDED_GLOBAL) {
416 nBytes = in.readInt();
417 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of global settings data");
418 if (nBytes > buffer.length) buffer = new byte[nBytes];
419 in.readFully(buffer, 0, nBytes);
420 movedToGlobal.clear(); // no redirection; this *is* the global namespace
421 restoreSettings(buffer, nBytes, Settings.Global.CONTENT_URI, movedToGlobal);
422 }
Christopher Tate75a99702011-05-18 16:28:19 -0700423
424 // locale
425 nBytes = in.readInt();
426 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of locale data");
427 if (nBytes > buffer.length) buffer = new byte[nBytes];
Christopher Tate2efd2db2011-07-19 16:32:49 -0700428 in.readFully(buffer, 0, nBytes);
Christopher Tate75a99702011-05-18 16:28:19 -0700429 mSettingsHelper.setLocaleData(buffer, nBytes);
430
431 // wifi supplicant
432 nBytes = in.readInt();
433 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi supplicant data");
434 if (nBytes > buffer.length) buffer = new byte[nBytes];
Christopher Tate2efd2db2011-07-19 16:32:49 -0700435 in.readFully(buffer, 0, nBytes);
Christopher Tate75a99702011-05-18 16:28:19 -0700436 int retainedWifiState = enableWifi(false);
437 restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, buffer, nBytes);
438 FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
439 FileUtils.S_IRUSR | FileUtils.S_IWUSR |
440 FileUtils.S_IRGRP | FileUtils.S_IWGRP,
441 Process.myUid(), Process.WIFI_UID);
442 // retain the previous WIFI state.
443 enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
444 retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
445
446 // wifi config
447 nBytes = in.readInt();
448 if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi config data");
449 if (nBytes > buffer.length) buffer = new byte[nBytes];
Christopher Tate2efd2db2011-07-19 16:32:49 -0700450 in.readFully(buffer, 0, nBytes);
Christopher Tate75a99702011-05-18 16:28:19 -0700451 restoreFileData(mWifiConfigFile, buffer, nBytes);
452
453 if (DEBUG_BACKUP) Log.d(TAG, "Full restore complete.");
454 } else {
455 data.close();
456 throw new IOException("Invalid file schema");
457 }
458 }
459
Amith Yamasanid1582142009-07-08 20:04:55 -0700460 private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
461 long[] stateChecksums = new long[STATE_SIZE];
462
463 DataInputStream dataInput = new DataInputStream(
464 new FileInputStream(oldState.getFileDescriptor()));
Christopher Tatea286f412009-09-18 15:51:15 -0700465
466 try {
467 int stateVersion = dataInput.readInt();
Christopher Tate66488d62012-10-02 11:58:01 -0700468 for (int i = 0; i < STATE_SIZES[stateVersion]; i++) {
469 stateChecksums[i] = dataInput.readLong();
Amith Yamasanid1582142009-07-08 20:04:55 -0700470 }
Christopher Tatea286f412009-09-18 15:51:15 -0700471 } catch (EOFException eof) {
472 // With the default 0 checksum we'll wind up forcing a backup of
473 // any unhandled data sets, which is appropriate.
Amith Yamasanid1582142009-07-08 20:04:55 -0700474 }
475 dataInput.close();
476 return stateChecksums;
477 }
478
479 private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
480 throws IOException {
481 DataOutputStream dataOutput = new DataOutputStream(
482 new FileOutputStream(newState.getFileDescriptor()));
Christopher Tatea286f412009-09-18 15:51:15 -0700483
484 dataOutput.writeInt(STATE_VERSION);
Amith Yamasanid1582142009-07-08 20:04:55 -0700485 for (int i = 0; i < STATE_SIZE; i++) {
486 dataOutput.writeLong(checksums[i]);
487 }
488 dataOutput.close();
489 }
490
491 private long writeIfChanged(long oldChecksum, String key, byte[] data,
492 BackupDataOutput output) {
493 CRC32 checkSummer = new CRC32();
494 checkSummer.update(data);
495 long newChecksum = checkSummer.getValue();
496 if (oldChecksum == newChecksum) {
497 return oldChecksum;
498 }
499 try {
500 output.writeEntityHeader(key, data.length);
501 output.writeEntityData(data, data.length);
502 } catch (IOException ioe) {
503 // Bail
504 }
505 return newChecksum;
506 }
507
Amith Yamasani220f4d62009-07-02 02:34:14 -0700508 private byte[] getSystemSettings() {
Svetoslav Ganova571a582011-09-20 18:32:20 -0700509 Cursor cursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION, null,
510 null, null);
Jeff Brown1d8e7d62011-10-09 15:24:53 -0700511 try {
512 return extractRelevantValues(cursor, Settings.System.SETTINGS_TO_BACKUP);
513 } finally {
514 cursor.close();
515 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700516 }
517
518 private byte[] getSecureSettings() {
Svetoslav Ganova571a582011-09-20 18:32:20 -0700519 Cursor cursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION, null,
520 null, null);
Jeff Brown1d8e7d62011-10-09 15:24:53 -0700521 try {
522 return extractRelevantValues(cursor, Settings.Secure.SETTINGS_TO_BACKUP);
523 } finally {
524 cursor.close();
525 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700526 }
527
Christopher Tate66488d62012-10-02 11:58:01 -0700528 private byte[] getGlobalSettings() {
529 Cursor cursor = getContentResolver().query(Settings.Global.CONTENT_URI, PROJECTION, null,
530 null, null);
531 try {
532 return extractRelevantValues(cursor, Settings.Global.SETTINGS_TO_BACKUP);
533 } finally {
534 cursor.close();
535 }
536 }
537
538 private void restoreSettings(BackupDataInput data, Uri contentUri,
539 HashSet<String> movedToGlobal) {
Christopher Tate75a99702011-05-18 16:28:19 -0700540 byte[] settings = new byte[data.getDataSize()];
541 try {
542 data.readEntityData(settings, 0, settings.length);
543 } catch (IOException ioe) {
544 Log.e(TAG, "Couldn't read entity data");
545 return;
546 }
Christopher Tate66488d62012-10-02 11:58:01 -0700547 restoreSettings(settings, settings.length, contentUri, movedToGlobal);
Christopher Tate75a99702011-05-18 16:28:19 -0700548 }
549
Christopher Tate66488d62012-10-02 11:58:01 -0700550 private void restoreSettings(byte[] settings, int bytes, Uri contentUri,
551 HashSet<String> movedToGlobal) {
Svetoslav Ganova571a582011-09-20 18:32:20 -0700552 if (DEBUG) {
553 Log.i(TAG, "restoreSettings: " + contentUri);
554 }
555
Christopher Tate66488d62012-10-02 11:58:01 -0700556 // Figure out the white list and redirects to the global table.
Christopher Tate796e0f02009-09-22 11:57:58 -0700557 String[] whitelist = null;
558 if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
559 whitelist = Settings.Secure.SETTINGS_TO_BACKUP;
560 } else if (contentUri.equals(Settings.System.CONTENT_URI)) {
561 whitelist = Settings.System.SETTINGS_TO_BACKUP;
Christopher Tate66488d62012-10-02 11:58:01 -0700562 } else if (contentUri.equals(Settings.Global.CONTENT_URI)) {
563 whitelist = Settings.Global.SETTINGS_TO_BACKUP;
Svetoslav Ganova571a582011-09-20 18:32:20 -0700564 } else {
565 throw new IllegalArgumentException("Unknown URI: " + contentUri);
Christopher Tate796e0f02009-09-22 11:57:58 -0700566 }
567
Svetoslav Ganova571a582011-09-20 18:32:20 -0700568 // Restore only the white list data.
Amith Yamasani220f4d62009-07-02 02:34:14 -0700569 int pos = 0;
Svetoslav Ganova571a582011-09-20 18:32:20 -0700570 Map<String, String> cachedEntries = new HashMap<String, String>();
571 ContentValues contentValues = new ContentValues(2);
572 SettingsHelper settingsHelper = mSettingsHelper;
Christopher Tate0738e882009-09-11 16:35:39 -0700573
Svetoslav Ganova571a582011-09-20 18:32:20 -0700574 final int whiteListSize = whitelist.length;
575 for (int i = 0; i < whiteListSize; i++) {
576 String key = whitelist[i];
577 String value = cachedEntries.remove(key);
Christopher Tate0738e882009-09-11 16:35:39 -0700578
Svetoslav Ganova571a582011-09-20 18:32:20 -0700579 // If the value not cached, let us look it up.
580 if (value == null) {
581 while (pos < bytes) {
582 int length = readInt(settings, pos);
583 pos += INTEGER_BYTE_COUNT;
584 String dataKey = length > 0 ? new String(settings, pos, length) : null;
585 pos += length;
586 length = readInt(settings, pos);
587 pos += INTEGER_BYTE_COUNT;
588 String dataValue = length > 0 ? new String(settings, pos, length) : null;
589 pos += length;
590 if (key.equals(dataKey)) {
591 value = dataValue;
592 break;
593 }
594 cachedEntries.put(dataKey, dataValue);
Amith Yamasani70c874b2009-07-06 14:53:25 -0700595 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700596 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700597
Svetoslav Ganova571a582011-09-20 18:32:20 -0700598 if (value == null) {
599 continue;
600 }
Christopher Tate796e0f02009-09-22 11:57:58 -0700601
Christopher Tate66488d62012-10-02 11:58:01 -0700602 final Uri destination = (movedToGlobal.contains(key))
603 ? Settings.Global.CONTENT_URI
604 : contentUri;
605
606 // The helper doesn't care what namespace the keys are in
Svetoslav Ganova571a582011-09-20 18:32:20 -0700607 if (settingsHelper.restoreValue(key, value)) {
608 contentValues.clear();
609 contentValues.put(Settings.NameValueTable.NAME, key);
610 contentValues.put(Settings.NameValueTable.VALUE, value);
Christopher Tate66488d62012-10-02 11:58:01 -0700611 getContentResolver().insert(destination, contentValues);
Svetoslav Ganova571a582011-09-20 18:32:20 -0700612 }
613
Christopher Tated7177882012-09-07 18:09:03 -0700614 if (DEBUG || true) {
Christopher Tate66488d62012-10-02 11:58:01 -0700615 Log.d(TAG, "Restored setting: " + destination + " : "+ key + "=" + value);
Christopher Tate0738e882009-09-11 16:35:39 -0700616 }
617 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700618 }
619
620 /**
Svetoslav Ganova571a582011-09-20 18:32:20 -0700621 * Given a cursor and a set of keys, extract the required keys and
622 * values and write them to a byte array.
623 *
624 * @param cursor A cursor with settings data.
625 * @param settings The settings to extract.
626 * @return The byte array of extracted values.
Amith Yamasani220f4d62009-07-02 02:34:14 -0700627 */
Svetoslav Ganova571a582011-09-20 18:32:20 -0700628 private byte[] extractRelevantValues(Cursor cursor, String[] settings) {
629 final int settingsCount = settings.length;
630 byte[][] values = new byte[settingsCount * 2][]; // keys and values
631 if (!cursor.moveToFirst()) {
Amith Yamasani220f4d62009-07-02 02:34:14 -0700632 Log.e(TAG, "Couldn't read from the cursor");
633 return new byte[0];
634 }
Svetoslav Ganova571a582011-09-20 18:32:20 -0700635
636 // Obtain the relevant data in a temporary array.
Amith Yamasani220f4d62009-07-02 02:34:14 -0700637 int totalSize = 0;
Svetoslav Ganova571a582011-09-20 18:32:20 -0700638 int backedUpSettingIndex = 0;
639 Map<String, String> cachedEntries = new HashMap<String, String>();
640 for (int i = 0; i < settingsCount; i++) {
641 String key = settings[i];
642 String value = cachedEntries.remove(key);
643
644 // If the value not cached, let us look it up.
645 if (value == null) {
646 while (!cursor.isAfterLast()) {
647 String cursorKey = cursor.getString(COLUMN_NAME);
648 String cursorValue = cursor.getString(COLUMN_VALUE);
649 cursor.moveToNext();
650 if (key.equals(cursorKey)) {
651 value = cursorValue;
652 break;
653 }
654 cachedEntries.put(cursorKey, cursorValue);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700655 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700656 }
Svetoslav Ganova571a582011-09-20 18:32:20 -0700657
658 if (value == null) {
659 continue;
660 }
661
662 // Write the key and value in the intermediary array.
663 byte[] keyBytes = key.getBytes();
664 totalSize += INTEGER_BYTE_COUNT + keyBytes.length;
665 values[backedUpSettingIndex * 2] = keyBytes;
666
667 byte[] valueBytes = value.getBytes();
668 totalSize += INTEGER_BYTE_COUNT + valueBytes.length;
669 values[backedUpSettingIndex * 2 + 1] = valueBytes;
670
671 backedUpSettingIndex++;
672
673 if (DEBUG) {
674 Log.d(TAG, "Backed up setting: " + key + "=" + value);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700675 }
676 }
677
Svetoslav Ganova571a582011-09-20 18:32:20 -0700678 // Aggregate the result.
Amith Yamasani220f4d62009-07-02 02:34:14 -0700679 byte[] result = new byte[totalSize];
680 int pos = 0;
Svetoslav Ganova571a582011-09-20 18:32:20 -0700681 final int keyValuePairCount = backedUpSettingIndex * 2;
682 for (int i = 0; i < keyValuePairCount; i++) {
683 pos = writeInt(result, pos, values[i].length);
684 pos = writeBytes(result, pos, values[i]);
Amith Yamasani220f4d62009-07-02 02:34:14 -0700685 }
686 return result;
687 }
688
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800689 private byte[] getFileData(String filename) {
690 InputStream is = null;
691 try {
692 File file = new File(filename);
693 is = new FileInputStream(file);
694
695 //Will truncate read on a very long file,
696 //should not happen for a config file
697 byte[] bytes = new byte[(int)file.length()];
698
699 int offset = 0;
700 int numRead = 0;
701 while (offset < bytes.length
702 && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
703 offset += numRead;
704 }
705
706 //read failure
707 if (offset < bytes.length) {
708 Log.w(TAG, "Couldn't backup " + filename);
709 return EMPTY_DATA;
710 }
711 return bytes;
712 } catch (IOException ioe) {
713 Log.w(TAG, "Couldn't backup " + filename);
714 return EMPTY_DATA;
715 } finally {
716 if (is != null) {
717 try {
718 is.close();
719 } catch (IOException e) {
720 }
721 }
722 }
723
724 }
725
726 private void restoreFileData(String filename, BackupDataInput data) {
727 byte[] bytes = new byte[data.getDataSize()];
728 if (bytes.length <= 0) return;
Christopher Tatef12fbcd2011-06-28 16:16:42 -0700729 try {
730 data.readEntityData(bytes, 0, data.getDataSize());
731 restoreFileData(filename, bytes, bytes.length);
732 } catch (IOException e) {
733 Log.w(TAG, "Unable to read file data for " + filename);
734 }
Christopher Tate75a99702011-05-18 16:28:19 -0700735 }
736
737 private void restoreFileData(String filename, byte[] bytes, int size) {
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800738 try {
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800739 File file = new File(filename);
740 if (file.exists()) file.delete();
741
742 OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
Christopher Tate75a99702011-05-18 16:28:19 -0700743 os.write(bytes, 0, size);
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800744 os.close();
745 } catch (IOException ioe) {
746 Log.w(TAG, "Couldn't restore " + filename);
747 }
748 }
749
750
Amith Yamasani2cfab842009-09-09 18:27:31 -0700751 private byte[] getWifiSupplicant(String filename) {
Brad Fitzpatrick70787892010-11-17 11:31:12 -0800752 BufferedReader br = null;
Amith Yamasani220f4d62009-07-02 02:34:14 -0700753 try {
754 File file = new File(filename);
755 if (file.exists()) {
Brad Fitzpatrick70787892010-11-17 11:31:12 -0800756 br = new BufferedReader(new FileReader(file));
Amith Yamasani2cfab842009-09-09 18:27:31 -0700757 StringBuffer relevantLines = new StringBuffer();
758 boolean started = false;
759 String line;
760 while ((line = br.readLine()) != null) {
761 if (!started && line.startsWith("network")) {
762 started = true;
763 }
764 if (started) {
765 relevantLines.append(line).append("\n");
766 }
767 }
768 if (relevantLines.length() > 0) {
769 return relevantLines.toString().getBytes();
770 } else {
771 return EMPTY_DATA;
772 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700773 } else {
Amith Yamasanid1582142009-07-08 20:04:55 -0700774 return EMPTY_DATA;
Amith Yamasani220f4d62009-07-02 02:34:14 -0700775 }
776 } catch (IOException ioe) {
777 Log.w(TAG, "Couldn't backup " + filename);
Amith Yamasanid1582142009-07-08 20:04:55 -0700778 return EMPTY_DATA;
Brad Fitzpatrick70787892010-11-17 11:31:12 -0800779 } finally {
780 if (br != null) {
781 try {
782 br.close();
783 } catch (IOException e) {
784 }
785 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700786 }
787 }
788
Amith Yamasani2cfab842009-09-09 18:27:31 -0700789 private void restoreWifiSupplicant(String filename, BackupDataInput data) {
Amith Yamasani220f4d62009-07-02 02:34:14 -0700790 byte[] bytes = new byte[data.getDataSize()];
791 if (bytes.length <= 0) return;
Christopher Tate28cdb9e2011-06-24 15:06:48 -0700792 try {
793 data.readEntityData(bytes, 0, data.getDataSize());
794 restoreWifiSupplicant(filename, bytes, bytes.length);
795 } catch (IOException e) {
796 Log.w(TAG, "Unable to read supplicant data");
797 }
Christopher Tate75a99702011-05-18 16:28:19 -0700798 }
799
800 private void restoreWifiSupplicant(String filename, byte[] bytes, int size) {
Amith Yamasani220f4d62009-07-02 02:34:14 -0700801 try {
Christopher Tate8dfe2b92012-05-15 15:05:04 -0700802 WifiNetworkSettings supplicantImage = new WifiNetworkSettings();
Amith Yamasani2cfab842009-09-09 18:27:31 -0700803
Christopher Tate8dfe2b92012-05-15 15:05:04 -0700804 File supplicantFile = new File(FILE_WIFI_SUPPLICANT);
805 if (supplicantFile.exists()) {
806 // Retain the existing APs; we'll append the restored ones to them
807 BufferedReader in = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT));
808 supplicantImage.readNetworks(in);
809 in.close();
810
811 supplicantFile.delete();
812 }
813
814 // Incorporate the restore AP information
815 if (size > 0) {
816 char[] restoredAsBytes = new char[size];
817 for (int i = 0; i < size; i++) restoredAsBytes[i] = (char) bytes[i];
818 BufferedReader in = new BufferedReader(new CharArrayReader(restoredAsBytes));
819 supplicantImage.readNetworks(in);
820
821 if (DEBUG_BACKUP) {
822 Log.v(TAG, "Final AP list:");
823 supplicantImage.dump();
824 }
825 }
826
827 // Install the correct default template
828 BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_WIFI_SUPPLICANT));
829 copyWifiSupplicantTemplate(bw);
830
831 // Write the restored supplicant config and we're done
832 supplicantImage.write(bw);
833 bw.close();
Amith Yamasani220f4d62009-07-02 02:34:14 -0700834 } catch (IOException ioe) {
835 Log.w(TAG, "Couldn't restore " + filename);
836 }
837 }
838
Christopher Tate8dfe2b92012-05-15 15:05:04 -0700839 private void copyWifiSupplicantTemplate(BufferedWriter bw) {
Amith Yamasani2cfab842009-09-09 18:27:31 -0700840 try {
841 BufferedReader br = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT_TEMPLATE));
Amith Yamasani2cfab842009-09-09 18:27:31 -0700842 char[] temp = new char[1024];
843 int size;
844 while ((size = br.read(temp)) > 0) {
845 bw.write(temp, 0, size);
846 }
Amith Yamasani2cfab842009-09-09 18:27:31 -0700847 br.close();
848 } catch (IOException ioe) {
849 Log.w(TAG, "Couldn't copy wpa_supplicant file");
850 }
851 }
852
Amith Yamasani220f4d62009-07-02 02:34:14 -0700853 /**
854 * Write an int in BigEndian into the byte array.
855 * @param out byte array
856 * @param pos current pos in array
857 * @param value integer to write
Svetoslav Ganova571a582011-09-20 18:32:20 -0700858 * @return the index after adding the size of an int (4) in bytes.
Amith Yamasani220f4d62009-07-02 02:34:14 -0700859 */
860 private int writeInt(byte[] out, int pos, int value) {
861 out[pos + 0] = (byte) ((value >> 24) & 0xFF);
862 out[pos + 1] = (byte) ((value >> 16) & 0xFF);
863 out[pos + 2] = (byte) ((value >> 8) & 0xFF);
864 out[pos + 3] = (byte) ((value >> 0) & 0xFF);
Svetoslav Ganova571a582011-09-20 18:32:20 -0700865 return pos + INTEGER_BYTE_COUNT;
Amith Yamasani220f4d62009-07-02 02:34:14 -0700866 }
867
868 private int writeBytes(byte[] out, int pos, byte[] value) {
869 System.arraycopy(value, 0, out, pos, value.length);
870 return pos + value.length;
871 }
872
873 private int readInt(byte[] in, int pos) {
874 int result =
875 ((in[pos ] & 0xFF) << 24) |
876 ((in[pos + 1] & 0xFF) << 16) |
877 ((in[pos + 2] & 0xFF) << 8) |
878 ((in[pos + 3] & 0xFF) << 0);
879 return result;
880 }
881
Christian Sonntagc5b5b0f2009-08-07 10:00:21 -0700882 private int enableWifi(boolean enable) {
Irfan Sheriff4f4f5162012-04-27 14:42:42 -0700883 if (mWfm == null) {
884 mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
885 }
Irfan Sheriff4aeca7c52011-03-10 16:53:33 -0800886 if (mWfm != null) {
887 int state = mWfm.getWifiState();
888 mWfm.setWifiEnabled(enable);
Christian Sonntagc5b5b0f2009-08-07 10:00:21 -0700889 return state;
Irfan Sheriff4f4f5162012-04-27 14:42:42 -0700890 } else {
891 Log.e(TAG, "Failed to fetch WifiManager instance");
Amith Yamasani220f4d62009-07-02 02:34:14 -0700892 }
Christian Sonntagc5b5b0f2009-08-07 10:00:21 -0700893 return WifiManager.WIFI_STATE_UNKNOWN;
Amith Yamasani220f4d62009-07-02 02:34:14 -0700894 }
Amith Yamasani220f4d62009-07-02 02:34:14 -0700895}