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