1 /*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <ctype.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <getopt.h>
21 #include <limits.h>
22 #include <linux/input.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/reboot.h>
27 #include <sys/types.h>
28 #include <time.h>
29 #include <unistd.h>
30
31 #include "bootloader.h"
32 #include "common.h"
33 #include "cutils/properties.h"
34 #include "firmware.h"
35 #include "install.h"
36 #include "minui/minui.h"
37 #include "minzip/DirUtil.h"
38 #include "roots.h"
39
40 static const struct option OPTIONS[] = {
41 { "send_intent", required_argument, NULL, 's' },
42 { "update_package", required_argument, NULL, 'u' },
43 { "wipe_data", no_argument, NULL, 'w' },
44 { "wipe_cache", no_argument, NULL, 'c' },
45 };
46
47 static const char *COMMAND_FILE = "CACHE:recovery/command";
48 static const char *INTENT_FILE = "CACHE:recovery/intent";
49 static const char *LOG_FILE = "CACHE:recovery/log";
50 static const char *SDCARD_PACKAGE_FILE = "SDCARD:update.zip";
51 static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
52
53 /*
54 * The recovery tool communicates with the main system through /cache files.
55 * /cache/recovery/command - INPUT - command line for tool, one arg per line
56 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
57 * /cache/recovery/intent - OUTPUT - intent that was passed in
58 *
59 * The arguments which may be supplied in the recovery.command file:
60 * --send_intent=anystring - write the text out to recovery.intent
61 * --update_package=root:path - verify install an OTA package file
62 * --wipe_data - erase user data (and cache), then reboot
63 * --wipe_cache - wipe cache (but not user data), then reboot
64 *
65 * After completing, we remove /cache/recovery/command and reboot.
66 * Arguments may also be supplied in the bootloader control block (BCB).
67 * These important scenarios must be safely restartable at any point:
68 *
69 * FACTORY RESET
70 * 1. user selects "factory reset"
71 * 2. main system writes "--wipe_data" to /cache/recovery/command
72 * 3. main system reboots into recovery
73 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
74 * -- after this, rebooting will restart the erase --
75 * 5. erase_root() reformats /data
76 * 6. erase_root() reformats /cache
77 * 7. finish_recovery() erases BCB
78 * -- after this, rebooting will restart the main system --
79 * 8. main() calls reboot() to boot main system
80 *
81 * OTA INSTALL
82 * 1. main system downloads OTA package to /cache/some-filename.zip
83 * 2. main system writes "--update_package=CACHE:some-filename.zip"
84 * 3. main system reboots into recovery
85 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
86 * -- after this, rebooting will attempt to reinstall the update --
87 * 5. install_package() attempts to install the update
88 * NOTE: the package install must itself be restartable from any point
89 * 6. finish_recovery() erases BCB
90 * -- after this, rebooting will (try to) restart the main system --
91 * 7. ** if install failed **
92 * 7a. prompt_and_wait() shows an error icon and waits for the user
93 * 7b; the user reboots (pulling the battery, etc) into the main system
94 * 8. main() calls maybe_install_firmware_update()
95 * ** if the update contained radio/hboot firmware **:
96 * 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
97 * -- after this, rebooting will reformat cache & restart main system --
98 * 8b. m_i_f_u() writes firmware image into raw cache partition
99 * 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
100 * -- after this, rebooting will attempt to reinstall firmware --
101 * 8d. bootloader tries to flash firmware
102 * 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
103 * -- after this, rebooting will reformat cache & restart main system --
104 * 8f. erase_root() reformats /cache
105 * 8g. finish_recovery() erases BCB
106 * -- after this, rebooting will (try to) restart the main system --
107 * 9. main() calls reboot() to boot main system
108 */
109
110 static const int MAX_ARG_LENGTH = 4096;
111 static const int MAX_ARGS = 100;
112
113 // open a file given in root:path format, mounting partitions as necessary
114 static FILE*
fopen_root_path(const char * root_path,const char * mode)115 fopen_root_path(const char *root_path, const char *mode) {
116 if (ensure_root_path_mounted(root_path) != 0) {
117 LOGE("Can't mount %s\n", root_path);
118 return NULL;
119 }
120
121 char path[PATH_MAX] = "";
122 if (translate_root_path(root_path, path, sizeof(path)) == NULL) {
123 LOGE("Bad path %s\n", root_path);
124 return NULL;
125 }
126
127 // When writing, try to create the containing directory, if necessary.
128 // Use generous permissions, the system (init.rc) will reset them.
129 if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1);
130
131 FILE *fp = fopen(path, mode);
132 if (fp == NULL) LOGE("Can't open %s\n", path);
133 return fp;
134 }
135
136 // close a file, log an error if the error indicator is set
137 static void
check_and_fclose(FILE * fp,const char * name)138 check_and_fclose(FILE *fp, const char *name) {
139 fflush(fp);
140 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
141 fclose(fp);
142 }
143
144 // command line args come from, in decreasing precedence:
145 // - the actual command line
146 // - the bootloader control block (one per line, after "recovery")
147 // - the contents of COMMAND_FILE (one per line)
148 static void
get_args(int * argc,char *** argv)149 get_args(int *argc, char ***argv) {
150 struct bootloader_message boot;
151 memset(&boot, 0, sizeof(boot));
152 get_bootloader_message(&boot); // this may fail, leaving a zeroed structure
153
154 if (boot.command[0] != 0 && boot.command[0] != 255) {
155 LOGI("Boot command: %.*s\n", sizeof(boot.command), boot.command);
156 }
157
158 if (boot.status[0] != 0 && boot.status[0] != 255) {
159 LOGI("Boot status: %.*s\n", sizeof(boot.status), boot.status);
160 }
161
162 // --- if arguments weren't supplied, look in the bootloader control block
163 if (*argc <= 1) {
164 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
165 const char *arg = strtok(boot.recovery, "\n");
166 if (arg != NULL && !strcmp(arg, "recovery")) {
167 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
168 (*argv)[0] = strdup(arg);
169 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
170 if ((arg = strtok(NULL, "\n")) == NULL) break;
171 (*argv)[*argc] = strdup(arg);
172 }
173 LOGI("Got arguments from boot message\n");
174 } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
175 LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
176 }
177 }
178
179 // --- if that doesn't work, try the command file
180 if (*argc <= 1) {
181 FILE *fp = fopen_root_path(COMMAND_FILE, "r");
182 if (fp != NULL) {
183 char *argv0 = (*argv)[0];
184 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
185 (*argv)[0] = argv0; // use the same program name
186
187 char buf[MAX_ARG_LENGTH];
188 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
189 if (!fgets(buf, sizeof(buf), fp)) break;
190 (*argv)[*argc] = strdup(strtok(buf, "\r\n")); // Strip newline.
191 }
192
193 check_and_fclose(fp, COMMAND_FILE);
194 LOGI("Got arguments from %s\n", COMMAND_FILE);
195 }
196 }
197
198 // --> write the arguments we have back into the bootloader control block
199 // always boot into recovery after this (until finish_recovery() is called)
200 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
201 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
202 int i;
203 for (i = 1; i < *argc; ++i) {
204 strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
205 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
206 }
207 set_bootloader_message(&boot);
208 }
209
210
211 // clear the recovery command and prepare to boot a (hopefully working) system,
212 // copy our log file to cache as well (for the system to read), and
213 // record any intent we were asked to communicate back to the system.
214 // this function is idempotent: call it as many times as you like.
215 static void
finish_recovery(const char * send_intent)216 finish_recovery(const char *send_intent)
217 {
218 // By this point, we're ready to return to the main system...
219 if (send_intent != NULL) {
220 FILE *fp = fopen_root_path(INTENT_FILE, "w");
221 if (fp != NULL) {
222 fputs(send_intent, fp);
223 check_and_fclose(fp, INTENT_FILE);
224 }
225 }
226
227 // Copy logs to cache so the system can find out what happened.
228 FILE *log = fopen_root_path(LOG_FILE, "a");
229 if (log != NULL) {
230 FILE *tmplog = fopen(TEMPORARY_LOG_FILE, "r");
231 if (tmplog == NULL) {
232 LOGE("Can't open %s\n", TEMPORARY_LOG_FILE);
233 } else {
234 static long tmplog_offset = 0;
235 fseek(tmplog, tmplog_offset, SEEK_SET); // Since last write
236 char buf[4096];
237 while (fgets(buf, sizeof(buf), tmplog)) fputs(buf, log);
238 tmplog_offset = ftell(tmplog);
239 check_and_fclose(tmplog, TEMPORARY_LOG_FILE);
240 }
241 check_and_fclose(log, LOG_FILE);
242 }
243
244 // Reset the bootloader message to revert to a normal main system boot.
245 struct bootloader_message boot;
246 memset(&boot, 0, sizeof(boot));
247 set_bootloader_message(&boot);
248
249 // Remove the command file, so recovery won't repeat indefinitely.
250 char path[PATH_MAX] = "";
251 if (ensure_root_path_mounted(COMMAND_FILE) != 0 ||
252 translate_root_path(COMMAND_FILE, path, sizeof(path)) == NULL ||
253 (unlink(path) && errno != ENOENT)) {
254 LOGW("Can't unlink %s\n", COMMAND_FILE);
255 }
256
257 sync(); // For good measure.
258 }
259
260 static int
erase_root(const char * root)261 erase_root(const char *root)
262 {
263 ui_set_background(BACKGROUND_ICON_INSTALLING);
264 ui_show_indeterminate_progress();
265 ui_print("Formatting %s...\n", root);
266 return format_root_device(root);
267 }
268
269 static void
prompt_and_wait()270 prompt_and_wait()
271 {
272 char* headers[] = { "Android system recovery <"
273 EXPAND(RECOVERY_API_VERSION) "e>",
274 "",
275 "Use trackball to highlight;",
276 "click to select.",
277 "",
278 NULL };
279
280 // these constants correspond to elements of the items[] list.
281 #define ITEM_REBOOT 0
282 #define ITEM_APPLY_SDCARD 1
283 #define ITEM_WIPE_DATA 2
284 #define ITEM_WIPE_CACHE 3
285 char* items[] = { "reboot system now [Home+Back]",
286 "apply sdcard:update.zip [Alt+S]",
287 "wipe data/factory reset [Alt+W]",
288 "wipe cache partition",
289 NULL };
290
291 ui_start_menu(headers, items);
292 int selected = 0;
293 int chosen_item = -1;
294
295 finish_recovery(NULL);
296 ui_reset_progress();
297 for (;;) {
298 int key = ui_wait_key();
299 int alt = ui_key_pressed(KEY_LEFTALT) || ui_key_pressed(KEY_RIGHTALT);
300 int visible = ui_text_visible();
301
302 if (key == KEY_DREAM_BACK && ui_key_pressed(KEY_DREAM_HOME)) {
303 // Wait for the keys to be released, to avoid triggering
304 // special boot modes (like coming back into recovery!).
305 while (ui_key_pressed(KEY_DREAM_BACK) ||
306 ui_key_pressed(KEY_DREAM_HOME)) {
307 usleep(1000);
308 }
309 chosen_item = ITEM_REBOOT;
310 } else if (alt && key == KEY_W) {
311 chosen_item = ITEM_WIPE_DATA;
312 } else if (alt && key == KEY_S) {
313 chosen_item = ITEM_APPLY_SDCARD;
314 } else if ((key == KEY_DOWN || key == KEY_VOLUMEDOWN) && visible) {
315 ++selected;
316 selected = ui_menu_select(selected);
317 } else if ((key == KEY_UP || key == KEY_VOLUMEUP) && visible) {
318 --selected;
319 selected = ui_menu_select(selected);
320 } else if (key == BTN_MOUSE && visible) {
321 chosen_item = selected;
322 }
323
324 if (chosen_item >= 0) {
325 // turn off the menu, letting ui_print() to scroll output
326 // on the screen.
327 ui_end_menu();
328
329 switch (chosen_item) {
330 case ITEM_REBOOT:
331 return;
332
333 case ITEM_WIPE_DATA:
334 ui_print("\n-- Wiping data...\n");
335 erase_root("DATA:");
336 erase_root("CACHE:");
337 ui_print("Data wipe complete.\n");
338 if (!ui_text_visible()) return;
339 break;
340
341 case ITEM_WIPE_CACHE:
342 ui_print("\n-- Wiping cache...\n");
343 erase_root("CACHE:");
344 ui_print("Cache wipe complete.\n");
345 if (!ui_text_visible()) return;
346 break;
347
348 case ITEM_APPLY_SDCARD:
349 ui_print("\n-- Install from sdcard...\n");
350 int status = install_package(SDCARD_PACKAGE_FILE);
351 if (status != INSTALL_SUCCESS) {
352 ui_set_background(BACKGROUND_ICON_ERROR);
353 ui_print("Installation aborted.\n");
354 } else if (!ui_text_visible()) {
355 return; // reboot if logs aren't visible
356 } else {
357 if (firmware_update_pending()) {
358 ui_print("\nReboot via home+back or menu\n"
359 "to complete installation.\n");
360 } else {
361 ui_print("\nInstall from sdcard complete.\n");
362 }
363 }
364 break;
365 }
366
367 // if we didn't return from this function to reboot, show
368 // the menu again.
369 ui_start_menu(headers, items);
370 selected = 0;
371 chosen_item = -1;
372
373 finish_recovery(NULL);
374 ui_reset_progress();
375
376 // throw away keys pressed while the command was running,
377 // so user doesn't accidentally trigger menu items.
378 ui_clear_key_queue();
379 }
380 }
381 }
382
383 static void
print_property(const char * key,const char * name,void * cookie)384 print_property(const char *key, const char *name, void *cookie)
385 {
386 fprintf(stderr, "%s=%s\n", key, name);
387 }
388
389 int
main(int argc,char ** argv)390 main(int argc, char **argv)
391 {
392 time_t start = time(NULL);
393
394 // If these fail, there's not really anywhere to complain...
395 freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
396 freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
397 fprintf(stderr, "Starting recovery on %s", ctime(&start));
398
399 ui_init();
400 get_args(&argc, &argv);
401
402 int previous_runs = 0;
403 const char *send_intent = NULL;
404 const char *update_package = NULL;
405 int wipe_data = 0, wipe_cache = 0;
406
407 int arg;
408 while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
409 switch (arg) {
410 case 'p': previous_runs = atoi(optarg); break;
411 case 's': send_intent = optarg; break;
412 case 'u': update_package = optarg; break;
413 case 'w': wipe_data = wipe_cache = 1; break;
414 case 'c': wipe_cache = 1; break;
415 case '?':
416 LOGE("Invalid command argument\n");
417 continue;
418 }
419 }
420
421 fprintf(stderr, "Command:");
422 for (arg = 0; arg < argc; arg++) {
423 fprintf(stderr, " \"%s\"", argv[arg]);
424 }
425 fprintf(stderr, "\n\n");
426
427 property_list(print_property, NULL);
428 fprintf(stderr, "\n");
429
430 int status = INSTALL_SUCCESS;
431
432 if (update_package != NULL) {
433 status = install_package(update_package);
434 if (status != INSTALL_SUCCESS) ui_print("Installation aborted.\n");
435 } else if (wipe_data || wipe_cache) {
436 if (wipe_data && erase_root("DATA:")) status = INSTALL_ERROR;
437 if (wipe_cache && erase_root("CACHE:")) status = INSTALL_ERROR;
438 if (status != INSTALL_SUCCESS) ui_print("Data wipe failed.\n");
439 } else {
440 status = INSTALL_ERROR; // No command specified
441 }
442
443 if (status != INSTALL_SUCCESS) ui_set_background(BACKGROUND_ICON_ERROR);
444 if (status != INSTALL_SUCCESS || ui_text_visible()) prompt_and_wait();
445
446 // If there is a radio image pending, reboot now to install it.
447 maybe_install_firmware_update(send_intent);
448
449 // Otherwise, get ready to boot the main system...
450 finish_recovery(send_intent);
451 ui_print("Rebooting...\n");
452 sync();
453 reboot(RB_AUTOBOOT);
454 return EXIT_SUCCESS;
455 }
456