Full local backup infrastructure

This is the basic infrastructure for pulling a full(*) backup of the
device's data over an adb(**) connection to the local device.  The
basic process consists of these interacting pieces:

1. The framework's BackupManagerService, which coordinates the
   collection of app data and routing to the destination.

2. A new framework-provided BackupAgent implementation called
   FullBackupAgent, which is instantiated in the target applications'
   processes in turn, and knows how to emit a datastream that contains
   all of the app's saved data files.

3. A new shell-level program called "bu" that is used to bridge from
   adb to the framework's Backup Manager.

4. adb itself, which now knows how to use 'bu' to kick off a backup
   operation and pull the resulting data stream to the desktop host.

5. A system-provided application that verifies with the user that
   an attempted backup/restore operation is in fact expected and to
   be allowed.

The full agent implementation is not used during normal operation of
the delta-based app-customized remote backup process.  Instead it's
used during user-confirmed *full* backup of applications and all their
data to a local destination, e.g. via the adb connection.

The output format is 'tar'.  This makes it very easy for the end
user to examine the resulting dataset, e.g. for purpose of extracting
files for debug purposes; as well as making it easy to contemplate
adding things like a direct gzip stage to the data pipeline during
backup/restore.  It also makes it convenient to construct and maintain
synthetic backup datasets for testing purposes.

Within the tar format, certain artificial conventions are used.
All files are stored within top-level directories according to
their semantic origin:

apps/pkgname/a/  : Application .apk file itself
apps/pkgname/obb/: The application's associated .obb containers
apps/pkgname/f/  : The subtree rooted at the getFilesDir() location
apps/pkgname/db/ : The subtree rooted at the getDatabasePath() parent
apps/pkgname/sp/ : The subtree rooted at the getSharedPrefsFile() parent
apps/pkgname/r/  : Files stored relative to the root of the app's file tree
apps/pkgname/c/  : Reserved for the app's getCacheDir() tree; not stored.

For each package, the first entry in the tar stream is a file called
"_manifest", nominally rooted at apps/pkgname.  This file contains some
metadata about the package whose data is stored in the archive.

The contents of shared storage can optionally be included in the tar
stream. It is placed in the synthetic location:

shared/...

uid/gid are ignored; app uids are assigned at install time, and the
app's data is handled from within its own execution environment, so
will automatically have the app's correct uid.

Forward-locked .apk files are never backed up.  System-partition
.apk files are not backed up unless they have been overridden by a
post-factory upgrade, in which case the current .apk *is* backed up --
i.e. the .apk that matches the on-disk data.  The manifest preceding
each application's portion of the tar stream provides version numbers
and signature blocks for version checking, as well as an indication
of whether the restore logic should expect to install the .apk before
extracting the data.

System packages can designate their own full backup agents.  This is
to manage things like the settings provider which (a) cannot be shut
down on the fly in order to do a clean snapshot of their file trees,
and (b) manage data that is not only irrelevant but actively hostile
to non-identical devices -- CDMA telephony settings would seriously
mess up a GSM device if emplaced there blind, for example.

When a full backup or restore is initiated from adb, the system will
present a confirmation UI that the user must explicitly respond to
within a short [~ 30 seconds] timeout.  This is to avoid the
possibility of malicious desktop-side software secretly grabbing a copy
of all the user's data for nefarious purposes.

(*) The backup is not strictly a full mirror.  In particular, the
    settings database is not cloned; it is handled the same way that
    it is in cloud backup/restore.  This is because some settings
    are actively destructive if cloned onto a different (or
    especially a different-model) device: telephony settings and
    AndroidID are good examples of this.

(**) On the framework side it doesn't care that it's adb; it just
    sends the tar stream to a file descriptor.  This can easily be
    retargeted around whatever transport we might decide to use
    in the future.

KNOWN ISSUES:

* the security UI is desperately ugly; no proper designs have yet
  been done for it
* restore is not yet implemented
* shared storage backup is not yet implemented
* symlinks aren't yet handled, though some infrastructure for
  dealing with them has been put in place.

Change-Id: Ia8347611e23b398af36ea22c36dff0a276b1ce91
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index f0e7e98..85e59b3 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -129,7 +129,7 @@
     /** @hide */
     public static final boolean DEBUG_BROADCAST = false;
     private static final boolean DEBUG_RESULTS = false;
-    private static final boolean DEBUG_BACKUP = false;
+    private static final boolean DEBUG_BACKUP = true;
     private static final boolean DEBUG_CONFIGURATION = false;
     private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
     private static final Pattern PATTERN_SEMICOLON = Pattern.compile(";");
@@ -1979,24 +1979,26 @@
 
         BackupAgent agent = null;
         String classname = data.appInfo.backupAgentName;
-        if (classname == null) {
-            if (data.backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) {
-                Slog.e(TAG, "Attempted incremental backup but no defined agent for "
-                        + packageName);
-                return;
+
+        if (data.backupMode == IApplicationThread.BACKUP_MODE_FULL) {
+            classname = "android.app.backup.FullBackupAgent";
+            if ((data.appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
+                // system packages can supply their own full-backup agent
+                if (data.appInfo.fullBackupAgentName != null) {
+                    classname = data.appInfo.fullBackupAgentName;
+                }
             }
-            classname = "android.app.FullBackupAgent";
         }
+
         try {
             IBinder binder = null;
             try {
+                if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
+
                 java.lang.ClassLoader cl = packageInfo.getClassLoader();
-                agent = (BackupAgent) cl.loadClass(data.appInfo.backupAgentName).newInstance();
+                agent = (BackupAgent) cl.loadClass(classname).newInstance();
 
                 // set up the agent's context
-                if (DEBUG_BACKUP) Slog.v(TAG, "Initializing BackupAgent "
-                        + data.appInfo.backupAgentName);
-
                 ContextImpl context = new ContextImpl();
                 context.init(packageInfo, null, this);
                 context.setOuterContext(agent);
@@ -2023,7 +2025,7 @@
             }
         } catch (Exception e) {
             throw new RuntimeException("Unable to create BackupAgent "
-                    + data.appInfo.backupAgentName + ": " + e.toString(), e);
+                    + classname + ": " + e.toString(), e);
         }
     }
 
diff --git a/core/java/android/app/FullBackupAgent.java b/core/java/android/app/FullBackupAgent.java
deleted file mode 100644
index acd20bd..0000000
--- a/core/java/android/app/FullBackupAgent.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app;
-
-import android.app.backup.BackupAgent;
-import android.app.backup.BackupDataInput;
-import android.app.backup.BackupDataOutput;
-import android.app.backup.FileBackupHelper;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.LinkedList;
-
-/**
- * Backs up an application's entire /data/data/<package>/... file system.  This
- * class is used by the desktop full backup mechanism and is not intended for direct
- * use by applications.
- * 
- * {@hide}
- */
-
-public class FullBackupAgent extends BackupAgent {
-    // !!! TODO: turn off debugging
-    private static final String TAG = "FullBackupAgent";
-    private static final boolean DEBUG = true;
-
-    @Override
-    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
-            ParcelFileDescriptor newState) {
-        LinkedList<File> dirsToScan = new LinkedList<File>();
-        ArrayList<String> allFiles = new ArrayList<String>();
-
-        // build the list of files in the app's /data/data tree
-        dirsToScan.add(getFilesDir());
-        if (DEBUG) Log.v(TAG, "Backing up dir tree @ " + getFilesDir().getAbsolutePath() + " :");
-        while (dirsToScan.size() > 0) {
-            File dir = dirsToScan.removeFirst();
-            File[] contents = dir.listFiles();
-            if (contents != null) {
-                for (File f : contents) {
-                    if (f.isDirectory()) {
-                        dirsToScan.add(f);
-                    } else if (f.isFile()) {
-                        if (DEBUG) Log.v(TAG, "    " + f.getAbsolutePath());
-                        allFiles.add(f.getAbsolutePath());
-                    }
-                }
-            }
-        }
-
-        // That's the file set; now back it all up
-        FileBackupHelper helper = new FileBackupHelper(this,
-                allFiles.toArray(new String[allFiles.size()]));
-        helper.performBackup(oldState, data, newState);
-    }
-
-    @Override
-    public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) {
-    }
-}
diff --git a/core/java/android/app/IBackupAgent.aidl b/core/java/android/app/IBackupAgent.aidl
index fed2bc5..52fc623 100644
--- a/core/java/android/app/IBackupAgent.aidl
+++ b/core/java/android/app/IBackupAgent.aidl
@@ -51,6 +51,7 @@
     void doBackup(in ParcelFileDescriptor oldState,
             in ParcelFileDescriptor data,
             in ParcelFileDescriptor newState,
+            boolean storeApk,
             int token, IBackupManager callbackBinder);
 
     /**
diff --git a/core/java/android/app/backup/BackupAgent.java b/core/java/android/app/backup/BackupAgent.java
index cb4e0e78..dc60e24 100644
--- a/core/java/android/app/backup/BackupAgent.java
+++ b/core/java/android/app/backup/BackupAgent.java
@@ -85,7 +85,7 @@
  */
 public abstract class BackupAgent extends ContextWrapper {
     private static final String TAG = "BackupAgent";
-    private static final boolean DEBUG = false;
+    private static final boolean DEBUG = true;
 
     public BackupAgent() {
         super(null);
@@ -172,11 +172,18 @@
      * @param newState An open, read/write ParcelFileDescriptor pointing to an
      *            empty file. The application should record the final backup
      *            state here after restoring its data from the <code>data</code> stream.
+     *            When a full-backup dataset is being restored, this will be <code>null</code>.
      */
     public abstract void onRestore(BackupDataInput data, int appVersionCode,
             ParcelFileDescriptor newState)
             throws IOException;
 
+    /**
+     * Package-private, used only for dispatching an extra step during full backup
+     */
+    void onSaveApk(BackupDataOutput data) {
+        if (DEBUG) Log.v(TAG, "--- base onSaveApk() ---");
+    }
 
     // ----- Core implementation -----
 
@@ -199,12 +206,18 @@
         public void doBackup(ParcelFileDescriptor oldState,
                 ParcelFileDescriptor data,
                 ParcelFileDescriptor newState,
+                boolean storeApk,
                 int token, IBackupManager callbackBinder) throws RemoteException {
             // Ensure that we're running with the app's normal permission level
             long ident = Binder.clearCallingIdentity();
 
             if (DEBUG) Log.v(TAG, "doBackup() invoked");
             BackupDataOutput output = new BackupDataOutput(data.getFileDescriptor());
+
+            if (storeApk) {
+                onSaveApk(output);
+            }
+
             try {
                 BackupAgent.this.onBackup(oldState, output, newState);
             } catch (IOException ex) {
diff --git a/core/java/android/app/backup/FullBackup.java b/core/java/android/app/backup/FullBackup.java
new file mode 100644
index 0000000..9850566
--- /dev/null
+++ b/core/java/android/app/backup/FullBackup.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.backup;
+
+/**
+ * Global constant definitions et cetera related to the full-backup-to-fd
+ * binary format.
+ *
+ * @hide
+ */
+public class FullBackup {
+    public static String APK_TREE_TOKEN = "a";
+    public static String OBB_TREE_TOKEN = "obb";
+    public static String ROOT_TREE_TOKEN = "r";
+    public static String DATA_TREE_TOKEN = "f";
+    public static String DATABASE_TREE_TOKEN = "db";
+    public static String SHAREDPREFS_TREE_TOKEN = "sp";
+    public static String CACHE_TREE_TOKEN = "c";
+
+    public static String FULL_BACKUP_INTENT_ACTION = "fullback";
+    public static String FULL_RESTORE_INTENT_ACTION = "fullrest";
+    public static String CONF_TOKEN_INTENT_EXTRA = "conftoken";
+
+    static public native int backupToTar(String packageName, String domain,
+            String linkdomain, String rootpath, String path, BackupDataOutput output);
+}
diff --git a/core/java/android/app/backup/FullBackupAgent.java b/core/java/android/app/backup/FullBackupAgent.java
new file mode 100644
index 0000000..f0a1f2a
--- /dev/null
+++ b/core/java/android/app/backup/FullBackupAgent.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.backup;
+
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.os.Environment;
+import android.os.ParcelFileDescriptor;
+import android.util.Log;
+
+import libcore.io.Libcore;
+import libcore.io.ErrnoException;
+import libcore.io.OsConstants;
+import libcore.io.StructStat;
+
+import java.io.File;
+import java.util.HashSet;
+import java.util.LinkedList;
+
+/**
+ * Backs up an application's entire /data/data/&lt;package&gt;/... file system.  This
+ * class is used by the desktop full backup mechanism and is not intended for direct
+ * use by applications.
+ * 
+ * {@hide}
+ */
+
+public class FullBackupAgent extends BackupAgent {
+    // !!! TODO: turn off debugging
+    private static final String TAG = "FullBackupAgent";
+    private static final boolean DEBUG = true;
+
+    PackageManager mPm;
+
+    private String mMainDir;
+    private String mFilesDir;
+    private String mDatabaseDir;
+    private String mSharedPrefsDir;
+    private String mCacheDir;
+    private String mLibDir;
+
+    @Override
+    public void onCreate() {
+        mPm = getPackageManager();
+        try {
+            ApplicationInfo appInfo = mPm.getApplicationInfo(getPackageName(), 0);
+            mMainDir = new File(appInfo.dataDir).getAbsolutePath();
+        } catch (PackageManager.NameNotFoundException e) {
+            Log.e(TAG, "Unable to find package " + getPackageName());
+            throw new RuntimeException(e);
+        }
+
+        mFilesDir = getFilesDir().getAbsolutePath();
+        mDatabaseDir = getDatabasePath("foo").getParentFile().getAbsolutePath();
+        mSharedPrefsDir = getSharedPrefsFile("foo").getParentFile().getAbsolutePath();
+        mCacheDir = getCacheDir().getAbsolutePath();
+
+        ApplicationInfo app = getApplicationInfo();
+        mLibDir = (app.nativeLibraryDir != null)
+                ? new File(app.nativeLibraryDir).getAbsolutePath()
+                : null;
+    }
+
+    @Override
+    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
+            ParcelFileDescriptor newState) {
+        // Filters, the scan queue, and the set of resulting entities
+        HashSet<String> filterSet = new HashSet<String>();
+
+        // Okay, start with the app's root tree, but exclude all of the canonical subdirs
+        if (mLibDir != null) {
+            filterSet.add(mLibDir);
+        }
+        filterSet.add(mCacheDir);
+        filterSet.add(mDatabaseDir);
+        filterSet.add(mSharedPrefsDir);
+        filterSet.add(mFilesDir);
+        processTree(FullBackup.ROOT_TREE_TOKEN, mMainDir, filterSet, data);
+
+        // Now do the same for the files dir, db dir, and shared prefs dir
+        filterSet.add(mMainDir);
+        filterSet.remove(mFilesDir);
+        processTree(FullBackup.DATA_TREE_TOKEN, mFilesDir, filterSet, data);
+
+        filterSet.add(mFilesDir);
+        filterSet.remove(mDatabaseDir);
+        processTree(FullBackup.DATABASE_TREE_TOKEN, mDatabaseDir, filterSet, data);
+
+        filterSet.add(mDatabaseDir);
+        filterSet.remove(mSharedPrefsDir);
+        processTree(FullBackup.SHAREDPREFS_TREE_TOKEN, mSharedPrefsDir, filterSet, data);
+    }
+
+    private void processTree(String domain, String rootPath,
+            HashSet<String> excludes, BackupDataOutput data) {
+        // Scan the dir tree (if it actually exists) and process each entry we find
+        File rootFile = new File(rootPath);
+        if (rootFile.exists()) {
+            LinkedList<File> scanQueue = new LinkedList<File>();
+            scanQueue.add(rootFile);
+
+            while (scanQueue.size() > 0) {
+                File file = scanQueue.remove(0);
+                String filePath = file.getAbsolutePath();
+
+                // prune this subtree?
+                if (excludes.contains(filePath)) {
+                    continue;
+                }
+
+                // If it's a directory, enqueue its contents for scanning.
+                try {
+                    StructStat stat = Libcore.os.lstat(filePath);
+                    if (OsConstants.S_ISLNK(stat.st_mode)) {
+                        if (DEBUG) Log.i(TAG, "Symlink (skipping)!: " + file);
+                        continue;
+                    } else if (OsConstants.S_ISDIR(stat.st_mode)) {
+                        File[] contents = file.listFiles();
+                        if (contents != null) {
+                            for (File entry : contents) {
+                                scanQueue.add(0, entry);
+                            }
+                        }
+                    }
+                } catch (ErrnoException e) {
+                    if (DEBUG) Log.w(TAG, "Error scanning file " + file + " : " + e);
+                    continue;
+                }
+
+                // Finally, back this file up before proceeding
+                FullBackup.backupToTar(getPackageName(), domain, null, rootPath, filePath, data);
+            }
+        }
+    }
+
+    @Override
+    void onSaveApk(BackupDataOutput data) {
+        ApplicationInfo app = getApplicationInfo();
+        if (DEBUG) Log.i(TAG, "APK flags: system=" + ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0)
+                + " updated=" + ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)
+                + " locked=" + ((app.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) );
+        if (DEBUG) Log.i(TAG, "codepath: " + getPackageCodePath());
+
+        // Forward-locked apps, system-bundled .apks, etc are filtered out before we get here
+        final String pkgName = getPackageName();
+        final String apkDir = new File(getPackageCodePath()).getParent();
+        FullBackup.backupToTar(pkgName, FullBackup.APK_TREE_TOKEN, null,
+                apkDir, getPackageCodePath(), data);
+
+        // Save associated .obb content if it exists and we did save the apk
+        // check for .obb and save those too
+        final File obbDir = Environment.getExternalStorageAppObbDirectory(pkgName);
+        if (obbDir != null) {
+            if (DEBUG) Log.i(TAG, "obb dir: " + obbDir.getAbsolutePath());
+            File[] obbFiles = obbDir.listFiles();
+            if (obbFiles != null) {
+                final String obbDirName = obbDir.getAbsolutePath();
+                for (File obb : obbFiles) {
+                    FullBackup.backupToTar(pkgName, FullBackup.OBB_TREE_TOKEN, null,
+                            obbDirName, obb.getAbsolutePath(), data);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) {
+    }
+}
diff --git a/core/java/android/app/backup/IBackupManager.aidl b/core/java/android/app/backup/IBackupManager.aidl
index b315b3a..94e31a8 100644
--- a/core/java/android/app/backup/IBackupManager.aidl
+++ b/core/java/android/app/backup/IBackupManager.aidl
@@ -16,7 +16,9 @@
 
 package android.app.backup;
 
+import android.app.backup.IFullBackupRestoreObserver;
 import android.app.backup.IRestoreSession;
+import android.os.ParcelFileDescriptor;
 import android.content.Intent;
 
 /**
@@ -121,6 +123,42 @@
     void backupNow();
 
     /**
+     * Write a full backup of the given package to the supplied file descriptor.
+     * The fd may be a socket or other non-seekable destination.  If no package names
+     * are supplied, then every application on the device will be backed up to the output.
+     *
+     * <p>This method is <i>synchronous</i> -- it does not return until the backup has
+     * completed.
+     *
+     * <p>Callers must hold the android.permission.BACKUP permission to use this method.
+     *
+     * @param fd The file descriptor to which a 'tar' file stream is to be written
+     * @param includeApks If <code>true</code>, the resulting tar stream will include the
+     *     application .apk files themselves as well as their data.
+     * @param includeShared If <code>true</code>, the resulting tar stream will include
+     *     the contents of the device's shared storage (SD card or equivalent).
+     * @param allApps If <code>true</code>, the resulting tar stream will include all
+     *     installed applications' data, not just those named in the <code>packageNames</code>
+     *     parameter.
+     * @param packageNames The package names of the apps whose data (and optionally .apk files)
+     *     are to be backed up.  The <code>allApps</code> parameter supersedes this.
+     */
+    void fullBackup(in ParcelFileDescriptor fd, boolean includeApks, boolean includeShared,
+            boolean allApps, in String[] packageNames);
+
+    /**
+     * Confirm that the requested full backup/restore operation can proceed.  The system will
+     * not actually perform the operation described to fullBackup() / fullRestore() unless the
+     * UI calls back into the Backup Manager to confirm, passing the correct token.  At
+     * the same time, the UI supplies a callback Binder for progress notifications during
+     * the operation.
+     *
+     * <p>Callers must hold the android.permission.BACKUP permission to use this method.
+     */
+    void acknowledgeFullBackupOrRestore(int token, boolean allow,
+            IFullBackupRestoreObserver observer);
+
+    /**
      * Identify the currently selected transport.  Callers must hold the
      * android.permission.BACKUP permission to use this method.
      */
diff --git a/core/java/android/app/backup/IFullBackupRestoreObserver.aidl b/core/java/android/app/backup/IFullBackupRestoreObserver.aidl
new file mode 100644
index 0000000..3e0b73d
--- /dev/null
+++ b/core/java/android/app/backup/IFullBackupRestoreObserver.aidl
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.backup;
+
+/**
+ * Observer of a full backup or restore process.  The observer is told "interesting"
+ * information about an ongoing full backup or restore action.
+ *
+ * {@hide}
+ */
+
+oneway interface IFullBackupRestoreObserver {
+    /**
+     * Notification: a full backup operation has begun.
+     */
+    void onStartBackup();
+
+    /**
+     * Notification: the system has begun backing up the given package.
+     *
+     * @param name The name of the application being saved.  This will typically be a
+     *     user-meaningful name such as "Browser" rather than a package name such as
+     *     "com.android.browser", though this is not guaranteed.
+     */
+    void onBackupPackage(String name);
+
+    /**
+     * Notification: the full backup operation has ended.
+     */
+    void onEndBackup();
+
+    /**
+     * Notification: a restore-from-full-backup operation has begun.
+     */
+    void onStartRestore();
+
+    /**
+     * Notification: the system has begun restore of the given package.
+     *
+     * @param name The name of the application being saved.  This will typically be a
+     *     user-meaningful name such as "Browser" rather than a package name such as
+     *     "com.android.browser", though this is not guaranteed.
+     */
+    void onRestorePackage(String name);
+
+    /**
+     * Notification: the restore-from-full-backup operation has ended.
+     */
+    void onEndRestore();
+
+    /**
+     * The user's window of opportunity for confirming the operation has timed out.
+     */
+    void onTimeout();
+}
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 92b2c3b..4b38d48 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -89,7 +89,16 @@
      * <p>If android:allowBackup is set to false, this attribute is ignored.
      */
     public String backupAgentName;
-    
+
+    /**
+     * Class implementing the package's *full* backup functionality.  This
+     * is not usable except by system-installed packages.  It can be the same
+     * as the backupAgent.
+     *
+     * @hide
+     */
+    public String fullBackupAgentName;
+
     /**
      * Value for {@link #flags}: if set, this application is installed in the
      * device's system image.
@@ -505,6 +514,7 @@
         dest.writeInt(installLocation);
         dest.writeString(manageSpaceActivityName);
         dest.writeString(backupAgentName);
+        dest.writeString(fullBackupAgentName);
         dest.writeInt(descriptionRes);
     }
 
@@ -538,6 +548,7 @@
         installLocation = source.readInt();
         manageSpaceActivityName = source.readString();
         backupAgentName = source.readString();
+        fullBackupAgentName = source.readString();
         descriptionRes = source.readInt();
     }
 
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 564f4f4..b8cb165 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -1506,7 +1506,17 @@
                 }
             }
         }
-        
+
+        name = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestApplication_fullBackupAgent, 0);
+        if (name != null) {
+            ai.fullBackupAgentName = buildClassName(pkgName, name, outError);
+            if (true) {
+                Log.v(TAG, "android:fullBackupAgent=" + ai.fullBackupAgentName
+                        + " from " + pkgName + "+" + name);
+            }
+        }
+
         TypedValue v = sa.peekValue(
                 com.android.internal.R.styleable.AndroidManifestApplication_label);
         if (v != null && (ai.labelRes=v.resourceId) == 0) {
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 8beb94b..223008c 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -151,6 +151,7 @@
 	android_backup_BackupDataOutput.cpp \
 	android_backup_FileBackupHelperBase.cpp \
 	android_backup_BackupHelperDispatcher.cpp \
+	android_app_backup_FullBackup.cpp \
 	android_content_res_ObbScanner.cpp \
 	android_content_res_Configuration.cpp \
     android_animation_PropertyValuesHolder.cpp
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 17f9246..b787e9f 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -165,6 +165,7 @@
 extern int register_android_backup_BackupDataOutput(JNIEnv *env);
 extern int register_android_backup_FileBackupHelperBase(JNIEnv *env);
 extern int register_android_backup_BackupHelperDispatcher(JNIEnv *env);
+extern int register_android_app_backup_FullBackup(JNIEnv *env);
 extern int register_android_app_ActivityThread(JNIEnv *env);
 extern int register_android_app_NativeActivity(JNIEnv *env);
 extern int register_android_view_InputChannel(JNIEnv* env);
@@ -1208,7 +1209,7 @@
     REG_JNI(register_android_backup_BackupDataOutput),
     REG_JNI(register_android_backup_FileBackupHelperBase),
     REG_JNI(register_android_backup_BackupHelperDispatcher),
-
+    REG_JNI(register_android_app_backup_FullBackup),
     REG_JNI(register_android_app_ActivityThread),
     REG_JNI(register_android_app_NativeActivity),
     REG_JNI(register_android_view_InputChannel),
diff --git a/core/jni/android_app_backup_FullBackup.cpp b/core/jni/android_app_backup_FullBackup.cpp
new file mode 100644
index 0000000..ecfe5ff
--- /dev/null
+++ b/core/jni/android_app_backup_FullBackup.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "FullBackup_native"
+#include <utils/Log.h>
+#include <utils/String8.h>
+
+#include "JNIHelp.h"
+#include <android_runtime/AndroidRuntime.h>
+
+#include <utils/BackupHelpers.h>
+
+#include <string.h>
+
+namespace android
+{
+
+// android.app.backup.BackupDataOutput
+static struct {
+    // This is actually a native pointer to the underlying BackupDataWriter instance
+    jfieldID mBackupWriter;
+} sBackupDataOutput;
+
+/*
+ * Write files to the given output.  This implementation does *not* create
+ * a standalone archive suitable for restore on its own.  In particular, the identification of
+ * the application's name etc is not in-band here; it's assumed that the calling code has
+ * taken care of supplying that information previously in the output stream.
+ *
+ * The file format is 'tar's, with special semantics applied by use of a "fake" directory
+ * hierarchy within the tar stream:
+ *
+ * apps/packagename/a/Filename.apk - this is an actual application binary, which will be
+ *   installed on the target device at restore time.  These need to appear first in the tar
+ *   stream.
+ * apps/packagename/obb/[relpath] - OBB containers belonging the app
+ * apps/packagename/r/[relpath] - these are files at the root of the app's data tree
+ * apps/packagename/f/[relpath] - this is a file within the app's getFilesDir() tree, stored
+ *   at [relpath] relative to the top of that tree.
+ * apps/packagename/db/[relpath] - as with "files" but for the getDatabasePath() tree
+ * apps/packagename/sp/[relpath] - as with "files" but for the getSharedPrefsFile() tree
+ * apps/packagename/c/[relpath] - as with "files" but for the getCacheDir() tree
+ *
+ * and for the shared storage hierarchy:
+ *
+ * shared/[relpaths] - files belonging in the device's shared storage location.  This will
+ *    *not* include .obb files; those are saved with their owning apps.
+ *
+ * This method writes one file data block.  'domain' is the name of the appropriate pseudo-
+ * directory to be applied for this file; 'linkdomain' is the pseudo-dir for a relative
+ * symlink's antecedent.
+ *
+ * packagename: the package name to use as the top level directory tag
+ * domain:      which semantic name the file is to be stored under (a, r, f, db, etc)
+ * linkdomain:  where a symlink points for purposes of rewriting; current unused
+ * rootpath:    prefix to be snipped from full path when encoding in tar
+ * path:        absolute path to the file to be saved
+ * dataOutput:  the BackupDataOutput object that we're saving into
+ */
+static int backupToTar(JNIEnv* env, jobject clazz, jstring packageNameObj,
+        jstring domainObj, jstring linkdomain,
+        jstring rootpathObj, jstring pathObj, jobject dataOutputObj) {
+    // Extract the various strings, allowing for null object pointers
+    const char* packagenamechars = env->GetStringUTFChars(packageNameObj, NULL);
+    const char* rootchars = env->GetStringUTFChars(rootpathObj, NULL);
+    const char* pathchars = env->GetStringUTFChars(pathObj, NULL);
+    const char* domainchars = env->GetStringUTFChars(domainObj, NULL);
+
+    String8 packageName(packagenamechars ? packagenamechars : "");
+    String8 rootpath(rootchars ? rootchars : "");
+    String8 path(pathchars ? pathchars : "");
+    String8 domain(domainchars ? domainchars : "");
+
+    if (domainchars) env->ReleaseStringUTFChars(domainObj, domainchars);
+    if (pathchars) env->ReleaseStringUTFChars(pathObj, pathchars);
+    if (rootchars) env->ReleaseStringUTFChars(rootpathObj, rootchars);
+    if (packagenamechars) env->ReleaseStringUTFChars(packageNameObj, packagenamechars);
+
+    // Extract the data output fd
+    BackupDataWriter* writer = (BackupDataWriter*) env->GetIntField(dataOutputObj,
+            sBackupDataOutput.mBackupWriter);
+
+    // Validate
+    if (!writer) {
+        LOGE("No output stream provided [%s]", path.string());
+        return -1;
+    }
+
+    if (path.length() < rootpath.length()) {
+        LOGE("file path [%s] shorter than root path [%s]",
+                path.string(), rootpath.string());
+        return -1;
+    }
+
+    return write_tarfile(packageName, domain, rootpath, path, writer);
+}
+
+static const JNINativeMethod g_methods[] = {
+    { "backupToTar",
+            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/backup/BackupDataOutput;)I",
+            (void*)backupToTar },
+};
+
+int register_android_app_backup_FullBackup(JNIEnv* env)
+{
+    jclass clazz = env->FindClass("android/app/backup/BackupDataOutput");
+    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.app.backup.BackupDataOutput");
+
+    sBackupDataOutput.mBackupWriter = env->GetFieldID(clazz, "mBackupWriter", "I");
+    LOG_FATAL_IF(sBackupDataOutput.mBackupwriter == NULL,
+            "Unable to find mBackupWriter field in android.app.backup.BackupDataOutput");
+
+    return AndroidRuntime::registerNativeMethods(env, "android/app/backup/FullBackup",
+            g_methods, NELEM(g_methods));
+}
+
+}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 1c4bffd..2d85ccc 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -1241,6 +1241,14 @@
         android:description="@string/permdesc_backup"
         android:protectionLevel="signatureOrSystem" />
 
+    <!-- Allows a package to launch the secure full-backup confirmation UI.
+         ONLY the system process may hold this permission.
+         @hide -->
+    <permission android:name="android.permission.CONFIRM_FULL_BACKUP"
+        android:label="@string/permlab_confirm_full_backup"
+        android:description="@string/permdesc_confirm_full_backup"
+        android:protectionLevel="signature" />
+
     <!-- Must be required by a {@link android.widget.RemoteViewsService},
          to ensure that only the system can bind to it. -->
     <permission android:name="android.permission.BIND_REMOTEVIEWS"
@@ -1329,12 +1337,17 @@
           android:protectionLevel="signature" />
     <uses-permission android:name="android.intent.category.MASTER_CLEAR.permission.C2D_MESSAGE"/>
 
+    <!-- The system process is explicitly the only one allowed to launch the
+         confirmation UI for full backup/restore -->
+    <uses-permission android:name="android.permission.CONFIRM_FULL_BACKUP"/>
+
     <application android:process="system"
                  android:persistent="true"
                  android:hasCode="false"
                  android:label="@string/android_system_label"
                  android:allowClearUserData="false"
                  android:backupAgent="com.android.server.SystemBackupAgent"
+                 android:fullBackupAgent="com.android.server.SystemBackupAgent"
                  android:killAfterRestore="false"
                  android:icon="@drawable/ic_launcher_android">
         <activity android:name="com.android.internal.app.ChooserActivity"
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 9b04f78..1463bc7 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -685,6 +685,13 @@
          <p>The default value of this attribute is <code>false</code>. -->
     <attr name="restoreAnyVersion" format="boolean" />
 
+    <!-- The agent to use for a *full* backup of the package.  Only system applications
+         can use this to override the ordinary FullBackupAgent with a custom implementation.
+         It's needed strictly for packages with strongly device-specific data, such as the
+         Settings provider.
+         -->
+    <attr name="fullBackupAgent" format="string" />
+
     <!-- The default install location defined by an application. -->
     <attr name="installLocation">
         <!-- Let the system decide ideal install location -->
@@ -782,6 +789,7 @@
         <attr name="killAfterRestore" />
         <attr name="restoreNeedsApplication" />
         <attr name="restoreAnyVersion" />
+        <attr name="fullBackupAgent" />
         <attr name="neverEncrypt" />
         <!-- Request that your application's processes be created with
              a large Dalvik heap.  This applies to <em>all</em> processes
@@ -790,7 +798,7 @@
              to allow multiple applications to use a process, they all must
              use this option consistently or will get unpredictable results. -->
         <attr name="largeHeap" format="boolean" />
-        <!-- Declare that this applicationn can't participate in the normal
+        <!-- Declare that this application can't participate in the normal
              state save/restore mechanism.  Since it is not able to save and
              restore its state on demand,
              it can not participate in the normal activity lifecycle.  It will
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 7ca5e98..652d791 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1668,4 +1668,6 @@
   <public type="attr" name="textEditSuggestionsTopWindowLayout" />
   <public type="attr" name="textEditSuggestionItemLayout" />
 
+  <public type="attr" name="fullBackupAgent" />
+
 </resources>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 358e0e0..3951623 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -631,6 +631,11 @@
     <string name="permdesc_backup">Allows the application to control the system\'s backup and restore mechanism.  Not for use by normal applications.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permlab_confirm_full_backup">confirm a full backup or restore operation</string>
+    <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+    <string name="permdesc_confirm_full_backup">Allows the application to launch the full backup confirmation UI.  Not to be used by any application.</string>
+
+    <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_internalSystemWindow">display unauthorized windows</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permdesc_internalSystemWindow">Allows the creation of