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