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