SettingsBackupAgent.java revision c5b5b0fb94d078148b5fe5f6b8bb4ee361949f3e
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    private static final String FILE_BT_ROOT = "/data/misc/hcid/";
87
88    private SettingsHelper mSettingsHelper;
89
90    public void onCreate() {
91        mSettingsHelper = new SettingsHelper(this);
92        super.onCreate();
93    }
94
95    @Override
96    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
97            ParcelFileDescriptor newState) throws IOException {
98
99        byte[] systemSettingsData = getSystemSettings();
100        byte[] secureSettingsData = getSecureSettings();
101        byte[] syncProviders = mSettingsHelper.getSyncProviders();
102        byte[] locale = mSettingsHelper.getLocaleData();
103        byte[] wifiData = getFileData(FILE_WIFI_SUPPLICANT);
104
105        long[] stateChecksums = readOldChecksums(oldState);
106
107        stateChecksums[STATE_SYSTEM] =
108                writeIfChanged(stateChecksums[STATE_SYSTEM], KEY_SYSTEM, systemSettingsData, data);
109        stateChecksums[STATE_SECURE] =
110                writeIfChanged(stateChecksums[STATE_SECURE], KEY_SECURE, secureSettingsData, data);
111        stateChecksums[STATE_SYNC] =
112                writeIfChanged(stateChecksums[STATE_SYNC], KEY_SYNC, syncProviders, data);
113        stateChecksums[STATE_LOCALE] =
114                writeIfChanged(stateChecksums[STATE_LOCALE], KEY_LOCALE, locale, data);
115        stateChecksums[STATE_WIFI] =
116                writeIfChanged(stateChecksums[STATE_WIFI], FILE_WIFI_SUPPLICANT, wifiData, data);
117
118        writeNewChecksums(stateChecksums, newState);
119    }
120
121    @Override
122    public void onRestore(BackupDataInput data, int appVersionCode,
123            ParcelFileDescriptor newState) throws IOException {
124
125
126        enableBluetooth(false);
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 (FILE_WIFI_SUPPLICANT.equals(key)) {
137                int retainedWifiState = enableWifi(false);
138                restoreFile(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_SYNC.equals(key)) {
147                mSettingsHelper.setSyncProviders(data);
148            } else if (KEY_LOCALE.equals(key)) {
149                byte[] localeData = new byte[size];
150                data.readEntityData(localeData, 0, size);
151                mSettingsHelper.setLocaleData(localeData);
152            } else {
153                data.skipEntityData();
154            }
155        }
156    }
157
158    private long[] readOldChecksums(ParcelFileDescriptor oldState) throws IOException {
159        long[] stateChecksums = new long[STATE_SIZE];
160
161        DataInputStream dataInput = new DataInputStream(
162                new FileInputStream(oldState.getFileDescriptor()));
163        for (int i = 0; i < STATE_SIZE; i++) {
164            try {
165                stateChecksums[i] = dataInput.readLong();
166            } catch (EOFException eof) {
167                break;
168            }
169        }
170        dataInput.close();
171        return stateChecksums;
172    }
173
174    private void writeNewChecksums(long[] checksums, ParcelFileDescriptor newState)
175            throws IOException {
176        DataOutputStream dataOutput = new DataOutputStream(
177                new FileOutputStream(newState.getFileDescriptor()));
178        for (int i = 0; i < STATE_SIZE; i++) {
179            dataOutput.writeLong(checksums[i]);
180        }
181        dataOutput.close();
182    }
183
184    private long writeIfChanged(long oldChecksum, String key, byte[] data,
185            BackupDataOutput output) {
186        CRC32 checkSummer = new CRC32();
187        checkSummer.update(data);
188        long newChecksum = checkSummer.getValue();
189        if (oldChecksum == newChecksum) {
190            return oldChecksum;
191        }
192        try {
193            output.writeEntityHeader(key, data.length);
194            output.writeEntityData(data, data.length);
195        } catch (IOException ioe) {
196            // Bail
197        }
198        return newChecksum;
199    }
200
201    private byte[] getSystemSettings() {
202        Cursor sortedCursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION,
203                null, null, Settings.NameValueTable.NAME);
204        // Copy and sort the array
205        if (sortedSystemKeys == null) {
206            sortedSystemKeys = copyAndSort(Settings.System.SETTINGS_TO_BACKUP);
207        }
208        byte[] result = extractRelevantValues(sortedCursor, sortedSystemKeys);
209        sortedCursor.close();
210        return result;
211    }
212
213    private byte[] getSecureSettings() {
214        Cursor sortedCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION,
215                null, null, Settings.NameValueTable.NAME);
216        // Copy and sort the array
217        if (sortedSecureKeys == null) {
218            sortedSecureKeys = copyAndSort(Settings.Secure.SETTINGS_TO_BACKUP);
219        }
220        byte[] result = extractRelevantValues(sortedCursor, sortedSecureKeys);
221        sortedCursor.close();
222        return result;
223    }
224
225    private void restoreSettings(BackupDataInput data, Uri contentUri) {
226        ContentValues cv = new ContentValues(2);
227        byte[] settings = new byte[data.getDataSize()];
228        try {
229            data.readEntityData(settings, 0, settings.length);
230        } catch (IOException ioe) {
231            Log.e(TAG, "Couldn't read entity data");
232            return;
233        }
234        int pos = 0;
235        while (pos < settings.length) {
236            int length = readInt(settings, pos);
237            pos += 4;
238            String settingName = length > 0? new String(settings, pos, length) : null;
239            pos += length;
240            length = readInt(settings, pos);
241            pos += 4;
242            String settingValue = length > 0? new String(settings, pos, length) : null;
243            pos += length;
244            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
245                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
246                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
247                    cv.clear();
248                    cv.put(Settings.NameValueTable.NAME, settingName);
249                    cv.put(Settings.NameValueTable.VALUE, settingValue);
250                    getContentResolver().insert(contentUri, cv);
251                }
252            }
253        }
254    }
255
256    private String[] copyAndSort(String[] keys) {
257        String[] sortedKeys = new String[keys.length];
258        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
259        Arrays.sort(sortedKeys);
260        return sortedKeys;
261    }
262
263    /**
264     * Given a cursor sorted by key name and a set of keys sorted by name,
265     * extract the required keys and values and write them to a byte array.
266     * @param sortedCursor
267     * @param sortedKeys
268     * @return
269     */
270    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
271        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
272        if (!sortedCursor.moveToFirst()) {
273            Log.e(TAG, "Couldn't read from the cursor");
274            return new byte[0];
275        }
276        int keyIndex = 0;
277        int totalSize = 0;
278        while (!sortedCursor.isAfterLast()) {
279            String name = sortedCursor.getString(COLUMN_NAME);
280            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
281                keyIndex++;
282                if (keyIndex == sortedKeys.length) break;
283            }
284            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
285                String value = sortedCursor.getString(COLUMN_VALUE);
286                byte[] nameBytes = name.toString().getBytes();
287                totalSize += 4 + nameBytes.length;
288                values[keyIndex * 2] = nameBytes;
289                byte[] valueBytes;
290                if (TextUtils.isEmpty(value)) {
291                    valueBytes = null;
292                    totalSize += 4;
293                } else {
294                    valueBytes = value.toString().getBytes();
295                    totalSize += 4 + valueBytes.length;
296                    //Log.i(TAG, "Backing up " + name + " = " + value);
297                }
298                values[keyIndex * 2 + 1] = valueBytes;
299                keyIndex++;
300            }
301            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
302                break;
303            }
304        }
305
306        byte[] result = new byte[totalSize];
307        int pos = 0;
308        for (int i = 0; i < sortedKeys.length * 2; i++) {
309            if (values[i] != null) {
310                pos = writeInt(result, pos, values[i].length);
311                pos = writeBytes(result, pos, values[i]);
312            }
313        }
314        return result;
315    }
316
317    private byte[] getFileData(String filename) {
318        try {
319            File file = new File(filename);
320            if (file.exists()) {
321                byte[] bytes = new byte[(int) file.length()];
322                FileInputStream fis = new FileInputStream(file);
323                int offset = 0;
324                int got = 0;
325                do {
326                    got = fis.read(bytes, offset, bytes.length - offset);
327                    if (got > 0) offset += got;
328                } while (offset < bytes.length && got > 0);
329                return bytes;
330            } else {
331                return EMPTY_DATA;
332            }
333        } catch (IOException ioe) {
334            Log.w(TAG, "Couldn't backup " + filename);
335            return EMPTY_DATA;
336        }
337    }
338
339    private void restoreFile(String filename, BackupDataInput data) {
340        byte[] bytes = new byte[data.getDataSize()];
341        if (bytes.length <= 0) return;
342        try {
343            data.readEntityData(bytes, 0, bytes.length);
344            FileOutputStream fos = new FileOutputStream(filename);
345            fos.write(bytes);
346        } catch (IOException ioe) {
347            Log.w(TAG, "Couldn't restore " + filename);
348        }
349    }
350
351    /**
352     * Write an int in BigEndian into the byte array.
353     * @param out byte array
354     * @param pos current pos in array
355     * @param value integer to write
356     * @return the index after adding the size of an int (4)
357     */
358    private int writeInt(byte[] out, int pos, int value) {
359        out[pos + 0] = (byte) ((value >> 24) & 0xFF);
360        out[pos + 1] = (byte) ((value >> 16) & 0xFF);
361        out[pos + 2] = (byte) ((value >>  8) & 0xFF);
362        out[pos + 3] = (byte) ((value >>  0) & 0xFF);
363        return pos + 4;
364    }
365
366    private int writeBytes(byte[] out, int pos, byte[] value) {
367        System.arraycopy(value, 0, out, pos, value.length);
368        return pos + value.length;
369    }
370
371    private int readInt(byte[] in, int pos) {
372        int result =
373                ((in[pos    ] & 0xFF) << 24) |
374                ((in[pos + 1] & 0xFF) << 16) |
375                ((in[pos + 2] & 0xFF) <<  8) |
376                ((in[pos + 3] & 0xFF) <<  0);
377        return result;
378    }
379
380    private int enableWifi(boolean enable) {
381        WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
382        if (wfm != null) {
383            int state = wfm.getWifiState();
384            wfm.setWifiEnabled(enable);
385            return state;
386        }
387        return WifiManager.WIFI_STATE_UNKNOWN;
388    }
389
390    private void enableBluetooth(boolean enable) {
391        BluetoothDevice bt = (BluetoothDevice) getSystemService(Context.BLUETOOTH_SERVICE);
392        if (bt != null) {
393            if (!enable) {
394                bt.disable();
395            } else {
396                bt.enable();
397            }
398        }
399    }
400}
401