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