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