blob: 864e8cb5331bd8e97e61d13728c42bbca27beac5 [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
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
Jerry Zhang6a648042018-05-04 11:24:10 -070017#include "recovery.h"
Tao Bao2ac56af2018-04-25 16:47:04 -070018
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080019#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070023#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080024#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070025#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080026#include <linux/input.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080030#include <sys/types.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080031#include <unistd.h>
32
Tao Baoc4a18ef2017-02-10 00:13:30 -080033#include <algorithm>
Tao Bao3aec6962018-04-20 09:24:58 -070034#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080035#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070036#include <string>
37#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070038
Elliott Hughes4b166f02015-12-04 15:30:20 -080039#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070040#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080041#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070042#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070044#include <android-base/strings.h>
45#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070046#include <bootloader_message/bootloader_message.h>
Elliott Hughescb220402016-09-23 15:30:55 -070047#include <cutils/properties.h> /* for property_list */
Yifan Hong056538c2018-07-11 17:04:12 -070048#include <healthhalutils/HealthHalUtils.h>
Tom Marshallbead2612019-01-04 14:37:31 -080049#include <volume_manager/VolumeManager.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070050#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080051
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080052#include "common.h"
David Andersonedee8362018-05-16 13:43:22 -070053#include "fsck_unshare_blocks.h"
xunchang24788852019-03-22 16:08:52 -070054#include "install/adb_install.h"
55#include "install/fuse_sdcard_install.h"
56#include "install/install.h"
57#include "install/package.h"
xunchang388d2532019-04-12 16:22:15 -070058#include "install/wipe_data.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070059#include "otautil/error_code.h"
xunchang388d2532019-04-12 16:22:15 -070060#include "otautil/logging.h"
Tao Bao641fa972018-04-25 18:59:40 -070061#include "otautil/paths.h"
xunchang24788852019-03-22 16:08:52 -070062#include "otautil/roots.h"
Tao Bao2c526392018-05-03 23:01:13 -070063#include "otautil/sysutil.h"
Tianjie Xu8f397302018-08-20 13:40:47 -070064#include "recovery_ui/screen_ui.h"
65#include "recovery_ui/ui.h"
Tom Marshallbead2612019-01-04 14:37:31 -080066#include "volclient.h"
67
68using android::volmgr::VolumeManager;
69using android::volmgr::VolumeInfo;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080070
Tao Baoaac9d9f2018-04-29 23:38:59 -070071static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
Tao Baoaac9d9f2018-04-29 23:38:59 -070072static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
73static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
74static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070075
Tao Baoaac9d9f2018-04-29 23:38:59 -070076static constexpr const char* CACHE_ROOT = "/cache";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070077
Tao Baobd0ddcd2017-05-04 13:03:18 -070078// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
79// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
80static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
81
xunchang388d2532019-04-12 16:22:15 -070082static bool save_current_log = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -080083std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -070084const char* reason = nullptr;
Tao Baoac9d94d2016-11-03 11:37:15 -070085
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080086/*
87 * The recovery tool communicates with the main system through /cache files.
88 * /cache/recovery/command - INPUT - command line for tool, one arg per line
89 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080090 *
91 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -070092 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080093 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070094 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
95 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080096 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -070097 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -080098 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -070099 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800100 *
101 * After completing, we remove /cache/recovery/command and reboot.
102 * Arguments may also be supplied in the bootloader control block (BCB).
103 * These important scenarios must be safely restartable at any point:
104 *
105 * FACTORY RESET
106 * 1. user selects "factory reset"
107 * 2. main system writes "--wipe_data" to /cache/recovery/command
108 * 3. main system reboots into recovery
109 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
110 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700111 * 5. erase_volume() reformats /data
112 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113 * 7. finish_recovery() erases BCB
114 * -- after this, rebooting will restart the main system --
115 * 8. main() calls reboot() to boot main system
116 *
117 * OTA INSTALL
118 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700119 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800120 * 3. main system reboots into recovery
121 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
122 * -- after this, rebooting will attempt to reinstall the update --
123 * 5. install_package() attempts to install the update
124 * NOTE: the package install must itself be restartable from any point
125 * 6. finish_recovery() erases BCB
126 * -- after this, rebooting will (try to) restart the main system --
127 * 7. ** if install failed **
128 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800129 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800130 */
131
Elliott Hughesf14af802015-02-10 14:46:14 -0800132bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700133 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800134}
135
Michael Bestas6108e702019-09-27 20:29:42 +0300136std::string get_build_type() {
137 return android::base::GetProperty("ro.build.type", "");
138}
139
Tao Baoec579032017-07-21 12:13:15 -0700140// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700141// copy our log file to cache as well (for the system to read). This function is
142// idempotent: call it as many times as you like.
Tao Bao551d2c32018-05-09 20:53:13 -0700143static void finish_recovery() {
144 std::string locale = ui->GetLocale();
Tao Baoec579032017-07-21 12:13:15 -0700145 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
146 // (e.g., directly from the bootloader) it will use the last-known locale.
147 if (!locale.empty() && has_cache) {
148 LOG(INFO) << "Saving locale \"" << locale << "\"";
149 if (ensure_path_mounted(LOCALE_FILE) != 0) {
150 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
151 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
152 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700153 }
Tao Baoec579032017-07-21 12:13:15 -0700154 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700155
xunchang388d2532019-04-12 16:22:15 -0700156 copy_logs(save_current_log, has_cache, sehandle);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800157
Tao Baoec579032017-07-21 12:13:15 -0700158 // Reset to normal system boot so recovery won't cycle indefinitely.
159 std::string err;
160 if (!clear_bootloader_message(&err)) {
161 LOG(ERROR) << "Failed to clear BCB message: " << err;
162 }
163
164 // Remove the command file, so recovery won't repeat indefinitely.
165 if (has_cache) {
166 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
167 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700168 }
Tao Baoec579032017-07-21 12:13:15 -0700169 ensure_path_unmounted(CACHE_ROOT);
170 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800171
Tao Baoec579032017-07-21 12:13:15 -0700172 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800173}
174
Elliott Hughes30694c92015-03-25 15:16:51 -0700175static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700176 std::vector<std::string> headers{ question1, question2 };
177 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700178
Tao Bao1fe1afe2018-05-01 15:56:05 -0700179 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700180 headers, items, 0, true,
181 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
182 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700183}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800184
Alessandro Astone4e1e8662020-03-17 22:26:22 +0100185bool ask_to_continue_unverified(Device* device) {
Tom Marshall03354052018-06-21 00:57:24 +0200186 if (get_build_type() == "user") {
187 return false;
188 } else {
189 ui->SetProgressType(RecoveryUI::EMPTY);
190 return yes_no(device, "Signature verification failed", "Install anyway?");
191 }
192}
193
Alessandro Astone8b726282020-03-17 23:06:52 +0100194bool ask_to_continue_downgrade(Device* device) {
195 if (get_build_type() == "user") {
196 return false;
197 } else {
198 ui->SetProgressType(RecoveryUI::EMPTY);
199 return yes_no(device, "This package will downgrade your system", "Install anyway?");
200 }
201}
202
Paul Crowley08404b42016-12-19 13:04:23 -0800203static bool ask_to_wipe_data(Device* device) {
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700204 std::vector<std::string> headers{ "Wipe all user data?", " THIS CAN NOT BE UNDONE!" };
205 std::vector<std::string> items{ " Cancel", " Factory data reset" };
206
Alessandro Astonec6ddbac2020-03-09 23:17:50 +0100207 size_t chosen_item = ui->ShowMenu(
208 headers, items, 0, true,
Tianjie Xu1a0a30a2018-10-25 15:22:07 -0700209 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
210
211 return (chosen_item == 1);
Paul Crowley08404b42016-12-19 13:04:23 -0800212}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700213
Tom Marshallbead2612019-01-04 14:37:31 -0800214static int apply_update_menu(Device* device, RecoveryUI* ui, Device::BuiltinAction* reboot_action){
215 std::vector<std::string> headers{ "Apply update" };
216 std::vector<std::string> items;
217
218 const int item_sideload = 0;
219 std::vector<VolumeInfo> volumes;
220
221 int status = INSTALL_ERROR;
222
223 for (;;) {
224 items.clear();
225 items.push_back("Apply from ADB");
226 VolumeManager::Instance()->getVolumeInfo(volumes);
Tom Marshallb00c91f2019-07-24 21:12:07 +0200227 for (auto vol = volumes.begin(); vol != volumes.end(); /* empty */) {
228 if (!vol->mMountable) {
229 vol = volumes.erase(vol);
230 continue;
231 }
232 items.push_back("Choose from " + vol->mLabel);
233 ++vol;
Tom Marshallbead2612019-01-04 14:37:31 -0800234 }
235
236 int chosen = ui->ShowMenu(
237 headers, items, 0, false,
238 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2),
239 true /* refreshable */);
240 if (chosen == Device::kRefresh) {
241 continue;
242 }
243 if (chosen == Device::kGoBack) {
244 break;
245 }
246 if (chosen == item_sideload) {
247 status = ApplyFromAdb(device, false /* rescue_mode */, reboot_action);
248 } else {
249 status = ApplyFromStorage(device, volumes[chosen - 1], ui);
250 }
251 }
252 return status;
253}
254
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700255static InstallResult prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700256 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tianjie Xub99e6062018-10-16 15:13:09 -0700257 std::vector<std::string> wipe_data_menu_headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700258 "Can't load Android system. Your data may be corrupt. "
259 "If you continue to get this message, you may need to "
260 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700261 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800262 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700263 // clang-format off
Tianjie Xub99e6062018-10-16 15:13:09 -0700264 std::vector<std::string> wipe_data_menu_items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700265 "Try again",
266 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800267 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700268 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800269 for (;;) {
Tianjie Xub99e6062018-10-16 15:13:09 -0700270 size_t chosen_item = ui->ShowPromptWipeDataMenu(
271 wipe_data_menu_headers, wipe_data_menu_items,
Tao Bao3aec6962018-04-20 09:24:58 -0700272 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700273 // If ShowMenu() returned RecoveryUI::KeyError::INTERRUPTED, WaitKey() was interrupted.
274 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700275 return INSTALL_KEY_INTERRUPTED;
Jerry Zhangb76af932018-05-22 12:08:35 -0700276 }
Tao Baofc5499f2017-02-23 19:06:53 -0800277 if (chosen_item != 1) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700278 return INSTALL_SUCCESS; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800279 }
Tianjie Xub99e6062018-10-16 15:13:09 -0700280
Tao Baofc5499f2017-02-23 19:06:53 -0800281 if (ask_to_wipe_data(device)) {
xunchang388d2532019-04-12 16:22:15 -0700282 bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
283 if (WipeData(device, convert_fbe)) {
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -0700284 return INSTALL_SUCCESS;
285 } else {
286 return INSTALL_ERROR;
287 }
Tao Baofc5499f2017-02-23 19:06:53 -0800288 }
289 }
Paul Crowley08404b42016-12-19 13:04:23 -0800290}
291
Tao Bao1b2a98b2017-03-24 10:45:34 -0700292// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
293// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700294static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700295 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
296 if (fd == -1) {
297 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
298 return false;
299 }
300
301 uint64_t range[2] = { 0, 0 };
302 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
303 PLOG(ERROR) << "Failed to get partition size";
304 return false;
305 }
306 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
307
308 LOG(INFO) << " Trying BLKSECDISCARD...";
309 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
310 PLOG(WARNING) << " Failed";
311
312 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
313 unsigned int zeroes;
314 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
315 LOG(INFO) << " Trying BLKDISCARD...";
316 if (ioctl(fd, BLKDISCARD, &range) == -1) {
317 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700318 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700319 }
320 } else {
321 LOG(INFO) << " Trying BLKZEROOUT...";
322 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
323 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700324 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700325 }
Tao Bao862a4c12016-06-02 11:16:50 -0700326 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700327 }
Tao Bao862a4c12016-06-02 11:16:50 -0700328
Tao Bao1b2a98b2017-03-24 10:45:34 -0700329 LOG(INFO) << " Done";
330 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700331}
332
xunchang55e3d222019-03-11 11:28:41 -0700333static std::unique_ptr<Package> ReadWipePackage(size_t wipe_package_size) {
xunchange0d991c2019-03-05 14:50:51 -0800334 if (wipe_package_size == 0) {
335 LOG(ERROR) << "wipe_package_size is zero";
xunchang55e3d222019-03-11 11:28:41 -0700336 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800337 }
338
339 std::string wipe_package;
340 std::string err_str;
341 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
342 PLOG(ERROR) << "Failed to read wipe package" << err_str;
xunchang55e3d222019-03-11 11:28:41 -0700343 return nullptr;
xunchange0d991c2019-03-05 14:50:51 -0800344 }
xunchang55e3d222019-03-11 11:28:41 -0700345
346 return Package::CreateMemoryPackage(
347 std::vector<uint8_t>(wipe_package.begin(), wipe_package.end()), nullptr);
xunchange0d991c2019-03-05 14:50:51 -0800348}
349
350// Checks if the wipe package matches expectation. If the check passes, reads the list of
351// partitions to wipe from the package. Checks include
Yabin Cuifd99a312016-06-09 14:09:39 -0700352// 1. verify the package.
353// 2. check metadata (ota-type, pre-device and serial number if having one).
xunchang55e3d222019-03-11 11:28:41 -0700354static bool CheckWipePackage(Package* wipe_package) {
xunchang24788852019-03-22 16:08:52 -0700355 if (!verify_package(wipe_package, ui)) {
xunchange0d991c2019-03-05 14:50:51 -0800356 LOG(ERROR) << "Failed to verify package";
357 return false;
358 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700359
xunchang55e3d222019-03-11 11:28:41 -0700360 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
361 if (!zip) {
362 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800363 return false;
364 }
365
366 std::map<std::string, std::string> metadata;
367 if (!ReadMetadataFromPackage(zip, &metadata)) {
368 LOG(ERROR) << "Failed to parse metadata in the zip file";
369 return false;
370 }
371
xunchang55e3d222019-03-11 11:28:41 -0700372 return CheckPackageMetadata(metadata, OtaType::BRICK) == 0;
xunchange0d991c2019-03-05 14:50:51 -0800373}
374
xunchang55e3d222019-03-11 11:28:41 -0700375std::vector<std::string> GetWipePartitionList(Package* wipe_package) {
376 ZipArchiveHandle zip = wipe_package->GetZipArchiveHandle();
377 if (!zip) {
378 LOG(ERROR) << "Failed to get ZipArchiveHandle";
xunchange0d991c2019-03-05 14:50:51 -0800379 return {};
380 }
381
382 static constexpr const char* RECOVERY_WIPE_ENTRY_NAME = "recovery.wipe";
383
384 std::string partition_list_content;
385 ZipString path(RECOVERY_WIPE_ENTRY_NAME);
386 ZipEntry entry;
387 if (FindEntry(zip, path, &entry) == 0) {
388 uint32_t length = entry.uncompressed_length;
389 partition_list_content = std::string(length, '\0');
390 if (auto err = ExtractToMemory(
391 zip, &entry, reinterpret_cast<uint8_t*>(partition_list_content.data()), length);
392 err != 0) {
393 LOG(ERROR) << "Failed to extract " << RECOVERY_WIPE_ENTRY_NAME << ": "
394 << ErrorCodeString(err);
xunchange0d991c2019-03-05 14:50:51 -0800395 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700396 }
xunchange0d991c2019-03-05 14:50:51 -0800397 } else {
398 LOG(INFO) << "Failed to find " << RECOVERY_WIPE_ENTRY_NAME
399 << ", falling back to use the partition list on device.";
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700400
xunchange0d991c2019-03-05 14:50:51 -0800401 static constexpr const char* RECOVERY_WIPE_ON_DEVICE = "/etc/recovery.wipe";
402 if (!android::base::ReadFileToString(RECOVERY_WIPE_ON_DEVICE, &partition_list_content)) {
403 PLOG(ERROR) << "failed to read \"" << RECOVERY_WIPE_ON_DEVICE << "\"";
xunchange0d991c2019-03-05 14:50:51 -0800404 return {};
Yabin Cuifd99a312016-06-09 14:09:39 -0700405 }
xunchange0d991c2019-03-05 14:50:51 -0800406 }
Tianjie Xu93b5bf22018-10-25 10:39:01 -0700407
xunchange0d991c2019-03-05 14:50:51 -0800408 std::vector<std::string> result;
409 std::vector<std::string> lines = android::base::Split(partition_list_content, "\n");
410 for (const std::string& line : lines) {
411 std::string partition = android::base::Trim(line);
412 // Ignore '#' comment or empty lines.
413 if (android::base::StartsWith(partition, "#") || partition.empty()) {
414 continue;
415 }
416 result.push_back(line);
417 }
Yabin Cuifd99a312016-06-09 14:09:39 -0700418
xunchange0d991c2019-03-05 14:50:51 -0800419 return result;
Yabin Cuifd99a312016-06-09 14:09:39 -0700420}
421
Tao Baoaac9d9f2018-04-29 23:38:59 -0700422// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700423static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700424 ui->SetBackground(RecoveryUI::ERASING);
425 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700426
xunchang55e3d222019-03-11 11:28:41 -0700427 auto wipe_package = ReadWipePackage(wipe_package_size);
428 if (!wipe_package) {
429 LOG(ERROR) << "Failed to open wipe package";
xunchange0d991c2019-03-05 14:50:51 -0800430 return false;
431 }
432
xunchang55e3d222019-03-11 11:28:41 -0700433 if (!CheckWipePackage(wipe_package.get())) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700434 LOG(ERROR) << "Failed to verify wipe package";
435 return false;
436 }
xunchange0d991c2019-03-05 14:50:51 -0800437
xunchang55e3d222019-03-11 11:28:41 -0700438 auto partition_list = GetWipePartitionList(wipe_package.get());
xunchange0d991c2019-03-05 14:50:51 -0800439 if (partition_list.empty()) {
440 LOG(ERROR) << "Empty wipe ab partition list";
Tao Baoaac9d9f2018-04-29 23:38:59 -0700441 return false;
442 }
443
xunchange0d991c2019-03-05 14:50:51 -0800444 for (const auto& partition : partition_list) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700445 // Proceed anyway even if it fails to wipe some partition.
446 secure_wipe_partition(partition);
447 }
448 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700449}
450
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700451static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800452 std::vector<std::string> entries;
453 if (has_cache) {
454 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
455 auto add_to_entries = [&](const char* filename) {
456 std::string log_file(filename);
457 if (i > 0) {
458 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700459 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800460
Yifan Hongd81b8e32018-12-17 14:29:06 -0800461 if (ensure_path_mounted(log_file) == 0 && access(log_file.c_str(), R_OK) == 0) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800462 entries.push_back(std::move(log_file));
463 }
464 };
465
466 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
467 add_to_entries(LAST_LOG_FILE);
468
469 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
470 add_to_entries(LAST_KMSG_FILE);
471 }
472 } else {
473 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700474 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800475 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700476 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700477 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700478 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800479 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700480
Tao Bao08fc6be2017-03-07 00:56:27 -0800481 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700482
Tao Bao1fe1afe2018-05-01 15:56:05 -0700483 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700484
Tao Bao1fe1afe2018-05-01 15:56:05 -0700485 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800486 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700487 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700488 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700489 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700490
491 // Handle WaitKey() interrupt.
492 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
493 break;
494 }
Tom Marshalld23b5102017-08-24 13:50:01 +0000495 if (chosen_item == Device::kGoHome || chosen_item == Device::kGoBack ||
496 chosen_item == entries.size() - 1) {
497 break;
498 }
Tao Bao1d156b92018-05-02 12:43:18 -0700499 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800500 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700501}
502
Tao Baodb7e8982017-03-06 23:53:16 -0800503static void run_graphics_test() {
504 // Switch to graphics screen.
505 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700506
Tao Baodb7e8982017-03-06 23:53:16 -0800507 ui->SetProgressType(RecoveryUI::INDETERMINATE);
508 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
509 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700510
Tao Baodb7e8982017-03-06 23:53:16 -0800511 ui->SetBackground(RecoveryUI::ERROR);
512 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700513
Tao Baodb7e8982017-03-06 23:53:16 -0800514 ui->SetBackground(RecoveryUI::NO_COMMAND);
515 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700516
Tao Baodb7e8982017-03-06 23:53:16 -0800517 ui->SetBackground(RecoveryUI::ERASING);
518 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700519
Tao Baodb7e8982017-03-06 23:53:16 -0800520 // Calling SetBackground() after SetStage() to trigger a redraw.
521 ui->SetStage(1, 3);
522 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
523 sleep(1);
524 ui->SetStage(2, 3);
525 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
526 sleep(1);
527 ui->SetStage(3, 3);
528 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
529 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700530
Tao Baodb7e8982017-03-06 23:53:16 -0800531 ui->SetStage(-1, -1);
532 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700533
Tao Baodb7e8982017-03-06 23:53:16 -0800534 ui->SetProgressType(RecoveryUI::DETERMINATE);
535 ui->ShowProgress(1.0, 10.0);
536 float fraction = 0.0;
537 for (size_t i = 0; i < 100; ++i) {
538 fraction += .01;
539 ui->SetProgress(fraction);
540 usleep(100000);
541 }
542
543 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700544}
545
Tao Bao50dd5322017-03-07 14:57:04 -0800546// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
547// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
548static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
549 for (;;) {
Tao Bao551d2c32018-05-09 20:53:13 -0700550 finish_recovery();
Tao Bao50dd5322017-03-07 14:57:04 -0800551 switch (status) {
552 case INSTALL_SUCCESS:
553 case INSTALL_NONE:
554 ui->SetBackground(RecoveryUI::NO_COMMAND);
555 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700556
Tao Bao50dd5322017-03-07 14:57:04 -0800557 case INSTALL_ERROR:
558 case INSTALL_CORRUPT:
559 ui->SetBackground(RecoveryUI::ERROR);
560 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800561 }
Tao Bao50dd5322017-03-07 14:57:04 -0800562 ui->SetProgressType(RecoveryUI::EMPTY);
563
Tom Marshall645801f2020-03-29 14:36:57 +0200564change_menu:
Tao Bao1fe1afe2018-05-01 15:56:05 -0700565 size_t chosen_item = ui->ShowMenu(
Tom Marshall645801f2020-03-29 14:36:57 +0200566 device->GetMenuHeaders(), device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700567 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Jerry Zhangb76af932018-05-22 12:08:35 -0700568 // Handle Interrupt key
569 if (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::INTERRUPTED)) {
570 return Device::KEY_INTERRUPTED;
571 }
Tom Marshall645801f2020-03-29 14:36:57 +0200572
Tom Marshalld23b5102017-08-24 13:50:01 +0000573 if (chosen_item == Device::kGoBack || chosen_item == Device::kGoHome) {
Tom Marshall645801f2020-03-29 14:36:57 +0200574 device->GoHome();
575 goto change_menu;
Tom Marshalld23b5102017-08-24 13:50:01 +0000576 }
577
Tao Bao50dd5322017-03-07 14:57:04 -0800578 // Device-specific code may take some action here. It may return one of the core actions
579 // handled in the switch statement below.
Jerry Zhangb76af932018-05-22 12:08:35 -0700580 Device::BuiltinAction chosen_action =
581 (chosen_item == static_cast<size_t>(RecoveryUI::KeyError::TIMED_OUT))
582 ? Device::REBOOT
583 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800584
Tao Bao50dd5322017-03-07 14:57:04 -0800585 switch (chosen_action) {
Tom Marshall645801f2020-03-29 14:36:57 +0200586 case Device::MENU_BASE:
Tom Marshall645801f2020-03-29 14:36:57 +0200587 case Device::MENU_WIPE:
588 case Device::MENU_ADVANCED:
589 goto change_menu;
590
Tao Bao50dd5322017-03-07 14:57:04 -0800591 case Device::NO_ACTION:
592 break;
593
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700594 case Device::ENTER_FASTBOOT:
595 case Device::ENTER_RECOVERY:
Tao Bao75321ad2019-04-23 11:46:25 -0700596 case Device::REBOOT:
597 case Device::REBOOT_BOOTLOADER:
598 case Device::REBOOT_FASTBOOT:
599 case Device::REBOOT_RECOVERY:
600 case Device::REBOOT_RESCUE:
601 case Device::SHUTDOWN:
Tao Bao50dd5322017-03-07 14:57:04 -0800602 return chosen_action;
603
604 case Device::WIPE_DATA:
xunchang388d2532019-04-12 16:22:15 -0700605 save_current_log = true;
Tao Bao50dd5322017-03-07 14:57:04 -0800606 if (ui->IsTextVisible()) {
607 if (ask_to_wipe_data(device)) {
xunchang388d2532019-04-12 16:22:15 -0700608 WipeData(device, false);
Tao Bao50dd5322017-03-07 14:57:04 -0800609 }
610 } else {
xunchang388d2532019-04-12 16:22:15 -0700611 WipeData(device, false);
Tao Bao50dd5322017-03-07 14:57:04 -0800612 return Device::NO_ACTION;
613 }
614 break;
615
xunchang388d2532019-04-12 16:22:15 -0700616 case Device::WIPE_CACHE: {
617 save_current_log = true;
618 std::function<bool()> confirm_func = [&device]() {
619 return yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!");
620 };
621 WipeCache(ui, ui->IsTextVisible() ? confirm_func : nullptr);
Tao Bao50dd5322017-03-07 14:57:04 -0800622 if (!ui->IsTextVisible()) return Device::NO_ACTION;
623 break;
xunchang388d2532019-04-12 16:22:15 -0700624 }
Tao Bao7b9b7db2019-04-19 15:22:15 -0700625
Michael Bestasc209c072019-09-27 19:52:13 +0300626 case Device::WIPE_SYSTEM: {
627 save_current_log = true;
628 std::function<bool()> confirm_func = [&device]() {
629 return yes_no(device, "Wipe system?", " THIS CAN NOT BE UNDONE!");
630 };
631 WipeSystem(ui, ui->IsTextVisible() ? confirm_func : nullptr);
632 if (!ui->IsTextVisible()) return Device::NO_ACTION;
633 break;
634 }
635
Tom Marshallbead2612019-01-04 14:37:31 -0800636 case Device::APPLY_UPDATE:
Tao Bao378bfbf2019-04-16 14:22:25 -0700637 case Device::ENTER_RESCUE: {
xunchang388d2532019-04-12 16:22:15 -0700638 save_current_log = true;
Tao Bao378bfbf2019-04-16 14:22:25 -0700639
Tao Bao7b9b7db2019-04-19 15:22:15 -0700640 Device::BuiltinAction reboot_action;
Tao Bao378bfbf2019-04-16 14:22:25 -0700641 if (chosen_action == Device::ENTER_RESCUE) {
642 // Switch to graphics screen.
643 ui->ShowText(false);
xunchang5a1916b2019-04-22 12:18:14 -0700644 status = ApplyFromAdb(device, true /* rescue_mode */, &reboot_action);
Tom Marshallbead2612019-01-04 14:37:31 -0800645 } else if (chosen_action == Device::APPLY_UPDATE) {
646 status = apply_update_menu(device, ui, &reboot_action);
Tao Bao50dd5322017-03-07 14:57:04 -0800647 }
xunchang3cc23d52019-03-18 15:03:33 -0700648
Tao Bao7b9b7db2019-04-19 15:22:15 -0700649 if (status == INSTALL_REBOOT) {
650 return reboot_action;
651 }
652
Tom Marshallbead2612019-01-04 14:37:31 -0800653 ui->Print("\nInstall completed with status %d.\n", status);
xunchang3cc23d52019-03-18 15:03:33 -0700654 if (status != INSTALL_SUCCESS) {
655 ui->SetBackground(RecoveryUI::ERROR);
656 ui->Print("Installation aborted.\n");
xunchang388d2532019-04-12 16:22:15 -0700657 copy_logs(save_current_log, has_cache, sehandle);
xunchang3cc23d52019-03-18 15:03:33 -0700658 } else if (!ui->IsTextVisible()) {
659 return Device::NO_ACTION; // reboot if logs aren't visible
xunchang3cc23d52019-03-18 15:03:33 -0700660 }
Tao Bao50dd5322017-03-07 14:57:04 -0800661 break;
xunchang3cc23d52019-03-18 15:03:33 -0700662 }
Tao Bao50dd5322017-03-07 14:57:04 -0800663
664 case Device::VIEW_RECOVERY_LOGS:
665 choose_recovery_file(device);
666 break;
667
668 case Device::RUN_GRAPHICS_TEST:
669 run_graphics_test();
670 break;
671
Tianjie Xu29d55752017-09-20 17:53:46 -0700672 case Device::RUN_LOCALE_TEST: {
673 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
Tao Bao39c49182018-05-07 22:50:33 -0700674 screen_ui->CheckBackgroundTextImages();
Tianjie Xu29d55752017-09-20 17:53:46 -0700675 break;
676 }
Tao Bao50dd5322017-03-07 14:57:04 -0800677 case Device::MOUNT_SYSTEM:
Jiyong Park8b7af4c2018-06-01 11:58:54 +0900678 // the system partition is mounted at /mnt/system
Yifan Hongd81b8e32018-12-17 14:29:06 -0800679 if (ensure_path_mounted_at(get_system_root(), "/mnt/system") != -1) {
Yifan Hong49327802018-11-26 14:59:09 -0800680 ui->Print("Mounted /system.\n");
Tao Bao50dd5322017-03-07 14:57:04 -0800681 }
682 break;
Jerry Zhangb76af932018-05-22 12:08:35 -0700683
684 case Device::KEY_INTERRUPTED:
685 return Device::KEY_INTERRUPTED;
Tao Bao50dd5322017-03-07 14:57:04 -0800686 }
687 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800688}
689
Tao Bao99f0d9e2016-10-13 12:46:38 -0700690static void print_property(const char* key, const char* name, void* /* cookie */) {
691 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800692}
693
Tao Bao6d90a9d2018-04-26 10:40:36 -0700694static bool is_battery_ok(int* required_battery_level) {
Yifan Honge8e4c402017-11-08 14:56:03 -0800695 using android::hardware::health::V1_0::BatteryStatus;
Yifan Hong056538c2018-07-11 17:04:12 -0700696 using android::hardware::health::V2_0::get_health_service;
697 using android::hardware::health::V2_0::IHealth;
Yifan Honge8e4c402017-11-08 14:56:03 -0800698 using android::hardware::health::V2_0::Result;
699 using android::hardware::health::V2_0::toString;
Yabin Cui99281df2016-02-17 12:21:52 -0800700
Yifan Hong056538c2018-07-11 17:04:12 -0700701 android::sp<IHealth> health = get_health_service();
Yifan Honge8e4c402017-11-08 14:56:03 -0800702
Tao Bao6d90a9d2018-04-26 10:40:36 -0700703 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
Yifan Honge8e4c402017-11-08 14:56:03 -0800704 int wait_second = 0;
705 while (true) {
706 auto charge_status = BatteryStatus::UNKNOWN;
Yifan Hong056538c2018-07-11 17:04:12 -0700707
708 if (health == nullptr) {
709 LOG(WARNING) << "no health implementation is found, assuming defaults";
710 } else {
711 health
712 ->getChargeStatus([&charge_status](auto res, auto out_status) {
713 if (res == Result::SUCCESS) {
714 charge_status = out_status;
715 }
716 })
717 .isOk(); // should not have transport error
718 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800719
720 // Treat unknown status as charged.
721 bool charged = (charge_status != BatteryStatus::DISCHARGING &&
722 charge_status != BatteryStatus::NOT_CHARGING);
723
724 Result res = Result::UNKNOWN;
725 int32_t capacity = INT32_MIN;
Yifan Hong056538c2018-07-11 17:04:12 -0700726 if (health != nullptr) {
727 health
728 ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
729 res = out_res;
730 capacity = out_capacity;
731 })
732 .isOk(); // should not have transport error
733 }
Yifan Honge8e4c402017-11-08 14:56:03 -0800734
Yifan Hong056538c2018-07-11 17:04:12 -0700735 LOG(INFO) << "charge_status " << toString(charge_status) << ", charged " << charged
736 << ", status " << toString(res) << ", capacity " << capacity;
Yifan Honge8e4c402017-11-08 14:56:03 -0800737 // At startup, the battery drivers in devices like N5X/N6P take some time to load
738 // the battery profile. Before the load finishes, it reports value 50 as a fake
739 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
740 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
741 if (res == Result::SUCCESS && capacity == 50) {
742 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
743 sleep(1);
744 wait_second++;
745 continue;
746 }
747 }
748 // If we can't read battery percentage, it may be a device without battery. In this
749 // situation, use 100 as a fake battery percentage.
750 if (res != Result::SUCCESS) {
751 capacity = 100;
752 }
Tao Bao6d90a9d2018-04-26 10:40:36 -0700753
754 // GmsCore enters recovery mode to install package when having enough battery percentage.
755 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
756 // battery with a slightly lower limitation.
757 static constexpr int BATTERY_OK_PERCENTAGE = 20;
758 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
759 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
760 return capacity >= *required_battery_level;
761 }
Yabin Cui99281df2016-02-17 12:21:52 -0800762}
763
Tianjie Xu99b73be2017-11-28 17:23:06 -0800764// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -0700765static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
766 std::vector<std::string> options;
767 for (const auto& arg : args) {
768 if (!android::base::StartsWith(arg, "--retry_count")) {
769 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -0800770 }
Tianjie Xu72449c92017-05-16 18:07:31 -0700771 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800772
Tianjie Xu99b73be2017-11-28 17:23:06 -0800773 // Update the retry counter in BCB.
774 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -0700775 std::string err;
776 if (!update_bootloader_message(options, &err)) {
777 LOG(ERROR) << err;
778 }
Tianjie Xu3c62b672016-02-05 18:25:58 -0800779}
780
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700781static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -0800782 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
783 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700784 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
785 static const std::vector<std::string> kBootreasonBlacklist{
786 "kernel_panic",
787 "Panic",
788 };
789 for (const auto& str : kBootreasonBlacklist) {
790 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700791 }
Tao Baoefc35592017-01-08 22:45:47 -0800792 }
793 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700794}
795
Tao Bao641fa972018-04-25 18:59:40 -0700796static void log_failure_code(ErrorCode code, const std::string& update_package) {
797 std::vector<std::string> log_buffer = {
798 update_package,
799 "0", // install result
800 "error: " + std::to_string(code),
801 };
802 std::string log_content = android::base::Join(log_buffer, "\n");
803 const std::string& install_file = Paths::Get().temporary_install_file();
804 if (!android::base::WriteStringToFile(log_content, install_file)) {
805 PLOG(ERROR) << "Failed to write " << install_file;
806 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700807
Tao Bao641fa972018-04-25 18:59:40 -0700808 // Also write the info into last_log.
809 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700810}
811
Jerry Zhang6a648042018-05-04 11:24:10 -0700812Device::BuiltinAction start_recovery(Device* device, const std::vector<std::string>& args) {
Tao Baof9f17342018-04-27 10:44:04 -0700813 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700814 { "fastboot", no_argument, nullptr, 0 },
David Andersonedee8362018-05-16 13:43:22 -0700815 { "fsck_unshare_blocks", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700816 { "just_exit", no_argument, nullptr, 'x' },
817 { "locale", required_argument, nullptr, 0 },
818 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
819 { "reason", required_argument, nullptr, 0 },
Tao Bao75321ad2019-04-23 11:46:25 -0700820 { "rescue", no_argument, nullptr, 0 },
Tao Baof9f17342018-04-27 10:44:04 -0700821 { "retry_count", required_argument, nullptr, 0 },
822 { "security", no_argument, nullptr, 0 },
823 { "show_text", no_argument, nullptr, 't' },
824 { "shutdown_after", no_argument, nullptr, 0 },
825 { "sideload", no_argument, nullptr, 0 },
826 { "sideload_auto_reboot", no_argument, nullptr, 0 },
827 { "update_package", required_argument, nullptr, 0 },
828 { "wipe_ab", no_argument, nullptr, 0 },
829 { "wipe_cache", no_argument, nullptr, 0 },
830 { "wipe_data", no_argument, nullptr, 0 },
831 { "wipe_package_size", required_argument, nullptr, 0 },
832 { nullptr, 0, nullptr, 0 },
833 };
834
Tianjie Xu99b73be2017-11-28 17:23:06 -0800835 const char* update_package = nullptr;
836 bool should_wipe_data = false;
837 bool should_prompt_and_wipe_data = false;
838 bool should_wipe_cache = false;
839 bool should_wipe_ab = false;
840 size_t wipe_package_size = 0;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800841 bool sideload = false;
842 bool sideload_auto_reboot = false;
Tao Bao75321ad2019-04-23 11:46:25 -0700843 bool rescue = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800844 bool just_exit = false;
845 bool shutdown_after = false;
David Andersonedee8362018-05-16 13:43:22 -0700846 bool fsck_unshare_blocks = false;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800847 int retry_count = 0;
848 bool security_update = false;
Jerry Zhang2dea53e2018-05-02 17:15:03 -0700849 std::string locale;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800850
Tao Bao1700cc42018-07-16 22:09:59 -0700851 auto args_to_parse = StringVectorToNullTerminatedArray(args);
852
Tianjie Xu99b73be2017-11-28 17:23:06 -0800853 int arg;
854 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700855 // Parse everything before the last element (which must be a nullptr). getopt_long(3) expects a
856 // null-terminated char* array, but without counting null as an arg (i.e. argv[argc] should be
857 // nullptr).
858 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Tianjie Xu99b73be2017-11-28 17:23:06 -0800859 &option_index)) != -1) {
860 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800861 case 't':
Jerry Zhang6a648042018-05-04 11:24:10 -0700862 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800863 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800864 case 'x':
865 just_exit = true;
866 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800867 case 0: {
868 std::string option = OPTIONS[option_index].name;
David Andersonedee8362018-05-16 13:43:22 -0700869 if (option == "fsck_unshare_blocks") {
870 fsck_unshare_blocks = true;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700871 } else if (option == "locale" || option == "fastboot") {
Jerry Zhang6a648042018-05-04 11:24:10 -0700872 // Handled in recovery_main.cpp
Tianjie Xu99b73be2017-11-28 17:23:06 -0800873 } else if (option == "prompt_and_wipe_data") {
874 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -0700875 } else if (option == "reason") {
876 reason = optarg;
Tao Bao75321ad2019-04-23 11:46:25 -0700877 } else if (option == "rescue") {
878 rescue = true;
Tao Baof9f17342018-04-27 10:44:04 -0700879 } else if (option == "retry_count") {
880 android::base::ParseInt(optarg, &retry_count, 0);
881 } else if (option == "security") {
882 security_update = true;
883 } else if (option == "sideload") {
884 sideload = true;
885 } else if (option == "sideload_auto_reboot") {
886 sideload = true;
887 sideload_auto_reboot = true;
888 } else if (option == "shutdown_after") {
889 shutdown_after = true;
890 } else if (option == "update_package") {
891 update_package = optarg;
892 } else if (option == "wipe_ab") {
893 should_wipe_ab = true;
894 } else if (option == "wipe_cache") {
895 should_wipe_cache = true;
896 } else if (option == "wipe_data") {
897 should_wipe_data = true;
898 } else if (option == "wipe_package_size") {
899 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800900 }
901 break;
902 }
903 case '?':
904 LOG(ERROR) << "Invalid command argument";
905 continue;
Doug Zongker9270a202012-01-09 15:16:13 -0800906 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800907 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700908 optind = 1;
Doug Zongker9270a202012-01-09 15:16:13 -0800909
Tianjie Xu99b73be2017-11-28 17:23:06 -0800910 printf("stage is [%s]\n", stage.c_str());
911 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -0700912
Tom Marshallbead2612019-01-04 14:37:31 -0800913 VolumeClient* volclient = new VolumeClient(device);
914 VolumeManager* volmgr = VolumeManager::Instance();
915 if (!volmgr->start(volclient, sehandle)) {
916 printf("Failed to start volume manager\n");
917 }
918
Tianjie Xu99b73be2017-11-28 17:23:06 -0800919 // Set background string to "installing security update" for security update,
920 // otherwise set it to "installing system update".
921 ui->SetSystemUpdateText(security_update);
922
923 int st_cur, st_max;
924 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
925 ui->SetStage(st_cur, st_max);
926 }
927
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700928 std::vector<std::string> title_lines =
929 android::base::Split(android::base::GetProperty("ro.bootimage.build.fingerprint", ""), ":");
Nolen Johnsonb146fe92020-02-12 00:03:01 +0000930 title_lines.insert(std::begin(title_lines), "Lineage Recovery");
Jerry Zhang0e577ee2018-05-07 11:21:10 -0700931 ui->SetTitle(title_lines);
932
Jerry Zhangb76af932018-05-22 12:08:35 -0700933 ui->ResetKeyInterruptStatus();
Tianjie Xu99b73be2017-11-28 17:23:06 -0800934 device->StartRecovery();
935
936 printf("Command:");
937 for (const auto& arg : args) {
938 printf(" \"%s\"", arg.c_str());
939 }
940 printf("\n\n");
941
942 property_list(print_property, nullptr);
943 printf("\n");
944
Tianjie Xu99b73be2017-11-28 17:23:06 -0800945 int status = INSTALL_SUCCESS;
Tao Bao7b9b7db2019-04-19 15:22:15 -0700946 // next_action indicates the next target to reboot into upon finishing the install. It could be
947 // overridden to a different reboot target per user request.
948 Device::BuiltinAction next_action = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800949
950 if (update_package != nullptr) {
951 // It's not entirely true that we will modify the flash. But we want
952 // to log the update attempt since update_package is non-NULL.
xunchang388d2532019-04-12 16:22:15 -0700953 save_current_log = true;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800954
Tao Bao6d90a9d2018-04-26 10:40:36 -0700955 int required_battery_level;
956 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
957 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
958 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800959 // Log the error code to last_install when installation skips due to
960 // low battery.
961 log_failure_code(kLowBattery, update_package);
962 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -0700963 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800964 // Skip update-on-reboot when bootreason is kernel_panic or similar
965 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
966 log_failure_code(kBootreasonInBlacklist, update_package);
967 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -0700968 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -0800969 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
970 // identify the interrupted update due to unexpected reboots.
971 if (retry_count == 0) {
972 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -0700973 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800974
Tom Marshall03354052018-06-21 00:57:24 +0200975 status = install_package(update_package, should_wipe_cache, true, retry_count,
Alessandro Astone8b726282020-03-17 23:06:52 +0100976 true /* verify */, false /* allow_ab_downgrade */, ui);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800977 if (status != INSTALL_SUCCESS) {
978 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -0700979
980 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
981 // RETRY_LIMIT times before we abandon this OTA update.
982 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -0800983 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
xunchang388d2532019-04-12 16:22:15 -0700984 copy_logs(save_current_log, has_cache, sehandle);
Tianjie Xu99b73be2017-11-28 17:23:06 -0800985 retry_count += 1;
986 set_retry_bootloader_message(retry_count, args);
987 // Print retry count on screen.
988 ui->Print("Retry attempt %d\n", retry_count);
989
990 // Reboot and retry the update
991 if (!reboot("reboot,recovery")) {
992 ui->Print("Reboot failed\n");
993 } else {
994 while (true) {
995 pause();
996 }
997 }
Tianjie Xud9d16292017-04-20 18:08:21 -0700998 }
Tianjie Xu99b73be2017-11-28 17:23:06 -0800999 // If this is an eng or userdebug build, then automatically
1000 // turn the text display on if the script fails so the error
1001 // message is visible.
1002 if (is_ro_debuggable()) {
1003 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001004 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001005 }
Doug Zongker8674a722010-09-15 11:08:23 -07001006 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001007 } else if (should_wipe_data) {
xunchang388d2532019-04-12 16:22:15 -07001008 save_current_log = true;
1009 bool convert_fbe = reason && strcmp(reason, "convert_fbe") == 0;
1010 if (!WipeData(device, convert_fbe)) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001011 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001012 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001013 } else if (should_prompt_and_wipe_data) {
Tao Baoa5bbcb92018-09-17 14:32:47 -07001014 // Trigger the logging to capture the cause, even if user chooses to not wipe data.
xunchang388d2532019-04-12 16:22:15 -07001015 save_current_log = true;
Tao Baoa5bbcb92018-09-17 14:32:47 -07001016
Tianjie Xu99b73be2017-11-28 17:23:06 -08001017 ui->ShowText(true);
1018 ui->SetBackground(RecoveryUI::ERROR);
Hridya Valsarajueb6f13a2018-09-12 10:25:01 -07001019 status = prompt_and_wipe_data(device);
1020 if (status != INSTALL_KEY_INTERRUPTED) {
1021 ui->ShowText(false);
Tao Bao75238632015-05-27 14:46:17 -07001022 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001023 } else if (should_wipe_cache) {
xunchang388d2532019-04-12 16:22:15 -07001024 save_current_log = true;
1025 if (!WipeCache(ui, nullptr)) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001026 status = INSTALL_ERROR;
1027 }
1028 } else if (should_wipe_ab) {
1029 if (!wipe_ab_device(wipe_package_size)) {
1030 status = INSTALL_ERROR;
1031 }
1032 } else if (sideload) {
Tao Bao7b9b7db2019-04-19 15:22:15 -07001033 // 'adb reboot sideload' acts the same as user presses key combinations to enter the sideload
1034 // mode. When 'sideload-auto-reboot' is used, text display will NOT be turned on by default. And
1035 // it will reboot after sideload finishes even if there are errors. This is to enable automated
Tianjie Xu99b73be2017-11-28 17:23:06 -08001036 // testing.
xunchang388d2532019-04-12 16:22:15 -07001037 save_current_log = true;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001038 if (!sideload_auto_reboot) {
1039 ui->ShowText(true);
1040 }
Alessandro Astone4e1e8662020-03-17 22:26:22 +01001041 status = ApplyFromAdb(device, false /* rescue_mode */, &next_action);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001042 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1043 if (sideload_auto_reboot) {
Tao Bao7b9b7db2019-04-19 15:22:15 -07001044 status = INSTALL_REBOOT;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001045 ui->Print("Rebooting automatically.\n");
1046 }
Tao Bao75321ad2019-04-23 11:46:25 -07001047 } else if (rescue) {
1048 save_current_log = true;
xunchang5a1916b2019-04-22 12:18:14 -07001049 status = ApplyFromAdb(device, true /* rescue_mode */, &next_action);
Tao Bao75321ad2019-04-23 11:46:25 -07001050 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
David Andersonedee8362018-05-16 13:43:22 -07001051 } else if (fsck_unshare_blocks) {
1052 if (!do_fsck_unshare_blocks()) {
1053 status = INSTALL_ERROR;
1054 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001055 } else if (!just_exit) {
Pat Erley85da9942016-01-05 16:50:02 -08001056 // Always show menu if no command is specified.
1057 // Note that this should be called before setting the background to avoid
Tianjie Xu99b73be2017-11-28 17:23:06 -08001058 // flickering the background image.
Pat Erley85da9942016-01-05 16:50:02 -08001059 ui->ShowText(true);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001060 status = INSTALL_NONE; // No command specified
1061 ui->SetBackground(RecoveryUI::NO_COMMAND);
1062 }
1063
1064 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1065 ui->SetBackground(RecoveryUI::ERROR);
1066 if (!ui->IsTextVisible()) {
1067 sleep(5);
1068 }
1069 }
1070
Tao Bao7b9b7db2019-04-19 15:22:15 -07001071 // Determine the next action.
1072 // - If the state is INSTALL_REBOOT, device will reboot into the target as specified in
1073 // `next_action`.
1074 // - If the recovery menu is visible, prompt and wait for commands.
1075 // - If the state is INSTALL_NONE, wait for commands (e.g. in user build, one manually boots
1076 // into recovery to sideload a package or to wipe the device).
1077 // - In all other cases, reboot the device. Therefore, normal users will observe the device
1078 // rebooting a) immediately upon successful finish (INSTALL_SUCCESS); or b) an "error" screen
1079 // for 5s followed by an automatic reboot.
1080 if (status != INSTALL_REBOOT) {
1081 if (status == INSTALL_NONE || ui->IsTextVisible()) {
1082 Device::BuiltinAction temp = prompt_and_wait(device, status);
1083 if (temp != Device::NO_ACTION) {
1084 next_action = temp;
1085 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001086 }
1087 }
1088
1089 // Save logs and clean up before rebooting or shutting down.
Tao Bao551d2c32018-05-09 20:53:13 -07001090 finish_recovery();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001091
Tom Marshallbead2612019-01-04 14:37:31 -08001092 volmgr->unmountAll();
1093 volmgr->stop();
1094 delete volclient;
1095
1096 sync();
1097
Tao Bao7b9b7db2019-04-19 15:22:15 -07001098 return next_action;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001099}