SettingsBackupAgent.java revision 4aeca7c5908387bc7efb0785830aea1053264062
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.content.ContentValues;
40import android.content.Context;
41import android.database.Cursor;
42import android.net.Uri;
43import android.net.wifi.WifiManager;
44import android.os.FileUtils;
45import android.os.ParcelFileDescriptor;
46import android.os.Process;
47import android.provider.Settings;
48import android.text.TextUtils;
49import android.util.Log;
50
51/**
52 * Performs backup and restore of the System and Secure settings.
53 * List of settings that are backed up are stored in the Settings.java file
54 */
55public class SettingsBackupAgent extends BackupAgentHelper {
56    private static final boolean DEBUG = false;
57
58    private static final String KEY_SYSTEM = "system";
59    private static final String KEY_SECURE = "secure";
60    private static final String KEY_LOCALE = "locale";
61
62    //Version 2 adds STATE_WIFI_CONFIG
63    private static final int STATE_VERSION_1       = 1;
64    private static final int STATE_VERSION_1_SIZE  = 4;
65
66    // Versioning of the state file.  Increment this version
67    // number any time the set of state items is altered.
68    private static final int STATE_VERSION = 2;
69
70    private static final int STATE_SYSTEM          = 0;
71    private static final int STATE_SECURE          = 1;
72    private static final int STATE_LOCALE          = 2;
73    private static final int STATE_WIFI_SUPPLICANT = 3;
74    private static final int STATE_WIFI_CONFIG     = 4;
75    private static final int STATE_SIZE            = 5; // The number of state items
76
77    private static String[] sortedSystemKeys = null;
78    private static String[] sortedSecureKeys = null;
79
80    private static final byte[] EMPTY_DATA = new byte[0];
81
82    private static final String TAG = "SettingsBackupAgent";
83
84    private static final int COLUMN_NAME = 1;
85    private static final int COLUMN_VALUE = 2;
86
87    private static final String[] PROJECTION = {
88        Settings.NameValueTable._ID,
89        Settings.NameValueTable.NAME,
90        Settings.NameValueTable.VALUE
91    };
92
93    private static final String FILE_WIFI_SUPPLICANT = "/data/misc/wifi/wpa_supplicant.conf";
94    private static final String FILE_WIFI_SUPPLICANT_TEMPLATE =
95            "/system/etc/wifi/wpa_supplicant.conf";
96
97    // the key to store the WIFI data under, should be sorted as last, so restore happens last.
98    // use very late unicode character to quasi-guarantee last sort position.
99    private static final String KEY_WIFI_SUPPLICANT = "\uffedWIFI";
100    private static final String KEY_WIFI_CONFIG = "\uffedCONFIG_WIFI";
101
102    private SettingsHelper mSettingsHelper;
103    private WifiManager mWfm;
104    private static String mWifiConfigFile;
105
106    public void onCreate() {
107        mSettingsHelper = new SettingsHelper(this);
108        super.onCreate();
109
110        WifiManager mWfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
111        if (mWfm != null) mWifiConfigFile = mWfm.getConfigFile();
112    }
113
114    @Override
115    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
116            ParcelFileDescriptor newState) throws IOException {
117
118        byte[] systemSettingsData = getSystemSettings();
119        byte[] secureSettingsData = getSecureSettings();
120        byte[] locale = mSettingsHelper.getLocaleData();
121        byte[] wifiSupplicantData = getWifiSupplicant(FILE_WIFI_SUPPLICANT);
122        byte[] wifiConfigData = getFileData(mWifiConfigFile);
123
124        long[] stateChecksums = readOldChecksums(oldState);
125
126        stateChecksums[STATE_SYSTEM] =
127                writeIfChanged(stateChecksums[STATE_SYSTEM], KEY_SYSTEM, systemSettingsData, data);
128        stateChecksums[STATE_SECURE] =
129                writeIfChanged(stateChecksums[STATE_SECURE], KEY_SECURE, secureSettingsData, data);
130        stateChecksums[STATE_LOCALE] =
131                writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
132        stateChecksums[STATE_WIFI_SUPPLICANT] =
133                writeIfChanged(stateChecksums[STATE_WIFI_SUPPLICANT], KEY_WIFI_SUPPLICANT,
134                wifiSupplicantData, data);
135        stateChecksums[STATE_WIFI_CONFIG] =
136                writeIfChanged(stateChecksums[STATE_WIFI_CONFIG], KEY_WIFI_CONFIG, wifiConfigData,
137                data);
138
139        writeNewChecksums(stateChecksums, newState);
140    }
141
142    @Override
143    public void onRestore(BackupDataInput data, int appVersionCode,
144            ParcelFileDescriptor newState) throws IOException {
145
146        while (data.readNextHeader()) {
147            final String key = data.getKey();
148            final int size = data.getDataSize();
149            if (KEY_SYSTEM.equals(key)) {
150                restoreSettings(data, Settings.System.CONTENT_URI);
151                mSettingsHelper.applyAudioSettings();
152            } else if (KEY_SECURE.equals(key)) {
153                restoreSettings(data, Settings.Secure.CONTENT_URI);
154            } else if (KEY_WIFI_SUPPLICANT.equals(key)) {
155                int retainedWifiState = enableWifi(false);
156                restoreWifiSupplicant(FILE_WIFI_SUPPLICANT, data);
157                FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
158                        FileUtils.S_IRUSR | FileUtils.S_IWUSR |
159                        FileUtils.S_IRGRP | FileUtils.S_IWGRP,
160                        Process.myUid(), Process.WIFI_UID);
161                // retain the previous WIFI state.
162                enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
163                        retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
164            } else if (KEY_LOCALE.equals(key)) {
165                byte[] localeData = new byte[size];
166                data.readEntityData(localeData, 0, size);
167                mSettingsHelper.setLocaleData(localeData);
168            } else if (KEY_WIFI_CONFIG.equals(key)) {
169                restoreFileData(mWifiConfigFile, data);
170             } else {
171                data.skipEntityData();
172            }
173        }
174    }
175
176    private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
177        long[] stateChecksums = new long[STATE_SIZE];
178
179        DataInputStream dataInput = new DataInputStream(
180                new FileInputStream(oldState.getFileDescriptor()));
181
182        try {
183            int stateVersion = dataInput.readInt();
184            if (stateVersion == STATE_VERSION_1) {
185                for (int i = 0; i < STATE_VERSION_1_SIZE; i++) {
186                    stateChecksums[i] = dataInput.readLong();
187                }
188            } else if (stateVersion == STATE_VERSION) {
189                for (int i = 0; i < STATE_SIZE; i++) {
190                    stateChecksums[i] = dataInput.readLong();
191                }
192            }
193        } catch (EOFException eof) {
194            // With the default 0 checksum we'll wind up forcing a backup of
195            // any unhandled data sets, which is appropriate.
196        }
197        dataInput.close();
198        return stateChecksums;
199    }
200
201    private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
202            throws IOException {
203        DataOutputStream dataOutput = new DataOutputStream(
204                new FileOutputStream(newState.getFileDescriptor()));
205
206        dataOutput.writeInt(STATE_VERSION);
207        for (int i = 0; i < STATE_SIZE; i++) {
208            dataOutput.writeLong(checksums[i]);
209        }
210        dataOutput.close();
211    }
212
213    private long writeIfChanged(long oldChecksum, String key, byte[] data,
214            BackupDataOutput output) {
215        CRC32 checkSummer = new CRC32();
216        checkSummer.update(data);
217        long newChecksum = checkSummer.getValue();
218        if (oldChecksum == newChecksum) {
219            return oldChecksum;
220        }
221        try {
222            output.writeEntityHeader(key, data.length);
223            output.writeEntityData(data, data.length);
224        } catch (IOException ioe) {
225            // Bail
226        }
227        return newChecksum;
228    }
229
230    private byte[] getSystemSettings() {
231        Cursor sortedCursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION,
232                null, null, Settings.NameValueTable.NAME);
233        // Copy and sort the array
234        if (sortedSystemKeys == null) {
235            sortedSystemKeys = copyAndSort(Settings.System.SETTINGS_TO_BACKUP);
236        }
237        byte[] result = extractRelevantValues(sortedCursor, sortedSystemKeys);
238        sortedCursor.close();
239        return result;
240    }
241
242    private byte[] getSecureSettings() {
243        Cursor sortedCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION,
244                null, null, Settings.NameValueTable.NAME);
245        // Copy and sort the array
246        if (sortedSecureKeys == null) {
247            sortedSecureKeys = copyAndSort(Settings.Secure.SETTINGS_TO_BACKUP);
248        }
249        byte[] result = extractRelevantValues(sortedCursor, sortedSecureKeys);
250        sortedCursor.close();
251        return result;
252    }
253
254    private void restoreSettings(BackupDataInput data, Uri contentUri) {
255        if (DEBUG) Log.i(TAG, "restoreSettings: " + contentUri);
256        String[] whitelist = null;
257        if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
258            whitelist = Settings.Secure.SETTINGS_TO_BACKUP;
259        } else if (contentUri.equals(Settings.System.CONTENT_URI)) {
260            whitelist = Settings.System.SETTINGS_TO_BACKUP;
261        }
262
263        ContentValues cv = new ContentValues(2);
264        byte[] settings = new byte[data.getDataSize()];
265        try {
266            data.readEntityData(settings, 0, settings.length);
267        } catch (IOException ioe) {
268            Log.e(TAG, "Couldn't read entity data");
269            return;
270        }
271        int pos = 0;
272        while (pos < settings.length) {
273            int length = readInt(settings, pos);
274            pos += 4;
275            String settingName = length > 0? new String(settings, pos, length) : null;
276            pos += length;
277            length = readInt(settings, pos);
278            pos += 4;
279            String settingValue = length > 0? new String(settings, pos, length) : null;
280            pos += length;
281            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
282                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
283
284                // Only restore settings in our list of known-acceptable data
285                if (invalidSavedSetting(whitelist, settingName)) {
286                    continue;
287                }
288
289                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
290                    cv.clear();
291                    cv.put(Settings.NameValueTable.NAME, settingName);
292                    cv.put(Settings.NameValueTable.VALUE, settingValue);
293                    getContentResolver().insert(contentUri, cv);
294                }
295            }
296        }
297    }
298
299    // Returns 'true' if the given setting is one that we refuse to restore
300    private boolean invalidSavedSetting(String[] knownNames, String candidate) {
301        // no filter? allow everything
302        if (knownNames == null) {
303            return false;
304        }
305
306        // whitelisted setting?  allow it
307        for (String name : knownNames) {
308            if (name.equals(candidate)) {
309                return false;
310            }
311        }
312
313        // refuse everything else
314        if (DEBUG) Log.v(TAG, "Ignoring restore datum: " + candidate);
315        return true;
316    }
317
318    private String[] copyAndSort(String[] keys) {
319        String[] sortedKeys = new String[keys.length];
320        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
321        Arrays.sort(sortedKeys);
322        return sortedKeys;
323    }
324
325    /**
326     * Given a cursor sorted by key name and a set of keys sorted by name,
327     * extract the required keys and values and write them to a byte array.
328     * @param sortedCursor
329     * @param sortedKeys
330     * @return
331     */
332    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
333        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
334        if (!sortedCursor.moveToFirst()) {
335            Log.e(TAG, "Couldn't read from the cursor");
336            return new byte[0];
337        }
338        int keyIndex = 0;
339        int totalSize = 0;
340        while (!sortedCursor.isAfterLast()) {
341            String name = sortedCursor.getString(COLUMN_NAME);
342            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
343                keyIndex++;
344                if (keyIndex == sortedKeys.length) break;
345            }
346            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
347                String value = sortedCursor.getString(COLUMN_VALUE);
348                byte[] nameBytes = name.toString().getBytes();
349                totalSize += 4 + nameBytes.length;
350                values[keyIndex * 2] = nameBytes;
351                byte[] valueBytes;
352                if (TextUtils.isEmpty(value)) {
353                    valueBytes = null;
354                    totalSize += 4;
355                } else {
356                    valueBytes = value.toString().getBytes();
357                    totalSize += 4 + valueBytes.length;
358                    //Log.i(TAG, "Backing up " + name + " = " + value);
359                }
360                values[keyIndex * 2 + 1] = valueBytes;
361                keyIndex++;
362            }
363            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
364                break;
365            }
366        }
367
368        byte[] result = new byte[totalSize];
369        int pos = 0;
370        for (int i = 0; i < sortedKeys.length * 2; i++) {
371            if (values[i] != null) {
372                pos = writeInt(result, pos, values[i].length);
373                pos = writeBytes(result, pos, values[i]);
374            }
375        }
376        return result;
377    }
378
379    private byte[] getFileData(String filename) {
380        InputStream is = null;
381        try {
382            File file = new File(filename);
383            is = new FileInputStream(file);
384
385            //Will truncate read on a very long file,
386            //should not happen for a config file
387            byte[] bytes = new byte[(int)file.length()];
388
389            int offset = 0;
390            int numRead = 0;
391            while (offset < bytes.length
392                    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
393                offset += numRead;
394            }
395
396            //read failure
397            if (offset < bytes.length) {
398                Log.w(TAG, "Couldn't backup " + filename);
399                return EMPTY_DATA;
400            }
401            return bytes;
402        } catch (IOException ioe) {
403            Log.w(TAG, "Couldn't backup " + filename);
404            return EMPTY_DATA;
405        } finally {
406            if (is != null) {
407                try {
408                    is.close();
409                } catch (IOException e) {
410                }
411            }
412        }
413
414    }
415
416    private void restoreFileData(String filename, BackupDataInput data) {
417        byte[] bytes = new byte[data.getDataSize()];
418        if (bytes.length <= 0) return;
419        try {
420            data.readEntityData(bytes, 0, bytes.length);
421            File file = new File(filename);
422            if (file.exists()) file.delete();
423
424            OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
425            os.write(bytes);
426            os.close();
427        } catch (IOException ioe) {
428            Log.w(TAG, "Couldn't restore " + filename);
429        }
430    }
431
432
433    private byte[] getWifiSupplicant(String filename) {
434        BufferedReader br = null;
435        try {
436            File file = new File(filename);
437            if (file.exists()) {
438                br = new BufferedReader(new FileReader(file));
439                StringBuffer relevantLines = new StringBuffer();
440                boolean started = false;
441                String line;
442                while ((line = br.readLine()) != null) {
443                    if (!started && line.startsWith("network")) {
444                        started = true;
445                    }
446                    if (started) {
447                        relevantLines.append(line).append("\n");
448                    }
449                }
450                if (relevantLines.length() > 0) {
451                    return relevantLines.toString().getBytes();
452                } else {
453                    return EMPTY_DATA;
454                }
455            } else {
456                return EMPTY_DATA;
457            }
458        } catch (IOException ioe) {
459            Log.w(TAG, "Couldn't backup " + filename);
460            return EMPTY_DATA;
461        } finally {
462            if (br != null) {
463                try {
464                    br.close();
465                } catch (IOException e) {
466                }
467            }
468        }
469    }
470
471    private void restoreWifiSupplicant(String filename, BackupDataInput data) {
472        byte[] bytes = new byte[data.getDataSize()];
473        if (bytes.length <= 0) return;
474        try {
475            data.readEntityData(bytes, 0, bytes.length);
476            File supplicantFile = new File(FILE_WIFI_SUPPLICANT);
477            if (supplicantFile.exists()) supplicantFile.delete();
478            copyWifiSupplicantTemplate();
479
480            OutputStream os = new BufferedOutputStream(new FileOutputStream(filename, true));
481            os.write("\n".getBytes());
482            os.write(bytes);
483            os.close();
484        } catch (IOException ioe) {
485            Log.w(TAG, "Couldn't restore " + filename);
486        }
487    }
488
489    private void copyWifiSupplicantTemplate() {
490        try {
491            BufferedReader br = new BufferedReader(new FileReader(FILE_WIFI_SUPPLICANT_TEMPLATE));
492            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_WIFI_SUPPLICANT));
493            char[] temp = new char[1024];
494            int size;
495            while ((size = br.read(temp)) > 0) {
496                bw.write(temp, 0, size);
497            }
498            bw.close();
499            br.close();
500        } catch (IOException ioe) {
501            Log.w(TAG, "Couldn't copy wpa_supplicant file");
502        }
503    }
504
505    /**
506     * Write an int in BigEndian into the byte array.
507     * @param out byte array
508     * @param pos current pos in array
509     * @param value integer to write
510     * @return the index after adding the size of an int (4)
511     */
512    private int writeInt(byte[] out, int pos, int value) {
513        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
514        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
515        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
516        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
517        return pos + 4;
518    }
519
520    private int writeBytes(byte[] out, int pos, byte[] value) {
521        System.arraycopy(value, 0, out, pos, value.length);
522        return pos + value.length;
523    }
524
525    private int readInt(byte[] in, int pos) {
526        int result =
527                ((in[pos    ] & 0xFF) << 24) |
528                ((in[pos + 1] & 0xFF) << 16) |
529                ((in[pos + 2] & 0xFF) <<  8) |
530                ((in[pos + 3] & 0xFF) <<  0);
531        return result;
532    }
533
534    private int enableWifi(boolean enable) {
535        if (mWfm != null) {
536            int state = mWfm.getWifiState();
537            mWfm.setWifiEnabled(enable);
538            return state;
539        }
540        return WifiManager.WIFI_STATE_UNKNOWN;
541    }
542}
543