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