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 <dirent.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <limits.h>
23 #include <linux/input.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/klog.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <time.h>
32 #include <unistd.h>
33 
34 #include <base/file.h>
35 #include <base/stringprintf.h>
36 
37 #include "bootloader.h"
38 #include "common.h"
39 #include "cutils/properties.h"
40 #include "cutils/android_reboot.h"
41 #include "install.h"
42 #include "minui/minui.h"
43 #include "minzip/DirUtil.h"
44 #include "roots.h"
45 #include "ui.h"
46 #include "screen_ui.h"
47 #include "device.h"
48 #include "adb_install.h"
49 #include "adb.h"
50 #include "fuse_sideload.h"
51 #include "fuse_sdcard_provider.h"
52 
53 struct selabel_handle *sehandle;
54 
55 static const struct option OPTIONS[] = {
56   { "send_intent", required_argument, NULL, 'i' },
57   { "update_package", required_argument, NULL, 'u' },
58   { "wipe_data", no_argument, NULL, 'w' },
59   { "wipe_cache", no_argument, NULL, 'c' },
60   { "show_text", no_argument, NULL, 't' },
61   { "sideload", no_argument, NULL, 's' },
62   { "sideload_auto_reboot", no_argument, NULL, 'a' },
63   { "just_exit", no_argument, NULL, 'x' },
64   { "locale", required_argument, NULL, 'l' },
65   { "stages", required_argument, NULL, 'g' },
66   { "shutdown_after", no_argument, NULL, 'p' },
67   { "reason", required_argument, NULL, 'r' },
68   { NULL, 0, NULL, 0 },
69 };
70 
71 static const char *CACHE_LOG_DIR = "/cache/recovery";
72 static const char *COMMAND_FILE = "/cache/recovery/command";
73 static const char *INTENT_FILE = "/cache/recovery/intent";
74 static const char *LOG_FILE = "/cache/recovery/log";
75 static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
76 static const char *LOCALE_FILE = "/cache/recovery/last_locale";
77 static const char *CACHE_ROOT = "/cache";
78 static const char *SDCARD_ROOT = "/sdcard";
79 static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
80 static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
81 static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
82 static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
83 static const int KEEP_LOG_COUNT = 10;
84 
85 RecoveryUI* ui = NULL;
86 char* locale = NULL;
87 char* stage = NULL;
88 char* reason = NULL;
89 bool modified_flash = false;
90 
91 /*
92  * The recovery tool communicates with the main system through /cache files.
93  *   /cache/recovery/command - INPUT - command line for tool, one arg per line
94  *   /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
95  *   /cache/recovery/intent - OUTPUT - intent that was passed in
96  *
97  * The arguments which may be supplied in the recovery.command file:
98  *   --send_intent=anystring - write the text out to recovery.intent
99  *   --update_package=path - verify install an OTA package file
100  *   --wipe_data - erase user data (and cache), then reboot
101  *   --wipe_cache - wipe cache (but not user data), then reboot
102  *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
103  *   --just_exit - do nothing; exit and reboot
104  *
105  * After completing, we remove /cache/recovery/command and reboot.
106  * Arguments may also be supplied in the bootloader control block (BCB).
107  * These important scenarios must be safely restartable at any point:
108  *
109  * FACTORY RESET
110  * 1. user selects "factory reset"
111  * 2. main system writes "--wipe_data" to /cache/recovery/command
112  * 3. main system reboots into recovery
113  * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
114  *    -- after this, rebooting will restart the erase --
115  * 5. erase_volume() reformats /data
116  * 6. erase_volume() reformats /cache
117  * 7. finish_recovery() erases BCB
118  *    -- after this, rebooting will restart the main system --
119  * 8. main() calls reboot() to boot main system
120  *
121  * OTA INSTALL
122  * 1. main system downloads OTA package to /cache/some-filename.zip
123  * 2. main system writes "--update_package=/cache/some-filename.zip"
124  * 3. main system reboots into recovery
125  * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
126  *    -- after this, rebooting will attempt to reinstall the update --
127  * 5. install_package() attempts to install the update
128  *    NOTE: the package install must itself be restartable from any point
129  * 6. finish_recovery() erases BCB
130  *    -- after this, rebooting will (try to) restart the main system --
131  * 7. ** if install failed **
132  *    7a. prompt_and_wait() shows an error icon and waits for the user
133  *    7b; the user reboots (pulling the battery, etc) into the main system
134  * 8. main() calls maybe_install_firmware_update()
135  *    ** if the update contained radio/hboot firmware **:
136  *    8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
137  *        -- after this, rebooting will reformat cache & restart main system --
138  *    8b. m_i_f_u() writes firmware image into raw cache partition
139  *    8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
140  *        -- after this, rebooting will attempt to reinstall firmware --
141  *    8d. bootloader tries to flash firmware
142  *    8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
143  *        -- after this, rebooting will reformat cache & restart main system --
144  *    8f. erase_volume() reformats /cache
145  *    8g. finish_recovery() erases BCB
146  *        -- after this, rebooting will (try to) restart the main system --
147  * 9. main() calls reboot() to boot main system
148  */
149 
150 static const int MAX_ARG_LENGTH = 4096;
151 static const int MAX_ARGS = 100;
152 
153 // open a given path, mounting partitions as necessary
154 FILE*
fopen_path(const char * path,const char * mode)155 fopen_path(const char *path, const char *mode) {
156     if (ensure_path_mounted(path) != 0) {
157         LOGE("Can't mount %s\n", path);
158         return NULL;
159     }
160 
161     // When writing, try to create the containing directory, if necessary.
162     // Use generous permissions, the system (init.rc) will reset them.
163     if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1, sehandle);
164 
165     FILE *fp = fopen(path, mode);
166     return fp;
167 }
168 
is_ro_debuggable()169 bool is_ro_debuggable() {
170     char value[PROPERTY_VALUE_MAX+1];
171     return (property_get("ro.debuggable", value, NULL) == 1 && value[0] == '1');
172 }
173 
redirect_stdio(const char * filename)174 static void redirect_stdio(const char* filename) {
175     // If these fail, there's not really anywhere to complain...
176     freopen(filename, "a", stdout); setbuf(stdout, NULL);
177     freopen(filename, "a", stderr); setbuf(stderr, NULL);
178 }
179 
180 // close a file, log an error if the error indicator is set
181 static void
check_and_fclose(FILE * fp,const char * name)182 check_and_fclose(FILE *fp, const char *name) {
183     fflush(fp);
184     if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
185     fclose(fp);
186 }
187 
188 // command line args come from, in decreasing precedence:
189 //   - the actual command line
190 //   - the bootloader control block (one per line, after "recovery")
191 //   - the contents of COMMAND_FILE (one per line)
192 static void
get_args(int * argc,char *** argv)193 get_args(int *argc, char ***argv) {
194     struct bootloader_message boot;
195     memset(&boot, 0, sizeof(boot));
196     get_bootloader_message(&boot);  // this may fail, leaving a zeroed structure
197     stage = strndup(boot.stage, sizeof(boot.stage));
198 
199     if (boot.command[0] != 0 && boot.command[0] != 255) {
200         LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command);
201     }
202 
203     if (boot.status[0] != 0 && boot.status[0] != 255) {
204         LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status);
205     }
206 
207     // --- if arguments weren't supplied, look in the bootloader control block
208     if (*argc <= 1) {
209         boot.recovery[sizeof(boot.recovery) - 1] = '\0';  // Ensure termination
210         const char *arg = strtok(boot.recovery, "\n");
211         if (arg != NULL && !strcmp(arg, "recovery")) {
212             *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
213             (*argv)[0] = strdup(arg);
214             for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
215                 if ((arg = strtok(NULL, "\n")) == NULL) break;
216                 (*argv)[*argc] = strdup(arg);
217             }
218             LOGI("Got arguments from boot message\n");
219         } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
220             LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
221         }
222     }
223 
224     // --- if that doesn't work, try the command file
225     if (*argc <= 1) {
226         FILE *fp = fopen_path(COMMAND_FILE, "r");
227         if (fp != NULL) {
228             char *token;
229             char *argv0 = (*argv)[0];
230             *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
231             (*argv)[0] = argv0;  // use the same program name
232 
233             char buf[MAX_ARG_LENGTH];
234             for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
235                 if (!fgets(buf, sizeof(buf), fp)) break;
236                 token = strtok(buf, "\r\n");
237                 if (token != NULL) {
238                     (*argv)[*argc] = strdup(token);  // Strip newline.
239                 } else {
240                     --*argc;
241                 }
242             }
243 
244             check_and_fclose(fp, COMMAND_FILE);
245             LOGI("Got arguments from %s\n", COMMAND_FILE);
246         }
247     }
248 
249     // --> write the arguments we have back into the bootloader control block
250     // always boot into recovery after this (until finish_recovery() is called)
251     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
252     strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
253     int i;
254     for (i = 1; i < *argc; ++i) {
255         strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
256         strlcat(boot.recovery, "\n", sizeof(boot.recovery));
257     }
258     set_bootloader_message(&boot);
259 }
260 
261 static void
set_sdcard_update_bootloader_message()262 set_sdcard_update_bootloader_message() {
263     struct bootloader_message boot;
264     memset(&boot, 0, sizeof(boot));
265     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
266     strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
267     set_bootloader_message(&boot);
268 }
269 
270 // Read from kernel log into buffer and write out to file.
save_kernel_log(const char * destination)271 static void save_kernel_log(const char* destination) {
272     int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
273     if (klog_buf_len <= 0) {
274         LOGE("Error getting klog size: %s\n", strerror(errno));
275         return;
276     }
277 
278     std::string buffer(klog_buf_len, 0);
279     int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
280     if (n == -1) {
281         LOGE("Error in reading klog: %s\n", strerror(errno));
282         return;
283     }
284     buffer.resize(n);
285     android::base::WriteStringToFile(buffer, destination);
286 }
287 
288 // How much of the temp log we have copied to the copy in cache.
289 static long tmplog_offset = 0;
290 
copy_log_file(const char * source,const char * destination,bool append)291 static void copy_log_file(const char* source, const char* destination, bool append) {
292     FILE* dest_fp = fopen_path(destination, append ? "a" : "w");
293     if (dest_fp == nullptr) {
294         LOGE("Can't open %s\n", destination);
295     } else {
296         FILE* source_fp = fopen(source, "r");
297         if (source_fp != nullptr) {
298             if (append) {
299                 fseek(source_fp, tmplog_offset, SEEK_SET);  // Since last write
300             }
301             char buf[4096];
302             size_t bytes;
303             while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
304                 fwrite(buf, 1, bytes, dest_fp);
305             }
306             if (append) {
307                 tmplog_offset = ftell(source_fp);
308             }
309             check_and_fclose(source_fp, source);
310         }
311         check_and_fclose(dest_fp, destination);
312     }
313 }
314 
315 // Rename last_log -> last_log.1 -> last_log.2 -> ... -> last_log.$max.
316 // Similarly rename last_kmsg -> last_kmsg.1 -> ... -> last_kmsg.$max.
317 // Overwrite any existing last_log.$max and last_kmsg.$max.
rotate_logs(int max)318 static void rotate_logs(int max) {
319     // Logs should only be rotated once.
320     static bool rotated = false;
321     if (rotated) {
322         return;
323     }
324     rotated = true;
325     ensure_path_mounted(LAST_LOG_FILE);
326     ensure_path_mounted(LAST_KMSG_FILE);
327 
328     for (int i = max-1; i >= 0; --i) {
329         std::string old_log = android::base::StringPrintf((i == 0) ? "%s" : "%s.%d",
330                 LAST_LOG_FILE, i);
331         std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
332         // Ignore errors if old_log doesn't exist.
333         rename(old_log.c_str(), new_log.c_str());
334 
335         std::string old_kmsg = android::base::StringPrintf((i == 0) ? "%s" : "%s.%d",
336                 LAST_KMSG_FILE, i);
337         std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
338         rename(old_kmsg.c_str(), new_kmsg.c_str());
339     }
340 }
341 
copy_logs()342 static void copy_logs() {
343     // We only rotate and record the log of the current session if there are
344     // actual attempts to modify the flash, such as wipes, installs from BCB
345     // or menu selections. This is to avoid unnecessary rotation (and
346     // possible deletion) of log files, if it does not do anything loggable.
347     if (!modified_flash) {
348         return;
349     }
350 
351     rotate_logs(KEEP_LOG_COUNT);
352 
353     // Copy logs to cache so the system can find out what happened.
354     copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
355     copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
356     copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
357     save_kernel_log(LAST_KMSG_FILE);
358     chmod(LOG_FILE, 0600);
359     chown(LOG_FILE, 1000, 1000);   // system user
360     chmod(LAST_KMSG_FILE, 0600);
361     chown(LAST_KMSG_FILE, 1000, 1000);   // system user
362     chmod(LAST_LOG_FILE, 0640);
363     chmod(LAST_INSTALL_FILE, 0644);
364     sync();
365 }
366 
367 // clear the recovery command and prepare to boot a (hopefully working) system,
368 // copy our log file to cache as well (for the system to read), and
369 // record any intent we were asked to communicate back to the system.
370 // this function is idempotent: call it as many times as you like.
371 static void
finish_recovery(const char * send_intent)372 finish_recovery(const char *send_intent) {
373     // By this point, we're ready to return to the main system...
374     if (send_intent != NULL) {
375         FILE *fp = fopen_path(INTENT_FILE, "w");
376         if (fp == NULL) {
377             LOGE("Can't open %s\n", INTENT_FILE);
378         } else {
379             fputs(send_intent, fp);
380             check_and_fclose(fp, INTENT_FILE);
381         }
382     }
383 
384     // Save the locale to cache, so if recovery is next started up
385     // without a --locale argument (eg, directly from the bootloader)
386     // it will use the last-known locale.
387     if (locale != NULL) {
388         LOGI("Saving locale \"%s\"\n", locale);
389         FILE* fp = fopen_path(LOCALE_FILE, "w");
390         fwrite(locale, 1, strlen(locale), fp);
391         fflush(fp);
392         fsync(fileno(fp));
393         check_and_fclose(fp, LOCALE_FILE);
394     }
395 
396     copy_logs();
397 
398     // Reset to normal system boot so recovery won't cycle indefinitely.
399     struct bootloader_message boot;
400     memset(&boot, 0, sizeof(boot));
401     set_bootloader_message(&boot);
402 
403     // Remove the command file, so recovery won't repeat indefinitely.
404     if (ensure_path_mounted(COMMAND_FILE) != 0 ||
405         (unlink(COMMAND_FILE) && errno != ENOENT)) {
406         LOGW("Can't unlink %s\n", COMMAND_FILE);
407     }
408 
409     ensure_path_unmounted(CACHE_ROOT);
410     sync();  // For good measure.
411 }
412 
413 typedef struct _saved_log_file {
414     char* name;
415     struct stat st;
416     unsigned char* data;
417     struct _saved_log_file* next;
418 } saved_log_file;
419 
erase_volume(const char * volume)420 static bool erase_volume(const char* volume) {
421     bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
422 
423     ui->SetBackground(RecoveryUI::ERASING);
424     ui->SetProgressType(RecoveryUI::INDETERMINATE);
425 
426     saved_log_file* head = NULL;
427 
428     if (is_cache) {
429         // If we're reformatting /cache, we load any past logs
430         // (i.e. "/cache/recovery/last_*") and the current log
431         // ("/cache/recovery/log") into memory, so we can restore them after
432         // the reformat.
433 
434         ensure_path_mounted(volume);
435 
436         DIR* d;
437         struct dirent* de;
438         d = opendir(CACHE_LOG_DIR);
439         if (d) {
440             char path[PATH_MAX];
441             strcpy(path, CACHE_LOG_DIR);
442             strcat(path, "/");
443             int path_len = strlen(path);
444             while ((de = readdir(d)) != NULL) {
445                 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
446                     saved_log_file* p = (saved_log_file*) malloc(sizeof(saved_log_file));
447                     strcpy(path+path_len, de->d_name);
448                     p->name = strdup(path);
449                     if (stat(path, &(p->st)) == 0) {
450                         // truncate files to 512kb
451                         if (p->st.st_size > (1 << 19)) {
452                             p->st.st_size = 1 << 19;
453                         }
454                         p->data = (unsigned char*) malloc(p->st.st_size);
455                         FILE* f = fopen(path, "rb");
456                         fread(p->data, 1, p->st.st_size, f);
457                         fclose(f);
458                         p->next = head;
459                         head = p;
460                     } else {
461                         free(p);
462                     }
463                 }
464             }
465             closedir(d);
466         } else {
467             if (errno != ENOENT) {
468                 printf("opendir failed: %s\n", strerror(errno));
469             }
470         }
471     }
472 
473     ui->Print("Formatting %s...\n", volume);
474 
475     ensure_path_unmounted(volume);
476     int result = format_volume(volume);
477 
478     if (is_cache) {
479         while (head) {
480             FILE* f = fopen_path(head->name, "wb");
481             if (f) {
482                 fwrite(head->data, 1, head->st.st_size, f);
483                 fclose(f);
484                 chmod(head->name, head->st.st_mode);
485                 chown(head->name, head->st.st_uid, head->st.st_gid);
486             }
487             free(head->name);
488             free(head->data);
489             saved_log_file* temp = head->next;
490             free(head);
491             head = temp;
492         }
493 
494         // Any part of the log we'd copied to cache is now gone.
495         // Reset the pointer so we copy from the beginning of the temp
496         // log.
497         tmplog_offset = 0;
498         copy_logs();
499     }
500 
501     return (result == 0);
502 }
503 
504 static int
get_menu_selection(const char * const * headers,const char * const * items,int menu_only,int initial_selection,Device * device)505 get_menu_selection(const char* const * headers, const char* const * items,
506                    int menu_only, int initial_selection, Device* device) {
507     // throw away keys pressed previously, so user doesn't
508     // accidentally trigger menu items.
509     ui->FlushKeys();
510 
511     ui->StartMenu(headers, items, initial_selection);
512     int selected = initial_selection;
513     int chosen_item = -1;
514 
515     while (chosen_item < 0) {
516         int key = ui->WaitKey();
517         int visible = ui->IsTextVisible();
518 
519         if (key == -1) {   // ui_wait_key() timed out
520             if (ui->WasTextEverVisible()) {
521                 continue;
522             } else {
523                 LOGI("timed out waiting for key input; rebooting.\n");
524                 ui->EndMenu();
525                 return 0; // XXX fixme
526             }
527         }
528 
529         int action = device->HandleMenuKey(key, visible);
530 
531         if (action < 0) {
532             switch (action) {
533                 case Device::kHighlightUp:
534                     selected = ui->SelectMenu(--selected);
535                     break;
536                 case Device::kHighlightDown:
537                     selected = ui->SelectMenu(++selected);
538                     break;
539                 case Device::kInvokeItem:
540                     chosen_item = selected;
541                     break;
542                 case Device::kNoAction:
543                     break;
544             }
545         } else if (!menu_only) {
546             chosen_item = action;
547         }
548     }
549 
550     ui->EndMenu();
551     return chosen_item;
552 }
553 
compare_string(const void * a,const void * b)554 static int compare_string(const void* a, const void* b) {
555     return strcmp(*(const char**)a, *(const char**)b);
556 }
557 
558 // Returns a malloc'd path, or NULL.
browse_directory(const char * path,Device * device)559 static char* browse_directory(const char* path, Device* device) {
560     ensure_path_mounted(path);
561 
562     DIR* d = opendir(path);
563     if (d == NULL) {
564         LOGE("error opening %s: %s\n", path, strerror(errno));
565         return NULL;
566     }
567 
568     int d_size = 0;
569     int d_alloc = 10;
570     char** dirs = (char**)malloc(d_alloc * sizeof(char*));
571     int z_size = 1;
572     int z_alloc = 10;
573     char** zips = (char**)malloc(z_alloc * sizeof(char*));
574     zips[0] = strdup("../");
575 
576     struct dirent* de;
577     while ((de = readdir(d)) != NULL) {
578         int name_len = strlen(de->d_name);
579 
580         if (de->d_type == DT_DIR) {
581             // skip "." and ".." entries
582             if (name_len == 1 && de->d_name[0] == '.') continue;
583             if (name_len == 2 && de->d_name[0] == '.' &&
584                 de->d_name[1] == '.') continue;
585 
586             if (d_size >= d_alloc) {
587                 d_alloc *= 2;
588                 dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
589             }
590             dirs[d_size] = (char*)malloc(name_len + 2);
591             strcpy(dirs[d_size], de->d_name);
592             dirs[d_size][name_len] = '/';
593             dirs[d_size][name_len+1] = '\0';
594             ++d_size;
595         } else if (de->d_type == DT_REG &&
596                    name_len >= 4 &&
597                    strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
598             if (z_size >= z_alloc) {
599                 z_alloc *= 2;
600                 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
601             }
602             zips[z_size++] = strdup(de->d_name);
603         }
604     }
605     closedir(d);
606 
607     qsort(dirs, d_size, sizeof(char*), compare_string);
608     qsort(zips, z_size, sizeof(char*), compare_string);
609 
610     // append dirs to the zips list
611     if (d_size + z_size + 1 > z_alloc) {
612         z_alloc = d_size + z_size + 1;
613         zips = (char**)realloc(zips, z_alloc * sizeof(char*));
614     }
615     memcpy(zips + z_size, dirs, d_size * sizeof(char*));
616     free(dirs);
617     z_size += d_size;
618     zips[z_size] = NULL;
619 
620     const char* headers[] = { "Choose a package to install:", path, NULL };
621 
622     char* result;
623     int chosen_item = 0;
624     while (true) {
625         chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
626 
627         char* item = zips[chosen_item];
628         int item_len = strlen(item);
629         if (chosen_item == 0) {          // item 0 is always "../"
630             // go up but continue browsing (if the caller is update_directory)
631             result = NULL;
632             break;
633         }
634 
635         char new_path[PATH_MAX];
636         strlcpy(new_path, path, PATH_MAX);
637         strlcat(new_path, "/", PATH_MAX);
638         strlcat(new_path, item, PATH_MAX);
639 
640         if (item[item_len-1] == '/') {
641             // recurse down into a subdirectory
642             new_path[strlen(new_path)-1] = '\0';  // truncate the trailing '/'
643             result = browse_directory(new_path, device);
644             if (result) break;
645         } else {
646             // selected a zip file: return the malloc'd path to the caller.
647             result = strdup(new_path);
648             break;
649         }
650     }
651 
652     for (int i = 0; i < z_size; ++i) free(zips[i]);
653     free(zips);
654 
655     return result;
656 }
657 
yes_no(Device * device,const char * question1,const char * question2)658 static bool yes_no(Device* device, const char* question1, const char* question2) {
659     const char* headers[] = { question1, question2, NULL };
660     const char* items[] = { " No", " Yes", NULL };
661 
662     int chosen_item = get_menu_selection(headers, items, 1, 0, device);
663     return (chosen_item == 1);
664 }
665 
666 // Return true on success.
wipe_data(int should_confirm,Device * device)667 static bool wipe_data(int should_confirm, Device* device) {
668     if (should_confirm && !yes_no(device, "Wipe all user data?", "  THIS CAN NOT BE UNDONE!")) {
669         return false;
670     }
671 
672     modified_flash = true;
673 
674     ui->Print("\n-- Wiping data...\n");
675     bool success =
676         device->PreWipeData() &&
677         erase_volume("/data") &&
678         erase_volume("/cache") &&
679         device->PostWipeData();
680     ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
681     return success;
682 }
683 
684 // Return true on success.
wipe_cache(bool should_confirm,Device * device)685 static bool wipe_cache(bool should_confirm, Device* device) {
686     if (should_confirm && !yes_no(device, "Wipe cache?", "  THIS CAN NOT BE UNDONE!")) {
687         return false;
688     }
689 
690     modified_flash = true;
691 
692     ui->Print("\n-- Wiping cache...\n");
693     bool success = erase_volume("/cache");
694     ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
695     return success;
696 }
697 
choose_recovery_file(Device * device)698 static void choose_recovery_file(Device* device) {
699     // "Back" + KEEP_LOG_COUNT * 2 + terminating nullptr entry
700     char* entries[1 + KEEP_LOG_COUNT * 2 + 1];
701     memset(entries, 0, sizeof(entries));
702 
703     unsigned int n = 0;
704 
705     // Add LAST_LOG_FILE + LAST_LOG_FILE.x
706     // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
707     for (int i = 0; i < KEEP_LOG_COUNT; i++) {
708         char* log_file;
709         if (asprintf(&log_file, (i == 0) ? "%s" : "%s.%d", LAST_LOG_FILE, i) == -1) {
710             // memory allocation failure - return early. Should never happen.
711             return;
712         }
713         if ((ensure_path_mounted(log_file) != 0) || (access(log_file, R_OK) == -1)) {
714             free(log_file);
715         } else {
716             entries[n++] = log_file;
717         }
718 
719         char* kmsg_file;
720         if (asprintf(&kmsg_file, (i == 0) ? "%s" : "%s.%d", LAST_KMSG_FILE, i) == -1) {
721             // memory allocation failure - return early. Should never happen.
722             return;
723         }
724         if ((ensure_path_mounted(kmsg_file) != 0) || (access(kmsg_file, R_OK) == -1)) {
725             free(kmsg_file);
726         } else {
727             entries[n++] = kmsg_file;
728         }
729     }
730 
731     entries[n++] = strdup("Back");
732 
733     const char* headers[] = { "Select file to view", nullptr };
734 
735     while (true) {
736         int chosen_item = get_menu_selection(headers, entries, 1, 0, device);
737         if (strcmp(entries[chosen_item], "Back") == 0) break;
738 
739         // TODO: do we need to redirect? ShowFile could just avoid writing to stdio.
740         redirect_stdio("/dev/null");
741         ui->ShowFile(entries[chosen_item]);
742         redirect_stdio(TEMPORARY_LOG_FILE);
743     }
744 
745     for (size_t i = 0; i < (sizeof(entries) / sizeof(*entries)); i++) {
746         free(entries[i]);
747     }
748 }
749 
apply_from_sdcard(Device * device,bool * wipe_cache)750 static int apply_from_sdcard(Device* device, bool* wipe_cache) {
751     modified_flash = true;
752 
753     if (ensure_path_mounted(SDCARD_ROOT) != 0) {
754         ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
755         return INSTALL_ERROR;
756     }
757 
758     char* path = browse_directory(SDCARD_ROOT, device);
759     if (path == NULL) {
760         ui->Print("\n-- No package file selected.\n");
761         return INSTALL_ERROR;
762     }
763 
764     ui->Print("\n-- Install %s ...\n", path);
765     set_sdcard_update_bootloader_message();
766     void* token = start_sdcard_fuse(path);
767 
768     int status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
769                                  TEMPORARY_INSTALL_FILE, false);
770 
771     finish_sdcard_fuse(token);
772     ensure_path_unmounted(SDCARD_ROOT);
773     return status;
774 }
775 
776 // Return REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER.  Returning NO_ACTION
777 // means to take the default, which is to reboot or shutdown depending
778 // on if the --shutdown_after flag was passed to recovery.
779 static Device::BuiltinAction
prompt_and_wait(Device * device,int status)780 prompt_and_wait(Device* device, int status) {
781     for (;;) {
782         finish_recovery(NULL);
783         switch (status) {
784             case INSTALL_SUCCESS:
785             case INSTALL_NONE:
786                 ui->SetBackground(RecoveryUI::NO_COMMAND);
787                 break;
788 
789             case INSTALL_ERROR:
790             case INSTALL_CORRUPT:
791                 ui->SetBackground(RecoveryUI::ERROR);
792                 break;
793         }
794         ui->SetProgressType(RecoveryUI::EMPTY);
795 
796         int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), 0, 0, device);
797 
798         // device-specific code may take some action here.  It may
799         // return one of the core actions handled in the switch
800         // statement below.
801         Device::BuiltinAction chosen_action = device->InvokeMenuItem(chosen_item);
802 
803         bool should_wipe_cache = false;
804         switch (chosen_action) {
805             case Device::NO_ACTION:
806                 break;
807 
808             case Device::REBOOT:
809             case Device::SHUTDOWN:
810             case Device::REBOOT_BOOTLOADER:
811                 return chosen_action;
812 
813             case Device::WIPE_DATA:
814                 wipe_data(ui->IsTextVisible(), device);
815                 if (!ui->IsTextVisible()) return Device::NO_ACTION;
816                 break;
817 
818             case Device::WIPE_CACHE:
819                 wipe_cache(ui->IsTextVisible(), device);
820                 if (!ui->IsTextVisible()) return Device::NO_ACTION;
821                 break;
822 
823             case Device::APPLY_ADB_SIDELOAD:
824             case Device::APPLY_SDCARD:
825                 {
826                     bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
827                     if (adb) {
828                         status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
829                     } else {
830                         status = apply_from_sdcard(device, &should_wipe_cache);
831                     }
832 
833                     if (status == INSTALL_SUCCESS && should_wipe_cache) {
834                         if (!wipe_cache(false, device)) {
835                             status = INSTALL_ERROR;
836                         }
837                     }
838 
839                     if (status != INSTALL_SUCCESS) {
840                         ui->SetBackground(RecoveryUI::ERROR);
841                         ui->Print("Installation aborted.\n");
842                         copy_logs();
843                     } else if (!ui->IsTextVisible()) {
844                         return Device::NO_ACTION;  // reboot if logs aren't visible
845                     } else {
846                         ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
847                     }
848                 }
849                 break;
850 
851             case Device::VIEW_RECOVERY_LOGS:
852                 choose_recovery_file(device);
853                 break;
854 
855             case Device::MOUNT_SYSTEM:
856                 if (ensure_path_mounted("/system") != -1) {
857                     ui->Print("Mounted /system.\n");
858                 }
859                 break;
860         }
861     }
862 }
863 
864 static void
print_property(const char * key,const char * name,void * cookie)865 print_property(const char *key, const char *name, void *cookie) {
866     printf("%s=%s\n", key, name);
867 }
868 
869 static void
load_locale_from_cache()870 load_locale_from_cache() {
871     FILE* fp = fopen_path(LOCALE_FILE, "r");
872     char buffer[80];
873     if (fp != NULL) {
874         fgets(buffer, sizeof(buffer), fp);
875         int j = 0;
876         unsigned int i;
877         for (i = 0; i < sizeof(buffer) && buffer[i]; ++i) {
878             if (!isspace(buffer[i])) {
879                 buffer[j++] = buffer[i];
880             }
881         }
882         buffer[j] = 0;
883         locale = strdup(buffer);
884         check_and_fclose(fp, LOCALE_FILE);
885     }
886 }
887 
888 static RecoveryUI* gCurrentUI = NULL;
889 
890 void
ui_print(const char * format,...)891 ui_print(const char* format, ...) {
892     char buffer[256];
893 
894     va_list ap;
895     va_start(ap, format);
896     vsnprintf(buffer, sizeof(buffer), format, ap);
897     va_end(ap);
898 
899     if (gCurrentUI != NULL) {
900         gCurrentUI->Print("%s", buffer);
901     } else {
902         fputs(buffer, stdout);
903     }
904 }
905 
906 int
main(int argc,char ** argv)907 main(int argc, char **argv) {
908     time_t start = time(NULL);
909 
910     redirect_stdio(TEMPORARY_LOG_FILE);
911 
912     // If this binary is started with the single argument "--adbd",
913     // instead of being the normal recovery binary, it turns into kind
914     // of a stripped-down version of adbd that only supports the
915     // 'sideload' command.  Note this must be a real argument, not
916     // anything in the command file or bootloader control block; the
917     // only way recovery should be run with this argument is when it
918     // starts a copy of itself from the apply_from_adb() function.
919     if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
920         adb_main(0, DEFAULT_ADB_PORT);
921         return 0;
922     }
923 
924     printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
925 
926     load_volume_table();
927     get_args(&argc, &argv);
928 
929     const char *send_intent = NULL;
930     const char *update_package = NULL;
931     bool should_wipe_data = false;
932     bool should_wipe_cache = false;
933     bool show_text = false;
934     bool sideload = false;
935     bool sideload_auto_reboot = false;
936     bool just_exit = false;
937     bool shutdown_after = false;
938 
939     int arg;
940     while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
941         switch (arg) {
942         case 'i': send_intent = optarg; break;
943         case 'u': update_package = optarg; break;
944         case 'w': should_wipe_data = true; break;
945         case 'c': should_wipe_cache = true; break;
946         case 't': show_text = true; break;
947         case 's': sideload = true; break;
948         case 'a': sideload = true; sideload_auto_reboot = true; break;
949         case 'x': just_exit = true; break;
950         case 'l': locale = optarg; break;
951         case 'g': {
952             if (stage == NULL || *stage == '\0') {
953                 char buffer[20] = "1/";
954                 strncat(buffer, optarg, sizeof(buffer)-3);
955                 stage = strdup(buffer);
956             }
957             break;
958         }
959         case 'p': shutdown_after = true; break;
960         case 'r': reason = optarg; break;
961         case '?':
962             LOGE("Invalid command argument\n");
963             continue;
964         }
965     }
966 
967     if (locale == NULL) {
968         load_locale_from_cache();
969     }
970     printf("locale is [%s]\n", locale);
971     printf("stage is [%s]\n", stage);
972     printf("reason is [%s]\n", reason);
973 
974     Device* device = make_device();
975     ui = device->GetUI();
976     gCurrentUI = ui;
977 
978     ui->SetLocale(locale);
979     ui->Init();
980 
981     int st_cur, st_max;
982     if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
983         ui->SetStage(st_cur, st_max);
984     }
985 
986     ui->SetBackground(RecoveryUI::NONE);
987     if (show_text) ui->ShowText(true);
988 
989     struct selinux_opt seopts[] = {
990       { SELABEL_OPT_PATH, "/file_contexts" }
991     };
992 
993     sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
994 
995     if (!sehandle) {
996         ui->Print("Warning: No file_contexts\n");
997     }
998 
999     device->StartRecovery();
1000 
1001     printf("Command:");
1002     for (arg = 0; arg < argc; arg++) {
1003         printf(" \"%s\"", argv[arg]);
1004     }
1005     printf("\n");
1006 
1007     if (update_package) {
1008         // For backwards compatibility on the cache partition only, if
1009         // we're given an old 'root' path "CACHE:foo", change it to
1010         // "/cache/foo".
1011         if (strncmp(update_package, "CACHE:", 6) == 0) {
1012             int len = strlen(update_package) + 10;
1013             char* modified_path = (char*)malloc(len);
1014             strlcpy(modified_path, "/cache/", len);
1015             strlcat(modified_path, update_package+6, len);
1016             printf("(replacing path \"%s\" with \"%s\")\n",
1017                    update_package, modified_path);
1018             update_package = modified_path;
1019         }
1020     }
1021     printf("\n");
1022 
1023     property_list(print_property, NULL);
1024     printf("\n");
1025 
1026     ui->Print("Supported API: %d\n", RECOVERY_API_VERSION);
1027 
1028     int status = INSTALL_SUCCESS;
1029 
1030     if (update_package != NULL) {
1031         status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true);
1032         if (status == INSTALL_SUCCESS && should_wipe_cache) {
1033             wipe_cache(false, device);
1034         }
1035         if (status != INSTALL_SUCCESS) {
1036             ui->Print("Installation aborted.\n");
1037 
1038             // If this is an eng or userdebug build, then automatically
1039             // turn the text display on if the script fails so the error
1040             // message is visible.
1041             if (is_ro_debuggable()) {
1042                 ui->ShowText(true);
1043             }
1044         }
1045     } else if (should_wipe_data) {
1046         if (!wipe_data(false, device)) {
1047             status = INSTALL_ERROR;
1048         }
1049     } else if (should_wipe_cache) {
1050         if (!wipe_cache(false, device)) {
1051             status = INSTALL_ERROR;
1052         }
1053     } else if (sideload) {
1054         // 'adb reboot sideload' acts the same as user presses key combinations
1055         // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1056         // display will NOT be turned on by default. And it will reboot after
1057         // sideload finishes even if there are errors. Unless one turns on the
1058         // text display during the installation. This is to enable automated
1059         // testing.
1060         if (!sideload_auto_reboot) {
1061             ui->ShowText(true);
1062         }
1063         status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
1064         if (status == INSTALL_SUCCESS && should_wipe_cache) {
1065             if (!wipe_cache(false, device)) {
1066                 status = INSTALL_ERROR;
1067             }
1068         }
1069         ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1070         if (sideload_auto_reboot) {
1071             ui->Print("Rebooting automatically.\n");
1072         }
1073     } else if (!just_exit) {
1074         status = INSTALL_NONE;  // No command specified
1075         ui->SetBackground(RecoveryUI::NO_COMMAND);
1076 
1077         // http://b/17489952
1078         // If this is an eng or userdebug build, automatically turn on the
1079         // text display if no command is specified.
1080         if (is_ro_debuggable()) {
1081             ui->ShowText(true);
1082         }
1083     }
1084 
1085     if (!sideload_auto_reboot && (status == INSTALL_ERROR || status == INSTALL_CORRUPT)) {
1086         copy_logs();
1087         ui->SetBackground(RecoveryUI::ERROR);
1088     }
1089 
1090     Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1091     if ((status != INSTALL_SUCCESS && !sideload_auto_reboot) || ui->IsTextVisible()) {
1092         Device::BuiltinAction temp = prompt_and_wait(device, status);
1093         if (temp != Device::NO_ACTION) {
1094             after = temp;
1095         }
1096     }
1097 
1098     // Save logs and clean up before rebooting or shutting down.
1099     finish_recovery(send_intent);
1100 
1101     switch (after) {
1102         case Device::SHUTDOWN:
1103             ui->Print("Shutting down...\n");
1104             property_set(ANDROID_RB_PROPERTY, "shutdown,");
1105             break;
1106 
1107         case Device::REBOOT_BOOTLOADER:
1108             ui->Print("Rebooting to bootloader...\n");
1109             property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
1110             break;
1111 
1112         default:
1113             ui->Print("Rebooting...\n");
1114             property_set(ANDROID_RB_PROPERTY, "reboot,");
1115             break;
1116     }
1117     sleep(5); // should reboot before this finishes
1118     return EXIT_SUCCESS;
1119 }
1120