summaryrefslogtreecommitdiff
path: root/backup/backup.cpp
blob: 48f64eecc77a0ce878487e645d7aeae79e728b5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
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");
}