SettingsBackupAgent.java revision 2efd2dbbac9eac89620683696c6076463c3a1cd6
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 java.io.BufferedOutputStream;
20import java.io.BufferedReader;
21import java.io.BufferedWriter;
22import java.io.DataInputStream;
23import java.io.DataOutputStream;
24import java.io.EOFException;
25import java.io.File;
26import java.io.FileInputStream;
27import java.io.FileOutputStream;
28import java.io.FileReader;
29import java.io.FileWriter;
30import java.io.InputStream;
31import java.io.IOException;
32import java.io.OutputStream;
33import java.util.Arrays;
34import java.util.zip.CRC32;
35
36import android.app.backup.BackupDataInput;
37import android.app.backup.BackupDataOutput;
38import android.app.backup.BackupAgentHelper;
39import android.app.backup.FullBackupDataOutput;
40import android.content.ContentValues;
41import android.content.Context;
42import android.database.Cursor;
43import android.net.Uri;
44import android.net.wifi.WifiManager;
45import android.os.FileUtils;
46import android.os.ParcelFileDescriptor;
47import android.os.Process;
48import android.provider.Settings;
49import android.text.TextUtils;
50import android.util.Log;
51
52/**
53 * Performs backup and restore of the System and Secure settings.
54 * List of settings that are backed up are stored in the Settings.java file
55 */
56public class SettingsBackupAgent extends BackupAgentHelper {
57    private static final boolean DEBUG = false;
58    private static final boolean DEBUG_BACKUP = DEBUG || true;
59
60    private static final String KEY_SYSTEM = "system";
61    private static final String KEY_SECURE = "secure";
62    private static final String KEY_LOCALE = "locale";
63
64    //Version 2 adds STATE_WIFI_CONFIG
65    private static final int STATE_VERSION_1       = 1;
66    private static final int STATE_VERSION_1_SIZE  = 4;
67
68    // Versioning of the state file.  Increment this version
69    // number any time the set of state items is altered.
70    private static final int STATE_VERSION = 2;
71
72    private static final int STATE_SYSTEM          = 0;
73    private static final int STATE_SECURE          = 1;
74    private static final int STATE_LOCALE          = 2;
75    private static final int STATE_WIFI_SUPPLICANT = 3;
76    private static final int STATE_WIFI_CONFIG     = 4;
77    private static final int STATE_SIZE            = 5; // The number of state items
78
79    // Versioning of the 'full backup' format
80    private static final int FULL_BACKUP_VERSION = 1;
81
82    private static String[] sortedSystemKeys = null;
83    private static String[] sortedSecureKeys = null;
84
85    private static final byte[] EMPTY_DATA = new byte[0];
86
87    private static final String TAG = "SettingsBackupAgent";
88
89    private static final int COLUMN_NAME = 1;
90    private static final int COLUMN_VALUE = 2;
91
92    private static final String[] PROJECTION = {
93        Settings.NameValueTable._ID,
94        Settings.NameValueTable.NAME,
95        Settings.NameValueTable.VALUE
96    };
97
98    private static final String FILE_WIFI_SUPPLICANT = "/data/misc/wifi/wpa_supplicant.conf";
99    private static final String FILE_WIFI_SUPPLICANT_TEMPLATE =
100            "/system/etc/wifi/wpa_supplicant.conf";
101
102    // the key to store the WIFI data under, should be sorted as last, so restore happens last.
103    // use very late unicode character to quasi-guarantee last sort position.
104    private static final String KEY_WIFI_SUPPLICANT = "\uffedWIFI";
105    private static final String KEY_WIFI_CONFIG = "\uffedCONFIG_WIFI";
106
107    // Name of the temporary file we use during full backup/restore.  This is
108    // stored in the full-backup tarfile as well, so should not be changed.
109    private static final String STAGE_FILE = "flattened-data";
110
111    private SettingsHelper mSettingsHelper;
112    private WifiManager mWfm;
113    private static String mWifiConfigFile;
114
115    public void onCreate() {
116        if (DEBUG_BACKUP) Log.d(TAG, "onCreate() invoked");
117
118        mSettingsHelper = new SettingsHelper(this);
119        super.onCreate();
120
121        WifiManager mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
122        if (mWfm != null) mWifiConfigFile = mWfm.getConfigFile();
123    }
124
125    @Override
126    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
127            ParcelFileDescriptor newState) throws IOException {
128
129        byte[] systemSettingsData = getSystemSettings();
130        byte[] secureSettingsData = getSecureSettings();
131        byte[] locale = mSettingsHelper.getLocaleData();
132        byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
133        byte[] wifiConfigData = getFileData(mWifiConfigFile);
134
135        long[] stateChecksums = readOldChecksums(oldState);
136
137        stateChecksums[STATE_SYSTEM] =
138            writeIfChanged(stateChecksums[STATE_SYSTEM], KEY_SYSTEM, systemSettingsData, data);
139        stateChecksums[STATE_SECURE] =
140            writeIfChanged(stateChecksums[STATE_SECURE], KEY_SECURE, secureSettingsData, data);
141        stateChecksums[STATE_LOCALE] =
142            writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
143        stateChecksums[STATE_WIFI_SUPPLICANT] =
144            writeIfChanged(stateChecksums[STATE_WIFI_SUPPLICANT], KEY_WIFI_SUPPLICANT,
145                    wifiSupplicantData, data);
146        stateChecksums[STATE_WIFI_CONFIG] =
147            writeIfChanged(stateChecksums[STATE_WIFI_CONFIG], KEY_WIFI_CONFIG, wifiConfigData,
148                    data);
149
150        writeNewChecksums(stateChecksums, newState);
151    }
152
153    @Override
154    public void onRestore(BackupDataInput data, int appVersionCode,
155            ParcelFileDescriptor newState) throws IOException {
156
157        while (data.readNextHeader()) {
158            final String key = data.getKey();
159            final int size = data.getDataSize();
160            if (KEY_SYSTEM.equals(key)) {
161                restoreSettings(data, Settings.System.CONTENT_URI);
162                mSettingsHelper.applyAudioSettings();
163            } else if (KEY_SECURE.equals(key)) {
164                restoreSettings(data, Settings.Secure.CONTENT_URI);
165            } else if (KEY_WIFI_SUPPLICANT.equals(key)) {
166                int retainedWifiState = enableWifi(false);
167                restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, data);
168                FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
169                        FileUtils.S_IRUSR | FileUtils.S_IWUSR |
170                        FileUtils.S_IRGRP | FileUtils.S_IWGRP,
171                        Process.myUid(), Process.WIFI_UID);
172                // retain the previous WIFI state.
173                enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
174                        retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
175            } else if (KEY_LOCALE.equals(key)) {
176                byte[] localeData = new byte[size];
177                data.readEntityData(localeData, 0, size);
178                mSettingsHelper.setLocaleData(localeData, size);
179            } else if (KEY_WIFI_CONFIG.equals(key)) {
180                restoreFileData(mWifiConfigFile, data);
181             } else {
182                data.skipEntityData();
183            }
184        }
185    }
186
187    @Override
188    public void onFullBackup(FullBackupDataOutput data)  throws IOException {
189        byte[] systemSettingsData = getSystemSettings();
190        byte[] secureSettingsData = getSecureSettings();
191        byte[] locale = mSettingsHelper.getLocaleData();
192        byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
193        byte[] wifiConfigData = getFileData(mWifiConfigFile);
194
195        // Write the data to the staging file, then emit that as our tarfile
196        // representation of the backed-up settings.
197        String root = getFilesDir().getAbsolutePath();
198        File stage = new File(root, STAGE_FILE);
199        try {
200            FileOutputStream filestream = new FileOutputStream(stage);
201            BufferedOutputStream bufstream = new BufferedOutputStream(filestream);
202            DataOutputStream out = new DataOutputStream(bufstream);
203
204            if (DEBUG_BACKUP) Log.d(TAG, "Writing flattened data version " + FULL_BACKUP_VERSION);
205            out.writeInt(FULL_BACKUP_VERSION);
206
207            if (DEBUG_BACKUP) Log.d(TAG, systemSettingsData.length + " bytes of settings data");
208            out.writeInt(systemSettingsData.length);
209            out.write(systemSettingsData);
210            if (DEBUG_BACKUP) Log.d(TAG, secureSettingsData.length + " bytes of secure settings data");
211            out.writeInt(secureSettingsData.length);
212            out.write(secureSettingsData);
213            if (DEBUG_BACKUP) Log.d(TAG, locale.length + " bytes of locale data");
214            out.writeInt(locale.length);
215            out.write(locale);
216            if (DEBUG_BACKUP) Log.d(TAG, wifiSupplicantData.length + " bytes of wifi supplicant data");
217            out.writeInt(wifiSupplicantData.length);
218            out.write(wifiSupplicantData);
219            if (DEBUG_BACKUP) Log.d(TAG, wifiConfigData.length + " bytes of wifi config data");
220            out.writeInt(wifiConfigData.length);
221            out.write(wifiConfigData);
222
223            out.flush();    // also flushes downstream
224
225            // now we're set to emit the tar stream
226            fullBackupFile(stage, data);
227        } finally {
228            stage.delete();
229        }
230    }
231
232    @Override
233    public void onRestoreFile(ParcelFileDescriptor data, long size,
234            int type, String domain, String relpath, long mode, long mtime)
235            throws IOException {
236        if (DEBUG_BACKUP) Log.d(TAG, "onRestoreFile() invoked");
237        // Our data is actually a blob of flattened settings data identical to that
238        // produced during incremental backups.  Just unpack and apply it all in
239        // turn.
240        FileInputStream instream = new FileInputStream(data.getFileDescriptor());
241        DataInputStream in = new DataInputStream(instream);
242
243        int version = in.readInt();
244        if (DEBUG_BACKUP) Log.d(TAG, "Flattened data version " + version);
245        if (version == FULL_BACKUP_VERSION) {
246            // system settings data first
247            int nBytes = in.readInt();
248            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of settings data");
249            byte[] buffer = new byte[nBytes];
250            in.readFully(buffer, 0, nBytes);
251            restoreSettings(buffer, nBytes, Settings.System.CONTENT_URI);
252
253            // secure settings
254            nBytes = in.readInt();
255            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of secure settings data");
256            if (nBytes > buffer.length) buffer = new byte[nBytes];
257            in.readFully(buffer, 0, nBytes);
258            restoreSettings(buffer, nBytes, Settings.Secure.CONTENT_URI);
259
260            // locale
261            nBytes = in.readInt();
262            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of locale data");
263            if (nBytes > buffer.length) buffer = new byte[nBytes];
264            in.readFully(buffer, 0, nBytes);
265            mSettingsHelper.setLocaleData(buffer, nBytes);
266
267            // wifi supplicant
268            nBytes = in.readInt();
269            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi supplicant data");
270            if (nBytes > buffer.length) buffer = new byte[nBytes];
271            in.readFully(buffer, 0, nBytes);
272            int retainedWifiState = enableWifi(false);
273            restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, buffer, nBytes);
274            FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
275                    FileUtils.S_IRUSR | FileUtils.S_IWUSR |
276                    FileUtils.S_IRGRP | FileUtils.S_IWGRP,
277                    Process.myUid(), Process.WIFI_UID);
278            // retain the previous WIFI state.
279            enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
280                    retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
281
282            // wifi config
283            nBytes = in.readInt();
284            if (DEBUG_BACKUP) Log.d(TAG, nBytes + " bytes of wifi config data");
285            if (nBytes > buffer.length) buffer = new byte[nBytes];
286            in.readFully(buffer, 0, nBytes);
287            restoreFileData(mWifiConfigFile, buffer, nBytes);
288
289            if (DEBUG_BACKUP) Log.d(TAG, "Full restore complete.");
290        } else {
291            data.close();
292            throw new IOException("Invalid file schema");
293        }
294    }
295
296    private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
297        long[] stateChecksums = new long[STATE_SIZE];
298
299        DataInputStream dataInput = new DataInputStream(
300                new FileInputStream(oldState.getFileDescriptor()));
301
302        try {
303            int stateVersion = dataInput.readInt();
304            if (stateVersion == STATE_VERSION_1) {
305                for (int i = 0; i < STATE_VERSION_1_SIZE; i++) {
306                    stateChecksums[i] = dataInput.readLong();
307                }
308            } else if (stateVersion == STATE_VERSION) {
309                for (int i = 0; i < STATE_SIZE; i++) {
310                    stateChecksums[i] = dataInput.readLong();
311                }
312            }
313        } catch (EOFException eof) {
314            // With the default 0 checksum we'll wind up forcing a backup of
315            // any unhandled data sets, which is appropriate.
316        }
317        dataInput.close();
318        return stateChecksums;
319    }
320
321    private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
322            throws IOException {
323        DataOutputStream dataOutput = new DataOutputStream(
324                new FileOutputStream(newState.getFileDescriptor()));
325
326        dataOutput.writeInt(STATE_VERSION);
327        for (int i = 0; i < STATE_SIZE; i++) {
328            dataOutput.writeLong(checksums[i]);
329        }
330        dataOutput.close();
331    }
332
333    private long writeIfChanged(long oldChecksum, String key, byte[] data,
334            BackupDataOutput output) {
335        CRC32 checkSummer = new CRC32();
336        checkSummer.update(data);
337        long newChecksum = checkSummer.getValue();
338        if (oldChecksum == newChecksum) {
339            return oldChecksum;
340        }
341        try {
342            output.writeEntityHeader(key, data.length);
343            output.writeEntityData(data, data.length);
344        } catch (IOException ioe) {
345            // Bail
346        }
347        return newChecksum;
348    }
349
350    private byte[] getSystemSettings() {
351        Cursor sortedCursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION,
352                null, null, Settings.NameValueTable.NAME);
353        // Copy and sort the array
354        if (sortedSystemKeys == null) {
355            sortedSystemKeys = copyAndSort(Settings.System.SETTINGS_TO_BACKUP);
356        }
357        byte[] result = extractRelevantValues(sortedCursor, sortedSystemKeys);
358        sortedCursor.close();
359        return result;
360    }
361
362    private byte[] getSecureSettings() {
363        Cursor sortedCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION,
364                null, null, Settings.NameValueTable.NAME);
365        // Copy and sort the array
366        if (sortedSecureKeys == null) {
367            sortedSecureKeys = copyAndSort(Settings.Secure.SETTINGS_TO_BACKUP);
368        }
369        byte[] result = extractRelevantValues(sortedCursor, sortedSecureKeys);
370        sortedCursor.close();
371        return result;
372    }
373
374    private void restoreSettings(BackupDataInput data, Uri contentUri) {
375        byte[] settings = new byte[data.getDataSize()];
376        try {
377            data.readEntityData(settings, 0, settings.length);
378        } catch (IOException ioe) {
379            Log.e(TAG, "Couldn't read entity data");
380            return;
381        }
382        restoreSettings(settings, settings.length, contentUri);
383    }
384
385    private void restoreSettings(byte[] settings, int bytes, Uri contentUri) {
386        if (DEBUG) Log.i(TAG, "restoreSettings: " + contentUri);
387        String[] whitelist = null;
388        if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
389            whitelist = Settings.Secure.SETTINGS_TO_BACKUP;
390        } else if (contentUri.equals(Settings.System.CONTENT_URI)) {
391            whitelist = Settings.System.SETTINGS_TO_BACKUP;
392        }
393
394        ContentValues cv = new ContentValues(2);
395        int pos = 0;
396        while (pos < bytes) {
397            int length = readInt(settings, pos);
398            pos += 4;
399            String settingName = length > 0? new String(settings, pos, length) : null;
400            pos += length;
401            length = readInt(settings, pos);
402            pos += 4;
403            String settingValue = length > 0? new String(settings, pos, length) : null;
404            pos += length;
405            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
406                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
407
408                // Only restore settings in our list of known-acceptable data
409                if (invalidSavedSetting(whitelist, settingName)) {
410                    continue;
411                }
412
413                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
414                    cv.clear();
415                    cv.put(Settings.NameValueTable.NAME, settingName);
416                    cv.put(Settings.NameValueTable.VALUE, settingValue);
417                    getContentResolver().insert(contentUri, cv);
418                }
419            }
420        }
421    }
422
423    // Returns 'true' if the given setting is one that we refuse to restore
424    private boolean invalidSavedSetting(String[] knownNames, String candidate) {
425        // no filter? allow everything
426        if (knownNames == null) {
427            return false;
428        }
429
430        // whitelisted setting?  allow it
431        for (String name : knownNames) {
432            if (name.equals(candidate)) {
433                return false;
434            }
435        }
436
437        // refuse everything else
438        if (DEBUG) Log.v(TAG, "Ignoring restore datum: " + candidate);
439        return true;
440    }
441
442    private String[] copyAndSort(String[] keys) {
443        String[] sortedKeys = new String[keys.length];
444        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
445        Arrays.sort(sortedKeys);
446        return sortedKeys;
447    }
448
449    /**
450     * Given a cursor sorted by key name and a set of keys sorted by name,
451     * extract the required keys and values and write them to a byte array.
452     * @param sortedCursor
453     * @param sortedKeys
454     * @return
455     */
456    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
457        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
458        if (!sortedCursor.moveToFirst()) {
459            Log.e(TAG, "Couldn't read from the cursor");
460            return new byte[0];
461        }
462        int keyIndex = 0;
463        int totalSize = 0;
464        while (!sortedCursor.isAfterLast()) {
465            String name = sortedCursor.getString(COLUMN_NAME);
466            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
467                keyIndex++;
468                if (keyIndex == sortedKeys.length) break;
469            }
470            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
471                String value = sortedCursor.getString(COLUMN_VALUE);
472                byte[] nameBytes = name.toString().getBytes();
473                totalSize += 4 + nameBytes.length;
474                values[keyIndex * 2] = nameBytes;
475                byte[] valueBytes;
476                if (TextUtils.isEmpty(value)) {
477                    valueBytes = null;
478                    totalSize += 4;
479                } else {
480                    valueBytes = value.toString().getBytes();
481                    totalSize += 4 + valueBytes.length;
482                    //Log.i(TAG, "Backing up " + name + " = " + value);
483                }
484                values[keyIndex * 2 + 1] = valueBytes;
485                keyIndex++;
486            }
487            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
488                break;
489            }
490        }
491
492        byte[] result = new byte[totalSize];
493        int pos = 0;
494        for (int i = 0; i < sortedKeys.length * 2; i++) {
495            if (values[i] != null) {
496                pos = writeInt(result, pos, values[i].length);
497                pos = writeBytes(result, pos, values[i]);
498            }
499        }
500        return result;
501    }
502
503    private byte[] getFileData(String filename) {
504        InputStream is = null;
505        try {
506            File file = new File(filename);
507            is = new FileInputStream(file);
508
509            //Will truncate read on a very long file,
510            //should not happen for a config file
511            byte[] bytes = new byte[(int)file.length()];
512
513            int offset = 0;
514            int numRead = 0;
515            while (offset < bytes.length
516                    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
517                offset += numRead;
518            }
519
520            //read failure
521            if (offset < bytes.length) {
522                Log.w(TAG, "Couldn't backup " + filename);
523                return EMPTY_DATA;
524            }
525            return bytes;
526        } catch (IOException ioe) {
527            Log.w(TAG, "Couldn't backup " + filename);
528            return EMPTY_DATA;
529        } finally {
530            if (is != null) {
531                try {
532                    is.close();
533                } catch (IOException e) {
534                }
535            }
536        }
537
538    }
539
540    private void restoreFileData(String filename, BackupDataInput data) {
541        byte[] bytes = new byte[data.getDataSize()];
542        if (bytes.length <= 0) return;
543        try {
544            data.readEntityData(bytes, 0, data.getDataSize());
545            restoreFileData(filename, bytes, bytes.length);
546        } catch (IOException e) {
547            Log.w(TAG, "Unable to read file data for " + filename);
548        }
549    }
550
551    private void restoreFileData(String filename, byte[] bytes, int size) {
552        try {
553            File file = new File(filename);
554            if (file.exists()) file.delete();
555
556            OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
557            os.write(bytes, 0, size);
558            os.close();
559        } catch (IOException ioe) {
560            Log.w(TAG, "Couldn't restore " + filename);
561        }
562    }
563
564
565    private byte[] getWifiSupplicant(String filename) {
566        BufferedReader br = null;
567        try {
568            File file = new File(filename);
569            if (file.exists()) {
570                br = new BufferedReader(new FileReader(file));
571                StringBuffer relevantLines = new StringBuffer();
572                boolean started = false;
573                String line;
574                while ((line = br.readLine()) != null) {
575                    if (!started && line.startsWith("network")) {
576                        started = true;
577                    }
578                    if (started) {
579                        relevantLines.append(line).append("\n");
580                    }
581                }
582                if (relevantLines.length() > 0) {
583                    return relevantLines.toString().getBytes();
584                } else {
585                    return EMPTY_DATA;
586                }
587            } else {
588                return EMPTY_DATA;
589            }
590        } catch (IOException ioe) {
591            Log.w(TAG, "Couldn't backup " + filename);
592            return EMPTY_DATA;
593        } finally {
594            if (br != null) {
595                try {
596                    br.close();
597                } catch (IOException e) {
598                }
599            }
600        }
601    }
602
603    private void restoreWifiSupplicant(String filename, BackupDataInput data) {
604        byte[] bytes = new byte[data.getDataSize()];
605        if (bytes.length <= 0) return;
606        try {
607            data.readEntityData(bytes, 0, data.getDataSize());
608            restoreWifiSupplicant(filename, bytes, bytes.length);
609        } catch (IOException e) {
610            Log.w(TAG, "Unable to read supplicant data");
611        }
612    }
613
614    private void restoreWifiSupplicant(String filename, byte[] bytes, int size) {
615        try {
616            File supplicantFile = new File(FILE_WIFI_SUPPLICANT);
617            if (supplicantFile.exists()) supplicantFile.delete();
618            copyWifiSupplicantTemplate();
619
620            OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
621            os.write("\n".getBytes());
622            os.write(bytes, 0, size);
623            os.close();
624        } catch (IOException ioe) {
625            Log.w(TAG, "Couldn't restore " + filename);
626        }
627    }
628
629    private void copyWifiSupplicantTemplate() {
630        try {
631            BufferedReader br = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT_TEMPLATE));
632            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_WIFI_SUPPLICANT));
633            char[] temp = new char[1024];
634            int size;
635            while ((size = br.read(temp)) > 0) {
636                bw.write(temp, 0, size);
637            }
638            bw.close();
639            br.close();
640        } catch (IOException ioe) {
641            Log.w(TAG, "Couldn't copy wpa_supplicant file");
642        }
643    }
644
645    /**
646     * Write an int in BigEndian into the byte array.
647     * @param out byte array
648     * @param pos current pos in array
649     * @param value integer to write
650     * @return the index after adding the size of an int (4)
651     */
652    private int writeInt(byte[] out, int pos, int value) {
653        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
654        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
655        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
656        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
657        return pos + 4;
658    }
659
660    private int writeBytes(byte[] out, int pos, byte[] value) {
661        System.arraycopy(value, 0, out, pos, value.length);
662        return pos + value.length;
663    }
664
665    private int readInt(byte[] in, int pos) {
666        int result =
667                ((in[pos    ] & 0xFF) << 24) |
668                ((in[pos + 1] & 0xFF) << 16) |
669                ((in[pos + 2] & 0xFF) <<  8) |
670                ((in[pos + 3] & 0xFF) <<  0);
671        return result;
672    }
673
674    private int enableWifi(boolean enable) {
675        if (mWfm != null) {
676            int state = mWfm.getWifiState();
677            mWfm.setWifiEnabled(enable);
678            return state;
679        }
680        return WifiManager.WIFI_STATE_UNKNOWN;
681    }
682}
683