SettingsBackupAgent.java revision 8150d2a2a12b38598fd55d8ae3c3b5662ec3520f
1/*
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
19import android.app.backup.BackupAgentHelper;
20import android.app.backup.BackupDataInput;
21import android.app.backup.BackupDataOutput;
22import android.app.backup.FullBackupDataOutput;
23import android.content.ContentResolver;
24import android.content.ContentValues;
25import android.content.Context;
26import android.database.Cursor;
27import android.net.Uri;
28import android.net.wifi.WifiConfiguration;
29import android.net.wifi.WifiConfiguration.KeyMgmt;
30import android.net.wifi.WifiManager;
31import android.os.FileUtils;
32import android.os.Handler;
33import android.os.ParcelFileDescriptor;
34import android.os.Process;
35import android.os.UserHandle;
36import android.provider.Settings;
37import android.util.Log;
38
39import com.android.internal.widget.LockPatternUtils;
40
41import libcore.io.IoUtils;
42
43import java.io.BufferedOutputStream;
44import java.io.BufferedReader;
45import java.io.BufferedWriter;
46import java.io.ByteArrayInputStream;
47import java.io.ByteArrayOutputStream;
48import java.io.CharArrayReader;
49import java.io.DataInputStream;
50import java.io.DataOutputStream;
51import java.io.EOFException;
52import java.io.File;
53import java.io.FileInputStream;
54import java.io.FileOutputStream;
55import java.io.FileReader;
56import java.io.FileWriter;
57import java.io.IOException;
58import java.io.InputStream;
59import java.io.OutputStream;
60import java.io.OutputStreamWriter;
61import java.io.Writer;
62import java.util.ArrayList;
63import java.util.BitSet;
64import java.util.HashMap;
65import java.util.HashSet;
66import java.util.List;
67import java.util.Map;
68import java.util.Objects;
69import java.util.zip.CRC32;
70
71/**
72 * Performs backup and restore of the System and Secure settings.
73 * List of settings that are backed up are stored in the Settings.java file
74 */
75public class SettingsBackupAgent extends BackupAgentHelper {
76    private static final boolean DEBUG = false;
77    private static final boolean DEBUG_BACKUP = DEBUG || false;
78
79    private static final String KEY_SYSTEM = "system";
80    private static final String KEY_SECURE = "secure";
81    private static final String KEY_GLOBAL = "global";
82    private static final String KEY_LOCALE = "locale";
83    private static final String KEY_LOCK_SETTINGS = "lock_settings";
84
85    // Versioning of the state file.  Increment this version
86    // number any time the set of state items is altered.
87    private static final int STATE_VERSION = 4;
88
89    // Slots in the checksum array.  Never insert new items in the middle
90    // of this array; new slots must be appended.
91    private static final int STATE_SYSTEM          = 0;
92    private static final int STATE_SECURE          = 1;
93    private static final int STATE_LOCALE          = 2;
94    private static final int STATE_WIFI_SUPPLICANT = 3;
95    private static final int STATE_WIFI_CONFIG     = 4;
96    private static final int STATE_GLOBAL          = 5;
97    private static final int STATE_LOCK_SETTINGS   = 6;
98
99    private static final int STATE_SIZE            = 7; // The current number of state items
100
101    // Number of entries in the checksum array at various version numbers
102    private static final int STATE_SIZES[] = {
103        0,
104        4,              // version 1
105        5,              // version 2 added STATE_WIFI_CONFIG
106        6,              // version 3 added STATE_GLOBAL
107        STATE_SIZE      // version 4 added STATE_LOCK_SETTINGS
108    };
109
110    // Versioning of the 'full backup' format
111    private static final int FULL_BACKUP_VERSION = 3;
112    private static final int FULL_BACKUP_ADDED_GLOBAL = 2;  // added the "global" entry
113    private static final int FULL_BACKUP_ADDED_LOCK_SETTINGS = 3; // added the "lock_settings" entry
114
115    private static final int INTEGER_BYTE_COUNT = Integer.SIZE / Byte.SIZE;
116
117    private static final byte[] EMPTY_DATA = new byte[0];
118
119    private static final String TAG = "SettingsBackupAgent";
120
121    private static final String[] PROJECTION = {
122        Settings.NameValueTable.NAME,
123        Settings.NameValueTable.VALUE
124    };
125
126    private static final String FILE_WIFI_SUPPLICANT = "/data/misc/wifi/wpa_supplicant.conf";
127    private static final String FILE_WIFI_SUPPLICANT_TEMPLATE =
128            "/system/etc/wifi/wpa_supplicant.conf";
129
130    // the key to store the WIFI data under, should be sorted as last, so restore happens last.
131    // use very late unicode character to quasi-guarantee last sort position.
132    private static final String KEY_WIFI_SUPPLICANT = "\uffedWIFI";
133    private static final String KEY_WIFI_CONFIG = "\uffedCONFIG_WIFI";
134
135    // Keys within the lock settings section
136    private static final String KEY_LOCK_SETTINGS_OWNER_INFO_ENABLED = "owner_info_enabled";
137    private static final String KEY_LOCK_SETTINGS_OWNER_INFO = "owner_info";
138
139    // Name of the temporary file we use during full backup/restore.  This is
140    // stored in the full-backup tarfile as well, so should not be changed.
141    private static final String STAGE_FILE = "flattened-data";
142
143    // Delay in milliseconds between the restore operation and when we will bounce
144    // wifi in order to rewrite the supplicant config etc.
145    private static final long WIFI_BOUNCE_DELAY_MILLIS = 60 * 1000; // one minute
146
147    private SettingsHelper mSettingsHelper;
148    private WifiManager mWfm;
149    private static String mWifiConfigFile;
150
151    WifiRestoreRunnable mWifiRestore = null;
152
153    // Class for capturing a network definition from the wifi supplicant config file
154    static class Network {
155        String ssid = "";  // equals() and hashCode() need these to be non-null
156        String key_mgmt = "";
157        boolean certUsed = false;
158        boolean hasWepKey = false;
159        final ArrayList<String> rawLines = new ArrayList<String>();
160
161        public static Network readFromStream(BufferedReader in) {
162            final Network n = new Network();
163            String line;
164            try {
165                while (in.ready()) {
166                    line = in.readLine();
167                    if (line == null || line.startsWith("}")) {
168                        break;
169                    }
170                    n.rememberLine(line);
171                }
172            } catch (IOException e) {
173                return null;
174            }
175            return n;
176        }
177
178        void rememberLine(String line) {
179            // can't rely on particular whitespace patterns so strip leading/trailing
180            line = line.trim();
181            if (line.isEmpty()) return; // only whitespace; drop the line
182            rawLines.add(line);
183
184            // remember the ssid and key_mgmt lines for duplicate culling
185            if (line.startsWith("ssid=")) {
186                ssid = line;
187            } else if (line.startsWith("key_mgmt=")) {
188                key_mgmt = line;
189            } else if (line.startsWith("client_cert=")) {
190                certUsed = true;
191            } else if (line.startsWith("ca_cert=")) {
192                certUsed = true;
193            } else if (line.startsWith("ca_path=")) {
194                certUsed = true;
195            } else if (line.startsWith("wep_")) {
196                hasWepKey = true;
197            }
198        }
199
200        public void write(Writer w) throws IOException {
201            w.write("\nnetwork={\n");
202            for (String line : rawLines) {
203                w.write("\t" + line + "\n");
204            }
205            w.write("}\n");
206        }
207
208        public void dump() {
209            Log.v(TAG, "network={");
210            for (String line : rawLines) {
211                Log.v(TAG, "   " + line);
212            }
213            Log.v(TAG, "}");
214        }
215
216        // Calculate the equivalent of WifiConfiguration's configKey()
217        public String configKey() {
218            if (ssid == null) {
219                // No SSID => malformed network definition
220                return null;
221            }
222
223            final String bareSsid = ssid.substring(ssid.indexOf('=') + 1);
224
225            final BitSet types = new BitSet();
226            if (key_mgmt == null) {
227                // no key_mgmt specified; this is defined as equivalent to "WPA-PSK WPA-EAP"
228                types.set(KeyMgmt.WPA_PSK);
229                types.set(KeyMgmt.WPA_EAP);
230            } else {
231                // Need to parse the key_mgmt line
232                final String bareKeyMgmt = key_mgmt.substring(key_mgmt.indexOf('=') + 1);
233                String[] typeStrings = bareKeyMgmt.split("\\s+");
234
235                // Parse out all the key management regimes permitted for this network.  The literal
236                // strings here are the standard values permitted in wpa_supplicant.conf.
237                for (int i = 0; i < typeStrings.length; i++) {
238                    final String ktype = typeStrings[i];
239                    if (ktype.equals("WPA-PSK")) {
240                        Log.v(TAG, "  + setting WPA_PSK bit");
241                        types.set(KeyMgmt.WPA_PSK);
242                    } else if (ktype.equals("WPA-EAP")) {
243                        Log.v(TAG, "  + setting WPA_EAP bit");
244                        types.set(KeyMgmt.WPA_EAP);
245                    } else if (ktype.equals("IEEE8021X")) {
246                        Log.v(TAG, "  + setting IEEE8021X bit");
247                        types.set(KeyMgmt.IEEE8021X);
248                    }
249                }
250            }
251
252            // Now build the canonical config key paralleling the WifiConfiguration semantics
253            final String key;
254            if (types.get(KeyMgmt.WPA_PSK)) {
255                key = bareSsid + KeyMgmt.strings[KeyMgmt.WPA_PSK];
256            } else if (types.get(KeyMgmt.WPA_EAP) || types.get(KeyMgmt.IEEE8021X)) {
257                key = bareSsid + KeyMgmt.strings[KeyMgmt.WPA_EAP];
258            } else if (hasWepKey) {
259                key = bareSsid + "WEP";  // hardcoded this way in WifiConfiguration
260            } else {
261                key = bareSsid + KeyMgmt.strings[KeyMgmt.NONE];
262            }
263            return key;
264        }
265
266        // Same approach as Pair.equals() and Pair.hashCode()
267        @Override
268        public boolean equals(Object o) {
269            if (o == this) return true;
270            if (!(o instanceof Network)) return false;
271            final Network other;
272            try {
273                other = (Network) o;
274            } catch (ClassCastException e) {
275                return false;
276            }
277            return ssid.equals(other.ssid) && key_mgmt.equals(other.key_mgmt);
278        }
279
280        @Override
281        public int hashCode() {
282            int result = 17;
283            result = 31 * result + ssid.hashCode();
284            result = 31 * result + key_mgmt.hashCode();
285            return result;
286        }
287    }
288
289    boolean networkInWhitelist(Network net, List<WifiConfiguration> whitelist) {
290        final String netConfigKey = net.configKey();
291        final int N = whitelist.size();
292        for (int i = 0; i < N; i++) {
293            if (Objects.equals(netConfigKey, whitelist.get(i).configKey(true))) {
294                return true;
295            }
296        }
297        return false;
298    }
299
300    // Ingest multiple wifi config file fragments, looking for network={} blocks
301    // and eliminating duplicates
302    class WifiNetworkSettings {
303        // One for fast lookup, one for maintaining ordering
304        final HashSet<Network> mKnownNetworks = new HashSet<Network>();
305        final ArrayList<Network> mNetworks = new ArrayList<Network>(8);
306
307        public void readNetworks(BufferedReader in, List<WifiConfiguration> whitelist) {
308            try {
309                String line;
310                while (in.ready()) {
311                    line = in.readLine();
312                    if (line != null) {
313                        // Parse out 'network=' decls so we can ignore duplicates
314                        if (line.startsWith("network")) {
315                            Network net = Network.readFromStream(in);
316                            if (whitelist != null) {
317                                if (!networkInWhitelist(net, whitelist)) {
318                                    if (DEBUG_BACKUP) {
319                                        Log.v(TAG, "Network not in whitelist, skipping: "
320                                                + net.ssid + " / " + net.key_mgmt);
321                                    }
322                                    continue;
323                                }
324                            }
325                            if (! mKnownNetworks.contains(net)) {
326                                if (DEBUG_BACKUP) {
327                                    Log.v(TAG, "Adding " + net.ssid + " / " + net.key_mgmt);
328                                }
329                                mKnownNetworks.add(net);
330                                mNetworks.add(net);
331                            } else {
332                                if (DEBUG_BACKUP) {
333                                    Log.v(TAG, "Dupe; skipped " + net.ssid + " / " + net.key_mgmt);
334                                }
335                            }
336                        }
337                    }
338                }
339            } catch (IOException e) {
340                // whatever happened, we're done now
341            }
342        }
343
344        public void write(Writer w) throws IOException {
345            for (Network net : mNetworks) {
346                if (net.certUsed) {
347                    // Networks that use certificates for authentication can't be restored
348                    // because the certificates they need don't get restored (because they
349                    // are stored in keystore, and can't be restored)
350                    continue;
351                }
352
353                net.write(w);
354            }
355        }
356
357        public void dump() {
358            for (Network net : mNetworks) {
359                net.dump();
360            }
361        }
362    }
363
364    @Override
365    public void onCreate() {
366        if (DEBUG_BACKUP) Log.d(TAG, "onCreate() invoked");
367
368        mSettingsHelper = new SettingsHelper(this);
369        super.onCreate();
370
371        WifiManager mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
372        if (mWfm != null) mWifiConfigFile = mWfm.getConfigFile();
373    }
374
375    @Override
376    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
377            ParcelFileDescriptor newState) throws IOException {
378
379        byte[] systemSettingsData = getSystemSettings();
380        byte[] secureSettingsData = getSecureSettings();
381        byte[] globalSettingsData = getGlobalSettings();
382        byte[] lockSettingsData   = getLockSettings();
383        byte[] locale = mSettingsHelper.getLocaleData();
384        byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
385        byte[] wifiConfigData = getFileData(mWifiConfigFile);
386
387        long[] stateChecksums = readOldChecksums(oldState);
388
389        stateChecksums[STATE_SYSTEM] =
390            writeIfChanged(stateChecksums[STATE_SYSTEM], KEY_SYSTEM, systemSettingsData, data);
391        stateChecksums[STATE_SECURE] =
392            writeIfChanged(stateChecksums[STATE_SECURE], KEY_SECURE, secureSettingsData, data);
393        stateChecksums[STATE_GLOBAL] =
394            writeIfChanged(stateChecksums[STATE_GLOBAL], KEY_GLOBAL, globalSettingsData, data);
395        stateChecksums[STATE_LOCALE] =
396            writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
397        stateChecksums[STATE_WIFI_SUPPLICANT] =
398            writeIfChanged(stateChecksums[STATE_WIFI_SUPPLICANT], KEY_WIFI_SUPPLICANT,
399                    wifiSupplicantData, data);
400        stateChecksums[STATE_WIFI_CONFIG] =
401            writeIfChanged(stateChecksums[STATE_WIFI_CONFIG], KEY_WIFI_CONFIG, wifiConfigData,
402                    data);
403        stateChecksums[STATE_LOCK_SETTINGS] =
404            writeIfChanged(stateChecksums[STATE_LOCK_SETTINGS], KEY_LOCK_SETTINGS,
405                    lockSettingsData, data);
406
407        writeNewChecksums(stateChecksums, newState);
408    }
409
410    class WifiRestoreRunnable implements Runnable {
411        private byte[] restoredSupplicantData;
412        private byte[] restoredWifiConfigFile;
413
414        void incorporateWifiSupplicant(BackupDataInput data) {
415            restoredSupplicantData = new byte[data.getDataSize()];
416            if (restoredSupplicantData.length <= 0) return;
417            try {
418                data.readEntityData(restoredSupplicantData, 0, data.getDataSize());
419            } catch (IOException e) {
420                Log.w(TAG, "Unable to read supplicant data");
421                restoredSupplicantData = null;
422            }
423        }
424
425        void incorporateWifiConfigFile(BackupDataInput data) {
426            restoredWifiConfigFile = new byte[data.getDataSize()];
427            if (restoredWifiConfigFile.length <= 0) return;
428            try {
429                data.readEntityData(restoredWifiConfigFile, 0, data.getDataSize());
430            } catch (IOException e) {
431                Log.w(TAG, "Unable to read config file");
432                restoredWifiConfigFile = null;
433            }
434        }
435
436        @Override
437        public void run() {
438            if (restoredSupplicantData != null || restoredWifiConfigFile != null) {
439                if (DEBUG_BACKUP) {
440                    Log.v(TAG, "Starting deferred restore of wifi data");
441                }
442                final ContentResolver cr = getContentResolver();
443                final int scanAlways = Settings.Global.getInt(cr,
444                        Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0);
445                final int retainedWifiState = enableWifi(false);
446                if (scanAlways != 0) {
447                    Settings.Global.putInt(cr,
448                            Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0);
449                }
450                // !!! Give the wifi stack a moment to quiesce
451                try { Thread.sleep(1500); } catch (InterruptedException e) {}
452                if (restoredSupplicantData != null) {
453                    restoreWifiSupplicant(FILE_WIFI_SUPPLICANT,
454                            restoredSupplicantData, restoredSupplicantData.length);
455                    FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
456                            FileUtils.S_IRUSR | FileUtils.S_IWUSR |
457                            FileUtils.S_IRGRP | FileUtils.S_IWGRP,
458                            Process.myUid(), Process.WIFI_UID);
459                }
460                if (restoredWifiConfigFile != null) {
461                    restoreFileData(mWifiConfigFile,
462                            restoredWifiConfigFile, restoredWifiConfigFile.length);
463                }
464                // restore the previous WIFI state.
465                if (scanAlways != 0) {
466                    Settings.Global.putInt(cr,
467                            Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, scanAlways);
468                }
469                enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
470                        retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
471            }
472        }
473    }
474
475    // Instantiate the wifi-config restore runnable, scheduling it for execution
476    // a minute hence
477    void initWifiRestoreIfNecessary() {
478        if (mWifiRestore == null) {
479            mWifiRestore = new WifiRestoreRunnable();
480        }
481    }
482
483    @Override
484    public void onRestore(BackupDataInput data, int appVersionCode,
485            ParcelFileDescriptor newState) throws IOException {
486
487        HashSet<String> movedToGlobal = new HashSet<String>();
488        Settings.System.getMovedToGlobalSettings(movedToGlobal);
489        Settings.Secure.getMovedToGlobalSettings(movedToGlobal);
490
491        while (data.readNextHeader()) {
492            final String key = data.getKey();
493            final int size = data.getDataSize();
494            if (KEY_SYSTEM.equals(key)) {
495                restoreSettings(data, Settings.System.CONTENT_URI, movedToGlobal);
496                mSettingsHelper.applyAudioSettings();
497            } else if (KEY_SECURE.equals(key)) {
498                restoreSettings(data, Settings.Secure.CONTENT_URI, movedToGlobal);
499            } else if (KEY_GLOBAL.equals(key)) {
500                restoreSettings(data, Settings.Global.CONTENT_URI, null);
501            } else if (KEY_WIFI_SUPPLICANT.equals(key)) {
502                initWifiRestoreIfNecessary();
503                mWifiRestore.incorporateWifiSupplicant(data);
504            } else if (KEY_LOCALE.equals(key)) {
505                byte[] localeData = new byte[size];
506                data.readEntityData(localeData, 0, size);
507                mSettingsHelper.setLocaleData(localeData, size);
508            } else if (KEY_WIFI_CONFIG.equals(key)) {
509                initWifiRestoreIfNecessary();
510                mWifiRestore.incorporateWifiConfigFile(data);
511            } else if (KEY_LOCK_SETTINGS.equals(key)) {
512                restoreLockSettings(data);
513             } else {
514                data.skipEntityData();
515            }
516        }
517
518        // If we have wifi data to restore, post a runnable to perform the
519        // bounce-and-update operation a little ways in the future.
520        if (mWifiRestore != null) {
521            long wifiBounceDelayMillis = Settings.Global.getLong(
522                    getContentResolver(),
523                    Settings.Global.WIFI_BOUNCE_DELAY_OVERRIDE_MS,
524                    WIFI_BOUNCE_DELAY_MILLIS);
525            new Handler(getMainLooper()).postDelayed(mWifiRestore, wifiBounceDelayMillis);
526        }
527    }
528
529    @Override
530    public void onFullBackup(FullBackupDataOutput data)  throws IOException {
531        byte[] systemSettingsData = getSystemSettings();
532        byte[] secureSettingsData = getSecureSettings();
533        byte[] globalSettingsData = getGlobalSettings();
534        byte[] lockSettingsData   = getLockSettings();
535        byte[] locale = mSettingsHelper.getLocaleData();
536        byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
537        byte[] wifiConfigData = getFileData(mWifiConfigFile);
538
539        // Write the data to the staging file, then emit that as our tarfile
540        // representation of the backed-up settings.
541        String root = getFilesDir().getAbsolutePath();
542        File stage = new File(root, STAGE_FILE);
543        try {
544            FileOutputStream filestream = new FileOutputStream(stage);
545            BufferedOutputStream bufstream = new BufferedOutputStream(filestream);
546            DataOutputStream out = new DataOutputStream(bufstream);
547
548            if (DEBUG_BACKUP) Log.d(TAG, "Writing flattened data version " + FULL_BACKUP_VERSION);
549            out.writeInt(FULL_BACKUP_VERSION);
550
551            if (DEBUG_BACKUP) Log.d(TAG, systemSettingsData.length + " bytes of settings data");
552            out.writeInt(systemSettingsData.length);
553            out.write(systemSettingsData);
554            if (DEBUG_BACKUP) Log.d(TAG, secureSettingsData.length + " bytes of secure settings data");
555            out.writeInt(secureSettingsData.length);
556            out.write(secureSettingsData);
557            if (DEBUG_BACKUP) Log.d(TAG, globalSettingsData.length + " bytes of global settings data");
558            out.writeInt(globalSettingsData.length);
559            out.write(globalSettingsData);
560            if (DEBUG_BACKUP) Log.d(TAG, locale.length + " bytes of locale data");
561            out.writeInt(locale.length);
562            out.write(locale);
563            if (DEBUG_BACKUP) Log.d(TAG, wifiSupplicantData.length + " bytes of wifi supplicant data");
564            out.writeInt(wifiSupplicantData.length);
565            out.write(wifiSupplicantData);
566            if (DEBUG_BACKUP) Log.d(TAG, wifiConfigData.length + " bytes of wifi config data");
567            out.writeInt(wifiConfigData.length);
568            out.write(wifiConfigData);
569            if (DEBUG_BACKUP) Log.d(TAG, lockSettingsData.length + " bytes of lock settings data");
570            out.writeInt(lockSettingsData.length);
571            out.write(lockSettingsData);
572
573            out.flush();    // also flushes downstream
574
575            // now we're set to emit the tar stream
576            fullBackupFile(stage, data);
577        } finally {
578            stage.delete();
579        }
580    }
581
582    @Override
583    public void onRestoreFile(ParcelFileDescriptor data, long size,
584            int type, String domain, String relpath, long mode, long mtime)
585            throws IOException {
586        if (DEBUG_BACKUP) Log.d(TAG, "onRestoreFile() invoked");
587        // Our data is actually a blob of flattened settings data identical to that
588        // produced during incremental backups.  Just unpack and apply it all in
589        // turn.
590        FileInputStream instream = new FileInputStream(data.getFileDescriptor());
591        DataInputStream in = new DataInputStream(instream);
592
593        int version = in.readInt();
594        if (DEBUG_BACKUP) Log.d(TAG, "Flattened data version " + version);
595        if (version <= FULL_BACKUP_VERSION) {
596            // Generate the moved-to-global lookup table
597            HashSet<String> movedToGlobal = new HashSet<String>();
598            Settings.System.getMovedToGlobalSettings(movedToGlobal);
599            Settings.Secure.getMovedToGlobalSettings(movedToGlobal);
600
601            // system settings data first
602            int nBytes = in.readInt();
603            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of settings data");
604            byte[] buffer = new byte[nBytes];
605            in.readFully(buffer, 0, nBytes);
606            restoreSettings(buffer, nBytes, Settings.System.CONTENT_URI, movedToGlobal);
607
608            // secure settings
609            nBytes = in.readInt();
610            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of secure settings data");
611            if (nBytes > buffer.length) buffer = new byte[nBytes];
612            in.readFully(buffer, 0, nBytes);
613            restoreSettings(buffer, nBytes, Settings.Secure.CONTENT_URI, movedToGlobal);
614
615            // Global only if sufficiently new
616            if (version >= FULL_BACKUP_ADDED_GLOBAL) {
617                nBytes = in.readInt();
618                if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of global settings data");
619                if (nBytes > buffer.length) buffer = new byte[nBytes];
620                in.readFully(buffer, 0, nBytes);
621                movedToGlobal.clear();  // no redirection; this *is* the global namespace
622                restoreSettings(buffer, nBytes, Settings.Global.CONTENT_URI, movedToGlobal);
623            }
624
625            // locale
626            nBytes = in.readInt();
627            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of locale data");
628            if (nBytes > buffer.length) buffer = new byte[nBytes];
629            in.readFully(buffer, 0, nBytes);
630            mSettingsHelper.setLocaleData(buffer, nBytes);
631
632            // wifi supplicant
633            nBytes = in.readInt();
634            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi supplicant data");
635            if (nBytes > buffer.length) buffer = new byte[nBytes];
636            in.readFully(buffer, 0, nBytes);
637            int retainedWifiState = enableWifi(false);
638            restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, buffer, nBytes);
639            FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
640                    FileUtils.S_IRUSR | FileUtils.S_IWUSR |
641                    FileUtils.S_IRGRP | FileUtils.S_IWGRP,
642                    Process.myUid(), Process.WIFI_UID);
643            // retain the previous WIFI state.
644            enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
645                    retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
646
647            // wifi config
648            nBytes = in.readInt();
649            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi config data");
650            if (nBytes > buffer.length) buffer = new byte[nBytes];
651            in.readFully(buffer, 0, nBytes);
652            restoreFileData(mWifiConfigFile, buffer, nBytes);
653
654            if (version >= FULL_BACKUP_ADDED_LOCK_SETTINGS) {
655                nBytes = in.readInt();
656                if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of lock settings data");
657                if (nBytes > buffer.length) buffer = new byte[nBytes];
658                if (nBytes > 0) {
659                    in.readFully(buffer, 0, nBytes);
660                    restoreLockSettings(buffer, nBytes);
661                }
662            }
663
664            if (DEBUG_BACKUP) Log.d(TAG, "Full restore complete.");
665        } else {
666            data.close();
667            throw new IOException("Invalid file schema");
668        }
669    }
670
671    private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
672        long[] stateChecksums = new long[STATE_SIZE];
673
674        DataInputStream dataInput = new DataInputStream(
675                new FileInputStream(oldState.getFileDescriptor()));
676
677        try {
678            int stateVersion = dataInput.readInt();
679            for (int i = 0; i < STATE_SIZES[stateVersion]; i++) {
680                stateChecksums[i] = dataInput.readLong();
681            }
682        } catch (EOFException eof) {
683            // With the default 0 checksum we'll wind up forcing a backup of
684            // any unhandled data sets, which is appropriate.
685        }
686        dataInput.close();
687        return stateChecksums;
688    }
689
690    private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
691            throws IOException {
692        DataOutputStream dataOutput = new DataOutputStream(
693                new BufferedOutputStream(new FileOutputStream(newState.getFileDescriptor())));
694
695        dataOutput.writeInt(STATE_VERSION);
696        for (int i = 0; i < STATE_SIZE; i++) {
697            dataOutput.writeLong(checksums[i]);
698        }
699        dataOutput.close();
700    }
701
702    private long writeIfChanged(long oldChecksum, String key, byte[] data,
703            BackupDataOutput output) {
704        CRC32 checkSummer = new CRC32();
705        checkSummer.update(data);
706        long newChecksum = checkSummer.getValue();
707        if (oldChecksum == newChecksum) {
708            return oldChecksum;
709        }
710        try {
711            if (DEBUG_BACKUP) {
712                Log.v(TAG, "Writing entity " + key + " of size " + data.length);
713            }
714            output.writeEntityHeader(key, data.length);
715            output.writeEntityData(data, data.length);
716        } catch (IOException ioe) {
717            // Bail
718        }
719        return newChecksum;
720    }
721
722    private byte[] getSystemSettings() {
723        Cursor cursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION, null,
724                null, null);
725        try {
726            return extractRelevantValues(cursor, Settings.System.SETTINGS_TO_BACKUP);
727        } finally {
728            cursor.close();
729        }
730    }
731
732    private byte[] getSecureSettings() {
733        Cursor cursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION, null,
734                null, null);
735        try {
736            return extractRelevantValues(cursor, Settings.Secure.SETTINGS_TO_BACKUP);
737        } finally {
738            cursor.close();
739        }
740    }
741
742    private byte[] getGlobalSettings() {
743        Cursor cursor = getContentResolver().query(Settings.Global.CONTENT_URI, PROJECTION, null,
744                null, null);
745        try {
746            return extractRelevantValues(cursor, Settings.Global.SETTINGS_TO_BACKUP);
747        } finally {
748            cursor.close();
749        }
750    }
751
752    /**
753     * Serialize the owner info settings
754     */
755    private byte[] getLockSettings() {
756        final LockPatternUtils lockPatternUtils = new LockPatternUtils(this);
757        final boolean ownerInfoEnabled = lockPatternUtils.isOwnerInfoEnabled(UserHandle.myUserId());
758        final String ownerInfo = lockPatternUtils.getOwnerInfo(UserHandle.myUserId());
759
760        ByteArrayOutputStream baos = new ByteArrayOutputStream();
761        DataOutputStream out = new DataOutputStream(baos);
762        try {
763            out.writeUTF(KEY_LOCK_SETTINGS_OWNER_INFO_ENABLED);
764            out.writeUTF(ownerInfoEnabled ? "1" : "0");
765            if (ownerInfo != null) {
766                out.writeUTF(KEY_LOCK_SETTINGS_OWNER_INFO);
767                out.writeUTF(ownerInfo != null ? ownerInfo : "");
768            }
769            // End marker
770            out.writeUTF("");
771            out.flush();
772        } catch (IOException ioe) {
773        }
774        return baos.toByteArray();
775    }
776
777    private void restoreSettings(BackupDataInput data, Uri contentUri,
778            HashSet<String> movedToGlobal) {
779        byte[] settings = new byte[data.getDataSize()];
780        try {
781            data.readEntityData(settings, 0, settings.length);
782        } catch (IOException ioe) {
783            Log.e(TAG, "Couldn't read entity data");
784            return;
785        }
786        restoreSettings(settings, settings.length, contentUri, movedToGlobal);
787    }
788
789    private void restoreSettings(byte[] settings, int bytes, Uri contentUri,
790            HashSet<String> movedToGlobal) {
791        if (DEBUG) {
792            Log.i(TAG, "restoreSettings: " + contentUri);
793        }
794
795        // Figure out the white list and redirects to the global table.
796        final String[] whitelist;
797        if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
798            whitelist = Settings.Secure.SETTINGS_TO_BACKUP;
799        } else if (contentUri.equals(Settings.System.CONTENT_URI)) {
800            whitelist = Settings.System.SETTINGS_TO_BACKUP;
801        } else if (contentUri.equals(Settings.Global.CONTENT_URI)) {
802            whitelist = Settings.Global.SETTINGS_TO_BACKUP;
803        } else {
804            throw new IllegalArgumentException("Unknown URI: " + contentUri);
805        }
806
807        // Restore only the white list data.
808        int pos = 0;
809        Map<String, String> cachedEntries = new HashMap<String, String>();
810        ContentValues contentValues = new ContentValues(2);
811        SettingsHelper settingsHelper = mSettingsHelper;
812        ContentResolver cr = getContentResolver();
813
814        final int whiteListSize = whitelist.length;
815        for (int i = 0; i < whiteListSize; i++) {
816            String key = whitelist[i];
817            String value = cachedEntries.remove(key);
818
819            // If the value not cached, let us look it up.
820            if (value == null) {
821                while (pos < bytes) {
822                    int length = readInt(settings, pos);
823                    pos += INTEGER_BYTE_COUNT;
824                    String dataKey = length > 0 ? new String(settings, pos, length) : null;
825                    pos += length;
826                    length = readInt(settings, pos);
827                    pos += INTEGER_BYTE_COUNT;
828                    String dataValue = length > 0 ? new String(settings, pos, length) : null;
829                    pos += length;
830                    if (key.equals(dataKey)) {
831                        value = dataValue;
832                        break;
833                    }
834                    cachedEntries.put(dataKey, dataValue);
835                }
836            }
837
838            if (value == null) {
839                continue;
840            }
841
842            final Uri destination = (movedToGlobal != null && movedToGlobal.contains(key))
843                    ? Settings.Global.CONTENT_URI
844                    : contentUri;
845            settingsHelper.restoreValue(this, cr, contentValues, destination, key, value);
846
847            if (DEBUG) {
848                Log.d(TAG, "Restored setting: " + destination + " : "+ key + "=" + value);
849            }
850        }
851    }
852
853    /**
854     * Restores the owner info enabled and owner info settings in LockSettings.
855     *
856     * @param buffer
857     * @param nBytes
858     */
859    private void restoreLockSettings(byte[] buffer, int nBytes) {
860        final LockPatternUtils lockPatternUtils = new LockPatternUtils(this);
861
862        ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, nBytes);
863        DataInputStream in = new DataInputStream(bais);
864        try {
865            String key;
866            // Read until empty string marker
867            while ((key = in.readUTF()).length() > 0) {
868                final String value = in.readUTF();
869                if (DEBUG_BACKUP) {
870                    Log.v(TAG, "Restoring lock_settings " + key + " = " + value);
871                }
872                switch (key) {
873                    case KEY_LOCK_SETTINGS_OWNER_INFO_ENABLED:
874                        lockPatternUtils.setOwnerInfoEnabled("1".equals(value),
875                                UserHandle.myUserId());
876                        break;
877                    case KEY_LOCK_SETTINGS_OWNER_INFO:
878                        lockPatternUtils.setOwnerInfo(value, UserHandle.myUserId());
879                        break;
880                }
881            }
882            in.close();
883        } catch (IOException ioe) {
884        }
885    }
886
887    private void restoreLockSettings(BackupDataInput data) {
888        final byte[] settings = new byte[data.getDataSize()];
889        try {
890            data.readEntityData(settings, 0, settings.length);
891        } catch (IOException ioe) {
892            Log.e(TAG, "Couldn't read entity data");
893            return;
894        }
895        restoreLockSettings(settings, settings.length);
896    }
897
898    /**
899     * Given a cursor and a set of keys, extract the required keys and
900     * values and write them to a byte array.
901     *
902     * @param cursor A cursor with settings data.
903     * @param settings The settings to extract.
904     * @return The byte array of extracted values.
905     */
906    private byte[] extractRelevantValues(Cursor cursor, String[] settings) {
907        final int settingsCount = settings.length;
908        byte[][] values = new byte[settingsCount * 2][]; // keys and values
909        if (!cursor.moveToFirst()) {
910            Log.e(TAG, "Couldn't read from the cursor");
911            return new byte[0];
912        }
913
914        // Obtain the relevant data in a temporary array.
915        int totalSize = 0;
916        int backedUpSettingIndex = 0;
917        Map<String, String> cachedEntries = new HashMap<String, String>();
918        for (int i = 0; i < settingsCount; i++) {
919            String key = settings[i];
920            String value = cachedEntries.remove(key);
921
922            final int nameColumnIndex = cursor.getColumnIndex(Settings.NameValueTable.NAME);
923            final int valueColumnIndex = cursor.getColumnIndex(Settings.NameValueTable.VALUE);
924
925            // If the value not cached, let us look it up.
926            if (value == null) {
927                while (!cursor.isAfterLast()) {
928                    String cursorKey = cursor.getString(nameColumnIndex);
929                    String cursorValue = cursor.getString(valueColumnIndex);
930                    cursor.moveToNext();
931                    if (key.equals(cursorKey)) {
932                        value = cursorValue;
933                        break;
934                    }
935                    cachedEntries.put(cursorKey, cursorValue);
936                }
937            }
938
939            // Intercept the keys and see if they need special handling
940            value = mSettingsHelper.onBackupValue(key, value);
941
942            if (value == null) {
943                continue;
944            }
945            // Write the key and value in the intermediary array.
946            byte[] keyBytes = key.getBytes();
947            totalSize += INTEGER_BYTE_COUNT + keyBytes.length;
948            values[backedUpSettingIndex * 2] = keyBytes;
949
950            byte[] valueBytes = value.getBytes();
951            totalSize += INTEGER_BYTE_COUNT + valueBytes.length;
952            values[backedUpSettingIndex * 2 + 1] = valueBytes;
953
954            backedUpSettingIndex++;
955
956            if (DEBUG) {
957                Log.d(TAG, "Backed up setting: " + key + "=" + value);
958            }
959        }
960
961        // Aggregate the result.
962        byte[] result = new byte[totalSize];
963        int pos = 0;
964        final int keyValuePairCount = backedUpSettingIndex * 2;
965        for (int i = 0; i < keyValuePairCount; i++) {
966            pos = writeInt(result, pos, values[i].length);
967            pos = writeBytes(result, pos, values[i]);
968        }
969        return result;
970    }
971
972    private byte[] getFileData(String filename) {
973        InputStream is = null;
974        try {
975            File file = new File(filename);
976            is = new FileInputStream(file);
977
978            //Will truncate read on a very long file,
979            //should not happen for a config file
980            byte[] bytes = new byte[(int)file.length()];
981
982            int offset = 0;
983            int numRead = 0;
984            while (offset < bytes.length
985                    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
986                offset += numRead;
987            }
988
989            //read failure
990            if (offset < bytes.length) {
991                Log.w(TAG, "Couldn't backup " + filename);
992                return EMPTY_DATA;
993            }
994            return bytes;
995        } catch (IOException ioe) {
996            Log.w(TAG, "Couldn't backup " + filename);
997            return EMPTY_DATA;
998        } finally {
999            if (is != null) {
1000                try {
1001                    is.close();
1002                } catch (IOException e) {
1003                }
1004            }
1005        }
1006
1007    }
1008
1009    private void restoreFileData(String filename, byte[] bytes, int size) {
1010        try {
1011            File file = new File(filename);
1012            if (file.exists()) file.delete();
1013
1014            OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
1015            os.write(bytes, 0, size);
1016            os.close();
1017        } catch (IOException ioe) {
1018            Log.w(TAG, "Couldn't restore " + filename);
1019        }
1020    }
1021
1022
1023    private byte[] getWifiSupplicant(String filename) {
1024        BufferedReader br = null;
1025        try {
1026            File file = new File(filename);
1027            if (!file.exists()) {
1028                return EMPTY_DATA;
1029            }
1030
1031            WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
1032            List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
1033
1034            WifiNetworkSettings fromFile = new WifiNetworkSettings();
1035            br = new BufferedReader(new FileReader(file));
1036            fromFile.readNetworks(br, configs);
1037
1038            // Write the parsed networks into a packed byte array
1039            if (fromFile.mKnownNetworks.size() > 0) {
1040                ByteArrayOutputStream bos = new ByteArrayOutputStream();
1041                OutputStreamWriter out = new OutputStreamWriter(bos);
1042                fromFile.write(out);
1043                out.flush();
1044                return bos.toByteArray();
1045            } else {
1046                return EMPTY_DATA;
1047            }
1048        } catch (IOException ioe) {
1049            Log.w(TAG, "Couldn't backup " + filename);
1050            return EMPTY_DATA;
1051        } finally {
1052            IoUtils.closeQuietly(br);
1053        }
1054    }
1055
1056    private void restoreWifiSupplicant(String filename, byte[] bytes, int size) {
1057        try {
1058            WifiNetworkSettings supplicantImage = new WifiNetworkSettings();
1059
1060            File supplicantFile = new File(FILE_WIFI_SUPPLICANT);
1061            if (supplicantFile.exists()) {
1062                // Retain the existing APs; we'll append the restored ones to them
1063                BufferedReader in = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT));
1064                supplicantImage.readNetworks(in, null);
1065                in.close();
1066
1067                supplicantFile.delete();
1068            }
1069
1070            // Incorporate the restore AP information
1071            if (size > 0) {
1072                char[] restoredAsBytes = new char[size];
1073                for (int i = 0; i < size; i++) restoredAsBytes[i] = (char) bytes[i];
1074                BufferedReader in = new BufferedReader(new CharArrayReader(restoredAsBytes));
1075                supplicantImage.readNetworks(in, null);
1076
1077                if (DEBUG_BACKUP) {
1078                    Log.v(TAG, "Final AP list:");
1079                    supplicantImage.dump();
1080                }
1081            }
1082
1083            // Install the correct default template
1084            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_WIFI_SUPPLICANT));
1085            copyWifiSupplicantTemplate(bw);
1086
1087            // Write the restored supplicant config and we're done
1088            supplicantImage.write(bw);
1089            bw.close();
1090        } catch (IOException ioe) {
1091            Log.w(TAG, "Couldn't restore " + filename);
1092        }
1093    }
1094
1095    private void copyWifiSupplicantTemplate(BufferedWriter bw) {
1096        try {
1097            BufferedReader br = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT_TEMPLATE));
1098            char[] temp = new char[1024];
1099            int size;
1100            while ((size = br.read(temp)) > 0) {
1101                bw.write(temp, 0, size);
1102            }
1103            br.close();
1104        } catch (IOException ioe) {
1105            Log.w(TAG, "Couldn't copy wpa_supplicant file");
1106        }
1107    }
1108
1109    /**
1110     * Write an int in BigEndian into the byte array.
1111     * @param out byte array
1112     * @param pos current pos in array
1113     * @param value integer to write
1114     * @return the index after adding the size of an int (4) in bytes.
1115     */
1116    private int writeInt(byte[] out, int pos, int value) {
1117        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
1118        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
1119        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
1120        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
1121        return pos + INTEGER_BYTE_COUNT;
1122    }
1123
1124    private int writeBytes(byte[] out, int pos, byte[] value) {
1125        System.arraycopy(value, 0, out, pos, value.length);
1126        return pos + value.length;
1127    }
1128
1129    private int readInt(byte[] in, int pos) {
1130        int result =
1131                ((in[pos    ] & 0xFF) << 24) |
1132                ((in[pos + 1] & 0xFF) << 16) |
1133                ((in[pos + 2] & 0xFF) <<  8) |
1134                ((in[pos + 3] & 0xFF) <<  0);
1135        return result;
1136    }
1137
1138    private int enableWifi(boolean enable) {
1139        if (mWfm == null) {
1140            mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
1141        }
1142        if (mWfm != null) {
1143            int state = mWfm.getWifiState();
1144            mWfm.setWifiEnabled(enable);
1145            return state;
1146        } else {
1147            Log.e(TAG, "Failed to fetch WifiManager instance");
1148        }
1149        return WifiManager.WIFI_STATE_UNKNOWN;
1150    }
1151}
1152