blob: 963c724ba5d3d986f796d28238d719958c281752 [file] [log] [blame]
preludedrew38058dc2011-01-29 23:30:44 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 * Copyright (c) 2010, Code Aurora Forum. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#include <ctype.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
22#include <limits.h>
23#include <linux/input.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/reboot.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <time.h>
31#include <unistd.h>
32#include <dirent.h>
33#include <sys/stat.h>
34
35#include "bootloader.h"
36#include "common.h"
37#include "cutils/properties.h"
38#include "install.h"
39#include "minui/minui.h"
40#include "minzip/DirUtil.h"
41#include "roots.h"
42#include "recovery_ui.h"
43#include "encryptedfs_provisioning.h"
44
45#include "extendedcommands.h"
46#include "flashutils/flashutils.h"
47
48static const struct option OPTIONS[] = {
49 { "send_intent", required_argument, NULL, 's' },
50 { "update_package", required_argument, NULL, 'u' },
51 { "wipe_data", no_argument, NULL, 'w' },
52 { "wipe_cache", no_argument, NULL, 'c' },
53 { "set_encrypted_filesystems", required_argument, NULL, 'e' },
54 { "show_text", no_argument, NULL, 't' },
55 { NULL, 0, NULL, 0 },
56};
57
58static const char *COMMAND_FILE = "/cache/recovery/command";
59static const char *INTENT_FILE = "/cache/recovery/intent";
60static const char *LOG_FILE = "/cache/recovery/log";
61static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
62static const char *SDCARD_ROOT = "/sdcard";
63static int allow_display_toggle = 1;
andrew.boren1acd15e2011-03-31 21:41:22 -070064static int poweroff = 0;
preludedrew38058dc2011-01-29 23:30:44 -070065static const char *SDCARD_PACKAGE_FILE = "/sdcard/update.zip";
66static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
67static const char *SIDELOAD_TEMP_DIR = "/tmp/sideload";
68
69/*
70 * The recovery tool communicates with the main system through /cache files.
71 * /cache/recovery/command - INPUT - command line for tool, one arg per line
72 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
73 * /cache/recovery/intent - OUTPUT - intent that was passed in
74 *
75 * The arguments which may be supplied in the recovery.command file:
76 * --send_intent=anystring - write the text out to recovery.intent
77 * --update_package=path - verify install an OTA package file
78 * --wipe_data - erase user data (and cache), then reboot
79 * --wipe_cache - wipe cache (but not user data), then reboot
80 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
81 *
82 * After completing, we remove /cache/recovery/command and reboot.
83 * Arguments may also be supplied in the bootloader control block (BCB).
84 * These important scenarios must be safely restartable at any point:
85 *
86 * FACTORY RESET
87 * 1. user selects "factory reset"
88 * 2. main system writes "--wipe_data" to /cache/recovery/command
89 * 3. main system reboots into recovery
90 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
91 * -- after this, rebooting will restart the erase --
92 * 5. erase_volume() reformats /data
93 * 6. erase_volume() reformats /cache
94 * 7. finish_recovery() erases BCB
95 * -- after this, rebooting will restart the main system --
96 * 8. main() calls reboot() to boot main system
97 *
98 * OTA INSTALL
99 * 1. main system downloads OTA package to /cache/some-filename.zip
100 * 2. main system writes "--update_package=/cache/some-filename.zip"
101 * 3. main system reboots into recovery
102 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
103 * -- after this, rebooting will attempt to reinstall the update --
104 * 5. install_package() attempts to install the update
105 * NOTE: the package install must itself be restartable from any point
106 * 6. finish_recovery() erases BCB
107 * -- after this, rebooting will (try to) restart the main system --
108 * 7. ** if install failed **
109 * 7a. prompt_and_wait() shows an error icon and waits for the user
110 * 7b; the user reboots (pulling the battery, etc) into the main system
111 * 8. main() calls maybe_install_firmware_update()
112 * ** if the update contained radio/hboot firmware **:
113 * 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
114 * -- after this, rebooting will reformat cache & restart main system --
115 * 8b. m_i_f_u() writes firmware image into raw cache partition
116 * 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
117 * -- after this, rebooting will attempt to reinstall firmware --
118 * 8d. bootloader tries to flash firmware
119 * 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
120 * -- after this, rebooting will reformat cache & restart main system --
121 * 8f. erase_volume() reformats /cache
122 * 8g. finish_recovery() erases BCB
123 * -- after this, rebooting will (try to) restart the main system --
124 * 9. main() calls reboot() to boot main system
125 *
126 * SECURE FILE SYSTEMS ENABLE/DISABLE
127 * 1. user selects "enable encrypted file systems"
128 * 2. main system writes "--set_encrypted_filesystems=on|off" to
129 * /cache/recovery/command
130 * 3. main system reboots into recovery
131 * 4. get_args() writes BCB with "boot-recovery" and
132 * "--set_encrypted_filesystems=on|off"
133 * -- after this, rebooting will restart the transition --
134 * 5. read_encrypted_fs_info() retrieves encrypted file systems settings from /data
135 * Settings include: property to specify the Encrypted FS istatus and
136 * FS encryption key if enabled (not yet implemented)
137 * 6. erase_volume() reformats /data
138 * 7. erase_volume() reformats /cache
139 * 8. restore_encrypted_fs_info() writes required encrypted file systems settings to /data
140 * Settings include: property to specify the Encrypted FS status and
141 * FS encryption key if enabled (not yet implemented)
142 * 9. finish_recovery() erases BCB
143 * -- after this, rebooting will restart the main system --
144 * 10. main() calls reboot() to boot main system
145 */
146
147static const int MAX_ARG_LENGTH = 4096;
148static const int MAX_ARGS = 100;
149
150// open a given path, mounting partitions as necessary
151static FILE*
152fopen_path(const char *path, const char *mode) {
153 if (ensure_path_mounted(path) != 0) {
154 LOGE("Can't mount %s\n", path);
155 return NULL;
156 }
157
158 // When writing, try to create the containing directory, if necessary.
159 // Use generous permissions, the system (init.rc) will reset them.
160 if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1);
161
162 FILE *fp = fopen(path, mode);
163 if (fp == NULL && path != COMMAND_FILE) LOGE("Can't open %s\n", path);
164 return fp;
165}
166
167// close a file, log an error if the error indicator is set
168static void
169check_and_fclose(FILE *fp, const char *name) {
170 fflush(fp);
171 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
172 fclose(fp);
173}
174
175// command line args come from, in decreasing precedence:
176// - the actual command line
177// - the bootloader control block (one per line, after "recovery")
178// - the contents of COMMAND_FILE (one per line)
179static void
180get_args(int *argc, char ***argv) {
181 struct bootloader_message boot;
182 memset(&boot, 0, sizeof(boot));
183 if (device_flash_type() == MTD) {
184 get_bootloader_message(&boot); // this may fail, leaving a zeroed structure
185 }
186
187 if (boot.command[0] != 0 && boot.command[0] != 255) {
188 LOGI("Boot command: %.*s\n", sizeof(boot.command), boot.command);
189 }
190
191 if (boot.status[0] != 0 && boot.status[0] != 255) {
192 LOGI("Boot status: %.*s\n", sizeof(boot.status), boot.status);
193 }
194
195 struct stat file_info;
196
197 // --- if arguments weren't supplied, look in the bootloader control block
198 if (*argc <= 1 && 0 != stat("/tmp/.ignorebootmessage", &file_info)) {
199 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
200 const char *arg = strtok(boot.recovery, "\n");
201 if (arg != NULL && !strcmp(arg, "recovery")) {
202 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
203 (*argv)[0] = strdup(arg);
204 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
205 if ((arg = strtok(NULL, "\n")) == NULL) break;
206 (*argv)[*argc] = strdup(arg);
207 }
208 LOGI("Got arguments from boot message\n");
209 } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
210 LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
211 }
212 }
213
214 // --- if that doesn't work, try the command file
215 if (*argc <= 1) {
216 FILE *fp = fopen_path(COMMAND_FILE, "r");
217 if (fp != NULL) {
218 char *argv0 = (*argv)[0];
219 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
220 (*argv)[0] = argv0; // use the same program name
221
222 char buf[MAX_ARG_LENGTH];
223 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
224 if (!fgets(buf, sizeof(buf), fp)) break;
225 (*argv)[*argc] = strdup(strtok(buf, "\r\n")); // Strip newline.
226 }
227
228 check_and_fclose(fp, COMMAND_FILE);
229 LOGI("Got arguments from %s\n", COMMAND_FILE);
230 }
231 }
232
233 // --> write the arguments we have back into the bootloader control block
234 // always boot into recovery after this (until finish_recovery() is called)
235 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
236 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
237 int i;
238 for (i = 1; i < *argc; ++i) {
239 strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
240 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
241 }
242 if (device_flash_type() == MTD) {
243 set_bootloader_message(&boot);
244 }
245}
246
247void
248set_sdcard_update_bootloader_message() {
249 struct bootloader_message boot;
250 memset(&boot, 0, sizeof(boot));
251 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
252 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
253 set_bootloader_message(&boot);
254}
255
256// How much of the temp log we have copied to the copy in cache.
257static long tmplog_offset = 0;
258
259static void
260copy_log_file(const char* destination, int append) {
261 FILE *log = fopen_path(destination, append ? "a" : "w");
262 if (log == NULL) {
263 LOGE("Can't open %s\n", destination);
264 } else {
265 FILE *tmplog = fopen(TEMPORARY_LOG_FILE, "r");
266 if (tmplog == NULL) {
267 LOGE("Can't open %s\n", TEMPORARY_LOG_FILE);
268 } else {
269 if (append) {
270 fseek(tmplog, tmplog_offset, SEEK_SET); // Since last write
271 }
272 char buf[4096];
273 while (fgets(buf, sizeof(buf), tmplog)) fputs(buf, log);
274 if (append) {
275 tmplog_offset = ftell(tmplog);
276 }
277 check_and_fclose(tmplog, TEMPORARY_LOG_FILE);
278 }
279 check_and_fclose(log, destination);
280 }
281}
282
283
284// clear the recovery command and prepare to boot a (hopefully working) system,
285// copy our log file to cache as well (for the system to read), and
286// record any intent we were asked to communicate back to the system.
287// this function is idempotent: call it as many times as you like.
288static void
289finish_recovery(const char *send_intent) {
290 // By this point, we're ready to return to the main system...
291 if (send_intent != NULL) {
292 FILE *fp = fopen_path(INTENT_FILE, "w");
293 if (fp == NULL) {
294 LOGE("Can't open %s\n", INTENT_FILE);
295 } else {
296 fputs(send_intent, fp);
297 check_and_fclose(fp, INTENT_FILE);
298 }
299 }
300
301 // Copy logs to cache so the system can find out what happened.
302 copy_log_file(LOG_FILE, true);
303 copy_log_file(LAST_LOG_FILE, false);
304 chmod(LAST_LOG_FILE, 0640);
305
306 if (device_flash_type() == MTD) {
307 // Reset to mormal system boot so recovery won't cycle indefinitely.
308 struct bootloader_message boot;
309 memset(&boot, 0, sizeof(boot));
310 set_bootloader_message(&boot);
311 }
312
313 // Remove the command file, so recovery won't repeat indefinitely.
314 if (ensure_path_mounted(COMMAND_FILE) != 0 ||
315 (unlink(COMMAND_FILE) && errno != ENOENT)) {
316 LOGW("Can't unlink %s\n", COMMAND_FILE);
317 }
318
319 sync(); // For good measure.
320}
321
322static int
323erase_volume(const char *volume) {
324 ui_set_background(BACKGROUND_ICON_INSTALLING);
325 ui_show_indeterminate_progress();
326 ui_print("Formatting %s...\n", volume);
327
328 if (strcmp(volume, "/cache") == 0) {
329 // Any part of the log we'd copied to cache is now gone.
330 // Reset the pointer so we copy from the beginning of the temp
331 // log.
332 tmplog_offset = 0;
333 }
334
335 return format_volume(volume);
336}
337
338static char*
339copy_sideloaded_package(const char* original_path) {
340 if (ensure_path_mounted(original_path) != 0) {
341 LOGE("Can't mount %s\n", original_path);
342 return NULL;
343 }
344
345 if (ensure_path_mounted(SIDELOAD_TEMP_DIR) != 0) {
346 LOGE("Can't mount %s\n", SIDELOAD_TEMP_DIR);
347 return NULL;
348 }
349
350 if (mkdir(SIDELOAD_TEMP_DIR, 0700) != 0) {
351 if (errno != EEXIST) {
352 LOGE("Can't mkdir %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
353 return NULL;
354 }
355 }
356
357 // verify that SIDELOAD_TEMP_DIR is exactly what we expect: a
358 // directory, owned by root, readable and writable only by root.
359 struct stat st;
360 if (stat(SIDELOAD_TEMP_DIR, &st) != 0) {
361 LOGE("failed to stat %s (%s)\n", SIDELOAD_TEMP_DIR, strerror(errno));
362 return NULL;
363 }
364 if (!S_ISDIR(st.st_mode)) {
365 LOGE("%s isn't a directory\n", SIDELOAD_TEMP_DIR);
366 return NULL;
367 }
368 if ((st.st_mode & 0777) != 0700) {
369 LOGE("%s has perms %o\n", SIDELOAD_TEMP_DIR, st.st_mode);
370 return NULL;
371 }
372 if (st.st_uid != 0) {
373 LOGE("%s owned by %lu; not root\n", SIDELOAD_TEMP_DIR, st.st_uid);
374 return NULL;
375 }
376
377 char copy_path[PATH_MAX];
378 strcpy(copy_path, SIDELOAD_TEMP_DIR);
379 strcat(copy_path, "/package.zip");
380
381 char* buffer = malloc(BUFSIZ);
382 if (buffer == NULL) {
383 LOGE("Failed to allocate buffer\n");
384 return NULL;
385 }
386
387 size_t read;
388 FILE* fin = fopen(original_path, "rb");
389 if (fin == NULL) {
390 LOGE("Failed to open %s (%s)\n", original_path, strerror(errno));
391 return NULL;
392 }
393 FILE* fout = fopen(copy_path, "wb");
394 if (fout == NULL) {
395 LOGE("Failed to open %s (%s)\n", copy_path, strerror(errno));
396 return NULL;
397 }
398
399 while ((read = fread(buffer, 1, BUFSIZ, fin)) > 0) {
400 if (fwrite(buffer, 1, read, fout) != read) {
401 LOGE("Short write of %s (%s)\n", copy_path, strerror(errno));
402 return NULL;
403 }
404 }
405
406 free(buffer);
407
408 if (fclose(fout) != 0) {
409 LOGE("Failed to close %s (%s)\n", copy_path, strerror(errno));
410 return NULL;
411 }
412
413 if (fclose(fin) != 0) {
414 LOGE("Failed to close %s (%s)\n", original_path, strerror(errno));
415 return NULL;
416 }
417
418 // "adb push" is happy to overwrite read-only files when it's
419 // running as root, but we'll try anyway.
420 if (chmod(copy_path, 0400) != 0) {
421 LOGE("Failed to chmod %s (%s)\n", copy_path, strerror(errno));
422 return NULL;
423 }
424
425 return strdup(copy_path);
426}
427
428static char**
429prepend_title(char** headers) {
430 char* title[] = { EXPAND(RECOVERY_VERSION),
431 "",
432 NULL };
433
434 // count the number of lines in our title, plus the
435 // caller-provided headers.
436 int count = 0;
437 char** p;
438 for (p = title; *p; ++p, ++count);
439 for (p = headers; *p; ++p, ++count);
440
441 char** new_headers = malloc((count+1) * sizeof(char*));
442 char** h = new_headers;
443 for (p = title; *p; ++p, ++h) *h = *p;
444 for (p = headers; *p; ++p, ++h) *h = *p;
445 *h = NULL;
446
447 return new_headers;
448}
449
450int
451get_menu_selection(char** headers, char** items, int menu_only,
452 int initial_selection) {
453 // throw away keys pressed previously, so user doesn't
454 // accidentally trigger menu items.
455 ui_clear_key_queue();
456
457 int item_count = ui_start_menu(headers, items, initial_selection);
458 int selected = initial_selection;
459 int chosen_item = -1;
460
461 // Some users with dead enter keys need a way to turn on power to select.
462 // Jiggering across the wrapping menu is one "secret" way to enable it.
463 // We can't rely on /cache or /sdcard since they may not be available.
464 int wrap_count = 0;
465
466 while (chosen_item < 0 && chosen_item != GO_BACK) {
467 int key = ui_wait_key();
468 int visible = ui_text_visible();
469
470 int action = device_handle_key(key, visible);
471
472 int old_selected = selected;
473
474 if (action < 0) {
475 switch (action) {
476 case HIGHLIGHT_UP:
477 --selected;
478 selected = ui_menu_select(selected);
479 break;
480 case HIGHLIGHT_DOWN:
481 ++selected;
482 selected = ui_menu_select(selected);
483 break;
484 case SELECT_ITEM:
485 chosen_item = selected;
486 if (ui_get_showing_back_button()) {
487 if (chosen_item == item_count) {
488 chosen_item = GO_BACK;
489 }
490 }
491 break;
492 case NO_ACTION:
493 break;
494 case GO_BACK:
495 chosen_item = GO_BACK;
496 break;
497 }
498 } else if (!menu_only) {
499 chosen_item = action;
500 }
501
502 if (abs(selected - old_selected) > 1) {
503 wrap_count++;
504 if (wrap_count == 3) {
505 wrap_count = 0;
506 if (ui_get_showing_back_button()) {
507 ui_print("Back menu button disabled.\n");
508 ui_set_showing_back_button(0);
509 }
510 else {
511 ui_print("Back menu button enabled.\n");
512 ui_set_showing_back_button(1);
513 }
514 }
515 }
516 }
517
518 ui_end_menu();
519 ui_clear_key_queue();
520 return chosen_item;
521}
522
523static int compare_string(const void* a, const void* b) {
524 return strcmp(*(const char**)a, *(const char**)b);
525}
526
527static int
528sdcard_directory(const char* path) {
529 ensure_path_mounted(SDCARD_ROOT);
530
531 const char* MENU_HEADERS[] = { "Choose a package to install:",
532 path,
533 "",
534 NULL };
535 DIR* d;
536 struct dirent* de;
537 d = opendir(path);
538 if (d == NULL) {
539 LOGE("error opening %s: %s\n", path, strerror(errno));
540 ensure_path_unmounted(SDCARD_ROOT);
541 return 0;
542 }
543
544 char** headers = prepend_title(MENU_HEADERS);
545
546 int d_size = 0;
547 int d_alloc = 10;
548 char** dirs = malloc(d_alloc * sizeof(char*));
549 int z_size = 1;
550 int z_alloc = 10;
551 char** zips = malloc(z_alloc * sizeof(char*));
552 zips[0] = strdup("../");
553
554 while ((de = readdir(d)) != NULL) {
555 int name_len = strlen(de->d_name);
556
557 if (de->d_type == DT_DIR) {
558 // skip "." and ".." entries
559 if (name_len == 1 && de->d_name[0] == '.') continue;
560 if (name_len == 2 && de->d_name[0] == '.' &&
561 de->d_name[1] == '.') continue;
562
563 if (d_size >= d_alloc) {
564 d_alloc *= 2;
565 dirs = realloc(dirs, d_alloc * sizeof(char*));
566 }
567 dirs[d_size] = malloc(name_len + 2);
568 strcpy(dirs[d_size], de->d_name);
569 dirs[d_size][name_len] = '/';
570 dirs[d_size][name_len+1] = '\0';
571 ++d_size;
572 } else if (de->d_type == DT_REG &&
573 name_len >= 4 &&
574 strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
575 if (z_size >= z_alloc) {
576 z_alloc *= 2;
577 zips = realloc(zips, z_alloc * sizeof(char*));
578 }
579 zips[z_size++] = strdup(de->d_name);
580 }
581 }
582 closedir(d);
583
584 qsort(dirs, d_size, sizeof(char*), compare_string);
585 qsort(zips, z_size, sizeof(char*), compare_string);
586
587 // append dirs to the zips list
588 if (d_size + z_size + 1 > z_alloc) {
589 z_alloc = d_size + z_size + 1;
590 zips = realloc(zips, z_alloc * sizeof(char*));
591 }
592 memcpy(zips + z_size, dirs, d_size * sizeof(char*));
593 free(dirs);
594 z_size += d_size;
595 zips[z_size] = NULL;
596
597 int result;
598 int chosen_item = 0;
599 do {
600 chosen_item = get_menu_selection(headers, zips, 1, chosen_item);
601
602 char* item = zips[chosen_item];
603 int item_len = strlen(item);
604 if (chosen_item == 0) { // item 0 is always "../"
605 // go up but continue browsing (if the caller is sdcard_directory)
606 result = -1;
607 break;
608 } else if (item[item_len-1] == '/') {
609 // recurse down into a subdirectory
610 char new_path[PATH_MAX];
611 strlcpy(new_path, path, PATH_MAX);
612 strlcat(new_path, "/", PATH_MAX);
613 strlcat(new_path, item, PATH_MAX);
614 new_path[strlen(new_path)-1] = '\0'; // truncate the trailing '/'
615 result = sdcard_directory(new_path);
616 if (result >= 0) break;
617 } else {
618 // selected a zip file: attempt to install it, and return
619 // the status to the caller.
620 char new_path[PATH_MAX];
621 strlcpy(new_path, path, PATH_MAX);
622 strlcat(new_path, "/", PATH_MAX);
623 strlcat(new_path, item, PATH_MAX);
624
625 ui_print("\n-- Install %s ...\n", path);
626 set_sdcard_update_bootloader_message();
627 char* copy = copy_sideloaded_package(new_path);
628 ensure_path_unmounted(SDCARD_ROOT);
629 if (copy) {
630 result = install_package(copy);
631 free(copy);
632 } else {
633 result = INSTALL_ERROR;
634 }
635 break;
636 }
637 } while (true);
638
639 int i;
640 for (i = 0; i < z_size; ++i) free(zips[i]);
641 free(zips);
642 free(headers);
643
644 ensure_path_unmounted(SDCARD_ROOT);
645 return result;
646}
647
648static void
649wipe_data(int confirm) {
650 if (confirm) {
651 static char** title_headers = NULL;
652
653 if (title_headers == NULL) {
654 char* headers[] = { "Confirm wipe of all user data?",
655 " THIS CAN NOT BE UNDONE.",
656 "",
657 NULL };
658 title_headers = prepend_title((const char**)headers);
659 }
660
661 char* items[] = { " No",
662 " No",
663 " No",
664 " No",
665 " No",
666 " No",
667 " No",
668 " Yes -- delete all user data", // [7]
669 " No",
670 " No",
671 " No",
672 NULL };
673
674 int chosen_item = get_menu_selection(title_headers, items, 1, 0);
675 if (chosen_item != 7) {
676 return;
677 }
678 }
679
680 ui_print("\n-- Wiping data...\n");
681 device_wipe_data();
682 erase_volume("/data");
683 erase_volume("/cache");
684 if (has_datadata()) {
685 erase_volume("/datadata");
686 }
687 erase_volume("/sd-ext");
688 erase_volume("/sdcard/.android_secure");
689 ui_print("Data wipe complete.\n");
690}
691
692static void
693prompt_and_wait() {
694 char** headers = prepend_title((const char**)MENU_HEADERS);
695
696 for (;;) {
697 finish_recovery(NULL);
698 ui_reset_progress();
699
700 allow_display_toggle = 1;
701 int chosen_item = get_menu_selection(headers, MENU_ITEMS, 0, 0);
702 allow_display_toggle = 0;
703
704 // device-specific code may take some action here. It may
705 // return one of the core actions handled in the switch
706 // statement below.
707 chosen_item = device_perform_action(chosen_item);
708
709 switch (chosen_item) {
710 case ITEM_REBOOT:
andrew.boren1acd15e2011-03-31 21:41:22 -0700711 poweroff=0;
preludedrew38058dc2011-01-29 23:30:44 -0700712 return;
713
714 case ITEM_WIPE_DATA:
715 wipe_data(ui_text_visible());
716 if (!ui_text_visible()) return;
717 break;
718
719 case ITEM_WIPE_CACHE:
720 if (confirm_selection("Confirm wipe?", "Yes - Wipe Cache"))
721 {
722 ui_print("\n-- Wiping cache...\n");
723 erase_volume("/cache");
724 ui_print("Cache wipe complete.\n");
725 if (!ui_text_visible()) return;
726 }
727 break;
728
729 case ITEM_APPLY_SDCARD:
730 if (confirm_selection("Confirm install?", "Yes - Install /sdcard/update.zip"))
731 {
732 ui_print("\n-- Install from sdcard...\n");
733 int status = install_package(SDCARD_PACKAGE_FILE);
734 if (status != INSTALL_SUCCESS) {
735 ui_set_background(BACKGROUND_ICON_ERROR);
736 ui_print("Installation aborted.\n");
737 } else if (!ui_text_visible()) {
738 return; // reboot if logs aren't visible
739 } else {
740 ui_print("\nInstall from sdcard complete.\n");
741 }
742 }
743 break;
744 case ITEM_INSTALL_ZIP:
745 show_install_update_menu();
746 break;
747 case ITEM_NANDROID:
748 show_nandroid_menu();
749 break;
750 case ITEM_PARTITION:
751 show_partition_menu();
752 break;
753 case ITEM_ADVANCED:
754 show_advanced_menu();
755 break;
andrew.boren1acd15e2011-03-31 21:41:22 -0700756 case ITEM_POWEROFF:
757 poweroff=1;
758 return;
preludedrew38058dc2011-01-29 23:30:44 -0700759 }
760 }
761}
762
763static void
764print_property(const char *key, const char *name, void *cookie) {
765 printf("%s=%s\n", key, name);
766}
767
768int
769main(int argc, char **argv) {
770 if (strstr(argv[0], "recovery") == NULL)
771 {
772 if (strstr(argv[0], "flash_image") != NULL)
773 return flash_image_main(argc, argv);
774 if (strstr(argv[0], "volume") != NULL)
775 return volume_main(argc, argv);
776 if (strstr(argv[0], "edify") != NULL)
777 return edify_main(argc, argv);
778 if (strstr(argv[0], "dump_image") != NULL)
779 return dump_image_main(argc, argv);
780 if (strstr(argv[0], "erase_image") != NULL)
781 return erase_image_main(argc, argv);
782 if (strstr(argv[0], "mkyaffs2image") != NULL)
783 return mkyaffs2image_main(argc, argv);
784 if (strstr(argv[0], "unyaffs") != NULL)
785 return unyaffs_main(argc, argv);
786 if (strstr(argv[0], "nandroid"))
787 return nandroid_main(argc, argv);
788 if (strstr(argv[0], "reboot"))
789 return reboot_main(argc, argv);
andrew.boren1acd15e2011-03-31 21:41:22 -0700790 if (strstr(argv[0], "poweroff")){
791 return reboot_main(argc, argv);
792 }
preludedrew38058dc2011-01-29 23:30:44 -0700793 if (strstr(argv[0], "setprop"))
794 return setprop_main(argc, argv);
795 return busybox_driver(argc, argv);
796 }
797 handle_chargemode();
798 __system("/sbin/postrecoveryboot.sh");
799
800 int is_user_initiated_recovery = 0;
801 time_t start = time(NULL);
802
803 // If these fail, there's not really anywhere to complain...
804 freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
805 freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
806 printf("Starting recovery on %s", ctime(&start));
807
808 ui_init();
809 ui_print(EXPAND(RECOVERY_VERSION)"\n");
810 load_volume_table();
811 process_volumes();
812 LOGI("Processing arguments.\n");
813 get_args(&argc, &argv);
814
815 int previous_runs = 0;
816 const char *send_intent = NULL;
817 const char *update_package = NULL;
818 const char *encrypted_fs_mode = NULL;
819 int wipe_data = 0, wipe_cache = 0;
820 int toggle_secure_fs = 0;
821 encrypted_fs_info encrypted_fs_data;
822
823 LOGI("Checking arguments.\n");
824 int arg;
825 while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
826 switch (arg) {
827 case 'p': previous_runs = atoi(optarg); break;
828 case 's': send_intent = optarg; break;
829 case 'u': update_package = optarg; break;
830 case 'w': wipe_data = wipe_cache = 1; break;
831 case 'c': wipe_cache = 1; break;
832 case 'e': encrypted_fs_mode = optarg; toggle_secure_fs = 1; break;
833 case 't': ui_show_text(1); break;
834 case '?':
835 LOGE("Invalid command argument\n");
836 continue;
837 }
838 }
839
840 LOGI("device_recovery_start()\n");
841 device_recovery_start();
842
843 printf("Command:");
844 for (arg = 0; arg < argc; arg++) {
845 printf(" \"%s\"", argv[arg]);
846 }
847 printf("\n");
848
849 if (update_package) {
850 // For backwards compatibility on the cache partition only, if
851 // we're given an old 'root' path "CACHE:foo", change it to
852 // "/cache/foo".
853 if (strncmp(update_package, "CACHE:", 6) == 0) {
854 int len = strlen(update_package) + 10;
855 char* modified_path = malloc(len);
856 strlcpy(modified_path, "/cache/", len);
857 strlcat(modified_path, update_package+6, len);
858 printf("(replacing path \"%s\" with \"%s\")\n",
859 update_package, modified_path);
860 update_package = modified_path;
861 }
862 }
863 printf("\n");
864
865 property_list(print_property, NULL);
866 printf("\n");
867
868 int status = INSTALL_SUCCESS;
869
870 if (toggle_secure_fs) {
871 if (strcmp(encrypted_fs_mode,"on") == 0) {
872 encrypted_fs_data.mode = MODE_ENCRYPTED_FS_ENABLED;
873 ui_print("Enabling Encrypted FS.\n");
874 } else if (strcmp(encrypted_fs_mode,"off") == 0) {
875 encrypted_fs_data.mode = MODE_ENCRYPTED_FS_DISABLED;
876 ui_print("Disabling Encrypted FS.\n");
877 } else {
878 ui_print("Error: invalid Encrypted FS setting.\n");
879 status = INSTALL_ERROR;
880 }
881
882 // Recovery strategy: if the data partition is damaged, disable encrypted file systems.
883 // This preventsthe device recycling endlessly in recovery mode.
884 if ((encrypted_fs_data.mode == MODE_ENCRYPTED_FS_ENABLED) &&
885 (read_encrypted_fs_info(&encrypted_fs_data))) {
886 ui_print("Encrypted FS change aborted, resetting to disabled state.\n");
887 encrypted_fs_data.mode = MODE_ENCRYPTED_FS_DISABLED;
888 }
889
890 if (status != INSTALL_ERROR) {
891 if (erase_volume("/data")) {
892 ui_print("Data wipe failed.\n");
893 status = INSTALL_ERROR;
894 } else if (erase_volume("/cache")) {
895 ui_print("Cache wipe failed.\n");
896 status = INSTALL_ERROR;
897 } else if ((encrypted_fs_data.mode == MODE_ENCRYPTED_FS_ENABLED) &&
898 (restore_encrypted_fs_info(&encrypted_fs_data))) {
899 ui_print("Encrypted FS change aborted.\n");
900 status = INSTALL_ERROR;
901 } else {
902 ui_print("Successfully updated Encrypted FS.\n");
903 status = INSTALL_SUCCESS;
904 }
905 }
906 } else if (update_package != NULL) {
907 status = install_package(update_package);
908 if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
909 } else if (wipe_data) {
910 if (device_wipe_data()) status = INSTALL_ERROR;
911 if (erase_volume("/data")) status = INSTALL_ERROR;
912 if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
913 if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
914 } else if (wipe_cache) {
915 if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
916 if (status != INSTALL_SUCCESS) ui_print("Cache wipe failed.\n");
917 } else {
918 LOGI("Checking for extendedcommand...\n");
919 status = INSTALL_ERROR; // No command specified
920 // we are starting up in user initiated recovery here
921 // let's set up some default options
922 signature_check_enabled = 0;
923 script_assert_enabled = 0;
924 is_user_initiated_recovery = 1;
925 ui_set_show_text(1);
926 ui_set_background(BACKGROUND_ICON_CLOCKWORK);
927
928 if (extendedcommand_file_exists()) {
929 LOGI("Running extendedcommand...\n");
930 int ret;
931 if (0 == (ret = run_and_remove_extendedcommand())) {
932 status = INSTALL_SUCCESS;
933 ui_set_show_text(0);
934 }
935 else {
936 handle_failure(ret);
937 }
938 } else {
939 LOGI("Skipping execution of extendedcommand, file not found...\n");
940 }
941 }
942
943 if (status != INSTALL_SUCCESS && !is_user_initiated_recovery) ui_set_background(BACKGROUND_ICON_ERROR);
944 if (status != INSTALL_SUCCESS || ui_text_visible()) {
945 prompt_and_wait();
946 }
947
948 // Otherwise, get ready to boot the main system...
949 finish_recovery(send_intent);
andrew.boren1acd15e2011-03-31 21:41:22 -0700950 if(!poweroff)
951 ui_print("Rebooting...\n");
952 else
953 ui_print("Shutting down...\n");
preludedrew38058dc2011-01-29 23:30:44 -0700954 sync();
andrew.boren1acd15e2011-03-31 21:41:22 -0700955 reboot((!poweroff) ? RB_AUTOBOOT : RB_POWER_OFF);
preludedrew38058dc2011-01-29 23:30:44 -0700956 return EXIT_SUCCESS;
957}
958
959int get_allow_toggle_display() {
960 return allow_display_toggle;
961}