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