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 "recovery.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <linux/input.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 
31 #include <functional>
32 #include <iterator>
33 #include <memory>
34 #include <string>
35 #include <vector>
36 
37 #include <android-base/file.h>
38 #include <android-base/logging.h>
39 #include <android-base/parseint.h>
40 #include <android-base/properties.h>
41 #include <android-base/stringprintf.h>
42 #include <android-base/strings.h>
43 #include <cutils/properties.h> /* for property_list */
44 #include <fs_mgr/roots.h>
45 #include <ziparchive/zip_archive.h>
46 
47 #include "bootloader_message/bootloader_message.h"
48 #include "install/adb_install.h"
49 #include "install/fuse_install.h"
50 #include "install/install.h"
51 #include "install/package.h"
52 #include "install/snapshot_utils.h"
53 #include "install/wipe_data.h"
54 #include "install/wipe_device.h"
55 #include "otautil/boot_state.h"
56 #include "otautil/error_code.h"
57 #include "otautil/paths.h"
58 #include "otautil/sysutil.h"
59 #include "recovery_ui/screen_ui.h"
60 #include "recovery_ui/ui.h"
61 #include "recovery_utils/battery_utils.h"
62 #include "recovery_utils/logging.h"
63 #include "recovery_utils/roots.h"
64 
65 static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
66 static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
67 static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
68 static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
69 
70 static constexpr const char* CACHE_ROOT = "/cache";
71 
72 static bool save_current_log = false;
73 
74 /*
75  * The recovery tool communicates with the main system through /cache files.
76  *   /cache/recovery/command - INPUT - command line for tool, one arg per line
77  *   /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
78  *
79  * The arguments which may be supplied in the recovery.command file:
80  *   --update_package=path - verify install an OTA package file
81  *   --install_with_fuse - install the update package with FUSE. This allows installation of large
82  *       packages on LP32 builds. Since the mmap will otherwise fail due to out of memory.
83  *   --wipe_data - erase user data (and cache), then reboot
84  *   --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
85  *       data (and cache), then reboot
86  *   --wipe_cache - wipe cache (but not user data), then reboot
87  *   --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
88  *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
89  *   --just_exit - do nothing; exit and reboot
90  *
91  * After completing, we remove /cache/recovery/command and reboot.
92  * Arguments may also be supplied in the bootloader control block (BCB).
93  * These important scenarios must be safely restartable at any point:
94  *
95  * FACTORY RESET
96  * 1. user selects "factory reset"
97  * 2. main system writes "--wipe_data" to /cache/recovery/command
98  * 3. main system reboots into recovery
99  * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
100  *    -- after this, rebooting will restart the erase --
101  * 5. erase_volume() reformats /data
102  * 6. erase_volume() reformats /cache
103  * 7. FinishRecovery() erases BCB
104  *    -- after this, rebooting will restart the main system --
105  * 8. main() calls reboot() to boot main system
106  *
107  * OTA INSTALL
108  * 1. main system downloads OTA package to /cache/some-filename.zip
109  * 2. main system writes "--update_package=/cache/some-filename.zip"
110  * 3. main system reboots into recovery
111  * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
112  *    -- after this, rebooting will attempt to reinstall the update --
113  * 5. InstallPackage() attempts to install the update
114  *    NOTE: the package install must itself be restartable from any point
115  * 6. FinishRecovery() erases BCB
116  *    -- after this, rebooting will (try to) restart the main system --
117  * 7. ** if install failed **
118  *    7a. PromptAndWait() shows an error icon and waits for the user
119  *    7b. the user reboots (pulling the battery, etc) into the main system
120  */
121 
IsRoDebuggable()122 static bool IsRoDebuggable() {
123   return android::base::GetBoolProperty("ro.debuggable", false);
124 }
125 
126 // Clear the recovery command and prepare to boot a (hopefully working) system,
127 // copy our log file to cache as well (for the system to read). This function is
128 // idempotent: call it as many times as you like.
FinishRecovery(RecoveryUI * ui)129 static void FinishRecovery(RecoveryUI* ui) {
130   std::string locale = ui->GetLocale();
131   // Save the locale to cache, so if recovery is next started up without a '--locale' argument
132   // (e.g., directly from the bootloader) it will use the last-known locale.
133   if (!locale.empty() && HasCache()) {
134     LOG(INFO) << "Saving locale \"" << locale << "\"";
135     if (ensure_path_mounted(LOCALE_FILE) != 0) {
136       LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
137     } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
138       PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
139     }
140   }
141 
142   copy_logs(save_current_log);
143 
144   // Reset to normal system boot so recovery won't cycle indefinitely.
145   std::string err;
146   if (!clear_bootloader_message(&err)) {
147     LOG(ERROR) << "Failed to clear BCB message: " << err;
148   }
149 
150   // Remove the command file, so recovery won't repeat indefinitely.
151   if (HasCache()) {
152     if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
153       LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
154     }
155     ensure_path_unmounted(CACHE_ROOT);
156   }
157 
158   sync();  // For good measure.
159 }
160 
yes_no(Device * device,const char * question1,const char * question2)161 static bool yes_no(Device* device, const char* question1, const char* question2) {
162   std::vector<std::string> headers{ question1, question2 };
163   std::vector<std::string> items{ " No", " Yes" };
164 
165   size_t chosen_item = device->GetUI()->ShowMenu(
166       headers, items, 0, true,
167       std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
168   return (chosen_item == 1);
169 }
170 
ask_to_wipe_data(Device * device)171 static bool ask_to_wipe_data(Device* device) {
172   std::vector<std::string> headers{ "Wipe all user data?", "  THIS CAN NOT BE UNDONE!" };
173   std::vector<std::string> items{ " Cancel", " Factory data reset" };
174 
175   size_t chosen_item = device->GetUI()->ShowPromptWipeDataConfirmationMenu(
176       headers, items,
177       std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
178 
179   return (chosen_item == 1);
180 }
181 
prompt_and_wipe_data(Device * device)182 static InstallResult prompt_and_wipe_data(Device* device) {
183   // Use a single string and let ScreenRecoveryUI handles the wrapping.
184   std::vector<std::string> wipe_data_menu_headers{
185     "Can't load Android system. Your data may be corrupt. "
186     "If you continue to get this message, you may need to "
187     "perform a factory data reset and erase all user data "
188     "stored on this device.",
189   };
190   // clang-format off
191   std::vector<std::string> wipe_data_menu_items {
192     "Try again",
193     "Factory data reset",
194   };
195   // clang-format on
196   for (;;) {
197     size_t chosen_item = device->GetUI()->ShowPromptWipeDataMenu(
198         wipe_data_menu_headers, wipe_data_menu_items,
199         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
200     // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
201     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
202       return INSTALL_KEY_INTERRUPTED;
203     }
204     if (chosen_item != 1) {
205       return INSTALL_SUCCESS;  // Just reboot, no wipe; not a failure, user asked for it
206     }
207 
208     if (ask_to_wipe_data(device)) {
209       CHECK(device->GetReason().has_value());
210       bool convert_fbe = device->GetReason().value() == "convert_fbe";
211       if (WipeData(device, convert_fbe)) {
212         return INSTALL_SUCCESS;
213       } else {
214         return INSTALL_ERROR;
215       }
216     }
217   }
218 }
219 
choose_recovery_file(Device * device)220 static void choose_recovery_file(Device* device) {
221   std::vector<std::string> entries;
222   if (HasCache()) {
223     for (int i = 0; i < KEEP_LOG_COUNT; i++) {
224       auto add_to_entries = [&](const char* filename) {
225         std::string log_file(filename);
226         if (i > 0) {
227           log_file += "." + std::to_string(i);
228         }
229 
230         if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
231           entries.push_back(std::move(log_file));
232         }
233       };
234 
235       // Add LAST_LOG_FILE + LAST_LOG_FILE.x
236       add_to_entries(LAST_LOG_FILE);
237 
238       // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
239       add_to_entries(LAST_KMSG_FILE);
240     }
241   } else {
242     // If cache partition is not found, view /tmp/recovery.log instead.
243     if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
244       return;
245     } else {
246       entries.push_back(Paths::Get().temporary_log_file());
247     }
248   }
249 
250   entries.push_back("Back");
251 
252   std::vector<std::string> headers{ "Select file to view" };
253 
254   size_t chosen_item = 0;
255   while (true) {
256     chosen_item = device->GetUI()->ShowMenu(
257         headers, entries, chosen_item, true,
258         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
259 
260     // Handle WaitKey() interrupt.
261     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
262       break;
263     }
264     if (entries[chosen_item] == "Back") break;
265 
266     device->GetUI()->ShowFile(entries[chosen_item]);
267   }
268 }
269 
run_graphics_test(RecoveryUI * ui)270 static void run_graphics_test(RecoveryUI* ui) {
271   // Switch to graphics screen.
272   ui->ShowText(false);
273 
274   ui->SetProgressType(RecoveryUI::INDETERMINATE);
275   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
276   sleep(1);
277 
278   ui->SetBackground(RecoveryUI::ERROR);
279   sleep(1);
280 
281   ui->SetBackground(RecoveryUI::NO_COMMAND);
282   sleep(1);
283 
284   ui->SetBackground(RecoveryUI::ERASING);
285   sleep(1);
286 
287   // Calling SetBackground() after SetStage() to trigger a redraw.
288   ui->SetStage(1, 3);
289   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
290   sleep(1);
291   ui->SetStage(2, 3);
292   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
293   sleep(1);
294   ui->SetStage(3, 3);
295   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
296   sleep(1);
297 
298   ui->SetStage(-1, -1);
299   ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
300 
301   ui->SetProgressType(RecoveryUI::DETERMINATE);
302   ui->ShowProgress(1.0, 10.0);
303   float fraction = 0.0;
304   for (size_t i = 0; i < 100; ++i) {
305     fraction += .01;
306     ui->SetProgress(fraction);
307     usleep(100000);
308   }
309 
310   ui->ShowText(true);
311 }
312 
WriteUpdateInProgress()313 static void WriteUpdateInProgress() {
314   std::string err;
315   if (!update_bootloader_message({ "--reason=update_in_progress" }, &err)) {
316     LOG(ERROR) << "Failed to WriteUpdateInProgress: " << err;
317   }
318 }
319 
AskToReboot(Device * device,Device::BuiltinAction chosen_action)320 static bool AskToReboot(Device* device, Device::BuiltinAction chosen_action) {
321   bool is_non_ab = android::base::GetProperty("ro.boot.slot_suffix", "").empty();
322   bool is_virtual_ab = android::base::GetBoolProperty("ro.virtual_ab.enabled", false);
323   if (!is_non_ab && !is_virtual_ab) {
324     // Only prompt for non-A/B or Virtual A/B devices.
325     return true;
326   }
327 
328   std::string header_text;
329   std::string item_text;
330   switch (chosen_action) {
331     case Device::REBOOT:
332       header_text = "reboot";
333       item_text = " Reboot system now";
334       break;
335     case Device::SHUTDOWN:
336       header_text = "power off";
337       item_text = " Power off";
338       break;
339     default:
340       LOG(FATAL) << "Invalid chosen action " << chosen_action;
341       break;
342   }
343 
344   std::vector<std::string> headers{ "WARNING: Previous installation has failed.",
345                                     "  Your device may fail to boot if you " + header_text +
346                                         " now.",
347                                     "  Confirm reboot?" };
348   std::vector<std::string> items{ " Cancel", item_text };
349 
350   size_t chosen_item = device->GetUI()->ShowMenu(
351       headers, items, 0, true /* menu_only */,
352       std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
353 
354   return (chosen_item == 1);
355 }
356 
357 // Shows the recovery UI and waits for user input. Returns one of the device builtin actions, such
358 // as REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default, which
359 // is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
PromptAndWait(Device * device,InstallResult status)360 static Device::BuiltinAction PromptAndWait(Device* device, InstallResult status) {
361   auto ui = device->GetUI();
362   bool update_in_progress = (device->GetReason().value_or("") == "update_in_progress");
363   for (;;) {
364     FinishRecovery(ui);
365     switch (status) {
366       case INSTALL_SUCCESS:
367       case INSTALL_NONE:
368       case INSTALL_SKIPPED:
369       case INSTALL_RETRY:
370       case INSTALL_KEY_INTERRUPTED:
371         ui->SetBackground(RecoveryUI::NO_COMMAND);
372         break;
373 
374       case INSTALL_ERROR:
375       case INSTALL_CORRUPT:
376         ui->SetBackground(RecoveryUI::ERROR);
377         break;
378 
379       case INSTALL_REBOOT:
380         // All the reboots should have been handled prior to entering PromptAndWait() or immediately
381         // after installing a package.
382         LOG(FATAL) << "Invalid status code of INSTALL_REBOOT";
383         break;
384     }
385     ui->SetProgressType(RecoveryUI::EMPTY);
386 
387     std::vector<std::string> headers;
388     if (update_in_progress) {
389       headers = { "WARNING: Previous installation has failed.",
390                   "  Your device may fail to boot if you reboot or power off now." };
391     }
392 
393     size_t chosen_item = ui->ShowMenu(
394         headers, device->GetMenuItems(), 0, false,
395         std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
396     // Handle Interrupt key
397     if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
398       return Device::KEY_INTERRUPTED;
399     }
400     // Device-specific code may take some action here. It may return one of the core actions
401     // handled in the switch statement below.
402     Device::BuiltinAction chosen_action =
403         (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
404             ? Device::REBOOT
405             : device->InvokeMenuItem(chosen_item);
406 
407     switch (chosen_action) {
408       case Device::REBOOT_FROM_FASTBOOT:    // Can not happen
409       case Device::SHUTDOWN_FROM_FASTBOOT:  // Can not happen
410       case Device::NO_ACTION:
411         break;
412 
413       case Device::ENTER_FASTBOOT:
414       case Device::ENTER_RECOVERY:
415       case Device::REBOOT_BOOTLOADER:
416       case Device::REBOOT_FASTBOOT:
417       case Device::REBOOT_RECOVERY:
418       case Device::REBOOT_RESCUE:
419         return chosen_action;
420 
421       case Device::REBOOT:
422       case Device::SHUTDOWN:
423         if (!ui->IsTextVisible()) {
424           return Device::REBOOT;
425         }
426         // okay to reboot; no need to ask.
427         if (!update_in_progress) {
428           return Device::REBOOT;
429         }
430         // An update might have been failed. Ask if user really wants to reboot.
431         if (AskToReboot(device, chosen_action)) {
432           return Device::REBOOT;
433         }
434         break;
435 
436       case Device::WIPE_DATA:
437         save_current_log = true;
438         if (ui->IsTextVisible()) {
439           if (ask_to_wipe_data(device)) {
440             WipeData(device, false);
441           }
442         } else {
443           WipeData(device, false);
444           return Device::NO_ACTION;
445         }
446         break;
447 
448       case Device::WIPE_CACHE: {
449         save_current_log = true;
450         std::function<bool()> confirm_func = [&device]() {
451           return yes_no(device, "Wipe cache?", "  THIS CAN NOT BE UNDONE!");
452         };
453         WipeCache(ui, ui->IsTextVisible() ? confirm_func : nullptr);
454         if (!ui->IsTextVisible()) return Device::NO_ACTION;
455         break;
456       }
457 
458       case Device::APPLY_ADB_SIDELOAD:
459       case Device::APPLY_SDCARD:
460       case Device::ENTER_RESCUE: {
461         save_current_log = true;
462 
463         update_in_progress = true;
464         WriteUpdateInProgress();
465 
466         bool adb = true;
467         Device::BuiltinAction reboot_action;
468         if (chosen_action == Device::ENTER_RESCUE) {
469           // Switch to graphics screen.
470           ui->ShowText(false);
471           status = ApplyFromAdb(device, true /* rescue_mode */, &reboot_action);
472         } else if (chosen_action == Device::APPLY_ADB_SIDELOAD) {
473           status = ApplyFromAdb(device, false /* rescue_mode */, &reboot_action);
474         } else {
475           adb = false;
476           status = ApplyFromSdcard(device);
477         }
478 
479         ui->Print("\nInstall from %s completed with status %d.\n", adb ? "ADB" : "SD card", status);
480         if (status == INSTALL_REBOOT) {
481           return reboot_action;
482         }
483 
484         if (status == INSTALL_SUCCESS) {
485           update_in_progress = false;
486           if (!ui->IsTextVisible()) {
487             return Device::NO_ACTION;  // reboot if logs aren't visible
488           }
489         } else {
490           ui->SetBackground(RecoveryUI::ERROR);
491           ui->Print("Installation aborted.\n");
492           copy_logs(save_current_log);
493         }
494         break;
495       }
496 
497       case Device::VIEW_RECOVERY_LOGS:
498         choose_recovery_file(device);
499         break;
500 
501       case Device::RUN_GRAPHICS_TEST:
502         run_graphics_test(ui);
503         break;
504 
505       case Device::RUN_LOCALE_TEST: {
506         ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
507         screen_ui->CheckBackgroundTextImages();
508         break;
509       }
510 
511       case Device::MOUNT_SYSTEM:
512         // For Virtual A/B, set up the snapshot devices (if exist).
513         if (!CreateSnapshotPartitions()) {
514           ui->Print("Virtual A/B: snapshot partitions creation failed.\n");
515           break;
516         }
517         if (ensure_path_mounted_at(android::fs_mgr::GetSystemRoot(), "/mnt/system") != -1) {
518           ui->Print("Mounted /system.\n");
519         }
520         break;
521 
522       case Device::KEY_INTERRUPTED:
523         return Device::KEY_INTERRUPTED;
524     }
525   }
526 }
527 
print_property(const char * key,const char * name,void *)528 static void print_property(const char* key, const char* name, void* /* cookie */) {
529   printf("%s=%s\n", key, name);
530 }
531 
IsBatteryOk(int * required_battery_level)532 static bool IsBatteryOk(int* required_battery_level) {
533   // GmsCore enters recovery mode to install package when having enough battery percentage.
534   // Normally, the threshold is 40% without charger and 20% with charger. So we check the battery
535   // level against a slightly lower limit.
536   constexpr int BATTERY_OK_PERCENTAGE = 20;
537   constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
538 
539   auto battery_info = GetBatteryInfo();
540   *required_battery_level =
541       battery_info.charging ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
542   return battery_info.capacity >= *required_battery_level;
543 }
544 
545 // Set the retry count to |retry_count| in BCB.
set_retry_bootloader_message(int retry_count,const std::vector<std::string> & args)546 static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
547   std::vector<std::string> options;
548   for (const auto& arg : args) {
549     if (!android::base::StartsWith(arg, "--retry_count")) {
550       options.push_back(arg);
551     }
552   }
553 
554   // Update the retry counter in BCB.
555   options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
556   std::string err;
557   if (!update_bootloader_message(options, &err)) {
558     LOG(ERROR) << err;
559   }
560 }
561 
bootreason_in_blocklist()562 static bool bootreason_in_blocklist() {
563   std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
564   if (!bootreason.empty()) {
565     // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
566     static const std::vector<std::string> kBootreasonBlocklist{
567       "kernel_panic",
568       "Panic",
569     };
570     for (const auto& str : kBootreasonBlocklist) {
571       if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
572     }
573   }
574   return false;
575 }
576 
log_failure_code(ErrorCode code,const std::string & update_package)577 static void log_failure_code(ErrorCode code, const std::string& update_package) {
578   std::vector<std::string> log_buffer = {
579     update_package,
580     "0",  // install result
581     "error: " + std::to_string(code),
582   };
583   std::string log_content = android::base::Join(log_buffer, "\n");
584   const std::string& install_file = Paths::Get().temporary_install_file();
585   if (!android::base::WriteStringToFile(log_content, install_file)) {
586     PLOG(ERROR) << "Failed to write " << install_file;
587   }
588 
589   // Also write the info into last_log.
590   LOG(INFO) << log_content;
591 }
592 
start_recovery(Device * device,const std::vector<std::string> & args)593 Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
594   static constexpr struct option OPTIONS[] = {
595     { "fastboot", no_argument, nullptr, 0 },
596     { "install_with_fuse", no_argument, nullptr, 0 },
597     { "just_exit", no_argument, nullptr, 'x' },
598     { "locale", required_argument, nullptr, 0 },
599     { "prompt_and_wipe_data", no_argument, nullptr, 0 },
600     { "reason", required_argument, nullptr, 0 },
601     { "rescue", no_argument, nullptr, 0 },
602     { "retry_count", required_argument, nullptr, 0 },
603     { "security", no_argument, nullptr, 0 },
604     { "show_text", no_argument, nullptr, 't' },
605     { "shutdown_after", no_argument, nullptr, 0 },
606     { "sideload", no_argument, nullptr, 0 },
607     { "sideload_auto_reboot", no_argument, nullptr, 0 },
608     { "update_package", required_argument, nullptr, 0 },
609     { "wipe_ab", no_argument, nullptr, 0 },
610     { "wipe_cache", no_argument, nullptr, 0 },
611     { "wipe_data", no_argument, nullptr, 0 },
612     { "wipe_package_size", required_argument, nullptr, 0 },
613     { nullptr, 0, nullptr, 0 },
614   };
615 
616   const char* update_package = nullptr;
617   bool install_with_fuse = false;  // memory map the update package by default.
618   bool should_wipe_data = false;
619   bool should_prompt_and_wipe_data = false;
620   bool should_wipe_cache = false;
621   bool should_wipe_ab = false;
622   size_t wipe_package_size = 0;
623   bool sideload = false;
624   bool sideload_auto_reboot = false;
625   bool rescue = false;
626   bool just_exit = false;
627   bool shutdown_after = false;
628   int retry_count = 0;
629   bool security_update = false;
630   std::string locale;
631 
632   auto args_to_parse = StringVectorToNullTerminatedArray(args);
633 
634   int arg;
635   int option_index;
636   // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
637   // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
638   // nullptr).
639   while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
640                             &option_index)) != -1) {
641     switch (arg) {
642       case 't':
643         // Handled in recovery_main.cpp
644         break;
645       case 'x':
646         just_exit = true;
647         break;
648       case 0: {
649         std::string option = OPTIONS[option_index].name;
650         if (option == "install_with_fuse") {
651           install_with_fuse = true;
652         } else if (option == "locale" || option == "fastboot" || option == "reason") {
653           // Handled in recovery_main.cpp
654         } else if (option == "prompt_and_wipe_data") {
655           should_prompt_and_wipe_data = true;
656         } else if (option == "rescue") {
657           rescue = true;
658         } else if (option == "retry_count") {
659           android::base::ParseInt(optarg, &retry_count, 0);
660         } else if (option == "security") {
661           security_update = true;
662         } else if (option == "sideload") {
663           sideload = true;
664         } else if (option == "sideload_auto_reboot") {
665           sideload = true;
666           sideload_auto_reboot = true;
667         } else if (option == "shutdown_after") {
668           shutdown_after = true;
669         } else if (option == "update_package") {
670           update_package = optarg;
671         } else if (option == "wipe_ab") {
672           should_wipe_ab = true;
673         } else if (option == "wipe_cache") {
674           should_wipe_cache = true;
675         } else if (option == "wipe_data") {
676           should_wipe_data = true;
677         } else if (option == "wipe_package_size") {
678           android::base::ParseUint(optarg, &wipe_package_size);
679         }
680         break;
681       }
682       case '?':
683         LOG(ERROR) << "Invalid command argument";
684         continue;
685     }
686   }
687   optind = 1;
688 
689   printf("stage is [%s]\n", device->GetStage().value_or("").c_str());
690   printf("reason is [%s]\n", device->GetReason().value_or("").c_str());
691 
692   auto ui = device->GetUI();
693 
694   // Set background string to "installing security update" for security update,
695   // otherwise set it to "installing system update".
696   ui->SetSystemUpdateText(security_update);
697 
698   int st_cur, st_max;
699   if (!device->GetStage().has_value() &&
700       sscanf(device->GetStage().value().c_str(), "%d/%d", &st_cur, &st_max) == 2) {
701     ui->SetStage(st_cur, st_max);
702   }
703 
704   std::vector<std::string> title_lines =
705       android::base::Split(android::base::GetProperty("ro.build.fingerprint", ""), ":");
706   title_lines.insert(std::begin(title_lines), "Android Recovery");
707   ui->SetTitle(title_lines);
708 
709   ui->ResetKeyInterruptStatus();
710   device->StartRecovery();
711 
712   printf("Command:");
713   for (const auto& arg : args) {
714     printf(" \"%s\"", arg.c_str());
715   }
716   printf("\n\n");
717 
718   property_list(print_property, nullptr);
719   printf("\n");
720 
721   InstallResult status = INSTALL_SUCCESS;
722   // next_action indicates the next target to reboot into upon finishing the install. It could be
723   // overridden to a different reboot target per user request.
724   Device::BuiltinAction next_action = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
725 
726   if (update_package != nullptr) {
727     // It's not entirely true that we will modify the flash. But we want
728     // to log the update attempt since update_package is non-NULL.
729     save_current_log = true;
730 
731     if (int required_battery_level; retry_count == 0 && !IsBatteryOk(&required_battery_level)) {
732       ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
733                 required_battery_level);
734       // Log the error code to last_install when installation skips due to low battery.
735       log_failure_code(kLowBattery, update_package);
736       status = INSTALL_SKIPPED;
737     } else if (retry_count == 0 && bootreason_in_blocklist()) {
738       // Skip update-on-reboot when bootreason is kernel_panic or similar
739       ui->Print("bootreason is in the blocklist; skip OTA installation\n");
740       log_failure_code(kBootreasonInBlocklist, update_package);
741       status = INSTALL_SKIPPED;
742     } else {
743       // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
744       // identify the interrupted update due to unexpected reboots.
745       if (retry_count == 0) {
746         set_retry_bootloader_message(retry_count + 1, args);
747       }
748 
749       if (update_package[0] == '@') {
750         ensure_path_mounted(update_package + 1);
751       } else {
752         ensure_path_mounted(update_package);
753       }
754 
755       bool should_use_fuse = false;
756       if (!SetupPackageMount(update_package, &should_use_fuse)) {
757         LOG(INFO) << "Failed to set up the package access, skipping installation";
758         status = INSTALL_ERROR;
759       } else if (install_with_fuse || should_use_fuse) {
760         LOG(INFO) << "Installing package " << update_package << " with fuse";
761         status = InstallWithFuseFromPath(update_package, ui);
762       } else if (auto memory_package = Package::CreateMemoryPackage(
763                      update_package,
764                      std::bind(&RecoveryUI::SetProgress, ui, std::placeholders::_1));
765                  memory_package != nullptr) {
766         status = InstallPackage(memory_package.get(), update_package, should_wipe_cache,
767                                 retry_count, ui);
768       } else {
769         // We may fail to memory map the package on 32 bit builds for packages with 2GiB+ size.
770         // In such cases, we will try to install the package with fuse. This is not the default
771         // installation method because it introduces a layer of indirection from the kernel space.
772         LOG(WARNING) << "Failed to memory map package " << update_package
773                      << "; falling back to install with fuse";
774         status = InstallWithFuseFromPath(update_package, ui);
775       }
776       if (status != INSTALL_SUCCESS) {
777         ui->Print("Installation aborted.\n");
778 
779         // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
780         // RETRY_LIMIT times before we abandon this OTA update.
781         static constexpr int RETRY_LIMIT = 4;
782         if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
783           copy_logs(save_current_log);
784           retry_count += 1;
785           set_retry_bootloader_message(retry_count, args);
786           // Print retry count on screen.
787           ui->Print("Retry attempt %d\n", retry_count);
788 
789           // Reboot back into recovery to retry the update.
790           Reboot("recovery");
791         }
792         // If this is an eng or userdebug build, then automatically
793         // turn the text display on if the script fails so the error
794         // message is visible.
795         if (IsRoDebuggable()) {
796           ui->ShowText(true);
797         }
798       }
799     }
800   } else if (should_wipe_data) {
801     save_current_log = true;
802     CHECK(device->GetReason().has_value());
803     bool convert_fbe = device->GetReason().value() == "convert_fbe";
804     if (!WipeData(device, convert_fbe)) {
805       status = INSTALL_ERROR;
806     }
807   } else if (should_prompt_and_wipe_data) {
808     // Trigger the logging to capture the cause, even if user chooses to not wipe data.
809     save_current_log = true;
810 
811     ui->ShowText(true);
812     ui->SetBackground(RecoveryUI::ERROR);
813     status = prompt_and_wipe_data(device);
814     if (status != INSTALL_KEY_INTERRUPTED) {
815       ui->ShowText(false);
816     }
817   } else if (should_wipe_cache) {
818     save_current_log = true;
819     if (!WipeCache(ui, nullptr)) {
820       status = INSTALL_ERROR;
821     }
822   } else if (should_wipe_ab) {
823     if (!WipeAbDevice(device, wipe_package_size)) {
824       status = INSTALL_ERROR;
825     }
826   } else if (sideload) {
827     // 'adb reboot sideload' acts the same as user presses key combinations to enter the sideload
828     // mode. When 'sideload-auto-reboot' is used, text display will NOT be turned on by default. And
829     // it will reboot after sideload finishes even if there are errors. This is to enable automated
830     // testing.
831     save_current_log = true;
832     if (!sideload_auto_reboot) {
833       ui->ShowText(true);
834     }
835     status = ApplyFromAdb(device, false /* rescue_mode */, &next_action);
836     ui->Print("\nInstall from ADB complete (status: %d).\n", status);
837     if (sideload_auto_reboot) {
838       status = INSTALL_REBOOT;
839       ui->Print("Rebooting automatically.\n");
840     }
841   } else if (rescue) {
842     save_current_log = true;
843     status = ApplyFromAdb(device, true /* rescue_mode */, &next_action);
844     ui->Print("\nInstall from ADB complete (status: %d).\n", status);
845   } else if (!just_exit) {
846     // If this is an eng or userdebug build, automatically turn on the text display if no command
847     // is specified. Note that this should be called before setting the background to avoid
848     // flickering the background image.
849     if (IsRoDebuggable()) {
850       ui->ShowText(true);
851     }
852     status = INSTALL_NONE;  // No command specified
853     ui->SetBackground(RecoveryUI::NO_COMMAND);
854   }
855 
856   if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
857     ui->SetBackground(RecoveryUI::ERROR);
858     if (!ui->IsTextVisible()) {
859       sleep(5);
860     }
861   }
862 
863   // Determine the next action.
864   //  - If the state is INSTALL_REBOOT, device will reboot into the target as specified in
865   //    `next_action`.
866   //  - If the recovery menu is visible, prompt and wait for commands.
867   //  - If the state is INSTALL_NONE, wait for commands (e.g. in user build, one manually boots
868   //    into recovery to sideload a package or to wipe the device).
869   //  - In all other cases, reboot the device. Therefore, normal users will observe the device
870   //    rebooting a) immediately upon successful finish (INSTALL_SUCCESS); or b) an "error" screen
871   //    for 5s followed by an automatic reboot.
872   if (status != INSTALL_REBOOT) {
873     if (status == INSTALL_NONE || ui->IsTextVisible()) {
874       auto temp = PromptAndWait(device, status);
875       if (temp != Device::NO_ACTION) {
876         next_action = temp;
877       }
878     }
879   }
880 
881   // Save logs and clean up before rebooting or shutting down.
882   FinishRecovery(ui);
883 
884   return next_action;
885 }
886