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