SettingsBackupAgent.java revision 92c1752175f0880a0e0a05fdca37b54a8fb2b52d
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.DataInputStream;
20import java.io.DataOutputStream;
21import java.io.File;
22import java.io.FileInputStream;
23import java.io.FileOutputStream;
24import java.io.IOException;
25import java.io.EOFException;
26import java.util.Arrays;
27import java.util.HashMap;
28import java.util.zip.CRC32;
29
30import android.backup.BackupDataInput;
31import android.backup.BackupDataOutput;
32import android.backup.BackupHelperAgent;
33import android.bluetooth.BluetoothDevice;
34import android.content.ContentResolver;
35import android.content.ContentValues;
36import android.content.Context;
37import android.database.Cursor;
38import android.media.AudioManager;
39import android.net.Uri;
40import android.net.wifi.WifiManager;
41import android.os.FileUtils;
42import android.os.ParcelFileDescriptor;
43import android.os.Process;
44import android.os.RemoteException;
45import android.os.ServiceManager;
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 BackupHelperAgent {
55
56    private static final String KEY_SYSTEM = "system";
57    private static final String KEY_SECURE = "secure";
58    private static final String KEY_SYNC = "sync_providers";
59    private static final String KEY_LOCALE = "locale";
60
61    private static final int STATE_SYSTEM = 0;
62    private static final int STATE_SECURE = 1;
63    private static final int STATE_SYNC   = 2;
64    private static final int STATE_LOCALE = 3;
65    private static final int STATE_WIFI   = 4;
66    private static final int STATE_SIZE   = 5; // The number of state items
67
68    private static String[] sortedSystemKeys = null;
69    private static String[] sortedSecureKeys = null;
70
71    private static final byte[] EMPTY_DATA = new byte[0];
72
73    private static final String TAG = "SettingsBackupAgent";
74
75    private static final int COLUMN_ID = 0;
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
87    // the key to store the WIFI data under, should be sorted as last, so restore happens last.
88    // use very late unicode character to quasi-guarantee last sort position.
89    private static final String KEY_WIFI_SUPPLICANT = "\uffeeWIFI";
90
91    private static final String FILE_BT_ROOT = "/data/misc/hcid/";
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[] syncProviders = mSettingsHelper.getSyncProviders();
107        byte[] locale = mSettingsHelper.getLocaleData();
108        byte[] wifiData = getFileData(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_SYNC] =
117                writeIfChanged(stateChecksums[STATE_SYNC], KEY_SYNC, syncProviders, data);
118        stateChecksums[STATE_LOCALE] =
119                writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
120        stateChecksums[STATE_WIFI] =
121                writeIfChanged(stateChecksums[STATE_WIFI], KEY_WIFI_SUPPLICANT, wifiData, data);
122
123        writeNewChecksums(stateChecksums, newState);
124    }
125
126    @Override
127    public void onRestore(BackupDataInput data, int appVersionCode,
128            ParcelFileDescriptor newState) throws IOException {
129
130
131        enableBluetooth(false);
132
133        while (data.readNextHeader()) {
134            final String key = data.getKey();
135            final int size = data.getDataSize();
136            if (KEY_SYSTEM.equals(key)) {
137                restoreSettings(data, Settings.System.CONTENT_URI);
138                mSettingsHelper.applyAudioSettings();
139            } else if (KEY_SECURE.equals(key)) {
140                restoreSettings(data, Settings.Secure.CONTENT_URI);
141            } else if (KEY_WIFI_SUPPLICANT.equals(key)) {
142                int retainedWifiState = enableWifi(false);
143                restoreFile(FILE_WIFI_SUPPLICANT, data);
144                FileUtils.setPermissions(FILE_WIFI_SUPPLICANT,
145                        FileUtils.S_IRUSR | FileUtils.S_IWUSR |
146                        FileUtils.S_IRGRP | FileUtils.S_IWGRP,
147                        Process.myUid(), Process.WIFI_UID);
148                // retain the previous WIFI state.
149                enableWifi(retainedWifiState == WifiManager.WIFI_STATE_ENABLED ||
150                        retainedWifiState == WifiManager.WIFI_STATE_ENABLING);
151            } else if (KEY_SYNC.equals(key)) {
152                mSettingsHelper.setSyncProviders(data);
153            } else if (KEY_LOCALE.equals(key)) {
154                byte[] localeData = new byte[size];
155                data.readEntityData(localeData, 0, size);
156                mSettingsHelper.setLocaleData(localeData);
157            } else {
158                data.skipEntityData();
159            }
160        }
161    }
162
163    private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
164        long[] stateChecksums = new long[STATE_SIZE];
165
166        DataInputStream dataInput = new DataInputStream(
167                new FileInputStream(oldState.getFileDescriptor()));
168        for (int i = 0; i < STATE_SIZE; i++) {
169            try {
170                stateChecksums[i] = dataInput.readLong();
171            } catch (EOFException eof) {
172                break;
173            }
174        }
175        dataInput.close();
176        return stateChecksums;
177    }
178
179    private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
180            throws IOException {
181        DataOutputStream dataOutput = new DataOutputStream(
182                new FileOutputStream(newState.getFileDescriptor()));
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        ContentValues cv = new ContentValues(2);
232        byte[] settings = new byte[data.getDataSize()];
233        try {
234            data.readEntityData(settings, 0, settings.length);
235        } catch (IOException ioe) {
236            Log.e(TAG, "Couldn't read entity data");
237            return;
238        }
239        int pos = 0;
240        while (pos < settings.length) {
241            int length = readInt(settings, pos);
242            pos += 4;
243            String settingName = length > 0? new String(settings, pos, length) : null;
244            pos += length;
245            length = readInt(settings, pos);
246            pos += 4;
247            String settingValue = length > 0? new String(settings, pos, length) : null;
248            pos += length;
249            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
250                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
251                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
252                    cv.clear();
253                    cv.put(Settings.NameValueTable.NAME, settingName);
254                    cv.put(Settings.NameValueTable.VALUE, settingValue);
255                    getContentResolver().insert(contentUri, cv);
256                }
257            }
258        }
259    }
260
261    private String[] copyAndSort(String[] keys) {
262        String[] sortedKeys = new String[keys.length];
263        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
264        Arrays.sort(sortedKeys);
265        return sortedKeys;
266    }
267
268    /**
269     * Given a cursor sorted by key name and a set of keys sorted by name,
270     * extract the required keys and values and write them to a byte array.
271     * @param sortedCursor
272     * @param sortedKeys
273     * @return
274     */
275    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
276        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
277        if (!sortedCursor.moveToFirst()) {
278            Log.e(TAG, "Couldn't read from the cursor");
279            return new byte[0];
280        }
281        int keyIndex = 0;
282        int totalSize = 0;
283        while (!sortedCursor.isAfterLast()) {
284            String name = sortedCursor.getString(COLUMN_NAME);
285            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
286                keyIndex++;
287                if (keyIndex == sortedKeys.length) break;
288            }
289            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
290                String value = sortedCursor.getString(COLUMN_VALUE);
291                byte[] nameBytes = name.toString().getBytes();
292                totalSize += 4 + nameBytes.length;
293                values[keyIndex * 2] = nameBytes;
294                byte[] valueBytes;
295                if (TextUtils.isEmpty(value)) {
296                    valueBytes = null;
297                    totalSize += 4;
298                } else {
299                    valueBytes = value.toString().getBytes();
300                    totalSize += 4 + valueBytes.length;
301                    //Log.i(TAG, "Backing up " + name + " = " + value);
302                }
303                values[keyIndex * 2 + 1] = valueBytes;
304                keyIndex++;
305            }
306            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
307                break;
308            }
309        }
310
311        byte[] result = new byte[totalSize];
312        int pos = 0;
313        for (int i = 0; i < sortedKeys.length * 2; i++) {
314            if (values[i] != null) {
315                pos = writeInt(result, pos, values[i].length);
316                pos = writeBytes(result, pos, values[i]);
317            }
318        }
319        return result;
320    }
321
322    private byte[] getFileData(String filename) {
323        try {
324            File file = new File(filename);
325            if (file.exists()) {
326                byte[] bytes = new byte[(int) file.length()];
327                FileInputStream fis = new FileInputStream(file);
328                int offset = 0;
329                int got = 0;
330                do {
331                    got = fis.read(bytes, offset, bytes.length - offset);
332                    if (got > 0) offset += got;
333                } while (offset < bytes.length && got > 0);
334                return bytes;
335            } else {
336                return EMPTY_DATA;
337            }
338        } catch (IOException ioe) {
339            Log.w(TAG, "Couldn't backup " + filename);
340            return EMPTY_DATA;
341        }
342    }
343
344    private void restoreFile(String filename, BackupDataInput data) {
345        byte[] bytes = new byte[data.getDataSize()];
346        if (bytes.length <= 0) return;
347        try {
348            data.readEntityData(bytes, 0, bytes.length);
349            FileOutputStream fos = new FileOutputStream(filename);
350            fos.write(bytes);
351        } catch (IOException ioe) {
352            Log.w(TAG, "Couldn't restore " + filename);
353        }
354    }
355
356    /**
357     * Write an int in BigEndian into the byte array.
358     * @param out byte array
359     * @param pos current pos in array
360     * @param value integer to write
361     * @return the index after adding the size of an int (4)
362     */
363    private int writeInt(byte[] out, int pos, int value) {
364        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
365        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
366        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
367        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
368        return pos + 4;
369    }
370
371    private int writeBytes(byte[] out, int pos, byte[] value) {
372        System.arraycopy(value, 0, out, pos, value.length);
373        return pos + value.length;
374    }
375
376    private int readInt(byte[] in, int pos) {
377        int result =
378                ((in[pos    ] & 0xFF) << 24) |
379                ((in[pos + 1] & 0xFF) << 16) |
380                ((in[pos + 2] & 0xFF) <<  8) |
381                ((in[pos + 3] & 0xFF) <<  0);
382        return result;
383    }
384
385    private int enableWifi(boolean enable) {
386        WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
387        if (wfm != null) {
388            int state = wfm.getWifiState();
389            wfm.setWifiEnabled(enable);
390            return state;
391        }
392        return WifiManager.WIFI_STATE_UNKNOWN;
393    }
394
395    private void enableBluetooth(boolean enable) {
396        BluetoothDevice bt = (BluetoothDevice) getSystemService(Context.BLUETOOTH_SERVICE);
397        if (bt != null) {
398            if (!enable) {
399                bt.disable();
400            } else {
401                bt.enable();
402            }
403        }
404    }
405}
406