Debian Codegraph @

tools/idevicebackup.c

raw
1 /*
2 * idevicebackup.c
3 * Command line interface to use the device's backup and restore service
4 *
5 * Copyright (c) 2009-2010 Martin Szulecki All Rights Reserved.
6 * Copyright (c) 2010 Nikias Bassen All Rights Reserved.
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #define TOOL_NAME "idevicebackup"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <stdlib.h>
33 #include <signal.h>
34 #include <getopt.h>
35 #include <unistd.h>
36 #include <ctype.h>
37 #include <time.h>
38 #include <sys/stat.h>
39
40 #include <libimobiledevice/libimobiledevice.h>
41 #include <libimobiledevice/lockdown.h>
42 #include <libimobiledevice/mobilebackup.h>
43 #include <libimobiledevice/notification_proxy.h>
44 #include <libimobiledevice/afc.h>
45 #include <libimobiledevice-glue/sha.h>
46 #include <libimobiledevice-glue/utils.h>
47 #include <plist/plist.h>
48
49 #define MOBILEBACKUP_SERVICE_NAME "com.apple.mobilebackup"
50 #define NP_SERVICE_NAME "com.apple.mobile.notification_proxy"
51
52 #define LOCK_ATTEMPTS 50
53 #define LOCK_WAIT 200000
54
55 #ifdef _WIN32
56 #include <windows.h>
57 #define sleep(x) Sleep(x*1000)
58 #endif
59
60 static mobilebackup_client_t mobilebackup = NULL;
61 static lockdownd_client_t client = NULL;
62 static idevice_t device = NULL;
63
64 static int quit_flag = 0;
65
66 enum cmd_mode {
67 CMD_BACKUP,
68 CMD_RESTORE,
69 CMD_LEAVE
70 };
71
72 enum device_link_file_status_t {
73 DEVICE_LINK_FILE_STATUS_NONE = 0,
74 DEVICE_LINK_FILE_STATUS_HUNK,
75 DEVICE_LINK_FILE_STATUS_LAST_HUNK
76 };
77
78 static int compare_hash(const unsigned char *hash1, const unsigned char *hash2, int hash_len)
79 {
80 int i;
81 for (i = 0; i < hash_len; i++) {
82 if (hash1[i] != hash2[i]) {
83 return 0;
84 }
85 }
86 return 1;
87 }
88
89 static void compute_datahash(const char *path, const char *destpath, uint8_t greylist, const char *domain, const char *appid, const char *version, unsigned char *hash_out)
90 {
91 sha1_context sha1;
92 sha1_init(&sha1);
93 FILE *f = fopen(path, "rb");
94 if (f) {
95 unsigned char buf[16384];
96 size_t len;
97 while ((len = fread(buf, 1, 16384, f)) > 0) {
98 sha1_update(&sha1, buf, len);
99 }
100 fclose(f);
101 sha1_update(&sha1, destpath, strlen(destpath));
102 sha1_update(&sha1, ";", 1);
103
104 if (greylist == 1) {
105 sha1_update(&sha1, "true", 4);
106 } else {
107 sha1_update(&sha1, "false", 5);
108 }
109 sha1_update(&sha1, ";", 1);
110
111 if (domain) {
112 sha1_update(&sha1, domain, strlen(domain));
113 } else {
114 sha1_update(&sha1, "(null)", 6);
115 }
116 sha1_update(&sha1, ";", 1);
117
118 if (appid) {
119 sha1_update(&sha1, appid, strlen(appid));
120 } else {
121 sha1_update(&sha1, "(null)", 6);
122 }
123 sha1_update(&sha1, ";", 1);
124
125 if (version) {
126 sha1_update(&sha1, version, strlen(version));
127 } else {
128 sha1_update(&sha1, "(null)", 6);
129 }
130 sha1_final(&sha1, hash_out);
131 }
132 }
133
134 static void print_hash(const unsigned char *hash, int len)
135 {
136 int i;
137 for (i = 0; i < len; i++) {
138 printf("%02x", hash[i]);
139 }
140 }
141
142 static void notify_cb(const char *notification, void *userdata)
143 {
144 if (!strcmp(notification, NP_SYNC_CANCEL_REQUEST)) {
145 printf("User has aborted on-device\n");
146 quit_flag++;
147 } else {
148 printf("unhandled notification '%s' (TODO: implement)\n", notification);
149 }
150 }
151
152 static plist_t mobilebackup_factory_info_plist_new(const char* udid)
153 {
154 /* gather data from lockdown */
155 plist_t value_node = NULL;
156 plist_t root_node = NULL;
157 char *udid_uppercase = NULL;
158
159 plist_t ret = plist_new_dict();
160
161 /* get basic device information in one go */
162 lockdownd_get_value(client, NULL, NULL, &root_node);
163
164 /* set fields we understand */
165 value_node = plist_dict_get_item(root_node, "BuildVersion");
166 plist_dict_set_item(ret, "Build Version", plist_copy(value_node));
167
168 value_node = plist_dict_get_item(root_node, "DeviceName");
169 plist_dict_set_item(ret, "Device Name", plist_copy(value_node));
170 plist_dict_set_item(ret, "Display Name", plist_copy(value_node));
171
172 /* FIXME: How is the GUID generated? */
173 plist_dict_set_item(ret, "GUID", plist_new_string("---"));
174
175 value_node = plist_dict_get_item(root_node, "InternationalMobileEquipmentIdentity");
176 if (value_node)
177 plist_dict_set_item(ret, "IMEI", plist_copy(value_node));
178
179 plist_dict_set_item(ret, "Last Backup Date",
180 #ifdef HAVE_PLIST_UNIX_DATE
181 plist_new_unix_date(time(NULL))
182 #else
183 plist_new_date(time(NULL) - MAC_EPOCH, 0)
184 #endif
185 );
186
187 value_node = plist_dict_get_item(root_node, "ProductType");
188 plist_dict_set_item(ret, "Product Type", plist_copy(value_node));
189
190 value_node = plist_dict_get_item(root_node, "ProductVersion");
191 plist_dict_set_item(ret, "Product Version", plist_copy(value_node));
192
193 value_node = plist_dict_get_item(root_node, "SerialNumber");
194 plist_dict_set_item(ret, "Serial Number", plist_copy(value_node));
195
196 value_node = plist_dict_get_item(root_node, "UniqueDeviceID");
197 plist_dict_set_item(ret, "Target Identifier", plist_new_string(udid));
198
199 /* uppercase */
200 udid_uppercase = string_toupper((char*)udid);
201 plist_dict_set_item(ret, "Unique Identifier", plist_new_string(udid_uppercase));
202 free(udid_uppercase);
203
204 /* FIXME: Embed files as <data> nodes */
205 plist_t files = plist_new_dict();
206 plist_dict_set_item(ret, "iTunes Files", files);
207 plist_dict_set_item(ret, "iTunes Version", plist_new_string("9.0.2"));
208
209 plist_free(root_node);
210
211 return ret;
212 }
213
214 static void mobilebackup_info_update_last_backup_date(plist_t info_plist)
215 {
216 plist_t node = NULL;
217
218 if (!info_plist)
219 return;
220
221 node = plist_dict_get_item(info_plist, "Last Backup Date");
222 #ifdef HAVE_PLIST_UNIX_DATE
223 plist_set_unix_date_val(node, time(NULL));
224 #else
225 plist_set_date_val(node, time(NULL) - MAC_EPOCH, 0);
226 #endif
227
228 node = NULL;
229 }
230
231 static int plist_strcmp(plist_t node, const char *str)
232 {
233 char *buffer = NULL;
234 int ret = 0;
235
236 if (plist_get_node_type(node) != PLIST_STRING)
237 return ret;
238
239 plist_get_string_val(node, &buffer);
240 ret = strcmp(buffer, str);
241 free(buffer);
242
243 return ret;
244 }
245
246 static char *mobilebackup_build_path(const char *backup_directory, const char *name, const char *extension)
247 {
248 char* filename = (char*)malloc(strlen(name)+(extension == NULL ? 0: strlen(extension))+1);
249 strcpy(filename, name);
250 if (extension != NULL)
251 strcat(filename, extension);
252 char *path = string_build_path(backup_directory, filename, NULL);
253 free(filename);
254 return path;
255 }
256
257 static void mobilebackup_write_status(const char *path, int status)
258 {
259 struct stat st;
260 plist_t status_plist = plist_new_dict();
261 plist_dict_set_item(status_plist, "Backup Success", plist_new_bool(status));
262 char *file_path = mobilebackup_build_path(path, "Status", ".plist");
263
264 if (stat(file_path, &st) == 0)
265 remove(file_path);
266
267 plist_write_to_file(status_plist, file_path, PLIST_FORMAT_XML, 0);
268
269 plist_free(status_plist);
270 status_plist = NULL;
271
272 free(file_path);
273 }
274
275 static int mobilebackup_read_status(const char *path)
276 {
277 int ret = -1;
278 plist_t status_plist = NULL;
279 char *file_path = mobilebackup_build_path(path, "Status", ".plist");
280
281 plist_read_from_file(file_path, &status_plist, NULL);
282 free(file_path);
283 if (!status_plist) {
284 printf("Could not read Status.plist!\n");
285 return ret;
286 }
287 plist_t node = plist_dict_get_item(status_plist, "Backup Success");
288 if (node && (plist_get_node_type(node) == PLIST_BOOLEAN)) {
289 uint8_t bval = 0;
290 plist_get_bool_val(node, &bval);
291 ret = bval;
292 } else {
293 printf("%s: ERROR could not get Backup Success key from Status.plist!\n", __func__);
294 }
295 plist_free(status_plist);
296 return ret;
297 }
298
299 static int mobilebackup_info_is_current_device(plist_t info)
300 {
301 plist_t value_node = NULL;
302 plist_t node = NULL;
303 plist_t root_node = NULL;
304 int ret = 0;
305
306 if (!info)
307 return ret;
308
309 if (plist_get_node_type(info) != PLIST_DICT)
310 return ret;
311
312 /* get basic device information in one go */
313 lockdownd_get_value(client, NULL, NULL, &root_node);
314
315 /* verify UDID */
316 value_node = plist_dict_get_item(root_node, "UniqueDeviceID");
317 node = plist_dict_get_item(info, "Target Identifier");
318
319 if(plist_compare_node_value(value_node, node))
320 ret = 1;
321 else {
322 printf("Info.plist: UniqueDeviceID does not match.\n");
323 }
324
325 /* verify SerialNumber */
326 if (ret == 1) {
327 value_node = plist_dict_get_item(root_node, "SerialNumber");
328 node = plist_dict_get_item(info, "Serial Number");
329
330 if(plist_compare_node_value(value_node, node))
331 ret = 1;
332 else {
333 printf("Info.plist: SerialNumber does not match.\n");
334 ret = 0;
335 }
336 }
337
338 /* verify ProductVersion to prevent using backup with different OS version */
339 if (ret == 1) {
340 value_node = plist_dict_get_item(root_node, "ProductVersion");
341 node = plist_dict_get_item(info, "Product Version");
342
343 if(plist_compare_node_value(value_node, node))
344 ret = 1;
345 else {
346 printf("Info.plist: ProductVersion does not match.\n");
347 ret = 0;
348 }
349 }
350
351 plist_free(root_node);
352 root_node = NULL;
353
354 value_node = NULL;
355 node = NULL;
356
357 return ret;
358 }
359
360 static int mobilebackup_delete_backup_file_by_hash(const char *backup_directory, const char *hash)
361 {
362 int ret = 0;
363 char *path = mobilebackup_build_path(backup_directory, hash, ".mddata");
364 printf("Removing \"%s\" ", path);
365 if (!remove( path ))
366 ret = 1;
367 else
368 ret = 0;
369
370 free(path);
371
372 if (!ret)
373 return ret;
374
375 path = mobilebackup_build_path(backup_directory, hash, ".mdinfo");
376 printf("and \"%s\"... ", path);
377 if (!remove( path ))
378 ret = 1;
379 else
380 ret = 0;
381
382 free(path);
383
384 return ret;
385 }
386
387 static int mobilebackup_check_file_integrity(const char *backup_directory, const char *hash, plist_t filedata)
388 {
389 char *datapath;
390 char *infopath;
391 plist_t mdinfo = NULL;
392 struct stat st;
393 unsigned char file_hash[20];
394
395 datapath = mobilebackup_build_path(backup_directory, hash, ".mddata");
396 if (stat(datapath, &st) != 0) {
397 printf("\r\n");
398 printf("ERROR: '%s.mddata' is missing!\n", hash);
399 free(datapath);
400 return 0;
401 }
402
403 infopath = mobilebackup_build_path(backup_directory, hash, ".mdinfo");
404 plist_read_from_file(infopath, &mdinfo, NULL);
405 free(infopath);
406 if (!mdinfo) {
407 printf("\r\n");
408 printf("ERROR: '%s.mdinfo' is missing or corrupted!\n", hash);
409 free(datapath);
410 return 0;
411 }
412
413 /* sha1 hash verification */
414 plist_t node = plist_dict_get_item(filedata, "DataHash");
415 if (!node || (plist_get_node_type(node) != PLIST_DATA)) {
416 printf("\r\n");
417 printf("ERROR: Could not get DataHash for file entry '%s'\n", hash);
418 plist_free(mdinfo);
419 free(datapath);
420 return 0;
421 }
422
423 node = plist_dict_get_item(mdinfo, "Metadata");
424 if (!node && (plist_get_node_type(node) != PLIST_DATA)) {
425 printf("\r\n");
426 printf("ERROR: Could not find Metadata in plist '%s.mdinfo'\n", hash);
427 plist_free(mdinfo);
428 free(datapath);
429 return 0;
430 }
431
432 char *meta_bin = NULL;
433 uint64_t meta_bin_size = 0;
434 plist_get_data_val(node, &meta_bin, &meta_bin_size);
435 plist_t metadata = NULL;
436 if (meta_bin) {
437 plist_from_bin(meta_bin, (uint32_t)meta_bin_size, &metadata);
438 }
439 if (!metadata) {
440 printf("\r\n");
441 printf("ERROR: Could not get Metadata from plist '%s.mdinfo'\n", hash);
442 plist_free(mdinfo);
443 free(datapath);
444 return 0;
445 }
446
447 char *version = NULL;
448 node = plist_dict_get_item(metadata, "Version");
449 if (node && (plist_get_node_type(node) == PLIST_STRING)) {
450 plist_get_string_val(node, &version);
451 }
452
453 char *destpath = NULL;
454 node = plist_dict_get_item(metadata, "Path");
455 if (node && (plist_get_node_type(node) == PLIST_STRING)) {
456 plist_get_string_val(node, &destpath);
457 }
458
459 uint8_t greylist = 0;
460 node = plist_dict_get_item(metadata, "Greylist");
461 if (node && (plist_get_node_type(node) == PLIST_BOOLEAN)) {
462 plist_get_bool_val(node, &greylist);
463 }
464
465 char *domain = NULL;
466 node = plist_dict_get_item(metadata, "Domain");
467 if (node && (plist_get_node_type(node) == PLIST_STRING)) {
468 plist_get_string_val(node, &domain);
469 }
470
471 char *fnstr = malloc(strlen(domain) + 1 + strlen(destpath) + 1);
472 strcpy(fnstr, domain);
473 strcat(fnstr, "-");
474 strcat(fnstr, destpath);
475 unsigned char fnhash[20];
476 char fnamehash[41];
477 char *p = fnamehash;
478 sha1((const unsigned char*)fnstr, strlen(fnstr), fnhash);
479 free(fnstr);
480 int i;
481 for ( i = 0; i < 20; i++, p += 2 ) {
482 snprintf (p, 3, "%02x", (unsigned char)fnhash[i] );
483 }
484 if (strcmp(fnamehash, hash) != 0) {
485 printf("\r\n");
486 printf("WARNING: filename hash does not match for entry '%s'\n", hash);
487 }
488
489 char *auth_version = NULL;
490 node = plist_dict_get_item(mdinfo, "AuthVersion");
491 if (node && (plist_get_node_type(node) == PLIST_STRING)) {
492 plist_get_string_val(node, &auth_version);
493 }
494
495 if (strcmp(auth_version, "1.0") != 0) {
496 printf("\r\n");
497 printf("WARNING: Unknown AuthVersion '%s', DataHash cannot be verified!\n", auth_version);
498 }
499
500 node = plist_dict_get_item(filedata, "DataHash");
501 if (!node || (plist_get_node_type(node) != PLIST_DATA)) {
502 printf("\r\n");
503 printf("WARNING: Could not get DataHash key from file info data for entry '%s'\n", hash);
504 }
505
506 int res = 1;
507 unsigned char *data_hash = NULL;
508 uint64_t data_hash_len = 0;
509 plist_get_data_val(node, (char**)&data_hash, &data_hash_len);
510 int hash_ok = 0;
511 if (data_hash && (data_hash_len == 20)) {
512 compute_datahash(datapath, destpath, greylist, domain, NULL, version, file_hash);
513 hash_ok = compare_hash(data_hash, file_hash, 20);
514 } else if (data_hash_len == 0) {
515 /* no datahash present */
516 hash_ok = 1;
517 }
518
519 free(domain);
520 free(version);
521 free(destpath);
522
523 if (!hash_ok) {
524 printf("\r\n");
525 printf("ERROR: The hash for '%s.mddata' does not match DataHash entry in Manifest\n", hash);
526 printf("datahash: ");
527 print_hash(data_hash, 20);
528 printf("\nfilehash: ");
529 print_hash(file_hash, 20);
530 printf("\n");
531 res = 0;
532 }
533 free(data_hash);
534 plist_free(mdinfo);
535 return res;
536 }
537
538 static void do_post_notification(const char *notification)
539 {
540 lockdownd_service_descriptor_t service = NULL;
541 np_client_t np;
542
543 if (!client) {
544 if (lockdownd_client_new_with_handshake(device, &client, TOOL_NAME) != LOCKDOWN_E_SUCCESS) {
545 return;
546 }
547 }
548
549 lockdownd_error_t ldret = lockdownd_start_service(client, NP_SERVICE_NAME, &service);
550 if (ldret == LOCKDOWN_E_SUCCESS) {
551 np_client_new(device, service, &np);
552 if (np) {
553 np_post_notification(np, notification);
554 np_client_free(np);
555 }
556 } else {
557 printf("Could not start %s: %s\n", NP_SERVICE_NAME, lockdownd_strerror(ldret));
558 }
559
560 if (service) {
561 lockdownd_service_descriptor_free(service);
562 service = NULL;
563 }
564 }
565
566 static void print_progress(double progress)
567 {
568 int i = 0;
569 if (progress < 0)
570 return;
571
572 if (progress > 100)
573 progress = 100;
574
575 printf("\r[");
576 for(i = 0; i < 50; i++) {
577 if(i < progress / 2) {
578 printf("=");
579 } else {
580 printf(" ");
581 }
582 }
583 printf("] %3.0f%%", progress);
584 fflush(stdout);
585 if (progress == 100)
586 printf("\n");
587 }
588
589 /**
590 * signal handler function for cleaning up properly
591 */
592 static void clean_exit(int sig)
593 {
594 fprintf(stderr, "Exiting...\n");
595 quit_flag++;
596 }
597
598 static void print_usage(int argc, char **argv, int is_error)
599 {
600 char *name = strrchr(argv[0], '/');
601 fprintf(is_error ? stderr : stdout, "Usage: %s [OPTIONS] CMD DIRECTORY\n", (name ? name + 1: argv[0]));
602 fprintf(is_error ? stderr : stdout,
603 "\n"
604 "Create or restore backup in/from the specified directory.\n"
605 "\n"
606 "CMD:\n"
607 " backup Saves a device backup into DIRECTORY\n"
608 " restore Restores a device backup from DIRECTORY.\n"
609 "\n"
610 "OPTIONS:\n"
611 " -u, --udid UDID target specific device by UDID\n"
612 " -n, --network connect to network device\n"
613 " -d, --debug enable communication debugging\n"
614 " -h, --help prints usage information\n"
615 " -v, --version prints version information\n"
616 "\n"
617 "Homepage: <" PACKAGE_URL ">\n"
618 "Bug Reports: <" PACKAGE_BUGREPORT ">\n"
619 );
620 }
621
622 int main(int argc, char *argv[])
623 {
624 idevice_error_t ret = IDEVICE_E_UNKNOWN_ERROR;
625 lockdownd_error_t ldret = LOCKDOWN_E_UNKNOWN_ERROR;
626 int i;
627 char* udid = NULL;
628 int use_network = 0;
629 lockdownd_service_descriptor_t service = NULL;
630 int cmd = -1;
631 int is_full_backup = 0;
632 char *backup_directory = NULL;
633 struct stat st;
634 plist_t node = NULL;
635 plist_t node_tmp = NULL;
636 plist_t manifest_plist = NULL;
637 plist_t info_plist = NULL;
638 char *buffer = NULL;
639 char *file_path = NULL;
640 uint64_t length = 0;
641 uint64_t backup_total_size = 0;
642 enum device_link_file_status_t file_status = DEVICE_LINK_FILE_STATUS_NONE;
643 int c = 0;
644 const struct option longopts[] = {
645 { "debug", no_argument, NULL, 'd' },
646 { "help", no_argument, NULL, 'h' },
647 { "udid", required_argument, NULL, 'u' },
648 { "network", no_argument, NULL, 'n' },
649 { "version", no_argument, NULL, 'v' },
650 { NULL, 0, NULL, 0}
651 };
652
653 /* we need to exit cleanly on running backups and restores or we cause havok */
654 signal(SIGINT, clean_exit);
655 signal(SIGTERM, clean_exit);
656 #ifndef _WIN32
657 signal(SIGQUIT, clean_exit);
658 signal(SIGPIPE, SIG_IGN);
659 #endif
660
661 /* parse cmdline args */
662 while ((c = getopt_long(argc, argv, "dhu:nv", longopts, NULL)) != -1) {
663 switch (c) {
664 case 'd':
665 idevice_set_debug_level(1);
666 break;
667 case 'u':
668 if (!*optarg) {
669 fprintf(stderr, "ERROR: UDID must not be empty!\n");
670 print_usage(argc, argv, 1);
671 return 2;
672 }
673 udid = strdup(optarg);
674 break;
675 case 'n':
676 use_network = 1;
677 break;
678 case 'h':
679 print_usage(argc, argv, 0);
680 return 0;
681 case 'v':
682 printf("%s %s\n", TOOL_NAME, PACKAGE_VERSION);
683 return 0;
684 default:
685 print_usage(argc, argv, 1);
686 return 2;
687 }
688 }
689 argc -= optind;
690 argv += optind;
691
692 if (argc < 1) {
693 fprintf(stderr, "ERROR: Missing command.\n");
694 print_usage(argc+optind, argv-optind, 1);
695 return 2;
696 }
697
698 if (!strcmp(argv[0], "backup")) {
699 cmd = CMD_BACKUP;
700 } else if (!strcmp(argv[0], "restore")) {
701 cmd = CMD_RESTORE;
702 } else {
703 fprintf(stderr, "ERROR: Invalid command '%s'.\n", argv[0]);
704 print_usage(argc+optind, argv-optind, 1);
705 return 2;
706 }
707
708 if (argc < 2) {
709 fprintf(stderr, "No target backup directory specified.\n");
710 print_usage(argc+optind, argv-optind, 1);
711 return 2;
712 }
713 backup_directory = argv[1];
714
715 /* verify if passed backup directory exists */
716 if (stat(backup_directory, &st) != 0) {
717 printf("ERROR: Backup directory \"%s\" does not exist!\n", backup_directory);
718 return -1;
719 }
720
721 /* restore directory must contain an Info.plist */
722 char *info_path = mobilebackup_build_path(backup_directory, "Info", ".plist");
723 if (cmd == CMD_RESTORE) {
724 if (stat(info_path, &st) != 0) {
725 free(info_path);
726 printf("ERROR: Backup directory \"%s\" is invalid. No Info.plist found.\n", backup_directory);
727 return -1;
728 }
729 }
730
731 printf("Backup directory is \"%s\"\n", backup_directory);
732
733 ret = idevice_new_with_options(&device, udid, (use_network) ? IDEVICE_LOOKUP_NETWORK : IDEVICE_LOOKUP_USBMUX);
734 if (ret != IDEVICE_E_SUCCESS) {
735 if (udid) {
736 printf("No device found with udid %s.\n", udid);
737 } else {
738 printf("No device found.\n");
739 }
740 return -1;
741 }
742
743 if (!udid) {
744 idevice_get_udid(device, &udid);
745 }
746
747 if (LOCKDOWN_E_SUCCESS != (ldret = lockdownd_client_new_with_handshake(device, &client, TOOL_NAME))) {
748 printf("ERROR: Could not connect to lockdownd, error code %d\n", ldret);
749 idevice_free(device);
750 free(udid);
751 return -1;
752 }
753
754 node = NULL;
755 lockdownd_get_value(client, NULL, "ProductVersion", &node);
756 if (node) {
757 char* str = NULL;
758 if (plist_get_node_type(node) == PLIST_STRING) {
759 plist_get_string_val(node, &str);
760 }
761 plist_free(node);
762 node = NULL;
763 if (str) {
764 int maj = strtol(str, NULL, 10);
765 free(str);
766 if (maj > 3) {
767 printf("ERROR: This tool is only compatible with iOS 3 or below. For newer iOS versions please use the idevicebackup2 tool.\n");
768 lockdownd_client_free(client);
769 idevice_free(device);
770 free(udid);
771 return -1;
772 }
773 }
774 }
775
776 /* start notification_proxy */
777 np_client_t np = NULL;
778 ldret = lockdownd_start_service(client, NP_SERVICE_NAME, &service);
779 if ((ldret == LOCKDOWN_E_SUCCESS) && service && service->port) {
780 np_client_new(device, service, &np);
781 np_set_notify_callback(np, notify_cb, NULL);
782 const char *noties[5] = {
783 NP_SYNC_CANCEL_REQUEST,
784 NP_SYNC_SUSPEND_REQUEST,
785 NP_SYNC_RESUME_REQUEST,
786 NP_BACKUP_DOMAIN_CHANGED,
787 NULL
788 };
789 np_observe_notifications(np, noties);
790 } else {
791 printf("ERROR: Could not start service %s: %s\n", NP_SERVICE_NAME, lockdownd_strerror(ldret));
792 }
793
794 afc_client_t afc = NULL;
795 if (cmd == CMD_BACKUP) {
796 /* start AFC, we need this for the lock file */
797 service->port = 0;
798 service->ssl_enabled = 0;
799 ldret = lockdownd_start_service(client, AFC_SERVICE_NAME, &service);
800 if ((ldret == LOCKDOWN_E_SUCCESS) && service->port) {
801 afc_client_new(device, service, &afc);
802 } else {
803 printf("ERROR: Could not start service %s: %s\n", AFC_SERVICE_NAME, lockdownd_strerror(ldret));
804 }
805 }
806
807 if (service) {
808 lockdownd_service_descriptor_free(service);
809 service = NULL;
810 }
811
812 /* start mobilebackup service and retrieve port */
813 ldret = lockdownd_start_service(client, MOBILEBACKUP_SERVICE_NAME, &service);
814 if ((ldret == LOCKDOWN_E_SUCCESS) && service && service->port) {
815 printf("Started \"%s\" service on port %d.\n", MOBILEBACKUP_SERVICE_NAME, service->port);
816 printf("%d\n", mobilebackup_client_new(device, service, &mobilebackup));
817
818 if (service) {
819 lockdownd_service_descriptor_free(service);
820 service = NULL;
821 }
822
823 /* check abort conditions */
824 if (quit_flag > 0) {
825 printf("Aborting backup. Cancelled by user.\n");
826 cmd = CMD_LEAVE;
827 }
828
829 /* verify existing Info.plist */
830 if (stat(info_path, &st) == 0) {
831 printf("Reading Info.plist from backup.\n");
832 plist_read_from_file(info_path, &info_plist, NULL);
833
834 if (!info_plist) {
835 printf("Could not read Info.plist\n");
836 is_full_backup = 1;
837 }
838 if (info_plist && (cmd == CMD_BACKUP)) {
839 if (mobilebackup_info_is_current_device(info_plist)) {
840 /* update the last backup time within Info.plist */
841 mobilebackup_info_update_last_backup_date(info_plist);
842 remove(info_path);
843 plist_write_to_file(info_plist, info_path, PLIST_FORMAT_XML, 0);
844 } else {
845 printf("Aborting backup. Backup is not compatible with the current device.\n");
846 cmd = CMD_LEAVE;
847 }
848 } else if (info_plist && (cmd == CMD_RESTORE)) {
849 if (!mobilebackup_info_is_current_device(info_plist)) {
850 printf("Aborting restore. Backup data is not compatible with the current device.\n");
851 cmd = CMD_LEAVE;
852 }
853 }
854 } else {
855 if (cmd == CMD_RESTORE) {
856 printf("Aborting restore. Info.plist is missing.\n");
857 cmd = CMD_LEAVE;
858 } else {
859 is_full_backup = 1;
860 }
861 }
862
863 uint64_t lockfile = 0;
864 if (cmd == CMD_BACKUP) {
865 do_post_notification(NP_SYNC_WILL_START);
866 afc_file_open(afc, "/com.apple.itunes.lock_sync", AFC_FOPEN_RW, &lockfile);
867 }
868 if (lockfile) {
869 afc_error_t aerr;
870 do_post_notification(NP_SYNC_LOCK_REQUEST);
871 for (i = 0; i < LOCK_ATTEMPTS; i++) {
872 aerr = afc_file_lock(afc, lockfile, AFC_LOCK_EX);
873 if (aerr == AFC_E_SUCCESS) {
874 do_post_notification(NP_SYNC_DID_START);
875 break;
876 }
877 if (aerr == AFC_E_OP_WOULD_BLOCK) {
878 usleep(LOCK_WAIT);
879 continue;
880 }
881
882 fprintf(stderr, "ERROR: could not lock file! error code: %d\n", aerr);
883 afc_file_close(afc, lockfile);
884 lockfile = 0;
885 cmd = CMD_LEAVE;
886 }
887 if (i == LOCK_ATTEMPTS) {
888 fprintf(stderr, "ERROR: timeout while locking for sync\n");
889 afc_file_close(afc, lockfile);
890 lockfile = 0;
891 cmd = CMD_LEAVE;
892 }
893 }
894
895 mobilebackup_error_t err;
896
897 /* Manifest.plist (backup manifest (backup state)) */
898 char *manifest_path = mobilebackup_build_path(backup_directory, "Manifest", ".plist");
899
900 switch(cmd) {
901 case CMD_BACKUP:
902 printf("Starting backup...\n");
903 /* TODO: check domain com.apple.mobile.backup key RequiresEncrypt and WillEncrypt with lockdown */
904 /* TODO: verify battery on AC enough battery remaining */
905
906 /* read the last Manifest.plist */
907 if (!is_full_backup) {
908 printf("Reading existing Manifest.\n");
909 plist_read_from_file(manifest_path, &manifest_plist, NULL);
910 if (!manifest_plist) {
911 printf("Could not read Manifest.plist, switching to full backup mode.\n");
912 is_full_backup = 1;
913 }
914 }
915
916 /* Info.plist (Device infos, IC-Info.sidb, photos, app_ids, iTunesPrefs) */
917
918 /* create new Info.plist on new backups */
919 if (is_full_backup) {
920 if (info_plist) {
921 plist_free(info_plist);
922 info_plist = NULL;
923 }
924 remove(info_path);
925 printf("Creating Info.plist for new backup.\n");
926 info_plist = mobilebackup_factory_info_plist_new(udid);
927 plist_write_to_file(info_plist, info_path, PLIST_FORMAT_XML, 0);
928 }
929 free(info_path);
930
931 plist_free(info_plist);
932 info_plist = NULL;
933
934 /* close down the lockdown connection as it is no longer needed */
935 if (client) {
936 lockdownd_client_free(client);
937 client = NULL;
938 }
939
940 /* create Status.plist with failed status for now */
941 mobilebackup_write_status(backup_directory, 0);
942
943 /* request backup from device with manifest from last backup */
944 printf("Requesting backup from device...\n");
945
946 err = mobilebackup_request_backup(mobilebackup, manifest_plist, "/", "1.6");
947 if (err == MOBILEBACKUP_E_SUCCESS) {
948 if (is_full_backup)
949 printf("Full backup mode.\n");
950 else
951 printf("Incremental backup mode.\n");
952 printf("Please wait. Device is preparing backup data...\n");
953 } else {
954 if (err == MOBILEBACKUP_E_BAD_VERSION) {
955 printf("ERROR: Could not start backup process: backup protocol version mismatch!\n");
956 } else if (err == MOBILEBACKUP_E_REPLY_NOT_OK) {
957 printf("ERROR: Could not start backup process: device refused to start the backup process.\n");
958 } else {
959 printf("ERROR: Could not start backup process: unspecified error occurred (%d)\n", err);
960 }
961 break;
962 }
963
964 /* reset backup status */
965 int backup_ok = 0;
966 plist_t message = NULL;
967
968 /* receive and save DLSendFile files and metadata, ACK each */
969 uint64_t file_size = 0;
970 uint64_t file_size_current = 0;
971 int file_index = 0;
972 int hunk_index = 0;
973 uint64_t backup_real_size = 0;
974 char *file_ext = NULL;
975 char *filename_mdinfo = NULL;
976 char *filename_mddata = NULL;
977 char *filename_source = NULL;
978 char *format_size = NULL;
979 int is_manifest = 0;
980 uint8_t b = 0;
981 uint64_t u64val = 0;
982
983 /* process series of DLSendFile messages */
984 do {
985 mobilebackup_receive(mobilebackup, &message);
986 if (!message) {
987 printf("Device is not ready yet. Going to try again in 2 seconds...\n");
988 sleep(2);
989 goto files_out;
990 }
991
992 node = plist_array_get_item(message, 0);
993
994 /* get out if we don't get a DLSendFile */
995 if (plist_strcmp(node, "DLSendFile"))
996 break;
997
998 node_tmp = plist_array_get_item(message, 2);
999
1000 /* first message hunk contains total backup size */
1001 if ((hunk_index == 0) && (file_index == 0)) {
1002 node = plist_dict_get_item(node_tmp, "BackupTotalSizeKey");
1003 if (node) {
1004 plist_get_uint_val(node, &backup_total_size);
1005 format_size = string_format_size(backup_total_size);
1006 printf("Backup data requires %s on the disk.\n", format_size);
1007 free(format_size);
1008 }
1009 }
1010
1011 /* check DLFileStatusKey (codes: 1 = Hunk, 2 = Last Hunk) */
1012 node = plist_dict_get_item(node_tmp, "DLFileStatusKey");
1013 plist_get_uint_val(node, &u64val);
1014 file_status = u64val;
1015
1016 /* get source filename */
1017 node = plist_dict_get_item(node_tmp, "BackupManifestKey");
1018 b = 0;
1019 if (node) {
1020 plist_get_bool_val(node, &b);
1021 }
1022 is_manifest = (b == 1) ? 1 : 0;
1023
1024 if ((hunk_index == 0) && (!is_manifest)) {
1025 /* get source filename */
1026 node = plist_dict_get_item(node_tmp, "DLFileSource");
1027 plist_get_string_val(node, &filename_source);
1028
1029 /* increase received size */
1030 node = plist_dict_get_item(node_tmp, "DLFileAttributesKey");
1031 node = plist_dict_get_item(node, "FileSize");
1032 plist_get_uint_val(node, &file_size);
1033 backup_real_size += file_size;
1034
1035 format_size = string_format_size(backup_real_size);
1036 printf("(%s", format_size);
1037 free(format_size);
1038
1039 format_size = string_format_size(backup_total_size);
1040 printf("/%s): ", format_size);
1041 free(format_size);
1042
1043 format_size = string_format_size(file_size);
1044 printf("Receiving file %s (%s)... \n", filename_source, format_size);
1045 free(format_size);
1046
1047 if (filename_source)
1048 free(filename_source);
1049 }
1050
1051 /* check if we completed a file */
1052 if ((file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK) && (!is_manifest)) {
1053 /* save <hash>.mdinfo */
1054 node = plist_dict_get_item(node_tmp, "BackupFileInfo");
1055 if (node) {
1056 node = plist_dict_get_item(node_tmp, "DLFileDest");
1057 plist_get_string_val(node, &file_path);
1058
1059 filename_mdinfo = mobilebackup_build_path(backup_directory, file_path, ".mdinfo");
1060
1061 /* remove any existing file */
1062 if (stat(filename_mdinfo, &st) == 0)
1063 remove(filename_mdinfo);
1064
1065 node = plist_dict_get_item(node_tmp, "BackupFileInfo");
1066 plist_write_to_file(node, filename_mdinfo, PLIST_FORMAT_BINARY, 0);
1067
1068 free(filename_mdinfo);
1069 }
1070
1071 file_index++;
1072 }
1073
1074 /* save <hash>.mddata */
1075 node = plist_dict_get_item(node_tmp, "BackupFileInfo");
1076 if (node_tmp) {
1077 node = plist_dict_get_item(node_tmp, "DLFileDest");
1078 plist_get_string_val(node, &file_path);
1079
1080 filename_mddata = mobilebackup_build_path(backup_directory, file_path, is_manifest ? NULL: ".mddata");
1081
1082 /* if this is the first hunk, remove any existing file */
1083 if ((hunk_index == 0) && (stat(filename_mddata, &st) == 0))
1084 remove(filename_mddata);
1085
1086 /* get file data hunk */
1087 node_tmp = plist_array_get_item(message, 1);
1088 plist_get_data_val(node_tmp, &buffer, &length);
1089
1090 buffer_write_to_filename(filename_mddata, buffer, length);
1091 if (!is_manifest)
1092 file_size_current += length;
1093
1094 /* activate currently sent manifest */
1095 if ((file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK) && (is_manifest)) {
1096 rename(filename_mddata, manifest_path);
1097 }
1098
1099 free(buffer);
1100 buffer = NULL;
1101
1102 free(filename_mddata);
1103 }
1104
1105 if ((!is_manifest)) {
1106 if (hunk_index == 0 && file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK) {
1107 print_progress(100);
1108 } else if (file_size > 0) {
1109 print_progress((double)(file_size_current*100)/file_size);
1110 }
1111 }
1112
1113 hunk_index++;
1114
1115 if (file_ext)
1116 free(file_ext);
1117
1118 if (message)
1119 plist_free(message);
1120 message = NULL;
1121
1122 if (file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK) {
1123 /* acknowlegdge that we received the file */
1124 mobilebackup_send_backup_file_received(mobilebackup);
1125 /* reset hunk_index */
1126 hunk_index = 0;
1127 if (!is_manifest) {
1128 file_size_current = 0;
1129 file_size = 0;
1130 }
1131 }
1132 files_out:
1133 if (quit_flag > 0) {
1134 /* need to cancel the backup here */
1135 mobilebackup_send_error(mobilebackup, "Cancelling DLSendFile");
1136
1137 /* remove any atomic Manifest.plist.tmp */
1138 if (manifest_path)
1139 free(manifest_path);
1140
1141 manifest_path = mobilebackup_build_path(backup_directory, "Manifest", ".plist.tmp");
1142 if (stat(manifest_path, &st) == 0)
1143 remove(manifest_path);
1144 break;
1145 }
1146 } while (1);
1147
1148 printf("Received %d files from device.\n", file_index);
1149
1150 if (!quit_flag && !plist_strcmp(node, "DLMessageProcessMessage")) {
1151 node_tmp = plist_array_get_item(message, 1);
1152 node = plist_dict_get_item(node_tmp, "BackupMessageTypeKey");
1153 /* check if we received the final "backup finished" message */
1154 if (node && !plist_strcmp(node, "BackupMessageBackupFinished")) {
1155 /* backup finished */
1156
1157 /* process BackupFilesToDeleteKey */
1158 node = plist_dict_get_item(node_tmp, "BackupFilesToDeleteKey");
1159 if (node) {
1160 length = plist_array_get_size(node);
1161 i = 0;
1162 while ((node_tmp = plist_array_get_item(node, i++)) != NULL) {
1163 plist_get_string_val(node_tmp, &file_path);
1164
1165 if (mobilebackup_delete_backup_file_by_hash(backup_directory, file_path)) {
1166 printf("DONE\n");
1167 } else
1168 printf("FAILED\n");
1169 }
1170 }
1171
1172 /* save last valid Manifest.plist */
1173 node_tmp = plist_array_get_item(message, 1);
1174 manifest_plist = plist_dict_get_item(node_tmp, "BackupManifestKey");
1175 if (manifest_plist) {
1176 remove(manifest_path);
1177 printf("Storing Manifest.plist...\n");
1178 plist_write_to_file(manifest_plist, manifest_path, PLIST_FORMAT_XML, 0);
1179 }
1180
1181 backup_ok = 1;
1182 }
1183 }
1184
1185 if (backup_ok) {
1186 /* Status.plist (Info on how the backup process turned out) */
1187 printf("Backup Successful.\n");
1188 mobilebackup_write_status(backup_directory, 1);
1189 } else {
1190 printf("Backup Failed.\n");
1191 }
1192 break;
1193 case CMD_RESTORE:
1194 /* close down the lockdown connection as it is no longer needed */
1195 if (client) {
1196 lockdownd_client_free(client);
1197 client = NULL;
1198 }
1199
1200 /* TODO: verify battery on AC enough battery remaining */
1201
1202 /* verify if Status.plist says we read from an successful backup */
1203 if (mobilebackup_read_status(backup_directory) <= 0) {
1204 printf("ERROR: Cannot ensure we restore from a successful backup. Aborting.\n");
1205 break;
1206 }
1207 /* now make sure backup integrity is ok! verify all files */
1208 printf("Reading existing Manifest.\n");
1209 plist_read_from_file(manifest_path, &manifest_plist, NULL);
1210 if (!manifest_plist) {
1211 printf("Could not read Manifest.plist. Aborting.\n");
1212 break;
1213 }
1214
1215 printf("Verifying backup integrity, please wait.\n");
1216 unsigned char *bin = NULL;
1217 uint64_t binsize = 0;
1218 node = plist_dict_get_item(manifest_plist, "Data");
1219 if (!node || (plist_get_node_type(node) != PLIST_DATA)) {
1220 printf("Could not read Data key from Manifest.plist!\n");
1221 break;
1222 }
1223 plist_get_data_val(node, (char**)&bin, &binsize);
1224 plist_t backup_data = NULL;
1225 if (bin) {
1226 char *auth_ver = NULL;
1227 unsigned char *auth_sig = NULL;
1228 uint64_t auth_sig_len = 0;
1229 /* verify AuthSignature */
1230 node = plist_dict_get_item(manifest_plist, "AuthVersion");
1231 plist_get_string_val(node, &auth_ver);
1232 if (auth_ver && (strcmp(auth_ver, "2.0") == 0)) {
1233 node = plist_dict_get_item(manifest_plist, "AuthSignature");
1234 if (node && (plist_get_node_type(node) == PLIST_DATA)) {
1235 plist_get_data_val(node, (char**)&auth_sig, &auth_sig_len);
1236 }
1237 if (auth_sig && (auth_sig_len == 20)) {
1238 /* calculate the sha1, then compare */
1239 unsigned char data_sha1[20];
1240 sha1(bin, binsize, data_sha1);
1241 if (compare_hash(auth_sig, data_sha1, 20)) {
1242 printf("AuthSignature is valid\n");
1243 } else {
1244 printf("ERROR: AuthSignature is NOT VALID\n");
1245 }
1246 } else {
1247 printf("Could not get AuthSignature from manifest!\n");
1248 }
1249 free(auth_sig);
1250 } else if (auth_ver) {
1251 printf("Unknown AuthVersion '%s', cannot verify AuthSignature\n", auth_ver);
1252 }
1253 plist_from_bin((char*)bin, (uint32_t)binsize, &backup_data);
1254 free(bin);
1255 }
1256 if (!backup_data) {
1257 printf("Could not read plist from Manifest.plist Data key!\n");
1258 break;
1259 }
1260 plist_t files = plist_dict_get_item(backup_data, "Files");
1261 if (files && (plist_get_node_type(files) == PLIST_DICT)) {
1262 plist_dict_iter iter = NULL;
1263 plist_dict_new_iter(files, &iter);
1264 if (iter) {
1265 /* loop over Files entries in Manifest data plist */
1266 char *hash = NULL;
1267 int file_ok = 0;
1268 int total_files = plist_dict_get_size(files);
1269 int cur_file = 1;
1270 node = NULL;
1271 plist_dict_next_item(files, iter, &hash, &node);
1272 while (node) {
1273 printf("Verifying file %d/%d (%d%%) \r", cur_file, total_files, (cur_file*100/total_files));
1274 cur_file++;
1275 /* make sure both .mddata/.mdinfo files are available for each entry */
1276 file_ok = mobilebackup_check_file_integrity(backup_directory, hash, node);
1277 node = NULL;
1278 free(hash);
1279 hash = NULL;
1280 if (!file_ok) {
1281 break;
1282 }
1283 plist_dict_next_item(files, iter, &hash, &node);
1284 }
1285 printf("\n");
1286 free(iter);
1287 if (!file_ok) {
1288 plist_free(backup_data);
1289 break;
1290 }
1291 printf("All backup files appear to be valid\n");
1292 }
1293 }
1294
1295 printf("Requesting restore from device...\n");
1296
1297 /* request restore from device with manifest (BackupMessageRestoreMigrate) */
1298 int restore_flags = MB_RESTORE_NOTIFY_SPRINGBOARD | MB_RESTORE_PRESERVE_SETTINGS | MB_RESTORE_PRESERVE_CAMERA_ROLL;
1299 err = mobilebackup_request_restore(mobilebackup, manifest_plist, restore_flags, "1.6");
1300 if (err != MOBILEBACKUP_E_SUCCESS) {
1301 if (err == MOBILEBACKUP_E_BAD_VERSION) {
1302 printf("ERROR: Could not start restore process: backup protocol version mismatch!\n");
1303 } else if (err == MOBILEBACKUP_E_REPLY_NOT_OK) {
1304 printf("ERROR: Could not start restore process: device refused to start the restore process.\n");
1305 } else {
1306 printf("ERROR: Could not start restore process: unspecified error occurred (%d)\n", err);
1307 }
1308 plist_free(backup_data);
1309 break;
1310 }
1311
1312 printf("Entered restore mode.\n");
1313
1314 int restore_ok = 0;
1315
1316 if (files && (plist_get_node_type(files) == PLIST_DICT)) {
1317 plist_dict_iter iter = NULL;
1318 plist_dict_new_iter(files, &iter);
1319 if (iter) {
1320 /* loop over Files entries in Manifest data plist */
1321 char *hash = NULL;
1322 plist_t file_info = NULL;
1323 char *file_info_path = NULL;
1324 int total_files = plist_dict_get_size(files);
1325 int cur_file = 0;
1326 uint64_t file_offset = 0;
1327 uint8_t is_encrypted = 0;
1328 plist_t tmp_node = NULL;
1329 plist_t file_path_node = NULL;
1330 plist_t send_file_node = NULL;
1331 node = NULL;
1332 plist_dict_next_item(files, iter, &hash, &node);
1333 while (node) {
1334 /* TODO: read mddata/mdinfo files and send to device using DLSendFile */
1335 file_info_path = mobilebackup_build_path(backup_directory, hash, ".mdinfo");
1336 plist_read_from_file(file_info_path, &file_info, NULL);
1337
1338 /* get encryption state */
1339 tmp_node = plist_dict_get_item(file_info, "IsEncrypted");
1340 plist_get_bool_val(tmp_node, &is_encrypted);
1341 tmp_node = NULL;
1342
1343 /* get real file path from metadata */
1344 tmp_node = plist_dict_get_item(file_info, "Metadata");
1345 plist_get_data_val(tmp_node, &buffer, &length);
1346 tmp_node = NULL;
1347 plist_from_bin(buffer, length, &tmp_node);
1348 file_path_node = plist_dict_get_item(tmp_node, "Path");
1349 plist_get_string_val(file_path_node, &file_path);
1350
1351 printf("Restoring file %s %d/%d (%d%%)... ", file_path, cur_file, total_files, (cur_file*100/total_files));
1352
1353 /* add additional device link file information keys */
1354 plist_dict_set_item(file_info, "DLFileAttributesKey", plist_copy(node));
1355 plist_dict_set_item(file_info, "DLFileSource", plist_new_string(file_info_path));
1356 plist_dict_set_item(file_info, "DLFileDest", plist_new_string("/tmp/RestoreFile.plist"));
1357 plist_dict_set_item(file_info, "DLFileIsEncrypted", plist_new_bool(is_encrypted));
1358 plist_dict_set_item(file_info, "DLFileOffsetKey", plist_new_uint(file_offset));
1359 plist_dict_set_item(file_info, "DLFileStatusKey", plist_new_uint(file_status));
1360
1361 /* read data from file */
1362 free(file_info_path);
1363 file_info_path = mobilebackup_build_path(backup_directory, hash, ".mddata");
1364
1365 /* determine file size */
1366 #ifdef _WIN32
1367 struct _stati64 fst;
1368 if (_stati64(file_info_path, &fst) != 0)
1369 #else
1370 struct stat fst;
1371 if (stat(file_info_path, &fst) != 0)
1372 #endif
1373 {
1374 printf("ERROR: stat() failed for '%s': %s\n", file_info_path, strerror(errno));
1375 free(file_info_path);
1376 break;
1377 }
1378 length = fst.st_size;
1379
1380 FILE *f = fopen(file_info_path, "rb");
1381 if (!f) {
1382 printf("ERROR: could not open local file '%s': %s\n", file_info_path, strerror(errno));
1383 free(file_info_path);
1384 break;
1385 }
1386 free(file_info_path);
1387
1388 /* send DLSendFile messages */
1389 file_offset = 0;
1390 do {
1391 char buf[8192];
1392 size_t len = fread(buf, 1, sizeof(buf), f);
1393
1394 if ((length-file_offset) <= sizeof(buf))
1395 file_status = DEVICE_LINK_FILE_STATUS_LAST_HUNK;
1396 else
1397 file_status = DEVICE_LINK_FILE_STATUS_HUNK;
1398
1399 plist_dict_remove_item(file_info, "DLFileOffsetKey");
1400 plist_dict_set_item(file_info, "DLFileOffsetKey", plist_new_uint(file_offset));
1401
1402 plist_dict_remove_item(file_info, "DLFileStatusKey");
1403 plist_dict_set_item(file_info, "DLFileStatusKey", plist_new_uint(file_status));
1404
1405 send_file_node = plist_new_array();
1406
1407 plist_array_append_item(send_file_node, plist_new_string("DLSendFile"));
1408
1409 plist_array_append_item(send_file_node, plist_new_data(buf, len));
1410 plist_array_append_item(send_file_node, plist_copy(file_info));
1411
1412 err = mobilebackup_send(mobilebackup, send_file_node);
1413 if (err != MOBILEBACKUP_E_SUCCESS) {
1414 printf("ERROR: Unable to send file hunk due to error %d. Aborting...\n", err);
1415 file_status = DEVICE_LINK_FILE_STATUS_NONE;
1416 }
1417
1418 if (file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK) {
1419 /* TODO: if all hunks of a file are sent, device must send ack */
1420 err = mobilebackup_receive_restore_file_received(mobilebackup, NULL);
1421 if (err != MOBILEBACKUP_E_SUCCESS) {
1422 printf("ERROR: Did not receive an ack for the sent file due to error %d. Aborting...\n", err);
1423 file_status = DEVICE_LINK_FILE_STATUS_NONE;
1424 }
1425 }
1426
1427 file_offset += len;
1428
1429 if (file_status == DEVICE_LINK_FILE_STATUS_LAST_HUNK)
1430 printf("DONE\n");
1431
1432 plist_free(send_file_node);
1433
1434 if (file_status == DEVICE_LINK_FILE_STATUS_NONE)
1435 break;
1436
1437 } while((file_offset < length));
1438
1439 free(hash);
1440 node = NULL;
1441 hash = NULL;
1442
1443 restore_ok = 1;
1444 if (file_status == DEVICE_LINK_FILE_STATUS_NONE) {
1445 restore_ok = 0;
1446 break;
1447 }
1448
1449 cur_file++;
1450 plist_dict_next_item(files, iter, &hash, &node);
1451 }
1452 free(iter);
1453
1454 printf("Restored %d files on device.\n", cur_file);
1455 }
1456 }
1457 /* TODO: observe notification_proxy id com.apple.mobile.application_installed */
1458 /* TODO: loop over Applications entries in Manifest data plist */
1459 plist_t applications = plist_dict_get_item(backup_data, "Applications");
1460 if (applications && (plist_get_node_type(applications) == PLIST_DICT) && restore_ok) {
1461 plist_dict_iter iter = NULL;
1462 plist_dict_new_iter(applications, &iter);
1463 if (iter) {
1464 /* loop over Application entries in Manifest data plist */
1465 char *hash = NULL;
1466 int total_files = plist_dict_get_size(applications);
1467 int cur_file = 1;
1468 plist_t tmp_node = NULL;
1469 plist_t dict = NULL;
1470 plist_t array = NULL;
1471 node = NULL;
1472 plist_dict_next_item(applications, iter, &hash, &node);
1473 while (node) {
1474 printf("Restoring Application %s %d/%d (%d%%)...", hash, cur_file, total_files, (cur_file*100/total_files));
1475 /* FIXME: receive com.apple.mobile.application_installed notification */
1476 /* send AppInfo entry */
1477 tmp_node = plist_dict_get_item(node, "AppInfo");
1478
1479 dict = plist_new_dict();
1480 plist_dict_set_item(dict, "AppInfo", plist_copy(tmp_node));
1481 plist_dict_set_item(dict, "BackupMessageTypeKey", plist_new_string("BackupMessageRestoreApplicationSent"));
1482
1483 array = plist_new_array();
1484 plist_array_append_item(array, plist_new_string("DLMessageProcessMessage"));
1485 plist_array_append_item(array, dict);
1486
1487 err = mobilebackup_send(mobilebackup, array);
1488 if (err != MOBILEBACKUP_E_SUCCESS) {
1489 printf("ERROR: Unable to restore application %s due to error %d. Aborting...\n", hash, err);
1490 restore_ok = 0;
1491 }
1492
1493 plist_free(array);
1494 array = NULL;
1495 dict = NULL;
1496
1497 /* receive BackupMessageRestoreApplicationReceived from device */
1498 if (restore_ok) {
1499 err = mobilebackup_receive_restore_application_received(mobilebackup, NULL);
1500 if (err != MOBILEBACKUP_E_SUCCESS) {
1501 printf("ERROR: Failed to receive an ack from the device for this application due to error %d. Aborting...\n", err);
1502 restore_ok = 0;
1503 }
1504 }
1505
1506 tmp_node = NULL;
1507 node = NULL;
1508 free(hash);
1509 hash = NULL;
1510
1511 if (restore_ok) {
1512 printf("DONE\n");
1513 cur_file++;
1514 plist_dict_next_item(applications, iter, &hash, &node);
1515 } else
1516 break;
1517 }
1518 free(iter);
1519
1520 if (restore_ok)
1521 printf("All applications restored.\n");
1522 else
1523 printf("Failed to restore applications.\n");
1524 }
1525 }
1526
1527 plist_free(backup_data);
1528
1529 /* signal restore finished message to device; BackupMessageRestoreComplete */
1530 if (restore_ok) {
1531 err = mobilebackup_send_restore_complete(mobilebackup);
1532 if (err != MOBILEBACKUP_E_SUCCESS) {
1533 printf("ERROR: Could not send BackupMessageRestoreComplete, error code %d\n", err);
1534 }
1535 }
1536
1537 if (restore_ok) {
1538 printf("Restore Successful.\n");
1539 } else {
1540 printf("Restore Failed.\n");
1541 }
1542 break;
1543 case CMD_LEAVE:
1544 default:
1545 break;
1546 }
1547 if (lockfile) {
1548 afc_file_lock(afc, lockfile, AFC_LOCK_UN);
1549 afc_file_close(afc, lockfile);
1550 lockfile = 0;
1551 do_post_notification(NP_SYNC_DID_FINISH);
1552 }
1553 if (manifest_path)
1554 free(manifest_path);
1555 } else {
1556 printf("ERROR: Could not start service %s: %s\n", MOBILEBACKUP_SERVICE_NAME, lockdownd_strerror(ldret));
1557 lockdownd_client_free(client);
1558 client = NULL;
1559 }
1560
1561 if (client) {
1562 lockdownd_client_free(client);
1563 client = NULL;
1564 }
1565
1566 if (afc)
1567 afc_client_free(afc);
1568
1569 if (np)
1570 np_client_free(np);
1571
1572 if (mobilebackup)
1573 mobilebackup_client_free(mobilebackup);
1574
1575 idevice_free(device);
1576
1577 free(udid);
1578
1579 return 0;
1580 }
1581