SettingsBackupAgent.java revision 8823c0a8c68fe669c21c539eef9fc6541f0c7494
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.File;
20import java.io.FileInputStream;
21import java.io.FileOutputStream;
22import java.io.IOException;
23import java.util.Arrays;
24import java.util.HashMap;
25
26import android.backup.BackupDataInput;
27import android.backup.BackupDataOutput;
28import android.backup.BackupHelperAgent;
29import android.bluetooth.BluetoothDevice;
30import android.content.ContentResolver;
31import android.content.ContentValues;
32import android.content.Context;
33import android.database.Cursor;
34import android.media.AudioManager;
35import android.net.Uri;
36import android.net.wifi.WifiManager;
37import android.os.ParcelFileDescriptor;
38import android.os.RemoteException;
39import android.os.ServiceManager;
40import android.provider.Settings;
41import android.text.TextUtils;
42import android.util.Log;
43
44/**
45 * Performs backup and restore of the System and Secure settings.
46 * List of settings that are backed up are stored in the Settings.java file
47 */
48public class SettingsBackupAgent extends BackupHelperAgent {
49
50    private static final String KEY_SYSTEM = "system";
51    private static final String KEY_SECURE = "secure";
52    private static final String KEY_SYNC = "sync_providers";
53    private static final String KEY_LOCALE = "locale";
54
55    private static String[] sortedSystemKeys = null;
56    private static String[] sortedSecureKeys = null;
57
58    private static final byte[] EMPTY_DATA = new byte[0];
59
60    private static final String TAG = "SettingsBackupAgent";
61
62    private static final int COLUMN_ID = 0;
63    private static final int COLUMN_NAME = 1;
64    private static final int COLUMN_VALUE = 2;
65
66    private static final String[] PROJECTION = {
67        Settings.NameValueTable._ID,
68        Settings.NameValueTable.NAME,
69        Settings.NameValueTable.VALUE
70    };
71
72    private static final String FILE_WIFI_SUPPLICANT = "/data/misc/wifi/wpa_supplicant.conf";
73    private static final String FILE_BT_ROOT = "/data/misc/hcid/";
74
75    private SettingsHelper mSettingsHelper;
76
77    public void onCreate() {
78        mSettingsHelper = new SettingsHelper(this);
79        super.onCreate();
80    }
81
82    @Override
83    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
84            ParcelFileDescriptor newState) throws IOException {
85
86        byte[] systemSettingsData = getSystemSettings();
87        byte[] secureSettingsData = getSecureSettings();
88        byte[] syncProviders = mSettingsHelper.getSyncProviders();
89        byte[] locale = mSettingsHelper.getLocaleData();
90
91        data.writeEntityHeader(KEY_SYSTEM, systemSettingsData.length);
92        data.writeEntityData(systemSettingsData, systemSettingsData.length);
93
94        data.writeEntityHeader(KEY_SECURE, secureSettingsData.length);
95        data.writeEntityData(secureSettingsData, secureSettingsData.length);
96
97        data.writeEntityHeader(KEY_SYNC, syncProviders.length);
98        data.writeEntityData(syncProviders, syncProviders.length);
99
100        data.writeEntityHeader(KEY_LOCALE, locale.length);
101        data.writeEntityData(locale, locale.length);
102
103        backupFile(FILE_WIFI_SUPPLICANT, data);
104    }
105
106    @Override
107    public void onRestore(BackupDataInput data, int appVersionCode,
108            ParcelFileDescriptor newState) throws IOException {
109
110        enableWifi(false);
111        enableBluetooth(false);
112
113        while (data.readNextHeader()) {
114            final String key = data.getKey();
115            final int size = data.getDataSize();
116            if (KEY_SYSTEM.equals(key)) {
117                restoreSettings(data, Settings.System.CONTENT_URI);
118            } else if (KEY_SECURE.equals(key)) {
119                restoreSettings(data, Settings.Secure.CONTENT_URI);
120// TODO: Re-enable WIFI restore when we figure out a solution for the permissions
121//            } else if (FILE_WIFI_SUPPLICANT.equals(key)) {
122//                restoreFile(FILE_WIFI_SUPPLICANT, data);
123            } else if (KEY_SYNC.equals(key)) {
124                mSettingsHelper.setSyncProviders(data);
125            } else if (KEY_LOCALE.equals(key)) {
126                byte[] localeData = new byte[size];
127                data.readEntityData(localeData, 0, size);
128                mSettingsHelper.setLocaleData(localeData);
129            } else {
130                data.skipEntityData();
131            }
132        }
133    }
134
135    private byte[] getSystemSettings() {
136        Cursor sortedCursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION,
137                null, null, Settings.NameValueTable.NAME);
138        // Copy and sort the array
139        if (sortedSystemKeys == null) {
140            sortedSystemKeys = copyAndSort(Settings.System.SETTINGS_TO_BACKUP);
141        }
142        byte[] result = extractRelevantValues(sortedCursor, sortedSystemKeys);
143        sortedCursor.close();
144        return result;
145    }
146
147    private byte[] getSecureSettings() {
148        Cursor sortedCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION,
149                null, null, Settings.NameValueTable.NAME);
150        // Copy and sort the array
151        if (sortedSecureKeys == null) {
152            sortedSecureKeys = copyAndSort(Settings.Secure.SETTINGS_TO_BACKUP);
153        }
154        byte[] result = extractRelevantValues(sortedCursor, sortedSecureKeys);
155        sortedCursor.close();
156        return result;
157    }
158
159    private void restoreSettings(BackupDataInput data, Uri contentUri) {
160        ContentValues cv = new ContentValues(2);
161        byte[] settings = new byte[data.getDataSize()];
162        try {
163            data.readEntityData(settings, 0, settings.length);
164        } catch (IOException ioe) {
165            Log.e(TAG, "Couldn't read entity data");
166            return;
167        }
168        int pos = 0;
169        while (pos < settings.length) {
170            int length = readInt(settings, pos);
171            pos += 4;
172            String settingName = length > 0? new String(settings, pos, length) : null;
173            pos += length;
174            length = readInt(settings, pos);
175            pos += 4;
176            String settingValue = length > 0? new String(settings, pos, length) : null;
177            pos += length;
178            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
179                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
180                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
181                    cv.clear();
182                    cv.put(Settings.NameValueTable.NAME, settingName);
183                    cv.put(Settings.NameValueTable.VALUE, settingValue);
184                    getContentResolver().insert(contentUri, cv);
185                }
186            }
187        }
188    }
189
190    private String[] copyAndSort(String[] keys) {
191        String[] sortedKeys = new String[keys.length];
192        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
193        Arrays.sort(sortedKeys);
194        return sortedKeys;
195    }
196
197    /**
198     * Given a cursor sorted by key name and a set of keys sorted by name,
199     * extract the required keys and values and write them to a byte array.
200     * @param sortedCursor
201     * @param sortedKeys
202     * @return
203     */
204    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
205        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
206        if (!sortedCursor.moveToFirst()) {
207            Log.e(TAG, "Couldn't read from the cursor");
208            return new byte[0];
209        }
210        int keyIndex = 0;
211        int totalSize = 0;
212        while (!sortedCursor.isAfterLast()) {
213            String name = sortedCursor.getString(COLUMN_NAME);
214            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
215                keyIndex++;
216                if (keyIndex == sortedKeys.length) break;
217            }
218            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
219                String value = sortedCursor.getString(COLUMN_VALUE);
220                byte[] nameBytes = name.toString().getBytes();
221                totalSize += 4 + nameBytes.length;
222                values[keyIndex * 2] = nameBytes;
223                byte[] valueBytes;
224                if (TextUtils.isEmpty(value)) {
225                    valueBytes = null;
226                    totalSize += 4;
227                } else {
228                    valueBytes = value.toString().getBytes();
229                    totalSize += 4 + valueBytes.length;
230                    //Log.i(TAG, "Backing up " + name + " = " + value);
231                }
232                values[keyIndex * 2 + 1] = valueBytes;
233                keyIndex++;
234            }
235            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
236                break;
237            }
238        }
239
240        byte[] result = new byte[totalSize];
241        int pos = 0;
242        for (int i = 0; i < sortedKeys.length * 2; i++) {
243            if (values[i] != null) {
244                pos = writeInt(result, pos, values[i].length);
245                pos = writeBytes(result, pos, values[i]);
246            }
247        }
248        return result;
249    }
250
251    private void backupFile(String filename, BackupDataOutput data) {
252        try {
253            File file = new File(filename);
254            if (file.exists()) {
255                byte[] bytes = new byte[(int) file.length()];
256                FileInputStream fis = new FileInputStream(file);
257                int offset = 0;
258                int got = 0;
259                do {
260                    got = fis.read(bytes, offset, bytes.length - offset);
261                    if (got > 0) offset += got;
262                } while (offset < bytes.length && got > 0);
263                data.writeEntityHeader(filename, bytes.length);
264                data.writeEntityData(bytes, bytes.length);
265            } else {
266                data.writeEntityHeader(filename, 0);
267                data.writeEntityData(EMPTY_DATA, 0);
268            }
269        } catch (IOException ioe) {
270            Log.w(TAG, "Couldn't backup " + filename);
271        }
272    }
273
274    private void restoreFile(String filename, BackupDataInput data) {
275        byte[] bytes = new byte[data.getDataSize()];
276        if (bytes.length <= 0) return;
277        try {
278            data.readEntityData(bytes, 0, bytes.length);
279            FileOutputStream fos = new FileOutputStream(filename);
280            fos.write(bytes);
281        } catch (IOException ioe) {
282            Log.w(TAG, "Couldn't restore " + filename);
283        }
284    }
285
286    /**
287     * Write an int in BigEndian into the byte array.
288     * @param out byte array
289     * @param pos current pos in array
290     * @param value integer to write
291     * @return the index after adding the size of an int (4)
292     */
293    private int writeInt(byte[] out, int pos, int value) {
294        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
295        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
296        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
297        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
298        return pos + 4;
299    }
300
301    private int writeBytes(byte[] out, int pos, byte[] value) {
302        System.arraycopy(value, 0, out, pos, value.length);
303        return pos + value.length;
304    }
305
306    private int readInt(byte[] in, int pos) {
307        int result =
308                ((in[pos    ] & 0xFF) << 24) |
309                ((in[pos + 1] & 0xFF) << 16) |
310                ((in[pos + 2] & 0xFF) <<  8) |
311                ((in[pos + 3] & 0xFF) <<  0);
312        return result;
313    }
314
315    private void enableWifi(boolean enable) {
316        WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
317        if (wfm != null) {
318            wfm.setWifiEnabled(enable);
319        }
320    }
321
322    private void enableBluetooth(boolean enable) {
323        BluetoothDevice bt = (BluetoothDevice) getSystemService(Context.BLUETOOTH_SERVICE);
324        if (bt != null) {
325            if (!enable) {
326                bt.disable();
327            } else {
328                bt.enable();
329            }
330        }
331    }
332}
333