idevicebackup2.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221
  1. /*
  2. * idevicebackup2.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. #include <stdio.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #include <stdlib.h>
  26. #include <signal.h>
  27. #include <unistd.h>
  28. #include <dirent.h>
  29. #include <libgen.h>
  30. #include <ctype.h>
  31. #include <time.h>
  32. #include <libimobiledevice/libimobiledevice.h>
  33. #include <libimobiledevice/lockdown.h>
  34. #include <libimobiledevice/mobilebackup2.h>
  35. #include <libimobiledevice/notification_proxy.h>
  36. #include <libimobiledevice/afc.h>
  37. #include "common/utils.h"
  38. #include <endianness.h>
  39. #define LOCK_ATTEMPTS 50
  40. #define LOCK_WAIT 200000
  41. #ifdef WIN32
  42. #include <windows.h>
  43. #include <conio.h>
  44. #define sleep(x) Sleep(x*1000)
  45. #else
  46. #include <termios.h>
  47. #include <sys/statvfs.h>
  48. #endif
  49. #include <sys/stat.h>
  50. #define CODE_SUCCESS 0x00
  51. #define CODE_ERROR_LOCAL 0x06
  52. #define CODE_ERROR_REMOTE 0x0b
  53. #define CODE_FILE_DATA 0x0c
  54. static int verbose = 1;
  55. static int quit_flag = 0;
  56. #define PRINT_VERBOSE(min_level, ...) if (verbose >= min_level) { printf(__VA_ARGS__); };
  57. enum cmd_mode {
  58. CMD_BACKUP,
  59. CMD_RESTORE,
  60. CMD_INFO,
  61. CMD_LIST,
  62. CMD_UNBACK,
  63. CMD_CHANGEPW,
  64. CMD_LEAVE,
  65. CMD_CLOUD
  66. };
  67. enum cmd_flags {
  68. CMD_FLAG_RESTORE_SYSTEM_FILES = (1 << 1),
  69. CMD_FLAG_RESTORE_REBOOT = (1 << 2),
  70. CMD_FLAG_RESTORE_COPY_BACKUP = (1 << 3),
  71. CMD_FLAG_RESTORE_SETTINGS = (1 << 4),
  72. CMD_FLAG_RESTORE_REMOVE_ITEMS = (1 << 5),
  73. CMD_FLAG_ENCRYPTION_ENABLE = (1 << 6),
  74. CMD_FLAG_ENCRYPTION_DISABLE = (1 << 7),
  75. CMD_FLAG_ENCRYPTION_CHANGEPW = (1 << 8),
  76. CMD_FLAG_FORCE_FULL_BACKUP = (1 << 9),
  77. CMD_FLAG_CLOUD_ENABLE = (1 << 10),
  78. CMD_FLAG_CLOUD_DISABLE = (1 << 11)
  79. };
  80. static int backup_domain_changed = 0;
  81. static void notify_cb(const char *notification, void *userdata)
  82. {
  83. if (strlen(notification) == 0) {
  84. return;
  85. }
  86. if (!strcmp(notification, NP_SYNC_CANCEL_REQUEST)) {
  87. PRINT_VERBOSE(1, "User has cancelled the backup process on the device.\n");
  88. quit_flag++;
  89. } else if (!strcmp(notification, NP_BACKUP_DOMAIN_CHANGED)) {
  90. backup_domain_changed = 1;
  91. } else {
  92. PRINT_VERBOSE(1, "Unhandled notification '%s' (TODO: implement)\n", notification);
  93. }
  94. }
  95. static void mobilebackup_afc_get_file_contents(afc_client_t afc, const char *filename, char **data, uint64_t *size)
  96. {
  97. if (!afc || !data || !size) {
  98. return;
  99. }
  100. char **fileinfo = NULL;
  101. uint32_t fsize = 0;
  102. afc_get_file_info(afc, filename, &fileinfo);
  103. if (!fileinfo) {
  104. return;
  105. }
  106. int i;
  107. for (i = 0; fileinfo[i]; i+=2) {
  108. if (!strcmp(fileinfo[i], "st_size")) {
  109. fsize = atol(fileinfo[i+1]);
  110. break;
  111. }
  112. }
  113. afc_dictionary_free(fileinfo);
  114. if (fsize == 0) {
  115. return;
  116. }
  117. uint64_t f = 0;
  118. afc_file_open(afc, filename, AFC_FOPEN_RDONLY, &f);
  119. if (!f) {
  120. return;
  121. }
  122. char *buf = (char*)malloc((uint32_t)fsize);
  123. uint32_t done = 0;
  124. while (done < fsize) {
  125. uint32_t bread = 0;
  126. afc_file_read(afc, f, buf+done, 65536, &bread);
  127. if (bread > 0) {
  128. } else {
  129. break;
  130. }
  131. done += bread;
  132. }
  133. if (done == fsize) {
  134. *size = fsize;
  135. *data = buf;
  136. } else {
  137. free(buf);
  138. }
  139. afc_file_close(afc, f);
  140. }
  141. static int __mkdir(const char* path, int mode)
  142. {
  143. #ifdef WIN32
  144. return mkdir(path);
  145. #else
  146. return mkdir(path, mode);
  147. #endif
  148. }
  149. static int mkdir_with_parents(const char *dir, int mode)
  150. {
  151. if (!dir) return -1;
  152. if (__mkdir(dir, mode) == 0) {
  153. return 0;
  154. } else {
  155. if (errno == EEXIST) return 0;
  156. }
  157. int res;
  158. char *parent = strdup(dir);
  159. char *parentdir = dirname(parent);
  160. if (parentdir) {
  161. res = mkdir_with_parents(parentdir, mode);
  162. } else {
  163. res = -1;
  164. }
  165. free(parent);
  166. if (res == 0) {
  167. mkdir_with_parents(dir, mode);
  168. }
  169. return res;
  170. }
  171. static plist_t mobilebackup_factory_info_plist_new(const char* udid, lockdownd_client_t lockdown, afc_client_t afc)
  172. {
  173. /* gather data from lockdown */
  174. plist_t value_node = NULL;
  175. plist_t root_node = NULL;
  176. char *udid_uppercase = NULL;
  177. plist_t ret = plist_new_dict();
  178. /* get basic device information in one go */
  179. lockdownd_get_value(lockdown, NULL, NULL, &root_node);
  180. /* set fields we understand */
  181. value_node = plist_dict_get_item(root_node, "BuildVersion");
  182. plist_dict_set_item(ret, "Build Version", plist_copy(value_node));
  183. value_node = plist_dict_get_item(root_node, "DeviceName");
  184. plist_dict_set_item(ret, "Device Name", plist_copy(value_node));
  185. plist_dict_set_item(ret, "Display Name", plist_copy(value_node));
  186. /* FIXME: How is the GUID generated? */
  187. plist_dict_set_item(ret, "GUID", plist_new_string("---"));
  188. value_node = plist_dict_get_item(root_node, "IntegratedCircuitCardIdentity");
  189. if (value_node)
  190. plist_dict_set_item(ret, "ICCID", plist_copy(value_node));
  191. value_node = plist_dict_get_item(root_node, "InternationalMobileEquipmentIdentity");
  192. if (value_node)
  193. plist_dict_set_item(ret, "IMEI", plist_copy(value_node));
  194. plist_dict_set_item(ret, "Last Backup Date", plist_new_date(time(NULL), 0));
  195. value_node = plist_dict_get_item(root_node, "PhoneNumber");
  196. if (value_node && (plist_get_node_type(value_node) == PLIST_STRING)) {
  197. plist_dict_set_item(ret, "Phone Number", plist_copy(value_node));
  198. }
  199. value_node = plist_dict_get_item(root_node, "ProductType");
  200. plist_dict_set_item(ret, "Product Type", plist_copy(value_node));
  201. value_node = plist_dict_get_item(root_node, "ProductVersion");
  202. plist_dict_set_item(ret, "Product Version", plist_copy(value_node));
  203. value_node = plist_dict_get_item(root_node, "SerialNumber");
  204. plist_dict_set_item(ret, "Serial Number", plist_copy(value_node));
  205. /* FIXME Sync Settings? */
  206. value_node = plist_dict_get_item(root_node, "UniqueDeviceID");
  207. plist_dict_set_item(ret, "Target Identifier", plist_new_string(udid));
  208. plist_dict_set_item(ret, "Target Type", plist_new_string("Device"));
  209. /* uppercase */
  210. udid_uppercase = string_toupper((char*)udid);
  211. plist_dict_set_item(ret, "Unique Identifier", plist_new_string(udid_uppercase));
  212. free(udid_uppercase);
  213. char *data_buf = NULL;
  214. uint64_t data_size = 0;
  215. mobilebackup_afc_get_file_contents(afc, "/Books/iBooksData2.plist", &data_buf, &data_size);
  216. if (data_buf) {
  217. plist_dict_set_item(ret, "iBooks Data 2", plist_new_data(data_buf, data_size));
  218. free(data_buf);
  219. }
  220. plist_t files = plist_new_dict();
  221. const char *itunesfiles[] = {
  222. "ApertureAlbumPrefs",
  223. "IC-Info.sidb",
  224. "IC-Info.sidv",
  225. "PhotosFolderAlbums",
  226. "PhotosFolderName",
  227. "PhotosFolderPrefs",
  228. "iPhotoAlbumPrefs",
  229. "iTunesApplicationIDs",
  230. "iTunesPrefs",
  231. "iTunesPrefs.plist",
  232. NULL
  233. };
  234. int i = 0;
  235. for (i = 0; itunesfiles[i]; i++) {
  236. data_buf = NULL;
  237. data_size = 0;
  238. char *fname = (char*)malloc(strlen("/iTunes_Control/iTunes/") + strlen(itunesfiles[i]) + 1);
  239. strcpy(fname, "/iTunes_Control/iTunes/");
  240. strcat(fname, itunesfiles[i]);
  241. mobilebackup_afc_get_file_contents(afc, fname, &data_buf, &data_size);
  242. free(fname);
  243. if (data_buf) {
  244. plist_dict_set_item(files, itunesfiles[i], plist_new_data(data_buf, data_size));
  245. free(data_buf);
  246. }
  247. }
  248. plist_dict_set_item(ret, "iTunes Files", files);
  249. plist_t itunes_settings = NULL;
  250. lockdownd_get_value(lockdown, "com.apple.iTunes", NULL, &itunes_settings);
  251. plist_dict_set_item(ret, "iTunes Settings", itunes_settings ? itunes_settings : plist_new_dict());
  252. plist_dict_set_item(ret, "iTunes Version", plist_new_string("10.0.1"));
  253. plist_free(root_node);
  254. return ret;
  255. }
  256. static int mb2_status_check_snapshot_state(const char *path, const char *udid, const char *matches)
  257. {
  258. int ret = -1;
  259. plist_t status_plist = NULL;
  260. char *file_path = string_build_path(path, udid, "Status.plist", NULL);
  261. plist_read_from_filename(&status_plist, file_path);
  262. free(file_path);
  263. if (!status_plist) {
  264. printf("Could not read Status.plist!\n");
  265. return ret;
  266. }
  267. plist_t node = plist_dict_get_item(status_plist, "SnapshotState");
  268. if (node && (plist_get_node_type(node) == PLIST_STRING)) {
  269. char* sval = NULL;
  270. plist_get_string_val(node, &sval);
  271. if (sval) {
  272. ret = (strcmp(sval, matches) == 0) ? 1 : 0;
  273. free(sval);
  274. }
  275. } else {
  276. printf("%s: ERROR could not get SnapshotState key from Status.plist!\n", __func__);
  277. }
  278. plist_free(status_plist);
  279. return ret;
  280. }
  281. static void do_post_notification(idevice_t device, const char *notification)
  282. {
  283. lockdownd_service_descriptor_t service = NULL;
  284. np_client_t np;
  285. lockdownd_client_t lockdown = NULL;
  286. if (lockdownd_client_new_with_handshake(device, &lockdown, "idevicebackup2") != LOCKDOWN_E_SUCCESS) {
  287. return;
  288. }
  289. lockdownd_start_service(lockdown, NP_SERVICE_NAME, &service);
  290. if (service && service->port) {
  291. np_client_new(device, service, &np);
  292. if (np) {
  293. np_post_notification(np, notification);
  294. np_client_free(np);
  295. }
  296. } else {
  297. printf("Could not start %s\n", NP_SERVICE_NAME);
  298. }
  299. if (service) {
  300. lockdownd_service_descriptor_free(service);
  301. service = NULL;
  302. }
  303. lockdownd_client_free(lockdown);
  304. }
  305. static void print_progress_real(double progress, int flush)
  306. {
  307. int i = 0;
  308. PRINT_VERBOSE(1, "\r[");
  309. for(i = 0; i < 50; i++) {
  310. if(i < progress / 2) {
  311. PRINT_VERBOSE(1, "=");
  312. } else {
  313. PRINT_VERBOSE(1, " ");
  314. }
  315. }
  316. PRINT_VERBOSE(1, "] %3.0f%%", progress);
  317. if (flush > 0) {
  318. fflush(stdout);
  319. if (progress == 100)
  320. PRINT_VERBOSE(1, "\n");
  321. }
  322. }
  323. static void print_progress(uint64_t current, uint64_t total)
  324. {
  325. char *format_size = NULL;
  326. double progress = ((double)current/(double)total)*100;
  327. if (progress < 0)
  328. return;
  329. if (progress > 100)
  330. progress = 100;
  331. print_progress_real((double)progress, 0);
  332. format_size = string_format_size(current);
  333. PRINT_VERBOSE(1, " (%s", format_size);
  334. free(format_size);
  335. format_size = string_format_size(total);
  336. PRINT_VERBOSE(1, "/%s) ", format_size);
  337. free(format_size);
  338. fflush(stdout);
  339. if (progress == 100)
  340. PRINT_VERBOSE(1, "\n");
  341. }
  342. static double overall_progress = 0;
  343. static void mb2_set_overall_progress(double progress)
  344. {
  345. if (progress > 0.0)
  346. overall_progress = progress;
  347. }
  348. static void mb2_set_overall_progress_from_message(plist_t message, char* identifier)
  349. {
  350. plist_t node = NULL;
  351. double progress = 0.0;
  352. if (!strcmp(identifier, "DLMessageDownloadFiles")) {
  353. node = plist_array_get_item(message, 3);
  354. } else if (!strcmp(identifier, "DLMessageUploadFiles")) {
  355. node = plist_array_get_item(message, 2);
  356. } else if (!strcmp(identifier, "DLMessageMoveFiles") || !strcmp(identifier, "DLMessageMoveItems")) {
  357. node = plist_array_get_item(message, 3);
  358. } else if (!strcmp(identifier, "DLMessageRemoveFiles") || !strcmp(identifier, "DLMessageRemoveItems")) {
  359. node = plist_array_get_item(message, 3);
  360. }
  361. if (node != NULL) {
  362. plist_get_real_val(node, &progress);
  363. mb2_set_overall_progress(progress);
  364. }
  365. }
  366. static void mb2_multi_status_add_file_error(plist_t status_dict, const char *path, int error_code, const char *error_message)
  367. {
  368. if (!status_dict) return;
  369. plist_t filedict = plist_new_dict();
  370. plist_dict_set_item(filedict, "DLFileErrorString", plist_new_string(error_message));
  371. plist_dict_set_item(filedict, "DLFileErrorCode", plist_new_uint(error_code));
  372. plist_dict_set_item(status_dict, path, filedict);
  373. }
  374. static int errno_to_device_error(int errno_value)
  375. {
  376. switch (errno_value) {
  377. case ENOENT:
  378. return -6;
  379. case EEXIST:
  380. return -7;
  381. default:
  382. return -errno_value;
  383. }
  384. }
  385. #ifdef WIN32
  386. static int win32err_to_errno(int err_value)
  387. {
  388. switch (err_value) {
  389. case ERROR_FILE_NOT_FOUND:
  390. return ENOENT;
  391. case ERROR_ALREADY_EXISTS:
  392. return EEXIST;
  393. default:
  394. return EFAULT;
  395. }
  396. }
  397. #endif
  398. static int mb2_handle_send_file(mobilebackup2_client_t mobilebackup2, const char *backup_dir, const char *path, plist_t *errplist)
  399. {
  400. uint32_t nlen = 0;
  401. uint32_t pathlen = strlen(path);
  402. uint32_t bytes = 0;
  403. char *localfile = string_build_path(backup_dir, path, NULL);
  404. char buf[32768];
  405. #ifdef WIN32
  406. struct _stati64 fst;
  407. #else
  408. struct stat fst;
  409. #endif
  410. FILE *f = NULL;
  411. uint32_t slen = 0;
  412. int errcode = -1;
  413. int result = -1;
  414. uint32_t length;
  415. #ifdef WIN32
  416. uint64_t total;
  417. uint64_t sent;
  418. #else
  419. off_t total;
  420. off_t sent;
  421. #endif
  422. mobilebackup2_error_t err;
  423. /* send path length */
  424. nlen = htobe32(pathlen);
  425. err = mobilebackup2_send_raw(mobilebackup2, (const char*)&nlen, sizeof(nlen), &bytes);
  426. if (err != MOBILEBACKUP2_E_SUCCESS) {
  427. goto leave_proto_err;
  428. }
  429. if (bytes != (uint32_t)sizeof(nlen)) {
  430. err = MOBILEBACKUP2_E_MUX_ERROR;
  431. goto leave_proto_err;
  432. }
  433. /* send path */
  434. err = mobilebackup2_send_raw(mobilebackup2, path, pathlen, &bytes);
  435. if (err != MOBILEBACKUP2_E_SUCCESS) {
  436. goto leave_proto_err;
  437. }
  438. if (bytes != pathlen) {
  439. err = MOBILEBACKUP2_E_MUX_ERROR;
  440. goto leave_proto_err;
  441. }
  442. #ifdef WIN32
  443. if (_stati64(localfile, &fst) < 0)
  444. #else
  445. if (stat(localfile, &fst) < 0)
  446. #endif
  447. {
  448. if (errno != ENOENT)
  449. printf("%s: stat failed on '%s': %d\n", __func__, localfile, errno);
  450. errcode = errno;
  451. goto leave;
  452. }
  453. total = fst.st_size;
  454. char *format_size = string_format_size(total);
  455. PRINT_VERBOSE(1, "Sending '%s' (%s)\n", path, format_size);
  456. free(format_size);
  457. if (total == 0) {
  458. errcode = 0;
  459. goto leave;
  460. }
  461. f = fopen(localfile, "rb");
  462. if (!f) {
  463. printf("%s: Error opening local file '%s': %d\n", __func__, localfile, errno);
  464. errcode = errno;
  465. goto leave;
  466. }
  467. sent = 0;
  468. do {
  469. length = ((total-sent) < (long long)sizeof(buf)) ? (uint32_t)total-sent : (uint32_t)sizeof(buf);
  470. /* send data size (file size + 1) */
  471. nlen = htobe32(length+1);
  472. memcpy(buf, &nlen, sizeof(nlen));
  473. buf[4] = CODE_FILE_DATA;
  474. err = mobilebackup2_send_raw(mobilebackup2, (const char*)buf, 5, &bytes);
  475. if (err != MOBILEBACKUP2_E_SUCCESS) {
  476. goto leave_proto_err;
  477. }
  478. if (bytes != 5) {
  479. goto leave_proto_err;
  480. }
  481. /* send file contents */
  482. size_t r = fread(buf, 1, sizeof(buf), f);
  483. if (r <= 0) {
  484. printf("%s: read error\n", __func__);
  485. errcode = errno;
  486. goto leave;
  487. }
  488. err = mobilebackup2_send_raw(mobilebackup2, buf, r, &bytes);
  489. if (err != MOBILEBACKUP2_E_SUCCESS) {
  490. goto leave_proto_err;
  491. }
  492. if (bytes != (uint32_t)r) {
  493. printf("Error: sent only %d of %d bytes\n", bytes, (int)r);
  494. goto leave_proto_err;
  495. }
  496. sent += r;
  497. } while (sent < total);
  498. fclose(f);
  499. f = NULL;
  500. errcode = 0;
  501. leave:
  502. if (errcode == 0) {
  503. result = 0;
  504. nlen = 1;
  505. nlen = htobe32(nlen);
  506. memcpy(buf, &nlen, 4);
  507. buf[4] = CODE_SUCCESS;
  508. mobilebackup2_send_raw(mobilebackup2, buf, 5, &bytes);
  509. } else {
  510. if (!*errplist) {
  511. *errplist = plist_new_dict();
  512. }
  513. char *errdesc = strerror(errcode);
  514. mb2_multi_status_add_file_error(*errplist, path, errno_to_device_error(errcode), errdesc);
  515. length = strlen(errdesc);
  516. nlen = htobe32(length+1);
  517. memcpy(buf, &nlen, 4);
  518. buf[4] = CODE_ERROR_LOCAL;
  519. slen = 5;
  520. memcpy(buf+slen, errdesc, length);
  521. slen += length;
  522. err = mobilebackup2_send_raw(mobilebackup2, (const char*)buf, slen, &bytes);
  523. if (err != MOBILEBACKUP2_E_SUCCESS) {
  524. printf("could not send message\n");
  525. }
  526. if (bytes != slen) {
  527. printf("could only send %d from %d\n", bytes, slen);
  528. }
  529. }
  530. leave_proto_err:
  531. if (f)
  532. fclose(f);
  533. free(localfile);
  534. return result;
  535. }
  536. static void mb2_handle_send_files(mobilebackup2_client_t mobilebackup2, plist_t message, const char *backup_dir)
  537. {
  538. uint32_t cnt;
  539. uint32_t i = 0;
  540. uint32_t sent;
  541. plist_t errplist = NULL;
  542. if (!message || (plist_get_node_type(message) != PLIST_ARRAY) || (plist_array_get_size(message) < 2) || !backup_dir) return;
  543. plist_t files = plist_array_get_item(message, 1);
  544. cnt = plist_array_get_size(files);
  545. for (i = 0; i < cnt; i++) {
  546. plist_t val = plist_array_get_item(files, i);
  547. if (plist_get_node_type(val) != PLIST_STRING) {
  548. continue;
  549. }
  550. char *str = NULL;
  551. plist_get_string_val(val, &str);
  552. if (!str)
  553. continue;
  554. if (mb2_handle_send_file(mobilebackup2, backup_dir, str, &errplist) < 0) {
  555. free(str);
  556. //printf("Error when sending file '%s' to device\n", str);
  557. // TODO: perhaps we can continue, we've got a multi status response?!
  558. break;
  559. }
  560. free(str);
  561. }
  562. /* send terminating 0 dword */
  563. uint32_t zero = 0;
  564. mobilebackup2_send_raw(mobilebackup2, (char*)&zero, 4, &sent);
  565. if (!errplist) {
  566. plist_t emptydict = plist_new_dict();
  567. mobilebackup2_send_status_response(mobilebackup2, 0, NULL, emptydict);
  568. plist_free(emptydict);
  569. } else {
  570. mobilebackup2_send_status_response(mobilebackup2, -13, "Multi status", errplist);
  571. plist_free(errplist);
  572. }
  573. }
  574. static int mb2_receive_filename(mobilebackup2_client_t mobilebackup2, char** filename)
  575. {
  576. uint32_t nlen = 0;
  577. uint32_t rlen = 0;
  578. do {
  579. nlen = 0;
  580. rlen = 0;
  581. mobilebackup2_receive_raw(mobilebackup2, (char*)&nlen, 4, &rlen);
  582. nlen = be32toh(nlen);
  583. if ((nlen == 0) && (rlen == 4)) {
  584. // a zero length means no more files to receive
  585. return 0;
  586. } else if(rlen == 0) {
  587. // device needs more time, waiting...
  588. continue;
  589. } else if (nlen > 4096) {
  590. // filename length is too large
  591. printf("ERROR: %s: too large filename length (%d)!\n", __func__, nlen);
  592. return 0;
  593. }
  594. if (*filename != NULL) {
  595. free(*filename);
  596. *filename = NULL;
  597. }
  598. *filename = (char*)malloc(nlen+1);
  599. rlen = 0;
  600. mobilebackup2_receive_raw(mobilebackup2, *filename, nlen, &rlen);
  601. if (rlen != nlen) {
  602. printf("ERROR: %s: could not read filename\n", __func__);
  603. return 0;
  604. }
  605. char* p = *filename;
  606. p[rlen] = 0;
  607. break;
  608. } while(1 && !quit_flag);
  609. return nlen;
  610. }
  611. static int mb2_handle_receive_files(mobilebackup2_client_t mobilebackup2, plist_t message, const char *backup_dir)
  612. {
  613. uint64_t backup_real_size = 0;
  614. uint64_t backup_total_size = 0;
  615. uint32_t blocksize;
  616. uint32_t bdone;
  617. uint32_t rlen;
  618. uint32_t nlen = 0;
  619. uint32_t r;
  620. char buf[32768];
  621. char *fname = NULL;
  622. char *dname = NULL;
  623. char *bname = NULL;
  624. char code = 0;
  625. char last_code = 0;
  626. plist_t node = NULL;
  627. FILE *f = NULL;
  628. unsigned int file_count = 0;
  629. if (!message || (plist_get_node_type(message) != PLIST_ARRAY) || plist_array_get_size(message) < 4 || !backup_dir) return 0;
  630. node = plist_array_get_item(message, 3);
  631. if (plist_get_node_type(node) == PLIST_UINT) {
  632. plist_get_uint_val(node, &backup_total_size);
  633. }
  634. if (backup_total_size > 0) {
  635. PRINT_VERBOSE(1, "Receiving files\n");
  636. }
  637. do {
  638. if (quit_flag)
  639. break;
  640. nlen = mb2_receive_filename(mobilebackup2, &dname);
  641. if (nlen == 0) {
  642. break;
  643. }
  644. nlen = mb2_receive_filename(mobilebackup2, &fname);
  645. if (!nlen) {
  646. break;
  647. }
  648. if (bname != NULL) {
  649. free(bname);
  650. bname = NULL;
  651. }
  652. bname = string_build_path(backup_dir, fname, NULL);
  653. if (fname != NULL) {
  654. free(fname);
  655. fname = NULL;
  656. }
  657. r = 0;
  658. nlen = 0;
  659. mobilebackup2_receive_raw(mobilebackup2, (char*)&nlen, 4, &r);
  660. if (r != 4) {
  661. printf("ERROR: %s: could not receive code length!\n", __func__);
  662. break;
  663. }
  664. nlen = be32toh(nlen);
  665. last_code = code;
  666. code = 0;
  667. mobilebackup2_receive_raw(mobilebackup2, &code, 1, &r);
  668. if (r != 1) {
  669. printf("ERROR: %s: could not receive code!\n", __func__);
  670. break;
  671. }
  672. /* TODO remove this */
  673. if ((code != CODE_SUCCESS) && (code != CODE_FILE_DATA) && (code != CODE_ERROR_REMOTE)) {
  674. PRINT_VERBOSE(1, "Found new flag %02x\n", code);
  675. }
  676. remove(bname);
  677. f = fopen(bname, "wb");
  678. while (f && (code == CODE_FILE_DATA)) {
  679. blocksize = nlen-1;
  680. bdone = 0;
  681. rlen = 0;
  682. while (bdone < blocksize) {
  683. if ((blocksize - bdone) < sizeof(buf)) {
  684. rlen = blocksize - bdone;
  685. } else {
  686. rlen = sizeof(buf);
  687. }
  688. mobilebackup2_receive_raw(mobilebackup2, buf, rlen, &r);
  689. if ((int)r <= 0) {
  690. break;
  691. }
  692. fwrite(buf, 1, r, f);
  693. bdone += r;
  694. }
  695. if (bdone == blocksize) {
  696. backup_real_size += blocksize;
  697. }
  698. if (backup_total_size > 0) {
  699. print_progress(backup_real_size, backup_total_size);
  700. }
  701. if (quit_flag)
  702. break;
  703. nlen = 0;
  704. mobilebackup2_receive_raw(mobilebackup2, (char*)&nlen, 4, &r);
  705. nlen = be32toh(nlen);
  706. if (nlen > 0) {
  707. last_code = code;
  708. mobilebackup2_receive_raw(mobilebackup2, &code, 1, &r);
  709. } else {
  710. break;
  711. }
  712. }
  713. if (f) {
  714. fclose(f);
  715. file_count++;
  716. } else {
  717. printf("Error opening '%s' for writing: %s\n", bname, strerror(errno));
  718. }
  719. if (nlen == 0) {
  720. break;
  721. }
  722. /* check if an error message was received */
  723. if (code == CODE_ERROR_REMOTE) {
  724. /* error message */
  725. char *msg = (char*)malloc(nlen);
  726. mobilebackup2_receive_raw(mobilebackup2, msg, nlen-1, &r);
  727. msg[r] = 0;
  728. /* If sent using CODE_FILE_DATA, end marker will be CODE_ERROR_REMOTE which is not an error! */
  729. if (last_code != CODE_FILE_DATA) {
  730. fprintf(stdout, "\nReceived an error message from device: %s\n", msg);
  731. }
  732. free(msg);
  733. }
  734. } while (1);
  735. if (fname != NULL)
  736. free(fname);
  737. /* if there are leftovers to read, finish up cleanly */
  738. if ((int)nlen-1 > 0) {
  739. PRINT_VERBOSE(1, "\nDiscarding current data hunk.\n");
  740. fname = (char*)malloc(nlen-1);
  741. mobilebackup2_receive_raw(mobilebackup2, fname, nlen-1, &r);
  742. free(fname);
  743. remove(bname);
  744. }
  745. /* clean up */
  746. if (bname != NULL)
  747. free(bname);
  748. if (dname != NULL)
  749. free(dname);
  750. // TODO error handling?!
  751. plist_t empty_plist = plist_new_dict();
  752. mobilebackup2_send_status_response(mobilebackup2, 0, NULL, empty_plist);
  753. plist_free(empty_plist);
  754. return file_count;
  755. }
  756. static void mb2_handle_list_directory(mobilebackup2_client_t mobilebackup2, plist_t message, const char *backup_dir)
  757. {
  758. if (!message || (plist_get_node_type(message) != PLIST_ARRAY) || plist_array_get_size(message) < 2 || !backup_dir) return;
  759. plist_t node = plist_array_get_item(message, 1);
  760. char *str = NULL;
  761. if (plist_get_node_type(node) == PLIST_STRING) {
  762. plist_get_string_val(node, &str);
  763. }
  764. if (!str) {
  765. printf("ERROR: Malformed DLContentsOfDirectory message\n");
  766. // TODO error handling
  767. return;
  768. }
  769. char *path = string_build_path(backup_dir, str, NULL);
  770. free(str);
  771. plist_t dirlist = plist_new_dict();
  772. DIR* cur_dir = opendir(path);
  773. if (cur_dir) {
  774. struct dirent* ep;
  775. while ((ep = readdir(cur_dir))) {
  776. if ((strcmp(ep->d_name, ".") == 0) || (strcmp(ep->d_name, "..") == 0)) {
  777. continue;
  778. }
  779. char *fpath = string_build_path(path, ep->d_name, NULL);
  780. if (fpath) {
  781. plist_t fdict = plist_new_dict();
  782. struct stat st;
  783. stat(fpath, &st);
  784. const char *ftype = "DLFileTypeUnknown";
  785. if (S_ISDIR(st.st_mode)) {
  786. ftype = "DLFileTypeDirectory";
  787. } else if (S_ISREG(st.st_mode)) {
  788. ftype = "DLFileTypeRegular";
  789. }
  790. plist_dict_set_item(fdict, "DLFileType", plist_new_string(ftype));
  791. plist_dict_set_item(fdict, "DLFileSize", plist_new_uint(st.st_size));
  792. plist_dict_set_item(fdict, "DLFileModificationDate", plist_new_date(st.st_mtime, 0));
  793. plist_dict_set_item(dirlist, ep->d_name, fdict);
  794. free(fpath);
  795. }
  796. }
  797. closedir(cur_dir);
  798. }
  799. free(path);
  800. /* TODO error handling */
  801. mobilebackup2_error_t err = mobilebackup2_send_status_response(mobilebackup2, 0, NULL, dirlist);
  802. plist_free(dirlist);
  803. if (err != MOBILEBACKUP2_E_SUCCESS) {
  804. printf("Could not send status response, error %d\n", err);
  805. }
  806. }
  807. static void mb2_handle_make_directory(mobilebackup2_client_t mobilebackup2, plist_t message, const char *backup_dir)
  808. {
  809. if (!message || (plist_get_node_type(message) != PLIST_ARRAY) || plist_array_get_size(message) < 2 || !backup_dir) return;
  810. plist_t dir = plist_array_get_item(message, 1);
  811. char *str = NULL;
  812. int errcode = 0;
  813. char *errdesc = NULL;
  814. plist_get_string_val(dir, &str);
  815. char *newpath = string_build_path(backup_dir, str, NULL);
  816. free(str);
  817. if (mkdir_with_parents(newpath, 0755) < 0) {
  818. errdesc = strerror(errno);
  819. if (errno != EEXIST) {
  820. printf("mkdir: %s (%d)\n", errdesc, errno);
  821. }
  822. errcode = errno_to_device_error(errno);
  823. }
  824. free(newpath);
  825. mobilebackup2_error_t err = mobilebackup2_send_status_response(mobilebackup2, errcode, errdesc, NULL);
  826. if (err != MOBILEBACKUP2_E_SUCCESS) {
  827. printf("Could not send status response, error %d\n", err);
  828. }
  829. }
  830. static void mb2_copy_file_by_path(const char *src, const char *dst)
  831. {
  832. FILE *from, *to;
  833. char buf[BUFSIZ];
  834. size_t length;
  835. /* open source file */
  836. if ((from = fopen(src, "rb")) == NULL) {
  837. printf("Cannot open source path '%s'.\n", src);
  838. return;
  839. }
  840. /* open destination file */
  841. if ((to = fopen(dst, "wb")) == NULL) {
  842. printf("Cannot open destination file '%s'.\n", dst);
  843. return;
  844. }
  845. /* copy the file */
  846. while ((length = fread(buf, 1, BUFSIZ, from)) != 0) {
  847. fwrite(buf, 1, length, to);
  848. }
  849. if(fclose(from) == EOF) {
  850. printf("Error closing source file.\n");
  851. }
  852. if(fclose(to) == EOF) {
  853. printf("Error closing destination file.\n");
  854. }
  855. }
  856. static void mb2_copy_directory_by_path(const char *src, const char *dst)
  857. {
  858. if (!src || !dst) {
  859. return;
  860. }
  861. struct stat st;
  862. /* if src does not exist */
  863. if ((stat(src, &st) < 0) || !S_ISDIR(st.st_mode)) {
  864. printf("ERROR: Source directory does not exist '%s': %s (%d)\n", src, strerror(errno), errno);
  865. return;
  866. }
  867. /* if dst directory does not exist */
  868. if ((stat(dst, &st) < 0) || !S_ISDIR(st.st_mode)) {
  869. /* create it */
  870. if (mkdir_with_parents(dst, 0755) < 0) {
  871. printf("ERROR: Unable to create destination directory '%s': %s (%d)\n", dst, strerror(errno), errno);
  872. return;
  873. }
  874. }
  875. /* loop over src directory contents */
  876. DIR *cur_dir = opendir(src);
  877. if (cur_dir) {
  878. struct dirent* ep;
  879. while ((ep = readdir(cur_dir))) {
  880. if ((strcmp(ep->d_name, ".") == 0) || (strcmp(ep->d_name, "..") == 0)) {
  881. continue;
  882. }
  883. char *srcpath = string_build_path(src, ep->d_name, NULL);
  884. char *dstpath = string_build_path(dst, ep->d_name, NULL);
  885. if (srcpath && dstpath) {
  886. /* copy file */
  887. mb2_copy_file_by_path(srcpath, dstpath);
  888. free(srcpath);
  889. free(dstpath);
  890. }
  891. }
  892. closedir(cur_dir);
  893. }
  894. }
  895. #ifdef WIN32
  896. #define BS_CC '\b'
  897. #define my_getch getch
  898. #else
  899. #define BS_CC 0x7f
  900. static int my_getch(void)
  901. {
  902. struct termios oldt, newt;
  903. int ch;
  904. tcgetattr(STDIN_FILENO, &oldt);
  905. newt = oldt;
  906. newt.c_lflag &= ~(ICANON | ECHO);
  907. tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  908. ch = getchar();
  909. tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  910. return ch;
  911. }
  912. #endif
  913. static void get_hidden_input(char *buf, int maxlen)
  914. {
  915. int pwlen = 0;
  916. int c;
  917. while ((c = my_getch())) {
  918. if ((c == '\r') || (c == '\n')) {
  919. break;
  920. } else if (isprint(c)) {
  921. if (pwlen < maxlen-1)
  922. buf[pwlen++] = c;
  923. fputc('*', stderr);
  924. } else if (c == BS_CC) {
  925. if (pwlen > 0) {
  926. fputs("\b \b", stderr);
  927. pwlen--;
  928. }
  929. }
  930. }
  931. buf[pwlen] = 0;
  932. }
  933. static char* ask_for_password(const char* msg, int type_again)
  934. {
  935. char pwbuf[256];
  936. fprintf(stderr, "%s: ", msg);
  937. fflush(stderr);
  938. get_hidden_input(pwbuf, 256);
  939. fputc('\n', stderr);
  940. if (type_again) {
  941. char pwrep[256];
  942. fprintf(stderr, "%s (repeat): ", msg);
  943. fflush(stderr);
  944. get_hidden_input(pwrep, 256);
  945. fputc('\n', stderr);
  946. if (strcmp(pwbuf, pwrep) != 0) {
  947. printf("ERROR: passwords don't match\n");
  948. return NULL;
  949. }
  950. }
  951. return strdup(pwbuf);
  952. }
  953. /**
  954. * signal handler function for cleaning up properly
  955. */
  956. static void clean_exit(int sig)
  957. {
  958. fprintf(stderr, "Exiting...\n");
  959. quit_flag++;
  960. }
  961. static void print_usage(int argc, char **argv)
  962. {
  963. char *name = NULL;
  964. name = strrchr(argv[0], '/');
  965. printf("Usage: %s [OPTIONS] CMD [CMDOPTIONS] DIRECTORY\n", (name ? name + 1: argv[0]));
  966. printf("Create or restore backup from the current or specified directory.\n\n");
  967. printf("commands:\n");
  968. printf(" backup\tcreate backup for the device\n");
  969. printf(" --full\t\tforce full backup from device.\n");
  970. printf(" restore\trestore last backup to the device\n");
  971. printf(" --system\t\trestore system files, too.\n");
  972. printf(" --reboot\t\treboot the system when done.\n");
  973. printf(" --copy\t\tcreate a copy of backup folder before restoring.\n");
  974. printf(" --settings\t\trestore device settings from the backup.\n");
  975. printf(" --remove\t\tremove items which are not being restored\n");
  976. printf(" --password PWD\tsupply the password of the source backup\n");
  977. printf(" info\t\tshow details about last completed backup of device\n");
  978. printf(" list\t\tlist files of last completed backup in CSV format\n");
  979. printf(" unback\tunpack a completed backup in DIRECTORY/_unback_/\n");
  980. printf(" encryption on|off [PWD]\tenable or disable backup encryption\n");
  981. printf(" NOTE: password will be requested in interactive mode if omitted\n");
  982. printf(" changepw [OLD NEW] change backup password on target device\n");
  983. printf(" NOTE: passwords will be requested in interactive mode if omitted\n");
  984. printf(" cloud on|off\tenable or disable cloud use (requires iCloud account)\n");
  985. printf("\n");
  986. printf("options:\n");
  987. printf(" -d, --debug\t\tenable communication debugging\n");
  988. printf(" -u, --udid UDID\ttarget specific device by its 40-digit device UDID\n");
  989. printf(" -s, --source UDID\tuse backup data from device specified by UDID\n");
  990. printf(" -i, --interactive\trequest passwords interactively\n");
  991. printf(" -h, --help\t\tprints usage information\n");
  992. printf("\n");
  993. printf("Homepage: <http://libimobiledevice.org>\n");
  994. }
  995. int main(int argc, char *argv[])
  996. {
  997. idevice_error_t ret = IDEVICE_E_UNKNOWN_ERROR;
  998. lockdownd_error_t ldret = LOCKDOWN_E_UNKNOWN_ERROR;
  999. int i;
  1000. char* udid = NULL;
  1001. char* source_udid = NULL;
  1002. lockdownd_service_descriptor_t service = NULL;
  1003. int cmd = -1;
  1004. int cmd_flags = 0;
  1005. int is_full_backup = 0;
  1006. int result_code = -1;
  1007. char* backup_directory = NULL;
  1008. int interactive_mode = 0;
  1009. char* backup_password = NULL;
  1010. char* newpw = NULL;
  1011. struct stat st;
  1012. plist_t node_tmp = NULL;
  1013. plist_t info_plist = NULL;
  1014. plist_t opts = NULL;
  1015. mobilebackup2_error_t err;
  1016. /* we need to exit cleanly on running backups and restores or we cause havok */
  1017. signal(SIGINT, clean_exit);
  1018. signal(SIGTERM, clean_exit);
  1019. #ifndef WIN32
  1020. signal(SIGQUIT, clean_exit);
  1021. signal(SIGPIPE, SIG_IGN);
  1022. #endif
  1023. /* parse cmdline args */
  1024. for (i = 1; i < argc; i++) {
  1025. if (!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")) {
  1026. idevice_set_debug_level(1);
  1027. continue;
  1028. }
  1029. else if (!strcmp(argv[i], "-u") || !strcmp(argv[i], "--udid")) {
  1030. i++;
  1031. if (!argv[i] || (strlen(argv[i]) != 40)) {
  1032. print_usage(argc, argv);
  1033. return -1;
  1034. }
  1035. udid = strdup(argv[i]);
  1036. continue;
  1037. }
  1038. else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--source")) {
  1039. i++;
  1040. if (!argv[i] || (strlen(argv[i]) != 40)) {
  1041. print_usage(argc, argv);
  1042. return -1;
  1043. }
  1044. source_udid = strdup(argv[i]);
  1045. continue;
  1046. }
  1047. else if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--interactive")) {
  1048. interactive_mode = 1;
  1049. continue;
  1050. }
  1051. else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
  1052. print_usage(argc, argv);
  1053. return 0;
  1054. }
  1055. else if (!strcmp(argv[i], "backup")) {
  1056. cmd = CMD_BACKUP;
  1057. }
  1058. else if (!strcmp(argv[i], "restore")) {
  1059. cmd = CMD_RESTORE;
  1060. }
  1061. else if (!strcmp(argv[i], "--system")) {
  1062. cmd_flags |= CMD_FLAG_RESTORE_SYSTEM_FILES;
  1063. }
  1064. else if (!strcmp(argv[i], "--reboot")) {
  1065. cmd_flags |= CMD_FLAG_RESTORE_REBOOT;
  1066. }
  1067. else if (!strcmp(argv[i], "--copy")) {
  1068. cmd_flags |= CMD_FLAG_RESTORE_COPY_BACKUP;
  1069. }
  1070. else if (!strcmp(argv[i], "--settings")) {
  1071. cmd_flags |= CMD_FLAG_RESTORE_SETTINGS;
  1072. }
  1073. else if (!strcmp(argv[i], "--remove")) {
  1074. cmd_flags |= CMD_FLAG_RESTORE_REMOVE_ITEMS;
  1075. }
  1076. else if (!strcmp(argv[i], "--password")) {
  1077. i++;
  1078. if (!argv[i]) {
  1079. print_usage(argc, argv);
  1080. return -1;
  1081. }
  1082. if (backup_password)
  1083. free(backup_password);
  1084. backup_password = strdup(argv[i]);
  1085. continue;
  1086. }
  1087. else if (!strcmp(argv[i], "cloud")) {
  1088. cmd = CMD_CLOUD;
  1089. i++;
  1090. if (!argv[i]) {
  1091. printf("No argument given for cloud command; requires either 'on' or 'off'.\n");
  1092. print_usage(argc, argv);
  1093. return -1;
  1094. }
  1095. if (!strcmp(argv[i], "on")) {
  1096. cmd_flags |= CMD_FLAG_CLOUD_ENABLE;
  1097. } else if (!strcmp(argv[i], "off")) {
  1098. cmd_flags |= CMD_FLAG_CLOUD_DISABLE;
  1099. } else {
  1100. printf("Invalid argument '%s' for cloud command; must be either 'on' or 'off'.\n", argv[i]);
  1101. }
  1102. continue;
  1103. }
  1104. else if (!strcmp(argv[i], "--full")) {
  1105. cmd_flags |= CMD_FLAG_FORCE_FULL_BACKUP;
  1106. }
  1107. else if (!strcmp(argv[i], "info")) {
  1108. cmd = CMD_INFO;
  1109. verbose = 0;
  1110. }
  1111. else if (!strcmp(argv[i], "list")) {
  1112. cmd = CMD_LIST;
  1113. verbose = 0;
  1114. }
  1115. else if (!strcmp(argv[i], "unback")) {
  1116. cmd = CMD_UNBACK;
  1117. }
  1118. else if (!strcmp(argv[i], "encryption")) {
  1119. cmd = CMD_CHANGEPW;
  1120. i++;
  1121. if (!argv[i]) {
  1122. printf("No argument given for encryption command; requires either 'on' or 'off'.\n");
  1123. print_usage(argc, argv);
  1124. return -1;
  1125. }
  1126. if (!strcmp(argv[i], "on")) {
  1127. cmd_flags |= CMD_FLAG_ENCRYPTION_ENABLE;
  1128. } else if (!strcmp(argv[i], "off")) {
  1129. cmd_flags |= CMD_FLAG_ENCRYPTION_DISABLE;
  1130. } else {
  1131. printf("Invalid argument '%s' for encryption command; must be either 'on' or 'off'.\n", argv[i]);
  1132. }
  1133. // check if a password was given on the command line
  1134. if (newpw) {
  1135. free(newpw);
  1136. newpw = NULL;
  1137. }
  1138. if (backup_password) {
  1139. free(backup_password);
  1140. backup_password = NULL;
  1141. }
  1142. i++;
  1143. if (argv[i]) {
  1144. if (cmd_flags & CMD_FLAG_ENCRYPTION_ENABLE) {
  1145. newpw = strdup(argv[i]);
  1146. } else if (cmd_flags & CMD_FLAG_ENCRYPTION_DISABLE) {
  1147. backup_password = strdup(argv[i]);
  1148. }
  1149. }
  1150. continue;
  1151. }
  1152. else if (!strcmp(argv[i], "changepw")) {
  1153. cmd = CMD_CHANGEPW;
  1154. cmd_flags |= CMD_FLAG_ENCRYPTION_CHANGEPW;
  1155. // check if passwords were given on command line
  1156. if (newpw) {
  1157. free(newpw);
  1158. newpw = NULL;
  1159. }
  1160. if (backup_password) {
  1161. free(backup_password);
  1162. backup_password = NULL;
  1163. }
  1164. i++;
  1165. if (argv[i]) {
  1166. backup_password = strdup(argv[i]);
  1167. i++;
  1168. if (!argv[i]) {
  1169. printf("Old and new passwords have to be passed as arguments for the changepw command\n");
  1170. print_usage(argc, argv);
  1171. return -1;
  1172. }
  1173. newpw = strdup(argv[i]);
  1174. }
  1175. continue;
  1176. }
  1177. else if (backup_directory == NULL) {
  1178. backup_directory = argv[i];
  1179. }
  1180. else {
  1181. print_usage(argc, argv);
  1182. return -1;
  1183. }
  1184. }
  1185. /* verify options */
  1186. if (cmd == -1) {
  1187. printf("No command specified.\n");
  1188. print_usage(argc, argv);
  1189. return -1;
  1190. }
  1191. if (cmd == CMD_CHANGEPW || cmd == CMD_CLOUD) {
  1192. backup_directory = (char*)".this_folder_is_not_present_on_purpose";
  1193. } else {
  1194. if (backup_directory == NULL) {
  1195. printf("No target backup directory specified.\n");
  1196. print_usage(argc, argv);
  1197. return -1;
  1198. }
  1199. /* verify if passed backup directory exists */
  1200. if (stat(backup_directory, &st) != 0) {
  1201. printf("ERROR: Backup directory \"%s\" does not exist!\n", backup_directory);
  1202. return -1;
  1203. }
  1204. }
  1205. idevice_t device = NULL;
  1206. if (udid) {
  1207. ret = idevice_new(&device, udid);
  1208. if (ret != IDEVICE_E_SUCCESS) {
  1209. printf("No device found with udid %s, is it plugged in?\n", udid);
  1210. return -1;
  1211. }
  1212. }
  1213. else
  1214. {
  1215. ret = idevice_new(&device, NULL);
  1216. if (ret != IDEVICE_E_SUCCESS) {
  1217. printf("No device found, is it plugged in?\n");
  1218. return -1;
  1219. }
  1220. idevice_get_udid(device, &udid);
  1221. }
  1222. if (!source_udid) {
  1223. source_udid = strdup(udid);
  1224. }
  1225. uint8_t is_encrypted = 0;
  1226. char *info_path = NULL;
  1227. if (cmd == CMD_CHANGEPW) {
  1228. if (!interactive_mode && !backup_password && !newpw) {
  1229. idevice_free(device);
  1230. printf("ERROR: Can't get password input in non-interactive mode. Either pass password(s) on the command line, or enable interactive mode with -i or --interactive.\n");
  1231. return -1;
  1232. }
  1233. } else if (cmd != CMD_CLOUD) {
  1234. /* backup directory must contain an Info.plist */
  1235. info_path = string_build_path(backup_directory, source_udid, "Info.plist", NULL);
  1236. if (cmd == CMD_RESTORE || cmd == CMD_UNBACK) {
  1237. if (stat(info_path, &st) != 0) {
  1238. idevice_free(device);
  1239. free(info_path);
  1240. printf("ERROR: Backup directory \"%s\" is invalid. No Info.plist found for UDID %s.\n", backup_directory, source_udid);
  1241. return -1;
  1242. }
  1243. char* manifest_path = string_build_path(backup_directory, source_udid, "Manifest.plist", NULL);
  1244. if (stat(manifest_path, &st) != 0) {
  1245. free(info_path);
  1246. }
  1247. plist_t manifest_plist = NULL;
  1248. plist_read_from_filename(&manifest_plist, manifest_path);
  1249. if (!manifest_plist) {
  1250. idevice_free(device);
  1251. free(info_path);
  1252. free(manifest_path);
  1253. printf("ERROR: Backup directory \"%s\" is invalid. No Manifest.plist found for UDID %s.\n", backup_directory, source_udid);
  1254. return -1;
  1255. }
  1256. node_tmp = plist_dict_get_item(manifest_plist, "IsEncrypted");
  1257. if (node_tmp && (plist_get_node_type(node_tmp) == PLIST_BOOLEAN)) {
  1258. plist_get_bool_val(node_tmp, &is_encrypted);
  1259. }
  1260. plist_free(manifest_plist);
  1261. free(manifest_path);
  1262. }
  1263. PRINT_VERBOSE(1, "Backup directory is \"%s\"\n", backup_directory);
  1264. }
  1265. if (cmd != CMD_CLOUD && is_encrypted) {
  1266. PRINT_VERBOSE(1, "This is an encrypted backup.\n");
  1267. if (backup_password == NULL) {
  1268. if (interactive_mode) {
  1269. backup_password = ask_for_password("Enter backup password", 0);
  1270. }
  1271. if (!backup_password || (strlen(backup_password) == 0)) {
  1272. if (backup_password) {
  1273. free(backup_password);
  1274. }
  1275. idevice_free(device);
  1276. if (cmd == CMD_RESTORE) {
  1277. printf("ERROR: a backup password is required to restore an encrypted backup. Cannot continue.\n");
  1278. } else if (cmd == CMD_UNBACK) {
  1279. printf("ERROR: a backup password is required to unback an encrypted backup. Cannot continue.\n");
  1280. }
  1281. return -1;
  1282. }
  1283. }
  1284. }
  1285. lockdownd_client_t lockdown = NULL;
  1286. if (LOCKDOWN_E_SUCCESS != (ldret = lockdownd_client_new_with_handshake(device, &lockdown, "idevicebackup2"))) {
  1287. printf("ERROR: Could not connect to lockdownd, error code %d\n", ldret);
  1288. idevice_free(device);
  1289. return -1;
  1290. }
  1291. /* start notification_proxy */
  1292. np_client_t np = NULL;
  1293. ldret = lockdownd_start_service(lockdown, NP_SERVICE_NAME, &service);
  1294. if ((ldret == LOCKDOWN_E_SUCCESS) && service && service->port) {
  1295. np_client_new(device, service, &np);
  1296. np_set_notify_callback(np, notify_cb, NULL);
  1297. const char *noties[5] = {
  1298. NP_SYNC_CANCEL_REQUEST,
  1299. NP_SYNC_SUSPEND_REQUEST,
  1300. NP_SYNC_RESUME_REQUEST,
  1301. NP_BACKUP_DOMAIN_CHANGED,
  1302. NULL
  1303. };
  1304. np_observe_notifications(np, noties);
  1305. } else {
  1306. printf("ERROR: Could not start service %s.\n", NP_SERVICE_NAME);
  1307. }
  1308. afc_client_t afc = NULL;
  1309. if (cmd == CMD_BACKUP) {
  1310. /* start AFC, we need this for the lock file */
  1311. service->port = 0;
  1312. service->ssl_enabled = 0;
  1313. ldret = lockdownd_start_service(lockdown, AFC_SERVICE_NAME, &service);
  1314. if ((ldret == LOCKDOWN_E_SUCCESS) && service->port) {
  1315. afc_client_new(device, service, &afc);
  1316. }
  1317. }
  1318. if (service) {
  1319. lockdownd_service_descriptor_free(service);
  1320. service = NULL;
  1321. }
  1322. /* start mobilebackup service and retrieve port */
  1323. mobilebackup2_client_t mobilebackup2 = NULL;
  1324. ldret = lockdownd_start_service_with_escrow_bag(lockdown, MOBILEBACKUP2_SERVICE_NAME, &service);
  1325. if ((ldret == LOCKDOWN_E_SUCCESS) && service && service->port) {
  1326. PRINT_VERBOSE(1, "Started \"%s\" service on port %d.\n", MOBILEBACKUP2_SERVICE_NAME, service->port);
  1327. mobilebackup2_client_new(device, service, &mobilebackup2);
  1328. if (service) {
  1329. lockdownd_service_descriptor_free(service);
  1330. service = NULL;
  1331. }
  1332. /* send Hello message */
  1333. double local_versions[2] = {2.0, 2.1};
  1334. double remote_version = 0.0;
  1335. err = mobilebackup2_version_exchange(mobilebackup2, local_versions, 2, &remote_version);
  1336. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1337. printf("Could not perform backup protocol version exchange, error code %d\n", err);
  1338. cmd = CMD_LEAVE;
  1339. goto checkpoint;
  1340. }
  1341. PRINT_VERBOSE(1, "Negotiated Protocol Version %.1f\n", remote_version);
  1342. /* check abort conditions */
  1343. if (quit_flag > 0) {
  1344. PRINT_VERBOSE(1, "Aborting as requested by user...\n");
  1345. cmd = CMD_LEAVE;
  1346. goto checkpoint;
  1347. }
  1348. /* verify existing Info.plist */
  1349. if (info_path && (stat(info_path, &st) == 0) && cmd != CMD_CLOUD) {
  1350. PRINT_VERBOSE(1, "Reading Info.plist from backup.\n");
  1351. plist_read_from_filename(&info_plist, info_path);
  1352. if (!info_plist) {
  1353. printf("Could not read Info.plist\n");
  1354. is_full_backup = 1;
  1355. }
  1356. } else {
  1357. if (cmd == CMD_RESTORE) {
  1358. printf("Aborting restore. Info.plist is missing.\n");
  1359. cmd = CMD_LEAVE;
  1360. } else {
  1361. is_full_backup = 1;
  1362. }
  1363. }
  1364. uint64_t lockfile = 0;
  1365. if (cmd == CMD_BACKUP) {
  1366. do_post_notification(device, NP_SYNC_WILL_START);
  1367. afc_file_open(afc, "/com.apple.itunes.lock_sync", AFC_FOPEN_RW, &lockfile);
  1368. }
  1369. if (lockfile) {
  1370. afc_error_t aerr;
  1371. do_post_notification(device, NP_SYNC_LOCK_REQUEST);
  1372. for (i = 0; i < LOCK_ATTEMPTS; i++) {
  1373. aerr = afc_file_lock(afc, lockfile, AFC_LOCK_EX);
  1374. if (aerr == AFC_E_SUCCESS) {
  1375. do_post_notification(device, NP_SYNC_DID_START);
  1376. break;
  1377. } else if (aerr == AFC_E_OP_WOULD_BLOCK) {
  1378. usleep(LOCK_WAIT);
  1379. continue;
  1380. } else {
  1381. fprintf(stderr, "ERROR: could not lock file! error code: %d\n", aerr);
  1382. afc_file_close(afc, lockfile);
  1383. lockfile = 0;
  1384. cmd = CMD_LEAVE;
  1385. }
  1386. }
  1387. if (i == LOCK_ATTEMPTS) {
  1388. fprintf(stderr, "ERROR: timeout while locking for sync\n");
  1389. afc_file_close(afc, lockfile);
  1390. lockfile = 0;
  1391. cmd = CMD_LEAVE;
  1392. }
  1393. }
  1394. uint8_t willEncrypt = 0;
  1395. node_tmp = NULL;
  1396. lockdownd_get_value(lockdown, "com.apple.mobile.backup", "WillEncrypt", &node_tmp);
  1397. if (node_tmp) {
  1398. if (plist_get_node_type(node_tmp) == PLIST_BOOLEAN) {
  1399. plist_get_bool_val(node_tmp, &willEncrypt);
  1400. }
  1401. plist_free(node_tmp);
  1402. node_tmp = NULL;
  1403. }
  1404. checkpoint:
  1405. switch(cmd) {
  1406. case CMD_CLOUD:
  1407. opts = plist_new_dict();
  1408. plist_dict_set_item(opts, "CloudBackupState", plist_new_bool(cmd_flags & CMD_FLAG_CLOUD_ENABLE ? 1: 0));
  1409. err = mobilebackup2_send_request(mobilebackup2, "EnableCloudBackup", udid, source_udid, opts);
  1410. plist_free(opts);
  1411. opts = NULL;
  1412. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1413. printf("Error setting cloud backup state on device, error code %d\n", err);
  1414. cmd = CMD_LEAVE;
  1415. }
  1416. break;
  1417. case CMD_BACKUP:
  1418. PRINT_VERBOSE(1, "Starting backup...\n");
  1419. /* make sure backup device sub-directory exists */
  1420. char* devbackupdir = string_build_path(backup_directory, source_udid, NULL);
  1421. __mkdir(devbackupdir, 0755);
  1422. free(devbackupdir);
  1423. if (strcmp(source_udid, udid) != 0) {
  1424. /* handle different source backup directory */
  1425. // make sure target backup device sub-directory exists
  1426. devbackupdir = string_build_path(backup_directory, udid, NULL);
  1427. __mkdir(devbackupdir, 0755);
  1428. free(devbackupdir);
  1429. // use Info.plist path in target backup folder */
  1430. free(info_path);
  1431. info_path = string_build_path(backup_directory, udid, "Info.plist", NULL);
  1432. }
  1433. /* TODO: check domain com.apple.mobile.backup key RequiresEncrypt and WillEncrypt with lockdown */
  1434. /* TODO: verify battery on AC enough battery remaining */
  1435. /* re-create Info.plist (Device infos, IC-Info.sidb, photos, app_ids, iTunesPrefs) */
  1436. if (info_plist) {
  1437. plist_free(info_plist);
  1438. info_plist = NULL;
  1439. }
  1440. info_plist = mobilebackup_factory_info_plist_new(udid, lockdown, afc);
  1441. remove(info_path);
  1442. plist_write_to_filename(info_plist, info_path, PLIST_FORMAT_XML);
  1443. free(info_path);
  1444. plist_free(info_plist);
  1445. info_plist = NULL;
  1446. if (cmd_flags & CMD_FLAG_FORCE_FULL_BACKUP) {
  1447. PRINT_VERBOSE(1, "Enforcing full backup from device.\n");
  1448. opts = plist_new_dict();
  1449. plist_dict_set_item(opts, "ForceFullBackup", plist_new_bool(1));
  1450. }
  1451. /* request backup from device with manifest from last backup */
  1452. if (willEncrypt) {
  1453. PRINT_VERBOSE(1, "Backup will be encrypted.\n");
  1454. } else {
  1455. PRINT_VERBOSE(1, "Backup will be unencrypted.\n");
  1456. }
  1457. PRINT_VERBOSE(1, "Requesting backup from device...\n");
  1458. err = mobilebackup2_send_request(mobilebackup2, "Backup", udid, source_udid, opts);
  1459. if (opts)
  1460. plist_free(opts);
  1461. if (err == MOBILEBACKUP2_E_SUCCESS) {
  1462. if (is_full_backup) {
  1463. PRINT_VERBOSE(1, "Full backup mode.\n");
  1464. } else {
  1465. PRINT_VERBOSE(1, "Incremental backup mode.\n");
  1466. }
  1467. } else {
  1468. if (err == MOBILEBACKUP2_E_BAD_VERSION) {
  1469. printf("ERROR: Could not start backup process: backup protocol version mismatch!\n");
  1470. } else if (err == MOBILEBACKUP2_E_REPLY_NOT_OK) {
  1471. printf("ERROR: Could not start backup process: device refused to start the backup process.\n");
  1472. } else {
  1473. printf("ERROR: Could not start backup process: unspecified error occured\n");
  1474. }
  1475. cmd = CMD_LEAVE;
  1476. }
  1477. break;
  1478. case CMD_RESTORE:
  1479. /* TODO: verify battery on AC enough battery remaining */
  1480. /* verify if Status.plist says we read from an successful backup */
  1481. if (!mb2_status_check_snapshot_state(backup_directory, source_udid, "finished")) {
  1482. printf("ERROR: Cannot ensure we restore from a successful backup. Aborting.\n");
  1483. cmd = CMD_LEAVE;
  1484. break;
  1485. }
  1486. PRINT_VERBOSE(1, "Starting Restore...\n");
  1487. opts = plist_new_dict();
  1488. plist_dict_set_item(opts, "RestoreSystemFiles", plist_new_bool(cmd_flags & CMD_FLAG_RESTORE_SYSTEM_FILES));
  1489. PRINT_VERBOSE(1, "Restoring system files: %s\n", (cmd_flags & CMD_FLAG_RESTORE_SYSTEM_FILES ? "Yes":"No"));
  1490. if ((cmd_flags & CMD_FLAG_RESTORE_REBOOT) == 0)
  1491. plist_dict_set_item(opts, "RestoreShouldReboot", plist_new_bool(0));
  1492. PRINT_VERBOSE(1, "Rebooting after restore: %s\n", (cmd_flags & CMD_FLAG_RESTORE_REBOOT ? "Yes":"No"));
  1493. if ((cmd_flags & CMD_FLAG_RESTORE_COPY_BACKUP) == 0)
  1494. plist_dict_set_item(opts, "RestoreDontCopyBackup", plist_new_bool(1));
  1495. PRINT_VERBOSE(1, "Don't copy backup: %s\n", ((cmd_flags & CMD_FLAG_RESTORE_COPY_BACKUP) == 0 ? "Yes":"No"));
  1496. plist_dict_set_item(opts, "RestorePreserveSettings", plist_new_bool((cmd_flags & CMD_FLAG_RESTORE_SETTINGS) == 0));
  1497. PRINT_VERBOSE(1, "Preserve settings of device: %s\n", ((cmd_flags & CMD_FLAG_RESTORE_SETTINGS) == 0 ? "Yes":"No"));
  1498. if (cmd_flags & CMD_FLAG_RESTORE_REMOVE_ITEMS)
  1499. plist_dict_set_item(opts, "RemoveItemsNotRestored", plist_new_bool(1));
  1500. PRINT_VERBOSE(1, "Remove items that are not restored: %s\n", ((cmd_flags & CMD_FLAG_RESTORE_REMOVE_ITEMS) ? "Yes":"No"));
  1501. if (backup_password != NULL) {
  1502. plist_dict_set_item(opts, "Password", plist_new_string(backup_password));
  1503. }
  1504. PRINT_VERBOSE(1, "Backup password: %s\n", (backup_password == NULL ? "No":"Yes"));
  1505. err = mobilebackup2_send_request(mobilebackup2, "Restore", udid, source_udid, opts);
  1506. plist_free(opts);
  1507. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1508. if (err == MOBILEBACKUP2_E_BAD_VERSION) {
  1509. printf("ERROR: Could not start restore process: backup protocol version mismatch!\n");
  1510. } else if (err == MOBILEBACKUP2_E_REPLY_NOT_OK) {
  1511. printf("ERROR: Could not start restore process: device refused to start the restore process.\n");
  1512. } else {
  1513. printf("ERROR: Could not start restore process: unspecified error occured\n");
  1514. }
  1515. cmd = CMD_LEAVE;
  1516. }
  1517. break;
  1518. case CMD_INFO:
  1519. PRINT_VERBOSE(1, "Requesting backup info from device...\n");
  1520. err = mobilebackup2_send_request(mobilebackup2, "Info", udid, source_udid, NULL);
  1521. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1522. printf("Error requesting backup info from device, error code %d\n", err);
  1523. cmd = CMD_LEAVE;
  1524. }
  1525. break;
  1526. case CMD_LIST:
  1527. PRINT_VERBOSE(1, "Requesting backup list from device...\n");
  1528. err = mobilebackup2_send_request(mobilebackup2, "List", udid, source_udid, NULL);
  1529. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1530. printf("Error requesting backup list from device, error code %d\n", err);
  1531. cmd = CMD_LEAVE;
  1532. }
  1533. break;
  1534. case CMD_UNBACK:
  1535. PRINT_VERBOSE(1, "Starting to unpack backup...\n");
  1536. if (backup_password != NULL) {
  1537. opts = plist_new_dict();
  1538. plist_dict_set_item(opts, "Password", plist_new_string(backup_password));
  1539. }
  1540. PRINT_VERBOSE(1, "Backup password: %s\n", (backup_password == NULL ? "No":"Yes"));
  1541. err = mobilebackup2_send_request(mobilebackup2, "Unback", udid, source_udid, opts);
  1542. if (backup_password !=NULL) {
  1543. plist_free(opts);
  1544. }
  1545. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1546. printf("Error requesting unback operation from device, error code %d\n", err);
  1547. cmd = CMD_LEAVE;
  1548. }
  1549. break;
  1550. case CMD_CHANGEPW:
  1551. opts = plist_new_dict();
  1552. plist_dict_set_item(opts, "TargetIdentifier", plist_new_string(udid));
  1553. if (cmd_flags & CMD_FLAG_ENCRYPTION_ENABLE) {
  1554. if (!willEncrypt) {
  1555. if (!newpw) {
  1556. newpw = ask_for_password("Enter new backup password", 1);
  1557. }
  1558. if (!newpw) {
  1559. printf("No backup password given. Aborting.\n");
  1560. }
  1561. } else {
  1562. printf("ERROR: Backup encryption is already enabled. Aborting.\n");
  1563. cmd = CMD_LEAVE;
  1564. if (newpw) {
  1565. free(newpw);
  1566. newpw = NULL;
  1567. }
  1568. }
  1569. } else if (cmd_flags & CMD_FLAG_ENCRYPTION_DISABLE) {
  1570. if (willEncrypt) {
  1571. if (!backup_password) {
  1572. backup_password = ask_for_password("Enter current backup password", 0);
  1573. }
  1574. } else {
  1575. printf("ERROR: Backup encryption is not enabled. Aborting.\n");
  1576. cmd = CMD_LEAVE;
  1577. if (backup_password) {
  1578. free(backup_password);
  1579. backup_password = NULL;
  1580. }
  1581. }
  1582. } else if (cmd_flags & CMD_FLAG_ENCRYPTION_CHANGEPW) {
  1583. if (willEncrypt) {
  1584. if (!backup_password) {
  1585. backup_password = ask_for_password("Enter old backup password", 0);
  1586. newpw = ask_for_password("Enter new backup password", 1);
  1587. }
  1588. } else {
  1589. printf("ERROR: Backup encryption is not enabled so can't change password. Aborting.\n");
  1590. cmd = CMD_LEAVE;
  1591. if (newpw) {
  1592. free(newpw);
  1593. newpw = NULL;
  1594. }
  1595. if (backup_password) {
  1596. free(backup_password);
  1597. backup_password = NULL;
  1598. }
  1599. }
  1600. }
  1601. if (newpw) {
  1602. plist_dict_set_item(opts, "NewPassword", plist_new_string(newpw));
  1603. }
  1604. if (backup_password) {
  1605. plist_dict_set_item(opts, "OldPassword", plist_new_string(backup_password));
  1606. }
  1607. if (newpw || backup_password) {
  1608. mobilebackup2_send_message(mobilebackup2, "ChangePassword", opts);
  1609. /*if (cmd_flags & CMD_FLAG_ENCRYPTION_ENABLE) {
  1610. int retr = 10;
  1611. while ((retr-- >= 0) && !backup_domain_changed) {
  1612. sleep(1);
  1613. }
  1614. }*/
  1615. } else {
  1616. cmd = CMD_LEAVE;
  1617. }
  1618. plist_free(opts);
  1619. break;
  1620. default:
  1621. break;
  1622. }
  1623. /* close down the lockdown connection as it is no longer needed */
  1624. if (lockdown) {
  1625. lockdownd_client_free(lockdown);
  1626. lockdown = NULL;
  1627. }
  1628. if (cmd != CMD_LEAVE) {
  1629. /* reset operation success status */
  1630. int operation_ok = 0;
  1631. plist_t message = NULL;
  1632. char *dlmsg = NULL;
  1633. int file_count = 0;
  1634. int errcode = 0;
  1635. const char *errdesc = NULL;
  1636. /* process series of DLMessage* operations */
  1637. do {
  1638. if (dlmsg) {
  1639. free(dlmsg);
  1640. dlmsg = NULL;
  1641. }
  1642. mobilebackup2_receive_message(mobilebackup2, &message, &dlmsg);
  1643. if (!message || !dlmsg) {
  1644. PRINT_VERBOSE(1, "Device is not ready yet. Going to try again in 2 seconds...\n");
  1645. sleep(2);
  1646. goto files_out;
  1647. }
  1648. if (!strcmp(dlmsg, "DLMessageDownloadFiles")) {
  1649. /* device wants to download files from the computer */
  1650. mb2_set_overall_progress_from_message(message, dlmsg);
  1651. mb2_handle_send_files(mobilebackup2, message, backup_directory);
  1652. } else if (!strcmp(dlmsg, "DLMessageUploadFiles")) {
  1653. /* device wants to send files to the computer */
  1654. mb2_set_overall_progress_from_message(message, dlmsg);
  1655. file_count += mb2_handle_receive_files(mobilebackup2, message, backup_directory);
  1656. } else if (!strcmp(dlmsg, "DLMessageGetFreeDiskSpace")) {
  1657. /* device wants to know how much disk space is available on the computer */
  1658. uint64_t freespace = 0;
  1659. int res = -1;
  1660. #ifdef WIN32
  1661. if (GetDiskFreeSpaceEx(backup_directory, (PULARGE_INTEGER)&freespace, NULL, NULL)) {
  1662. res = 0;
  1663. }
  1664. #else
  1665. struct statvfs fs;
  1666. memset(&fs, '\0', sizeof(fs));
  1667. res = statvfs(backup_directory, &fs);
  1668. if (res == 0) {
  1669. freespace = (uint64_t)fs.f_bavail * (uint64_t)fs.f_bsize;
  1670. }
  1671. #endif
  1672. plist_t freespace_item = plist_new_uint(freespace);
  1673. mobilebackup2_send_status_response(mobilebackup2, res, NULL, freespace_item);
  1674. plist_free(freespace_item);
  1675. } else if (!strcmp(dlmsg, "DLContentsOfDirectory")) {
  1676. /* list directory contents */
  1677. mb2_handle_list_directory(mobilebackup2, message, backup_directory);
  1678. } else if (!strcmp(dlmsg, "DLMessageCreateDirectory")) {
  1679. /* make a directory */
  1680. mb2_handle_make_directory(mobilebackup2, message, backup_directory);
  1681. } else if (!strcmp(dlmsg, "DLMessageMoveFiles") || !strcmp(dlmsg, "DLMessageMoveItems")) {
  1682. /* perform a series of rename operations */
  1683. mb2_set_overall_progress_from_message(message, dlmsg);
  1684. plist_t moves = plist_array_get_item(message, 1);
  1685. uint32_t cnt = plist_dict_get_size(moves);
  1686. PRINT_VERBOSE(1, "Moving %d file%s\n", cnt, (cnt == 1) ? "" : "s");
  1687. plist_dict_iter iter = NULL;
  1688. plist_dict_new_iter(moves, &iter);
  1689. errcode = 0;
  1690. errdesc = NULL;
  1691. if (iter) {
  1692. char *key = NULL;
  1693. plist_t val = NULL;
  1694. do {
  1695. plist_dict_next_item(moves, iter, &key, &val);
  1696. if (key && (plist_get_node_type(val) == PLIST_STRING)) {
  1697. char *str = NULL;
  1698. plist_get_string_val(val, &str);
  1699. if (str) {
  1700. char *newpath = string_build_path(backup_directory, str, NULL);
  1701. free(str);
  1702. char *oldpath = string_build_path(backup_directory, key, NULL);
  1703. #ifdef WIN32
  1704. if ((stat(newpath, &st) == 0) && S_ISDIR(st.st_mode))
  1705. RemoveDirectory(newpath);
  1706. else
  1707. DeleteFile(newpath);
  1708. #else
  1709. remove(newpath);
  1710. #endif
  1711. if (rename(oldpath, newpath) < 0) {
  1712. printf("Renameing '%s' to '%s' failed: %s (%d)\n", oldpath, newpath, strerror(errno), errno);
  1713. errcode = errno_to_device_error(errno);
  1714. errdesc = strerror(errno);
  1715. break;
  1716. }
  1717. free(oldpath);
  1718. free(newpath);
  1719. }
  1720. free(key);
  1721. key = NULL;
  1722. }
  1723. } while (val);
  1724. free(iter);
  1725. } else {
  1726. errcode = -1;
  1727. errdesc = "Could not create dict iterator";
  1728. printf("Could not create dict iterator\n");
  1729. }
  1730. plist_t empty_dict = plist_new_dict();
  1731. err = mobilebackup2_send_status_response(mobilebackup2, errcode, errdesc, empty_dict);
  1732. plist_free(empty_dict);
  1733. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1734. printf("Could not send status response, error %d\n", err);
  1735. }
  1736. } else if (!strcmp(dlmsg, "DLMessageRemoveFiles") || !strcmp(dlmsg, "DLMessageRemoveItems")) {
  1737. mb2_set_overall_progress_from_message(message, dlmsg);
  1738. plist_t removes = plist_array_get_item(message, 1);
  1739. uint32_t cnt = plist_array_get_size(removes);
  1740. PRINT_VERBOSE(1, "Removing %d file%s\n", cnt, (cnt == 1) ? "" : "s");
  1741. uint32_t ii = 0;
  1742. errcode = 0;
  1743. errdesc = NULL;
  1744. for (ii = 0; ii < cnt; ii++) {
  1745. plist_t val = plist_array_get_item(removes, ii);
  1746. if (plist_get_node_type(val) == PLIST_STRING) {
  1747. char *str = NULL;
  1748. plist_get_string_val(val, &str);
  1749. if (str) {
  1750. const char *checkfile = strchr(str, '/');
  1751. int suppress_warning = 0;
  1752. if (checkfile) {
  1753. if (strcmp(checkfile+1, "Manifest.mbdx") == 0) {
  1754. suppress_warning = 1;
  1755. }
  1756. }
  1757. char *newpath = string_build_path(backup_directory, str, NULL);
  1758. free(str);
  1759. #ifdef WIN32
  1760. int res = 0;
  1761. if ((stat(newpath, &st) == 0) && S_ISDIR(st.st_mode))
  1762. res = RemoveDirectory(newpath);
  1763. else
  1764. res = DeleteFile(newpath);
  1765. if (!res) {
  1766. int e = win32err_to_errno(GetLastError());
  1767. if (!suppress_warning)
  1768. printf("Could not remove '%s': %s (%d)\n", newpath, strerror(e), e);
  1769. errcode = errno_to_device_error(e);
  1770. errdesc = strerror(e);
  1771. }
  1772. #else
  1773. if (remove(newpath) < 0) {
  1774. if (!suppress_warning)
  1775. printf("Could not remove '%s': %s (%d)\n", newpath, strerror(errno), errno);
  1776. errcode = errno_to_device_error(errno);
  1777. errdesc = strerror(errno);
  1778. }
  1779. #endif
  1780. free(newpath);
  1781. }
  1782. }
  1783. }
  1784. plist_t empty_dict = plist_new_dict();
  1785. err = mobilebackup2_send_status_response(mobilebackup2, errcode, errdesc, empty_dict);
  1786. plist_free(empty_dict);
  1787. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1788. printf("Could not send status response, error %d\n", err);
  1789. }
  1790. } else if (!strcmp(dlmsg, "DLMessageCopyItem")) {
  1791. plist_t srcpath = plist_array_get_item(message, 1);
  1792. plist_t dstpath = plist_array_get_item(message, 2);
  1793. errcode = 0;
  1794. errdesc = NULL;
  1795. if ((plist_get_node_type(srcpath) == PLIST_STRING) && (plist_get_node_type(dstpath) == PLIST_STRING)) {
  1796. char *src = NULL;
  1797. char *dst = NULL;
  1798. plist_get_string_val(srcpath, &src);
  1799. plist_get_string_val(dstpath, &dst);
  1800. if (src && dst) {
  1801. char *oldpath = string_build_path(backup_directory, src, NULL);
  1802. char *newpath = string_build_path(backup_directory, dst, NULL);
  1803. PRINT_VERBOSE(1, "Copying '%s' to '%s'\n", src, dst);
  1804. /* check that src exists */
  1805. if ((stat(oldpath, &st) == 0) && S_ISDIR(st.st_mode)) {
  1806. mb2_copy_directory_by_path(oldpath, newpath);
  1807. } else if ((stat(oldpath, &st) == 0) && S_ISREG(st.st_mode)) {
  1808. mb2_copy_file_by_path(oldpath, newpath);
  1809. }
  1810. free(newpath);
  1811. free(oldpath);
  1812. }
  1813. free(src);
  1814. free(dst);
  1815. }
  1816. plist_t empty_dict = plist_new_dict();
  1817. err = mobilebackup2_send_status_response(mobilebackup2, errcode, errdesc, empty_dict);
  1818. plist_free(empty_dict);
  1819. if (err != MOBILEBACKUP2_E_SUCCESS) {
  1820. printf("Could not send status response, error %d\n", err);
  1821. }
  1822. } else if (!strcmp(dlmsg, "DLMessageDisconnect")) {
  1823. break;
  1824. } else if (!strcmp(dlmsg, "DLMessageProcessMessage")) {
  1825. node_tmp = plist_array_get_item(message, 1);
  1826. if (plist_get_node_type(node_tmp) != PLIST_DICT) {
  1827. printf("Unknown message received!\n");
  1828. }
  1829. plist_t nn;
  1830. int error_code = -1;
  1831. nn = plist_dict_get_item(node_tmp, "ErrorCode");
  1832. if (nn && (plist_get_node_type(nn) == PLIST_UINT)) {
  1833. uint64_t ec = 0;
  1834. plist_get_uint_val(nn, &ec);
  1835. error_code = (uint32_t)ec;
  1836. if (error_code == 0) {
  1837. operation_ok = 1;
  1838. result_code = 0;
  1839. } else {
  1840. result_code = -error_code;
  1841. }
  1842. }
  1843. nn = plist_dict_get_item(node_tmp, "ErrorDescription");
  1844. char *str = NULL;
  1845. if (nn && (plist_get_node_type(nn) == PLIST_STRING)) {
  1846. plist_get_string_val(nn, &str);
  1847. }
  1848. if (error_code != 0) {
  1849. if (str) {
  1850. printf("ErrorCode %d: %s\n", error_code, str);
  1851. } else {
  1852. printf("ErrorCode %d: (Unknown)\n", error_code);
  1853. }
  1854. }
  1855. if (str) {
  1856. free(str);
  1857. }
  1858. nn = plist_dict_get_item(node_tmp, "Content");
  1859. if (nn && (plist_get_node_type(nn) == PLIST_STRING)) {
  1860. str = NULL;
  1861. plist_get_string_val(nn, &str);
  1862. PRINT_VERBOSE(1, "Content:\n");
  1863. printf("%s", str);
  1864. free(str);
  1865. }
  1866. break;
  1867. }
  1868. /* print status */
  1869. if (overall_progress > 0) {
  1870. print_progress_real(overall_progress, 0);
  1871. PRINT_VERBOSE(1, " Finished\n");
  1872. }
  1873. files_out:
  1874. if (message)
  1875. plist_free(message);
  1876. message = NULL;
  1877. if (dlmsg)
  1878. free(dlmsg);
  1879. dlmsg = NULL;
  1880. if (quit_flag > 0) {
  1881. /* need to cancel the backup here */
  1882. //mobilebackup_send_error(mobilebackup, "Cancelling DLSendFile");
  1883. /* remove any atomic Manifest.plist.tmp */
  1884. /*manifest_path = mobilebackup_build_path(backup_directory, "Manifest", ".plist.tmp");
  1885. if (stat(manifest_path, &st) == 0)
  1886. remove(manifest_path);*/
  1887. break;
  1888. }
  1889. } while (1);
  1890. /* report operation status to user */
  1891. switch (cmd) {
  1892. case CMD_CLOUD:
  1893. if (cmd_flags & CMD_FLAG_CLOUD_ENABLE) {
  1894. if (operation_ok) {
  1895. PRINT_VERBOSE(1, "Cloud backup has been enabled successfully.\n");
  1896. } else {
  1897. PRINT_VERBOSE(1, "Could not enable cloud backup.\n");
  1898. }
  1899. } else if (cmd_flags & CMD_FLAG_CLOUD_DISABLE) {
  1900. if (operation_ok) {
  1901. PRINT_VERBOSE(1, "Cloud backup has been disabled successfully.\n");
  1902. } else {
  1903. PRINT_VERBOSE(1, "Could not disable cloud backup.\n");
  1904. }
  1905. }
  1906. break;
  1907. case CMD_BACKUP:
  1908. PRINT_VERBOSE(1, "Received %d files from device.\n", file_count);
  1909. if (operation_ok && mb2_status_check_snapshot_state(backup_directory, udid, "finished")) {
  1910. PRINT_VERBOSE(1, "Backup Successful.\n");
  1911. } else {
  1912. if (quit_flag) {
  1913. PRINT_VERBOSE(1, "Backup Aborted.\n");
  1914. } else {
  1915. PRINT_VERBOSE(1, "Backup Failed (Error Code %d).\n", -result_code);
  1916. }
  1917. }
  1918. break;
  1919. case CMD_UNBACK:
  1920. if (quit_flag) {
  1921. PRINT_VERBOSE(1, "Unback Aborted.\n");
  1922. } else {
  1923. PRINT_VERBOSE(1, "The files can now be found in the \"_unback_\" directory.\n");
  1924. PRINT_VERBOSE(1, "Unback Successful.\n");
  1925. }
  1926. break;
  1927. case CMD_CHANGEPW:
  1928. if (cmd_flags & CMD_FLAG_ENCRYPTION_ENABLE) {
  1929. if (operation_ok) {
  1930. PRINT_VERBOSE(1, "Backup encryption has been enabled successfully.\n");
  1931. } else {
  1932. PRINT_VERBOSE(1, "Could not enable backup encryption.\n");
  1933. }
  1934. } else if (cmd_flags & CMD_FLAG_ENCRYPTION_DISABLE) {
  1935. if (operation_ok) {
  1936. PRINT_VERBOSE(1, "Backup encryption has been disabled successfully.\n");
  1937. } else {
  1938. PRINT_VERBOSE(1, "Could not disable backup encryption.\n");
  1939. }
  1940. } else if (cmd_flags & CMD_FLAG_ENCRYPTION_CHANGEPW) {
  1941. if (operation_ok) {
  1942. PRINT_VERBOSE(1, "Backup encryption password has been changed successfully.\n");
  1943. } else {
  1944. PRINT_VERBOSE(1, "Could not change backup encryption password.\n");
  1945. }
  1946. }
  1947. break;
  1948. case CMD_RESTORE:
  1949. if (cmd_flags & CMD_FLAG_RESTORE_REBOOT)
  1950. PRINT_VERBOSE(1, "The device should reboot now.\n");
  1951. if (operation_ok) {
  1952. PRINT_VERBOSE(1, "Restore Successful.\n");
  1953. } else {
  1954. PRINT_VERBOSE(1, "Restore Failed (Error Code %d).\n", -result_code);
  1955. }
  1956. break;
  1957. case CMD_INFO:
  1958. case CMD_LIST:
  1959. case CMD_LEAVE:
  1960. default:
  1961. if (quit_flag) {
  1962. PRINT_VERBOSE(1, "Operation Aborted.\n");
  1963. } else if (cmd == CMD_LEAVE) {
  1964. PRINT_VERBOSE(1, "Operation Failed.\n");
  1965. } else {
  1966. PRINT_VERBOSE(1, "Operation Successful.\n");
  1967. }
  1968. break;
  1969. }
  1970. }
  1971. if (lockfile) {
  1972. afc_file_lock(afc, lockfile, AFC_LOCK_UN);
  1973. afc_file_close(afc, lockfile);
  1974. lockfile = 0;
  1975. if (cmd == CMD_BACKUP)
  1976. do_post_notification(device, NP_SYNC_DID_FINISH);
  1977. }
  1978. } else {
  1979. printf("ERROR: Could not start service %s.\n", MOBILEBACKUP2_SERVICE_NAME);
  1980. lockdownd_client_free(lockdown);
  1981. lockdown = NULL;
  1982. }
  1983. if (lockdown) {
  1984. lockdownd_client_free(lockdown);
  1985. lockdown = NULL;
  1986. }
  1987. if (mobilebackup2) {
  1988. mobilebackup2_client_free(mobilebackup2);
  1989. mobilebackup2 = NULL;
  1990. }
  1991. if (afc) {
  1992. afc_client_free(afc);
  1993. afc = NULL;
  1994. }
  1995. if (np) {
  1996. np_client_free(np);
  1997. np = NULL;
  1998. }
  1999. idevice_free(device);
  2000. device = NULL;
  2001. if (backup_password) {
  2002. free(backup_password);
  2003. }
  2004. if (udid) {
  2005. free(udid);
  2006. udid = NULL;
  2007. }
  2008. if (source_udid) {
  2009. free(source_udid);
  2010. source_udid = NULL;
  2011. }
  2012. return result_code;
  2013. }