OSDN Git Service

AI 143417: am: CL 143416 Quick and dirty backup command. This should only be include...
authorDianne Hackborn <>
Sat, 28 Mar 2009 03:59:40 +0000 (20:59 -0700)
committerThe Android Open Source Project <initial-contribution@android.com>
Sat, 28 Mar 2009 03:59:40 +0000 (20:59 -0700)
  Original author: hackbod
  Merged from: //branches/cupcake/...

Automated import of CL 143417

backup/Android.mk [new file with mode: 0644]
backup/NOTICE [new file with mode: 0644]
backup/backup.cpp [new file with mode: 0644]

diff --git a/backup/Android.mk b/backup/Android.mk
new file mode 100644 (file)
index 0000000..6a3d3fe
--- /dev/null
@@ -0,0 +1,15 @@
+# Copyright 2009 The Android Open Source Project
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= backup.cpp
+
+LOCAL_SHARED_LIBRARIES := libcutils libc
+
+LOCAL_MODULE:= backup
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
+LOCAL_MODULE_TAGS := debug
+
+include $(BUILD_EXECUTABLE)
diff --git a/backup/NOTICE b/backup/NOTICE
new file mode 100644 (file)
index 0000000..c5b1efa
--- /dev/null
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2005-2008, 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.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/backup/backup.cpp b/backup/backup.cpp
new file mode 100644 (file)
index 0000000..48f64ee
--- /dev/null
@@ -0,0 +1,674 @@
+// Copyright 2009 The Android Open Source Project
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <time.h>
+#include <dirent.h>
+#include <errno.h>
+#include <assert.h>
+#include <ctype.h>
+#include <utime.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <cutils/properties.h>
+
+#include <private/android_filesystem_config.h>
+
+#ifndef PATH_MAX
+#define PATH_MAX 4096
+#endif
+
+#define FILE_VERSION 0xffff0001
+
+namespace android {
+
+static char nameBuffer[PATH_MAX];
+static struct stat statBuffer;
+
+static char copyBuffer[8192];
+
+#define SPECIAL_NO_TOUCH 0
+#define SPECIAL_NO_BACKUP 1
+
+struct special_dir {
+    const char* path;
+    int type;
+};
+
+/* Directory paths that we will not backup/restore */
+static const struct special_dir SKIP_PATHS[] = {
+    { "/data/misc", SPECIAL_NO_TOUCH },
+    { "/data/system/batterystats.bin", SPECIAL_NO_TOUCH },
+    { "/data/system/location", SPECIAL_NO_TOUCH },
+    { "/data/dalvik-cache", SPECIAL_NO_BACKUP },
+    { NULL, 0 },
+};
+
+/* This is just copied from the shell's built-in wipe command. */
+static int wipe (const char *path) 
+{
+    DIR *dir;
+    struct dirent *de;
+    int ret;
+    int i;
+
+    dir = opendir(path);
+
+    if (dir == NULL) {
+        fprintf (stderr, "Error opendir'ing %s: %s\n",
+                    path, strerror(errno));
+        return 0;
+    }
+
+    char *filenameOffset;
+
+    strcpy(nameBuffer, path);
+    strcat(nameBuffer, "/");
+
+    filenameOffset = nameBuffer + strlen(nameBuffer);
+
+    for (;;) {
+        de = readdir(dir);
+
+        if (de == NULL) {
+            break;
+        }
+
+        if (0 == strcmp(de->d_name, ".")
+                || 0 == strcmp(de->d_name, "..")
+                || 0 == strcmp(de->d_name, "lost+found")
+        ) {
+            continue;
+        }
+
+        strcpy(filenameOffset, de->d_name);
+        bool noBackup = false;
+        
+        /* See if this is a path we should skip. */
+        for (i = 0; SKIP_PATHS[i].path; i++) {
+            if (strcmp(SKIP_PATHS[i].path, nameBuffer) == 0) {
+                if (SKIP_PATHS[i].type == SPECIAL_NO_BACKUP) {
+                    // In this case we aren't backing up the directory --
+                    // we do want to wipe its contents, but not the
+                    // directory itself, since the restore file won't
+                    // contain the directory.
+                    noBackup = true;
+                }
+                break;
+            }
+        }
+        if (!noBackup && SKIP_PATHS[i].path != NULL) {
+            continue;
+        }
+
+        ret = lstat (nameBuffer, &statBuffer);
+
+        if (ret != 0) {
+            fprintf(stderr, "warning -- stat() error on '%s': %s\n", 
+                    nameBuffer, strerror(errno));
+            continue;
+        }
+
+        if(S_ISDIR(statBuffer.st_mode)) {
+            int i;
+            char *newpath;
+
+            newpath = strdup(nameBuffer);
+            if (wipe(newpath) == 0) {
+                free(newpath);
+                closedir(dir);
+                return 0;
+            }
+            
+            if (!noBackup) {
+                ret = rmdir(newpath);
+                if (ret != 0) {
+                    fprintf(stderr, "warning -- rmdir() error on '%s': %s\n", 
+                        newpath, strerror(errno));
+                }
+            }
+
+            free(newpath);
+
+            strcpy(nameBuffer, path);
+            strcat(nameBuffer, "/");
+
+        } else {
+            ret = unlink(nameBuffer);
+
+            if (ret != 0) {
+                fprintf(stderr, "warning -- unlink() error on '%s': %s\n", 
+                    nameBuffer, strerror(errno));
+            }
+        }
+    }
+
+    closedir(dir);
+    
+    return 1;
+}
+
+static int write_int32(FILE* fh, int32_t val)
+{
+    int res = fwrite(&val, 1, sizeof(val), fh);
+    if (res != sizeof(val)) {
+        fprintf(stderr, "unable to write int32 (%d bytes): %s\n", res, strerror(errno));
+        return 0;
+    }
+    
+    return 1;
+}
+
+static int write_int64(FILE* fh, int64_t val)
+{
+    int res = fwrite(&val, 1, sizeof(val), fh); 
+    if (res != sizeof(val)) {
+        fprintf(stderr, "unable to write int64 (%d bytes): %s\n", res, strerror(errno));
+        return 0;
+    }
+    
+    return 1;
+}
+
+static int copy_file(FILE* dest, FILE* src, off_t size, const char* destName,
+        const char* srcName)
+{
+    errno = 0;
+    
+    off_t origSize = size;
+    
+    while (size > 0) {
+        int amt = size > (off_t)sizeof(copyBuffer) ? sizeof(copyBuffer) : (int)size;
+        int readLen = fread(copyBuffer, 1, amt, src);
+        if (readLen <= 0) {
+            if (srcName != NULL) {
+                fprintf(stderr, "unable to read source (%d of %ld bytes) file '%s': %s\n",
+                    amt, origSize, srcName, errno != 0 ? strerror(errno) : "unexpected EOF");
+            } else {
+                fprintf(stderr, "unable to read buffer (%d of %ld bytes): %s\n",
+                    amt, origSize, errno != 0 ? strerror(errno) : "unexpected EOF");
+            }
+            return 0;
+        }
+        int writeLen = fwrite(copyBuffer, 1, readLen, dest); 
+        if (writeLen != readLen) {
+            if (destName != NULL) {
+                fprintf(stderr, "unable to write file (%d of %d bytes) '%s': '%s'\n",
+                    writeLen, readLen, destName, strerror(errno));
+            } else {
+                fprintf(stderr, "unable to write buffer (%d of %d bytes): '%s'\n",
+                    writeLen, readLen, strerror(errno));
+            }
+            return 0;
+        }
+        size -= readLen;
+    }
+    return 1;
+}
+
+#define TYPE_END 0
+#define TYPE_DIR 1
+#define TYPE_FILE 2
+
+static int write_header(FILE* fh, int type, const char* path, const struct stat* st)
+{
+    int pathLen = strlen(path);
+    if (!write_int32(fh, type)) return 0;
+    if (!write_int32(fh, pathLen)) return 0;
+    if (fwrite(path, 1, pathLen, fh) != (size_t)pathLen) {
+        fprintf(stderr, "unable to write: %s\n", strerror(errno));
+        return 0;
+    }
+    
+    if (!write_int32(fh, st->st_uid)) return 0;
+    if (!write_int32(fh, st->st_gid)) return 0;
+    if (!write_int32(fh, st->st_mode)) return 0;
+    if (!write_int64(fh, ((int64_t)st->st_atime)*1000*1000*1000)) return 0;
+    if (!write_int64(fh, ((int64_t)st->st_mtime)*1000*1000*1000)) return 0;
+    if (!write_int64(fh, ((int64_t)st->st_ctime)*1000*1000*1000)) return 0;
+    
+    return 1;
+}
+
+static int backup_dir(FILE* fh, const char* srcPath)
+{
+    DIR *dir;
+    struct dirent *de;
+    char* fullPath = NULL;
+    int srcLen = strlen(srcPath);
+    int result = 1;
+    int i;
+    
+    dir = opendir(srcPath);
+
+    if (dir == NULL) {
+        fprintf (stderr, "error opendir'ing '%s': %s\n",
+                    srcPath, strerror(errno));
+        return 0;
+    }
+    
+    for (;;) {
+        de = readdir(dir);
+
+        if (de == NULL) {
+            break;
+        }
+
+        if (0 == strcmp(de->d_name, ".")
+                || 0 == strcmp(de->d_name, "..")
+                || 0 == strcmp(de->d_name, "lost+found")
+        ) {
+            continue;
+        }
+
+        if (fullPath == NULL) {
+            free(fullPath);
+        }
+        fullPath = (char*)malloc(srcLen + strlen(de->d_name) + 2);
+        strcpy(fullPath, srcPath);
+        fullPath[srcLen] = '/';
+        strcpy(fullPath+srcLen+1, de->d_name);
+
+        /* See if this is a path we should skip. */
+        for (i = 0; SKIP_PATHS[i].path; i++) {
+            if (strcmp(SKIP_PATHS[i].path, fullPath) == 0) {
+                break;
+            }
+        }
+        if (SKIP_PATHS[i].path != NULL) {
+            continue;
+        }
+
+        int ret = lstat(fullPath, &statBuffer);
+
+        if (ret != 0) {
+            fprintf(stderr, "stat() error on '%s': %s\n", 
+                    fullPath, strerror(errno));
+            result = 0;
+            goto done;
+        }
+
+        if(S_ISDIR(statBuffer.st_mode)) {
+            printf("Processing dir %s...\n", fullPath);
+            
+            if (write_header(fh, TYPE_DIR, fullPath, &statBuffer) == 0) {
+                result = 0;
+                goto done;
+            }
+            if (backup_dir(fh, fullPath) == 0) {
+                result = 0;
+                goto done;
+            }
+        } else {
+            printf("Processing file %s...\n", fullPath);
+            
+            if (write_header(fh, TYPE_FILE, fullPath, &statBuffer) == 0) {
+                result = 0;
+                goto done;
+            }
+            
+            off_t size = statBuffer.st_size;
+            if (!write_int64(fh, size)) {
+                result = 0;
+                goto done;
+            }
+            
+            FILE* src = fopen(fullPath, "r");
+            if (src == NULL) {
+                fprintf(stderr, "unable to open source file '%s': %s\n",
+                    fullPath, strerror(errno));
+                result = 0;
+                goto done;
+            }
+            
+            int copyres = copy_file(fh, src, size, NULL, fullPath);
+            fclose(src);
+            if (!copyres) {
+                result = 0;
+                goto done;
+            }
+        }
+    }
+
+done:
+    if (fullPath != NULL) {
+        free(fullPath);
+    }
+    
+    closedir(dir);
+    
+    return result;
+}
+
+static int backup_data(const char* destPath)
+{
+    int res = -1;
+    
+    FILE* fh = fopen(destPath, "w");
+    if (fh == NULL) {
+        fprintf(stderr, "unable to open destination '%s': %s\n",
+                destPath, strerror(errno));
+        return -1;
+    }
+    
+    printf("Backing up /data to %s...\n", destPath);
+
+    if (!write_int32(fh, FILE_VERSION)) goto done;
+    if (!backup_dir(fh, "/data")) goto done;
+    if (!write_int32(fh, 0)) goto done;
+    
+    res = 0;
+    
+done:
+    if (fflush(fh) != 0) {
+        fprintf(stderr, "error flushing destination '%s': %s\n",
+            destPath, strerror(errno));
+        res = -1;
+        goto donedone;
+    }
+    if (fsync(fileno(fh)) != 0) {
+        fprintf(stderr, "error syncing destination '%s': %s\n",
+            destPath, strerror(errno));
+        res = -1;
+        goto donedone;
+    }
+    fclose(fh);
+    sync();
+
+donedone:    
+    return res;
+}
+
+static int32_t read_int32(FILE* fh, int32_t defVal)
+{
+    int32_t val;
+    if (fread(&val, 1, sizeof(val), fh) != sizeof(val)) {
+        fprintf(stderr, "unable to read: %s\n", strerror(errno));
+        return defVal;
+    }
+    
+    return val;
+}
+
+static int64_t read_int64(FILE* fh, int64_t defVal)
+{
+    int64_t val;
+    if (fread(&val, 1, sizeof(val), fh) != sizeof(val)) {
+        fprintf(stderr, "unable to read: %s\n", strerror(errno));
+        return defVal;
+    }
+    
+    return val;
+}
+
+static int read_header(FILE* fh, int* type, char** path, struct stat* st)
+{
+    *type = read_int32(fh, -1);
+    if (*type == TYPE_END) {
+        return 1;
+    }
+    
+    if (*type < 0) {
+        fprintf(stderr, "bad token %d in restore file\n", *type);
+        return 0;
+    }
+    
+    int32_t pathLen = read_int32(fh, -1);
+    if (pathLen <= 0) {
+        fprintf(stderr, "bad path length %d in restore file\n", pathLen);
+        return 0;
+    }
+    char* readPath = (char*)malloc(pathLen+1);
+    if (fread(readPath, 1, pathLen, fh) != (size_t)pathLen) {
+        fprintf(stderr, "truncated path in restore file\n");
+        free(readPath);
+        return 0;
+    }
+    readPath[pathLen] = 0;
+    *path = readPath;
+    
+    st->st_uid = read_int32(fh, -1);
+    if (st->st_uid == (uid_t)-1) {
+        fprintf(stderr, "bad uid in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    st->st_gid = read_int32(fh, -1);
+    if (st->st_gid == (gid_t)-1) {
+        fprintf(stderr, "bad gid in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    st->st_mode = read_int32(fh, -1);
+    if (st->st_mode == (mode_t)-1) {
+        fprintf(stderr, "bad mode in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    int64_t ltime = read_int64(fh, -1);
+    if (ltime < 0) {
+        fprintf(stderr, "bad atime in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    st->st_atime = (time_t)(ltime/1000/1000/1000);
+    ltime = read_int64(fh, -1);
+    if (ltime < 0) {
+        fprintf(stderr, "bad mtime in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    st->st_mtime = (time_t)(ltime/1000/1000/1000);
+    ltime = read_int64(fh, -1);
+    if (ltime < 0) {
+        fprintf(stderr, "bad ctime in restore file at '%s'\n", readPath);
+        return 0;
+    }
+    st->st_ctime = (time_t)(ltime/1000/1000/1000);
+    
+    st->st_mode &= (S_IRWXU|S_IRWXG|S_IRWXO);
+    
+    return 1;
+}
+
+static int restore_data(const char* srcPath)
+{
+    int res = -1;
+    
+    FILE* fh = fopen(srcPath, "r");
+    if (fh == NULL) {
+        fprintf(stderr, "Unable to open source '%s': %s\n",
+                srcPath, strerror(errno));
+        return -1;
+    }
+    
+    if (read_int32(fh, 0) != (int32_t)FILE_VERSION) {
+        fprintf(stderr, "Restore file has bad version\n");
+        goto done;
+    }
+    
+    printf("Wiping contents of /data...\n");
+    if (!wipe("/data")) {
+        goto done;
+    }
+
+    printf("Restoring from %s to /data...\n", srcPath);
+
+    while (1) {
+        int type;
+        char* path = NULL;
+        if (read_header(fh, &type, &path, &statBuffer) == 0) {
+            goto done;
+        }
+        if (type == 0) {
+            break;
+        }
+        
+        const char* typeName = "?";
+        
+        if (type == TYPE_DIR) {
+            typeName = "dir";
+            
+            printf("Processing dir %s...\n", path);
+            
+            if (mkdir(path, statBuffer.st_mode) != 0) {
+                if (errno != EEXIST) {
+                    fprintf(stderr, "unable to create directory '%s': %s\n",
+                        path, strerror(errno));
+                    free(path);
+                    goto done;
+                }
+            }
+            
+        } else if (type == TYPE_FILE) {
+            typeName = "file";
+            off_t size = read_int64(fh, -1);
+            if (size < 0) {
+                fprintf(stderr, "bad file size %ld in restore file\n", size);
+                free(path);
+                goto done;
+            }
+            
+            printf("Processing file %s...\n", path);
+            
+            FILE* dest = fopen(path, "w");
+            if (dest == NULL) {
+                fprintf(stderr, "unable to open destination file '%s': %s\n",
+                    path, strerror(errno));
+                free(path);
+                goto done;
+            }
+            
+            int copyres = copy_file(dest, fh, size, path, NULL);
+            fclose(dest);
+            if (!copyres) {
+                free(path);
+                goto done;
+            }
+        
+        } else {
+            fprintf(stderr, "unknown node type %d\n", type);
+            goto done;
+        }
+        
+        // Do this even for directories, since the dir may have already existed
+        // so we need to make sure it gets the correct mode.    
+        if (chmod(path, statBuffer.st_mode&(S_IRWXU|S_IRWXG|S_IRWXO)) != 0) {
+            fprintf(stderr, "unable to chmod destination %s '%s' to 0x%x: %s\n",
+                typeName, path, statBuffer.st_mode, strerror(errno));
+            free(path);
+            goto done;
+        }
+        
+        if (chown(path, statBuffer.st_uid, statBuffer.st_gid) != 0) {
+            fprintf(stderr, "unable to chown destination %s '%s' to uid %d / gid %d: %s\n",
+                typeName, path, (int)statBuffer.st_uid, (int)statBuffer.st_gid, strerror(errno));
+            free(path);
+            goto done;
+        }
+        
+        struct utimbuf timbuf;
+        timbuf.actime = statBuffer.st_atime;
+        timbuf.modtime = statBuffer.st_mtime;
+        if (utime(path, &timbuf) != 0) {
+            fprintf(stderr, "unable to utime destination %s '%s': %s\n",
+                typeName, path, strerror(errno));
+            free(path);
+            goto done;
+        }
+        
+        
+        free(path);
+    }
+    
+    res = 0;
+        
+done:    
+    fclose(fh);
+    
+    return res;
+}
+
+static void show_help(const char *cmd)
+{
+    fprintf(stderr,"Usage: %s [options] [backup-file-path]\n", cmd);
+
+    fprintf(stderr, "options include:\n"
+                    "  -r              Perform restore of previous backup.\n");
+}
+
+} /* namespace android */
+
+int main (int argc, char **argv)
+{
+    int restore = 0;
+
+    if (getuid() != AID_ROOT) {
+        fprintf(stderr, "error -- %s must run as root\n", argv[0]);
+        exit(-1);
+    }
+        
+    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
+        android::show_help(argv[0]);
+        exit(0);
+    }
+
+    for (;;) {
+        int ret;
+
+        ret = getopt(argc, argv, "r");
+
+        if (ret < 0) {
+            break;
+        }
+
+        switch(ret) {
+            case 'r':
+                restore = 1;
+            break;
+
+            default:
+                fprintf(stderr,"Unrecognized Option\n");
+                android::show_help(argv[0]);
+                exit(-1);
+            break;
+        }
+    }
+
+    const char* backupFile = "/sdcard/backup.dat";
+    
+    if (argc > optind) {
+        backupFile = argv[optind];
+        optind++;
+        if (argc != optind) {
+            fprintf(stderr, "Too many arguments\n");
+            android::show_help(argv[0]);
+            exit(-1);
+        }
+    }
+    
+    printf("Stopping system...\n");
+    property_set("ctl.stop", "runtime");
+    property_set("ctl.stop", "zygote");
+    sleep(1);
+    
+    int res;
+    if (restore) {
+        res = android::restore_data(backupFile);
+        if (res != 0) {
+            // Don't restart system, since the data partition is hosed.
+            return res;
+        }
+        printf("Restore complete!  Restarting system, cross your fingers...\n");
+    } else {
+        res = android::backup_data(backupFile);
+        if (res == 0) {
+            printf("Backup complete!  Restarting system...\n");
+        } else {
+            printf("Restarting system...\n");
+        }
+    }
+    
+    property_set("ctl.start", "zygote");
+    property_set("ctl.start", "runtime");
+}