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