blob: bd176da5a747f26adf090cb9e1ef3bae7d0fa312 [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
Tao Bao6d99d4b2018-04-25 16:47:04 -070017#include "private/recovery.h"
18
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080019#include <ctype.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070020#include <dirent.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080021#include <errno.h>
22#include <fcntl.h>
23#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070024#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080025#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070026#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080027#include <linux/input.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070028#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080029#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
Patrick Tjincd055ee2014-12-09 11:26:40 -080032#include <sys/klog.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070033#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080034#include <sys/types.h>
Tao Baocdcf28f2016-01-13 15:05:20 -080035#include <sys/wait.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080036#include <time.h>
37#include <unistd.h>
38
Tao Baoc4a18ef2017-02-10 00:13:30 -080039#include <algorithm>
Tao Baoc4a18ef2017-02-10 00:13:30 -080040#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070041#include <string>
42#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070043
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070045#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080046#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070047#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080048#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070049#include <android-base/strings.h>
50#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070051#include <bootloader_message/bootloader_message.h>
Tao Bao75238632015-05-27 14:46:17 -070052#include <cutils/android_reboot.h>
Elliott Hughescb220402016-09-23 15:30:55 -070053#include <cutils/properties.h> /* for property_list */
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070054#include <healthd/BatteryMonitor.h>
Tao Baoe1905ad2017-03-22 14:57:04 -070055#include <private/android_filesystem_config.h> /* for AID_SYSTEM */
Tao Bao6d99d4b2018-04-25 16:47:04 -070056#include <private/android_logger.h> /* private pmsg functions */
Jeff Vander Stoepe35926e2017-06-14 15:30:39 -070057#include <selinux/android.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070058#include <selinux/label.h>
59#include <selinux/selinux.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070060#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080061
Tao Bao75238632015-05-27 14:46:17 -070062#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080063#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070064#include "device.h"
65#include "fuse_sdcard_provider.h"
66#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080067#include "install.h"
68#include "minui/minui.h"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070069#include "otautil/DirUtil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070070#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070071#include "otautil/paths.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080072#include "roots.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070073#include "rotate_logs.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070074#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080075#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070076#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080077
Tao Baoaac9d9f2018-04-29 23:38:59 -070078static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
79static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
80static constexpr const char* LOG_FILE = "/cache/recovery/log";
81static constexpr const char* LAST_INSTALL_FILE = "/cache/recovery/last_install";
82static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
83static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
84static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070085
Tao Baoaac9d9f2018-04-29 23:38:59 -070086static constexpr const char* CACHE_ROOT = "/cache";
87static constexpr const char* DATA_ROOT = "/data";
88static constexpr const char* METADATA_ROOT = "/metadata";
89static constexpr const char* SDCARD_ROOT = "/sdcard";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070090
Tao Baobd0ddcd2017-05-04 13:03:18 -070091// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
92// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
93static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
94
Tao Baoac9d94d2016-11-03 11:37:15 -070095static std::string locale;
Dan Albert8584fcf2016-10-27 03:08:08 +000096static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -070097
Tao Baoac9d94d2016-11-03 11:37:15 -070098RecoveryUI* ui = nullptr;
99bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -0800100std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -0700101const char* reason = nullptr;
102struct selabel_handle* sehandle;
103
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800104/*
105 * The recovery tool communicates with the main system through /cache files.
106 * /cache/recovery/command - INPUT - command line for tool, one arg per line
107 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800108 *
109 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700110 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800111 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700112 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
113 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800114 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700115 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -0800116 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700117 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800118 *
119 * After completing, we remove /cache/recovery/command and reboot.
120 * Arguments may also be supplied in the bootloader control block (BCB).
121 * These important scenarios must be safely restartable at any point:
122 *
123 * FACTORY RESET
124 * 1. user selects "factory reset"
125 * 2. main system writes "--wipe_data" to /cache/recovery/command
126 * 3. main system reboots into recovery
127 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
128 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700129 * 5. erase_volume() reformats /data
130 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800131 * 7. finish_recovery() erases BCB
132 * -- after this, rebooting will restart the main system --
133 * 8. main() calls reboot() to boot main system
134 *
135 * OTA INSTALL
136 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700137 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800138 * 3. main system reboots into recovery
139 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
140 * -- after this, rebooting will attempt to reinstall the update --
141 * 5. install_package() attempts to install the update
142 * NOTE: the package install must itself be restartable from any point
143 * 6. finish_recovery() erases BCB
144 * -- after this, rebooting will (try to) restart the main system --
145 * 7. ** if install failed **
146 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800147 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800148 */
149
Tao Bao641fa972018-04-25 18:59:40 -0700150FILE* fopen_path(const std::string& path, const char* mode) {
151 if (ensure_path_mounted(path.c_str()) != 0) {
Tao Baoac3d1ed2017-07-23 00:01:02 -0700152 LOG(ERROR) << "Can't mount " << path;
153 return nullptr;
154 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800155
Tao Baoac3d1ed2017-07-23 00:01:02 -0700156 // When writing, try to create the containing directory, if necessary. Use generous permissions,
157 // the system (init.rc) will reset them.
158 if (strchr("wa", mode[0])) {
159 mkdir_recursively(path, 0777, true, sehandle);
160 }
Tao Bao641fa972018-04-25 18:59:40 -0700161 return fopen(path.c_str(), mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800162}
163
Tao Bao6d99d4b2018-04-25 16:47:04 -0700164void check_and_fclose(FILE* fp, const std::string& name) {
Tao Bao641fa972018-04-25 18:59:40 -0700165 fflush(fp);
166 if (fsync(fileno(fp)) == -1) {
167 PLOG(ERROR) << "Failed to fsync " << name;
168 }
169 if (ferror(fp)) {
170 PLOG(ERROR) << "Error in " << name;
171 }
172 fclose(fp);
Tao Bao04ca4262015-09-10 15:32:24 -0700173}
174
Elliott Hughesf14af802015-02-10 14:46:14 -0800175bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700176 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800177}
178
Dmitri Plotnikov8706a982017-04-18 08:28:26 -0700179bool reboot(const std::string& command) {
180 std::string cmd = command;
181 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
182 cmd += ",quiescent";
183 }
184 return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
185}
186
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800187// command line args come from, in decreasing precedence:
188// - the actual command line
189// - the bootloader control block (one per line, after "recovery")
190// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800191static std::vector<std::string> get_args(const int argc, char** const argv) {
192 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800193
Tao Baof0ed1592016-12-02 11:32:19 -0800194 bootloader_message boot = {};
195 std::string err;
196 if (!read_bootloader_message(&boot, &err)) {
197 LOG(ERROR) << err;
198 // If fails, leave a zeroed bootloader_message.
199 boot = {};
200 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800201 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800202
Tao Baof0ed1592016-12-02 11:32:19 -0800203 if (boot.command[0] != 0) {
204 std::string boot_command = std::string(boot.command, sizeof(boot.command));
205 LOG(INFO) << "Boot command: " << boot_command;
206 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800207
Tao Baof0ed1592016-12-02 11:32:19 -0800208 if (boot.status[0] != 0) {
209 std::string boot_status = std::string(boot.status, sizeof(boot.status));
210 LOG(INFO) << "Boot status: " << boot_status;
211 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800212
Tao Baof0ed1592016-12-02 11:32:19 -0800213 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800214
Tao Baof0ed1592016-12-02 11:32:19 -0800215 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800216 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800217 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
218 std::string boot_recovery(boot.recovery);
219 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
220 if (!tokens.empty() && tokens[0] == "recovery") {
221 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
222 // Skip empty and '\0'-filled tokens.
223 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
224 }
225 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
226 } else if (boot.recovery[0] != 0) {
227 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
228 }
229 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800230
Tao Baof0ed1592016-12-02 11:32:19 -0800231 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800232 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800233 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800234 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
235 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800236 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800237 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
238 // COMMAND_FILE doesn't use filename as the first argument).
239 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800240 // Skip empty and '\0'-filled tokens.
241 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
242 }
243 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800244 }
Tao Baof0ed1592016-12-02 11:32:19 -0800245 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800246
Tao Baof0ed1592016-12-02 11:32:19 -0800247 // Write the arguments (excluding the filename in args[0]) back into the
248 // bootloader control block. So the device will always boot into recovery to
249 // finish the pending work, until finish_recovery() is called.
250 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800251 if (!update_bootloader_message(options, &err)) {
252 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800253 }
254
255 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800256}
257
Tao Bao2292db82016-12-13 21:53:31 -0800258// Set the BCB to reboot back into recovery (it won't resume the install from
259// sdcard though).
260static void set_sdcard_update_bootloader_message() {
261 std::vector<std::string> options;
262 std::string err;
263 if (!update_bootloader_message(options, &err)) {
264 LOG(ERROR) << "Failed to set BCB message: " << err;
265 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700266}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800267
Tao Baobef39712015-05-04 18:50:27 -0700268// Read from kernel log into buffer and write out to file.
269static void save_kernel_log(const char* destination) {
270 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800271 if (klog_buf_len <= 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700272 PLOG(ERROR) << "Error getting klog size";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800273 return;
274 }
275
Tao Baobef39712015-05-04 18:50:27 -0700276 std::string buffer(klog_buf_len, 0);
277 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
278 if (n == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700279 PLOG(ERROR) << "Error in reading klog";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800280 return;
281 }
Tao Baobef39712015-05-04 18:50:27 -0700282 buffer.resize(n);
283 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800284}
285
Tao Bao641fa972018-04-25 18:59:40 -0700286// Writes content to the current pmsg session.
287static ssize_t __pmsg_write(const std::string& filename, const std::string& buf) {
288 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filename.c_str(),
289 buf.data(), buf.size());
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800290}
291
Tao Bao641fa972018-04-25 18:59:40 -0700292static void copy_log_file_to_pmsg(const std::string& source, const std::string& destination) {
293 std::string content;
294 android::base::ReadFileToString(source, &content);
295 __pmsg_write(destination, content);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800296}
297
Tao Baof0124322015-04-11 02:04:11 +0000298// How much of the temp log we have copied to the copy in cache.
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700299static off_t tmplog_offset = 0;
Tao Baof0124322015-04-11 02:04:11 +0000300
Tao Bao641fa972018-04-25 18:59:40 -0700301static void copy_log_file(const std::string& source, const std::string& destination, bool append) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700302 FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
303 if (dest_fp == nullptr) {
304 PLOG(ERROR) << "Can't open " << destination;
305 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700306 FILE* source_fp = fopen(source.c_str(), "re");
Tianjie Xude6735e2017-07-10 15:13:33 -0700307 if (source_fp != nullptr) {
308 if (append) {
309 fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
310 }
311 char buf[4096];
312 size_t bytes;
313 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
314 fwrite(buf, 1, bytes, dest_fp);
315 }
316 if (append) {
317 tmplog_offset = ftello(source_fp);
318 }
319 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700320 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700321 check_and_fclose(dest_fp, destination);
322 }
Doug Zongker2c3539e2010-09-29 13:21:30 -0700323}
324
Tao Bao682c34b2015-04-07 17:16:35 -0700325static void copy_logs() {
Tao Bao641fa972018-04-25 18:59:40 -0700326 // We only rotate and record the log of the current session if there are actual attempts to modify
327 // the flash, such as wipes, installs from BCB or menu selections. This is to avoid unnecessary
328 // rotation (and possible deletion) of log files, if it does not do anything loggable.
329 if (!modified_flash) {
330 return;
331 }
Tao Bao682c34b2015-04-07 17:16:35 -0700332
Tao Bao641fa972018-04-25 18:59:40 -0700333 // Always write to pmsg, this allows the OTA logs to be caught in `logcat -L`.
334 copy_log_file_to_pmsg(Paths::Get().temporary_log_file(), LAST_LOG_FILE);
335 copy_log_file_to_pmsg(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800336
Tao Bao641fa972018-04-25 18:59:40 -0700337 // We can do nothing for now if there's no /cache partition.
338 if (!has_cache) {
339 return;
340 }
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800341
Tao Bao641fa972018-04-25 18:59:40 -0700342 ensure_path_mounted(LAST_LOG_FILE);
343 ensure_path_mounted(LAST_KMSG_FILE);
344 rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700345
Tao Bao641fa972018-04-25 18:59:40 -0700346 // Copy logs to cache so the system can find out what happened.
347 copy_log_file(Paths::Get().temporary_log_file(), LOG_FILE, true);
348 copy_log_file(Paths::Get().temporary_log_file(), LAST_LOG_FILE, false);
349 copy_log_file(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE, false);
350 save_kernel_log(LAST_KMSG_FILE);
351 chmod(LOG_FILE, 0600);
352 chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
353 chmod(LAST_KMSG_FILE, 0600);
354 chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
355 chmod(LAST_LOG_FILE, 0640);
356 chmod(LAST_INSTALL_FILE, 0644);
357 sync();
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700358}
359
Tao Baoec579032017-07-21 12:13:15 -0700360// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700361// copy our log file to cache as well (for the system to read). This function is
362// idempotent: call it as many times as you like.
Tao Baoac9d94d2016-11-03 11:37:15 -0700363static void finish_recovery() {
Tao Baoec579032017-07-21 12:13:15 -0700364 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
365 // (e.g., directly from the bootloader) it will use the last-known locale.
366 if (!locale.empty() && has_cache) {
367 LOG(INFO) << "Saving locale \"" << locale << "\"";
368 if (ensure_path_mounted(LOCALE_FILE) != 0) {
369 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
370 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
371 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700372 }
Tao Baoec579032017-07-21 12:13:15 -0700373 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700374
Tao Baoec579032017-07-21 12:13:15 -0700375 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800376
Tao Baoec579032017-07-21 12:13:15 -0700377 // Reset to normal system boot so recovery won't cycle indefinitely.
378 std::string err;
379 if (!clear_bootloader_message(&err)) {
380 LOG(ERROR) << "Failed to clear BCB message: " << err;
381 }
382
383 // Remove the command file, so recovery won't repeat indefinitely.
384 if (has_cache) {
385 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
386 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700387 }
Tao Baoec579032017-07-21 12:13:15 -0700388 ensure_path_unmounted(CACHE_ROOT);
389 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800390
Tao Baoec579032017-07-21 12:13:15 -0700391 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800392}
393
Tao Bao3f5a3822016-12-13 11:14:37 -0800394struct saved_log_file {
395 std::string name;
396 struct stat sb;
397 std::string data;
398};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700399
Elliott Hughes945548e2015-06-05 17:59:56 -0700400static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800401 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
402 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700403
Tao Bao3f5a3822016-12-13 11:14:37 -0800404 ui->SetBackground(RecoveryUI::ERASING);
405 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700406
Tao Bao3f5a3822016-12-13 11:14:37 -0800407 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700408
Tao Bao3f5a3822016-12-13 11:14:37 -0800409 if (is_cache) {
410 // If we're reformatting /cache, we load any past logs
411 // (i.e. "/cache/recovery/last_*") and the current log
412 // ("/cache/recovery/log") into memory, so we can restore them after
413 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700414
Tao Bao3f5a3822016-12-13 11:14:37 -0800415 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700416
Tao Bao3f5a3822016-12-13 11:14:37 -0800417 struct dirent* de;
418 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
419 if (d) {
420 while ((de = readdir(d.get())) != nullptr) {
421 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
422 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
423
424 struct stat sb;
425 if (stat(path.c_str(), &sb) == 0) {
426 // truncate files to 512kb
427 if (sb.st_size > (1 << 19)) {
428 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700429 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800430
431 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700432 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800433 fread(&data[0], 1, data.size(), f);
434 fclose(f);
435
436 log_files.emplace_back(saved_log_file{ path, sb, data });
437 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700438 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800439 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800440 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800441 if (errno != ENOENT) {
442 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
443 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800444 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800445 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700446
Tao Bao3f5a3822016-12-13 11:14:37 -0800447 ui->Print("Formatting %s...\n", volume);
448
449 ensure_path_unmounted(volume);
450
451 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800452 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700453 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
454 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
455 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
456 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800457 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700458 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
459 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800460 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700461 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800462 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700463 PLOG(ERROR) << "Failed to convert to file encryption";
464 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800465 }
466 fclose(f);
467 result = format_volume(volume, CONVERT_FBE_DIR);
468 remove(CONVERT_FBE_FILE);
469 rmdir(CONVERT_FBE_DIR);
470 } else {
471 result = format_volume(volume);
472 }
473
474 if (is_cache) {
475 // Re-create the log dir and write back the log entries.
476 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700477 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800478 for (const auto& log : log_files) {
479 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
480 log.sb.st_gid)) {
481 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700482 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800483 }
484 } else {
485 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700486 }
487
Tao Bao3f5a3822016-12-13 11:14:37 -0800488 // Any part of the log we'd copied to cache is now gone.
489 // Reset the pointer so we copy from the beginning of the temp
490 // log.
491 tmplog_offset = 0;
492 copy_logs();
493 }
494
495 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800496}
497
Tao Baofc5499f2017-02-23 19:06:53 -0800498// Display a menu with the specified 'headers' and 'items'. Device specific HandleMenuKey() may
499// return a positive number beyond the given range. Caller sets 'menu_only' to true to ensure only
Tao Bao50dd5322017-03-07 14:57:04 -0800500// a menu item gets selected. 'initial_selection' controls the initial cursor location. Returns the
501// (non-negative) chosen item number, or -1 if timed out waiting for input.
Tao Baofc5499f2017-02-23 19:06:53 -0800502static int get_menu_selection(const char* const* headers, const char* const* items, bool menu_only,
503 int initial_selection, Device* device) {
504 // Throw away keys pressed previously, so user doesn't accidentally trigger menu items.
505 ui->FlushKeys();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700506
Tao Baofc5499f2017-02-23 19:06:53 -0800507 ui->StartMenu(headers, items, initial_selection);
Tao Bao50dd5322017-03-07 14:57:04 -0800508
Tao Baofc5499f2017-02-23 19:06:53 -0800509 int selected = initial_selection;
510 int chosen_item = -1;
Tao Baofc5499f2017-02-23 19:06:53 -0800511 while (chosen_item < 0) {
512 int key = ui->WaitKey();
Tao Bao50dd5322017-03-07 14:57:04 -0800513 if (key == -1) { // WaitKey() timed out.
Tao Baofc5499f2017-02-23 19:06:53 -0800514 if (ui->WasTextEverVisible()) {
515 continue;
516 } else {
Tao Bao50dd5322017-03-07 14:57:04 -0800517 LOG(INFO) << "Timed out waiting for key input; rebooting.";
Tao Baofc5499f2017-02-23 19:06:53 -0800518 ui->EndMenu();
Tao Bao50dd5322017-03-07 14:57:04 -0800519 return -1;
Tao Baofc5499f2017-02-23 19:06:53 -0800520 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700521 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800522
Tao Baofc5499f2017-02-23 19:06:53 -0800523 bool visible = ui->IsTextVisible();
524 int action = device->HandleMenuKey(key, visible);
525
526 if (action < 0) {
527 switch (action) {
528 case Device::kHighlightUp:
529 selected = ui->SelectMenu(--selected);
530 break;
531 case Device::kHighlightDown:
532 selected = ui->SelectMenu(++selected);
533 break;
534 case Device::kInvokeItem:
535 chosen_item = selected;
536 break;
537 case Device::kNoAction:
538 break;
539 }
540 } else if (!menu_only) {
541 chosen_item = action;
542 }
543 }
544
545 ui->EndMenu();
546 return chosen_item;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700547}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800548
Tao Baoc4a18ef2017-02-10 00:13:30 -0800549// Returns the selected filename, or an empty string.
550static std::string browse_directory(const std::string& path, Device* device) {
551 ensure_path_mounted(path.c_str());
Doug Zongker8674a722010-09-15 11:08:23 -0700552
Tao Baoc4a18ef2017-02-10 00:13:30 -0800553 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
554 if (!d) {
555 PLOG(ERROR) << "error opening " << path;
556 return "";
557 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700558
Tao Baoc4a18ef2017-02-10 00:13:30 -0800559 std::vector<std::string> dirs;
560 std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
561
562 dirent* de;
563 while ((de = readdir(d.get())) != nullptr) {
564 std::string name(de->d_name);
565
566 if (de->d_type == DT_DIR) {
567 // Skip "." and ".." entries.
568 if (name == "." || name == "..") continue;
569 dirs.push_back(name + "/");
570 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
571 zips.push_back(name);
572 }
573 }
574
575 std::sort(dirs.begin(), dirs.end());
576 std::sort(zips.begin(), zips.end());
577
578 // Append dirs to the zips list.
579 zips.insert(zips.end(), dirs.begin(), dirs.end());
580
581 const char* entries[zips.size() + 1];
582 entries[zips.size()] = nullptr;
583 for (size_t i = 0; i < zips.size(); i++) {
584 entries[i] = zips[i].c_str();
585 }
586
587 const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
588
589 int chosen_item = 0;
590 while (true) {
Tao Baofc5499f2017-02-23 19:06:53 -0800591 chosen_item = get_menu_selection(headers, entries, true, chosen_item, device);
Tao Baoc4a18ef2017-02-10 00:13:30 -0800592
593 const std::string& item = zips[chosen_item];
594 if (chosen_item == 0) {
595 // Go up but continue browsing (if the caller is browse_directory).
596 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700597 }
598
Tao Baoc4a18ef2017-02-10 00:13:30 -0800599 std::string new_path = path + "/" + item;
600 if (new_path.back() == '/') {
601 // Recurse down into a subdirectory.
602 new_path.pop_back();
603 std::string result = browse_directory(new_path, device);
604 if (!result.empty()) return result;
605 } else {
606 // Selected a zip file: return the path to the caller.
607 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700608 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800609 }
Doug Zongker8674a722010-09-15 11:08:23 -0700610
Tao Baoc4a18ef2017-02-10 00:13:30 -0800611 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700612}
613
Elliott Hughes30694c92015-03-25 15:16:51 -0700614static bool yes_no(Device* device, const char* question1, const char* question2) {
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700615 const char* headers[] = { question1, question2, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700616 const char* items[] = { " No", " Yes", NULL };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700617
Tao Baofc5499f2017-02-23 19:06:53 -0800618 int chosen_item = get_menu_selection(headers, items, true, 0, device);
Elliott Hughes30694c92015-03-25 15:16:51 -0700619 return (chosen_item == 1);
620}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800621
Paul Crowley08404b42016-12-19 13:04:23 -0800622static bool ask_to_wipe_data(Device* device) {
623 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
624}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700625
Paul Crowley08404b42016-12-19 13:04:23 -0800626// Return true on success.
627static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700628 modified_flash = true;
629
Doug Zongker211aebc2011-10-28 15:13:10 -0700630 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700631 bool success = device->PreWipeData();
632 if (success) {
633 success &= erase_volume(DATA_ROOT);
634 if (has_cache) {
635 success &= erase_volume(CACHE_ROOT);
636 }
637 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
638 success &= erase_volume(METADATA_ROOT);
639 }
640 }
641 if (success) {
642 success &= device->PostWipeData();
643 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700644 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
645 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700646}
647
Paul Crowley08404b42016-12-19 13:04:23 -0800648static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700649 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Baofc5499f2017-02-23 19:06:53 -0800650 const char* const headers[] = {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700651 "Can't load Android system. Your data may be corrupt. "
652 "If you continue to get this message, you may need to "
653 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700654 "stored on this device.",
Tao Bao2bbc6d62017-08-13 23:48:55 -0700655 nullptr
Tao Baofc5499f2017-02-23 19:06:53 -0800656 };
657 const char* const items[] = {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700658 "Try again",
659 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800660 NULL
661 };
662 for (;;) {
663 int chosen_item = get_menu_selection(headers, items, true, 0, device);
664 if (chosen_item != 1) {
665 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800666 }
Tao Baofc5499f2017-02-23 19:06:53 -0800667 if (ask_to_wipe_data(device)) {
668 return wipe_data(device);
669 }
670 }
Paul Crowley08404b42016-12-19 13:04:23 -0800671}
672
Tao Baoe39a9bc2015-03-31 12:19:05 -0700673// Return true on success.
674static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800675 if (!has_cache) {
676 ui->Print("No /cache partition found.\n");
677 return false;
678 }
679
Elliott Hughes30694c92015-03-25 15:16:51 -0700680 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700681 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700682 }
683
Tao Bao682c34b2015-04-07 17:16:35 -0700684 modified_flash = true;
685
Elliott Hughes30694c92015-03-25 15:16:51 -0700686 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700687 bool success = erase_volume("/cache");
688 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
689 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700690}
691
Tao Bao1b2a98b2017-03-24 10:45:34 -0700692// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
693// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700694static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700695 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
696 if (fd == -1) {
697 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
698 return false;
699 }
700
701 uint64_t range[2] = { 0, 0 };
702 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
703 PLOG(ERROR) << "Failed to get partition size";
704 return false;
705 }
706 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
707
708 LOG(INFO) << " Trying BLKSECDISCARD...";
709 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
710 PLOG(WARNING) << " Failed";
711
712 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
713 unsigned int zeroes;
714 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
715 LOG(INFO) << " Trying BLKDISCARD...";
716 if (ioctl(fd, BLKDISCARD, &range) == -1) {
717 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700718 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700719 }
720 } else {
721 LOG(INFO) << " Trying BLKZEROOUT...";
722 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
723 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700724 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700725 }
Tao Bao862a4c12016-06-02 11:16:50 -0700726 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700727 }
Tao Bao862a4c12016-06-02 11:16:50 -0700728
Tao Bao1b2a98b2017-03-24 10:45:34 -0700729 LOG(INFO) << " Done";
730 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700731}
732
Yabin Cuifd99a312016-06-09 14:09:39 -0700733// Check if the wipe package matches expectation:
734// 1. verify the package.
735// 2. check metadata (ota-type, pre-device and serial number if having one).
736static bool check_wipe_package(size_t wipe_package_size) {
737 if (wipe_package_size == 0) {
738 LOG(ERROR) << "wipe_package_size is zero";
739 return false;
740 }
741 std::string wipe_package;
742 std::string err_str;
743 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
744 PLOG(ERROR) << "Failed to read wipe package";
745 return false;
746 }
747 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
748 wipe_package.size())) {
749 LOG(ERROR) << "Failed to verify package";
750 return false;
751 }
752
753 // Extract metadata
754 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -0800755 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
756 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -0700757 if (err != 0) {
758 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
759 return false;
760 }
761 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700762 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -0700763 CloseArchive(zip);
764 return false;
765 }
766 CloseArchive(zip);
767
768 // Check metadata
769 std::vector<std::string> lines = android::base::Split(metadata, "\n");
770 bool ota_type_matched = false;
771 bool device_type_matched = false;
772 bool has_serial_number = false;
773 bool serial_number_matched = false;
774 for (const auto& line : lines) {
775 if (line == "ota-type=BRICK") {
776 ota_type_matched = true;
777 } else if (android::base::StartsWith(line, "pre-device=")) {
778 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -0800779 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700780 device_type_matched = (device_type == real_device_type);
781 } else if (android::base::StartsWith(line, "serialno=")) {
782 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -0800783 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700784 has_serial_number = true;
785 serial_number_matched = (serial_no == real_serial_no);
786 }
787 }
788 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
789}
790
Tao Baoaac9d9f2018-04-29 23:38:59 -0700791// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700792static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700793 ui->SetBackground(RecoveryUI::ERASING);
794 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700795
Tao Baoaac9d9f2018-04-29 23:38:59 -0700796 if (!check_wipe_package(wipe_package_size)) {
797 LOG(ERROR) << "Failed to verify wipe package";
798 return false;
799 }
800 static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
801 std::string partition_list;
802 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
803 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
804 return false;
805 }
806
807 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
808 for (const std::string& line : lines) {
809 std::string partition = android::base::Trim(line);
810 // Ignore '#' comment or empty lines.
811 if (android::base::StartsWith(partition, "#") || partition.empty()) {
812 continue;
Tao Bao862a4c12016-06-02 11:16:50 -0700813 }
814
Tao Baoaac9d9f2018-04-29 23:38:59 -0700815 // Proceed anyway even if it fails to wipe some partition.
816 secure_wipe_partition(partition);
817 }
818 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700819}
820
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700821static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800822 std::vector<std::string> entries;
823 if (has_cache) {
824 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
825 auto add_to_entries = [&](const char* filename) {
826 std::string log_file(filename);
827 if (i > 0) {
828 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700829 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800830
831 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
832 entries.push_back(std::move(log_file));
833 }
834 };
835
836 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
837 add_to_entries(LAST_LOG_FILE);
838
839 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
840 add_to_entries(LAST_KMSG_FILE);
841 }
842 } else {
843 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700844 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800845 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700846 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700847 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700848 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800849 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700850
Tao Bao08fc6be2017-03-07 00:56:27 -0800851 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700852
Tao Bao08fc6be2017-03-07 00:56:27 -0800853 std::vector<const char*> menu_entries(entries.size());
854 std::transform(entries.cbegin(), entries.cend(), menu_entries.begin(),
855 [](const std::string& entry) { return entry.c_str(); });
856 menu_entries.push_back(nullptr);
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700857
Tao Bao08fc6be2017-03-07 00:56:27 -0800858 const char* headers[] = { "Select file to view", nullptr };
Elliott Hughes8de52072015-04-08 20:06:50 -0700859
Tao Bao08fc6be2017-03-07 00:56:27 -0800860 int chosen_item = 0;
861 while (true) {
Tao Baofc5499f2017-02-23 19:06:53 -0800862 chosen_item = get_menu_selection(headers, menu_entries.data(), true, chosen_item, device);
Tao Bao08fc6be2017-03-07 00:56:27 -0800863 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700864
Tao Bao08fc6be2017-03-07 00:56:27 -0800865 ui->ShowFile(entries[chosen_item].c_str());
866 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700867}
868
Tao Baodb7e8982017-03-06 23:53:16 -0800869static void run_graphics_test() {
870 // Switch to graphics screen.
871 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700872
Tao Baodb7e8982017-03-06 23:53:16 -0800873 ui->SetProgressType(RecoveryUI::INDETERMINATE);
874 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
875 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700876
Tao Baodb7e8982017-03-06 23:53:16 -0800877 ui->SetBackground(RecoveryUI::ERROR);
878 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700879
Tao Baodb7e8982017-03-06 23:53:16 -0800880 ui->SetBackground(RecoveryUI::NO_COMMAND);
881 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700882
Tao Baodb7e8982017-03-06 23:53:16 -0800883 ui->SetBackground(RecoveryUI::ERASING);
884 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700885
Tao Baodb7e8982017-03-06 23:53:16 -0800886 // Calling SetBackground() after SetStage() to trigger a redraw.
887 ui->SetStage(1, 3);
888 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
889 sleep(1);
890 ui->SetStage(2, 3);
891 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
892 sleep(1);
893 ui->SetStage(3, 3);
894 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
895 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700896
Tao Baodb7e8982017-03-06 23:53:16 -0800897 ui->SetStage(-1, -1);
898 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700899
Tao Baodb7e8982017-03-06 23:53:16 -0800900 ui->SetProgressType(RecoveryUI::DETERMINATE);
901 ui->ShowProgress(1.0, 10.0);
902 float fraction = 0.0;
903 for (size_t i = 0; i < 100; ++i) {
904 fraction += .01;
905 ui->SetProgress(fraction);
906 usleep(100000);
907 }
908
909 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700910}
911
Tao Baocdcf28f2016-01-13 15:05:20 -0800912// How long (in seconds) we wait for the fuse-provided package file to
913// appear, before timing out.
914#define SDCARD_INSTALL_TIMEOUT 10
915
Tao Bao145d8612015-03-25 15:51:15 -0700916static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700917 modified_flash = true;
918
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000919 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
920 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
921 return INSTALL_ERROR;
922 }
923
Tao Baoc4a18ef2017-02-10 00:13:30 -0800924 std::string path = browse_directory(SDCARD_ROOT, device);
925 if (path.empty()) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700926 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800927 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000928 return INSTALL_ERROR;
929 }
930
Tao Baoc4a18ef2017-02-10 00:13:30 -0800931 ui->Print("\n-- Install %s ...\n", path.c_str());
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000932 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000933
Tao Baocdcf28f2016-01-13 15:05:20 -0800934 // We used to use fuse in a thread as opposed to a process. Since accessing
935 // through fuse involves going from kernel to userspace to kernel, it leads
936 // to deadlock when a page fault occurs. (Bug: 26313124)
937 pid_t child;
938 if ((child = fork()) == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800939 bool status = start_sdcard_fuse(path.c_str());
Tao Baocdcf28f2016-01-13 15:05:20 -0800940
941 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
942 }
943
944 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
945 // process is ready.
946 int result = INSTALL_ERROR;
947 int status;
948 bool waited = false;
949 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
950 if (waitpid(child, &status, WNOHANG) == -1) {
951 result = INSTALL_ERROR;
952 waited = true;
953 break;
954 }
955
956 struct stat sb;
957 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
958 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
959 sleep(1);
960 continue;
961 } else {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700962 LOG(ERROR) << "Timed out waiting for the fuse-provided package.";
Tao Baocdcf28f2016-01-13 15:05:20 -0800963 result = INSTALL_ERROR;
964 kill(child, SIGKILL);
965 break;
966 }
967 }
968
Tao Bao641fa972018-04-25 18:59:40 -0700969 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -0800970 break;
971 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000972
Tao Baocdcf28f2016-01-13 15:05:20 -0800973 if (!waited) {
974 // Calling stat() on this magic filename signals the fuse
975 // filesystem to shut down.
976 struct stat sb;
977 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
978
979 waitpid(child, &status, 0);
980 }
981
982 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700983 LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status);
Tao Baocdcf28f2016-01-13 15:05:20 -0800984 }
985
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000986 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -0800987 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000988}
989
Tao Bao50dd5322017-03-07 14:57:04 -0800990// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
991// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
992static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
993 for (;;) {
994 finish_recovery();
995 switch (status) {
996 case INSTALL_SUCCESS:
997 case INSTALL_NONE:
998 ui->SetBackground(RecoveryUI::NO_COMMAND);
999 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -07001000
Tao Bao50dd5322017-03-07 14:57:04 -08001001 case INSTALL_ERROR:
1002 case INSTALL_CORRUPT:
1003 ui->SetBackground(RecoveryUI::ERROR);
1004 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001005 }
Tao Bao50dd5322017-03-07 14:57:04 -08001006 ui->SetProgressType(RecoveryUI::EMPTY);
1007
1008 int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), false, 0, device);
1009
1010 // Device-specific code may take some action here. It may return one of the core actions
1011 // handled in the switch statement below.
1012 Device::BuiltinAction chosen_action =
1013 (chosen_item == -1) ? Device::REBOOT : device->InvokeMenuItem(chosen_item);
1014
1015 bool should_wipe_cache = false;
1016 switch (chosen_action) {
1017 case Device::NO_ACTION:
1018 break;
1019
1020 case Device::REBOOT:
1021 case Device::SHUTDOWN:
1022 case Device::REBOOT_BOOTLOADER:
1023 return chosen_action;
1024
1025 case Device::WIPE_DATA:
1026 if (ui->IsTextVisible()) {
1027 if (ask_to_wipe_data(device)) {
1028 wipe_data(device);
1029 }
1030 } else {
1031 wipe_data(device);
1032 return Device::NO_ACTION;
1033 }
1034 break;
1035
1036 case Device::WIPE_CACHE:
1037 wipe_cache(ui->IsTextVisible(), device);
1038 if (!ui->IsTextVisible()) return Device::NO_ACTION;
1039 break;
1040
1041 case Device::APPLY_ADB_SIDELOAD:
1042 case Device::APPLY_SDCARD:
1043 {
1044 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
1045 if (adb) {
Tao Bao641fa972018-04-25 18:59:40 -07001046 status = apply_from_adb(&should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -08001047 } else {
1048 status = apply_from_sdcard(device, &should_wipe_cache);
1049 }
1050
1051 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1052 if (!wipe_cache(false, device)) {
1053 status = INSTALL_ERROR;
1054 }
1055 }
1056
1057 if (status != INSTALL_SUCCESS) {
1058 ui->SetBackground(RecoveryUI::ERROR);
1059 ui->Print("Installation aborted.\n");
1060 copy_logs();
1061 } else if (!ui->IsTextVisible()) {
1062 return Device::NO_ACTION; // reboot if logs aren't visible
1063 } else {
1064 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
1065 }
1066 }
1067 break;
1068
1069 case Device::VIEW_RECOVERY_LOGS:
1070 choose_recovery_file(device);
1071 break;
1072
1073 case Device::RUN_GRAPHICS_TEST:
1074 run_graphics_test();
1075 break;
1076
Tianjie Xu29d55752017-09-20 17:53:46 -07001077 case Device::RUN_LOCALE_TEST: {
1078 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
1079 screen_ui->CheckBackgroundTextImages(locale);
1080 break;
1081 }
Tao Bao50dd5322017-03-07 14:57:04 -08001082 case Device::MOUNT_SYSTEM:
1083 // For a system image built with the root directory (i.e. system_root_image == "true"), we
1084 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
1085 // work (the symlink is created through the build system). (Bug: 22855115)
1086 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
1087 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1088 ui->Print("Mounted /system.\n");
1089 }
1090 } else {
1091 if (ensure_path_mounted("/system") != -1) {
1092 ui->Print("Mounted /system.\n");
1093 }
1094 }
1095 break;
1096 }
1097 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001098}
1099
Tao Bao99f0d9e2016-10-13 12:46:38 -07001100static void print_property(const char* key, const char* name, void* /* cookie */) {
1101 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001102}
1103
Tao Baoac9d94d2016-11-03 11:37:15 -07001104static std::string load_locale_from_cache() {
1105 if (ensure_path_mounted(LOCALE_FILE) != 0) {
1106 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
1107 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -07001108 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001109
1110 std::string content;
1111 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
1112 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
1113 return "";
1114 }
1115
1116 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001117}
1118
Tao Baoac9d94d2016-11-03 11:37:15 -07001119void ui_print(const char* format, ...) {
1120 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -07001121 va_list ap;
1122 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -07001123 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001124 va_end(ap);
1125
Tao Baoac9d94d2016-11-03 11:37:15 -07001126 if (ui != nullptr) {
1127 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -07001128 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -07001129 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001130 }
1131}
1132
Tao Baof2ea6d72018-04-26 10:40:36 -07001133static bool is_battery_ok(int* required_battery_level) {
1134 struct healthd_config healthd_config = {
1135 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1136 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1137 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1138 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1139 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1140 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1141 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1142 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1143 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1144 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1145 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1146 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1147 .energyCounter = nullptr,
1148 .boot_min_cap = 0,
1149 .screen_on = nullptr
1150 };
1151 healthd_board_init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001152
Tao Baof2ea6d72018-04-26 10:40:36 -07001153 android::BatteryMonitor monitor;
1154 monitor.init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001155
Tao Baof2ea6d72018-04-26 10:40:36 -07001156 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
1157 int wait_second = 0;
1158 while (true) {
1159 int charge_status = monitor.getChargeStatus();
1160 // Treat unknown status as charged.
1161 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1162 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1163 android::BatteryProperty capacity;
1164 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1165 ui_print("charge_status %d, charged %d, status %d, capacity %" PRId64 "\n", charge_status,
1166 charged, status, capacity.valueInt64);
1167 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1168 // the battery profile. Before the load finishes, it reports value 50 as a fake
1169 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1170 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1171 if (status == 0 && capacity.valueInt64 == 50) {
1172 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1173 sleep(1);
1174 wait_second++;
1175 continue;
1176 }
Yabin Cui99281df2016-02-17 12:21:52 -08001177 }
Tao Baof2ea6d72018-04-26 10:40:36 -07001178 // If we can't read battery percentage, it may be a device without battery. In this situation,
1179 // use 100 as a fake battery percentage.
1180 if (status != 0) {
1181 capacity.valueInt64 = 100;
1182 }
1183
1184 // GmsCore enters recovery mode to install package when having enough battery percentage.
1185 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
1186 // battery with a slightly lower limitation.
1187 static constexpr int BATTERY_OK_PERCENTAGE = 20;
1188 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
1189 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
1190 return capacity.valueInt64 >= *required_battery_level;
1191 }
Yabin Cui99281df2016-02-17 12:21:52 -08001192}
1193
Tianjie Xu99b73be2017-11-28 17:23:06 -08001194// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001195static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1196 std::vector<std::string> options;
1197 for (const auto& arg : args) {
1198 if (!android::base::StartsWith(arg, "--retry_count")) {
1199 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001200 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001201 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001202
Tianjie Xu99b73be2017-11-28 17:23:06 -08001203 // Update the retry counter in BCB.
1204 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001205 std::string err;
1206 if (!update_bootloader_message(options, &err)) {
1207 LOG(ERROR) << err;
1208 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001209}
1210
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001211static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001212 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1213 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001214 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
1215 static const std::vector<std::string> kBootreasonBlacklist{
1216 "kernel_panic",
1217 "Panic",
1218 };
1219 for (const auto& str : kBootreasonBlacklist) {
1220 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001221 }
Tao Baoefc35592017-01-08 22:45:47 -08001222 }
1223 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001224}
1225
Tao Bao641fa972018-04-25 18:59:40 -07001226static void log_failure_code(ErrorCode code, const std::string& update_package) {
1227 std::vector<std::string> log_buffer = {
1228 update_package,
1229 "0", // install result
1230 "error: " + std::to_string(code),
1231 };
1232 std::string log_content = android::base::Join(log_buffer, "\n");
1233 const std::string& install_file = Paths::Get().temporary_install_file();
1234 if (!android::base::WriteStringToFile(log_content, install_file)) {
1235 PLOG(ERROR) << "Failed to write " << install_file;
1236 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001237
Tao Bao641fa972018-04-25 18:59:40 -07001238 // Also write the info into last_log.
1239 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001240}
1241
Tao Bao6d99d4b2018-04-25 16:47:04 -07001242int start_recovery(int argc, char** argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001243 time_t start = time(nullptr);
1244
Tianjie Xu99b73be2017-11-28 17:23:06 -08001245 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1246
1247 load_volume_table();
1248 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1249
1250 std::vector<std::string> args = get_args(argc, argv);
1251 std::vector<char*> args_to_parse(args.size());
1252 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1253 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1254
Tao Baof9f17342018-04-27 10:44:04 -07001255 static constexpr struct option OPTIONS[] = {
1256 { "just_exit", no_argument, nullptr, 'x' },
1257 { "locale", required_argument, nullptr, 0 },
1258 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
1259 { "reason", required_argument, nullptr, 0 },
1260 { "retry_count", required_argument, nullptr, 0 },
1261 { "security", no_argument, nullptr, 0 },
1262 { "show_text", no_argument, nullptr, 't' },
1263 { "shutdown_after", no_argument, nullptr, 0 },
1264 { "sideload", no_argument, nullptr, 0 },
1265 { "sideload_auto_reboot", no_argument, nullptr, 0 },
1266 { "update_package", required_argument, nullptr, 0 },
1267 { "wipe_ab", no_argument, nullptr, 0 },
1268 { "wipe_cache", no_argument, nullptr, 0 },
1269 { "wipe_data", no_argument, nullptr, 0 },
1270 { "wipe_package_size", required_argument, nullptr, 0 },
1271 { nullptr, 0, nullptr, 0 },
1272 };
1273
Tianjie Xu99b73be2017-11-28 17:23:06 -08001274 const char* update_package = nullptr;
1275 bool should_wipe_data = false;
1276 bool should_prompt_and_wipe_data = false;
1277 bool should_wipe_cache = false;
1278 bool should_wipe_ab = false;
1279 size_t wipe_package_size = 0;
1280 bool show_text = false;
1281 bool sideload = false;
1282 bool sideload_auto_reboot = false;
1283 bool just_exit = false;
1284 bool shutdown_after = false;
1285 int retry_count = 0;
1286 bool security_update = false;
1287
1288 int arg;
1289 int option_index;
1290 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1291 &option_index)) != -1) {
1292 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001293 case 't':
1294 show_text = true;
1295 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001296 case 'x':
1297 just_exit = true;
1298 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001299 case 0: {
1300 std::string option = OPTIONS[option_index].name;
Tao Baof9f17342018-04-27 10:44:04 -07001301 if (option == "locale") {
1302 locale = optarg;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001303 } else if (option == "prompt_and_wipe_data") {
1304 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -07001305 } else if (option == "reason") {
1306 reason = optarg;
1307 } else if (option == "retry_count") {
1308 android::base::ParseInt(optarg, &retry_count, 0);
1309 } else if (option == "security") {
1310 security_update = true;
1311 } else if (option == "sideload") {
1312 sideload = true;
1313 } else if (option == "sideload_auto_reboot") {
1314 sideload = true;
1315 sideload_auto_reboot = true;
1316 } else if (option == "shutdown_after") {
1317 shutdown_after = true;
1318 } else if (option == "update_package") {
1319 update_package = optarg;
1320 } else if (option == "wipe_ab") {
1321 should_wipe_ab = true;
1322 } else if (option == "wipe_cache") {
1323 should_wipe_cache = true;
1324 } else if (option == "wipe_data") {
1325 should_wipe_data = true;
1326 } else if (option == "wipe_package_size") {
1327 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001328 }
1329 break;
1330 }
1331 case '?':
1332 LOG(ERROR) << "Invalid command argument";
1333 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001334 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001335 }
Doug Zongker9270a202012-01-09 15:16:13 -08001336
Tianjie Xu99b73be2017-11-28 17:23:06 -08001337 if (locale.empty()) {
1338 if (has_cache) {
1339 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001340 }
1341
Tao Baoac9d94d2016-11-03 11:37:15 -07001342 if (locale.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001343 static constexpr const char* DEFAULT_LOCALE = "en-US";
Tianjie Xu99b73be2017-11-28 17:23:06 -08001344 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001345 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001346 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001347
Tianjie Xu99b73be2017-11-28 17:23:06 -08001348 printf("locale is [%s]\n", locale.c_str());
1349 printf("stage is [%s]\n", stage.c_str());
1350 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001351
Tianjie Xu99b73be2017-11-28 17:23:06 -08001352 Device* device = make_device();
1353 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1354 printf("Quiescent recovery mode.\n");
1355 ui = new StubRecoveryUI();
1356 } else {
1357 ui = device->GetUI();
1358
1359 if (!ui->Init(locale)) {
1360 printf("Failed to initialize UI, use stub UI instead.\n");
1361 ui = new StubRecoveryUI();
1362 }
1363 }
1364
1365 // Set background string to "installing security update" for security update,
1366 // otherwise set it to "installing system update".
1367 ui->SetSystemUpdateText(security_update);
1368
1369 int st_cur, st_max;
1370 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1371 ui->SetStage(st_cur, st_max);
1372 }
1373
1374 ui->SetBackground(RecoveryUI::NONE);
1375 if (show_text) ui->ShowText(true);
1376
1377 sehandle = selinux_android_file_context_handle();
1378 selinux_android_set_sehandle(sehandle);
1379 if (!sehandle) {
1380 ui->Print("Warning: No file_contexts\n");
1381 }
1382
1383 device->StartRecovery();
1384
1385 printf("Command:");
1386 for (const auto& arg : args) {
1387 printf(" \"%s\"", arg.c_str());
1388 }
1389 printf("\n\n");
1390
1391 property_list(print_property, nullptr);
1392 printf("\n");
1393
1394 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1395
1396 int status = INSTALL_SUCCESS;
1397
1398 if (update_package != nullptr) {
1399 // It's not entirely true that we will modify the flash. But we want
1400 // to log the update attempt since update_package is non-NULL.
1401 modified_flash = true;
1402
Tao Baof2ea6d72018-04-26 10:40:36 -07001403 int required_battery_level;
1404 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1405 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1406 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001407 // Log the error code to last_install when installation skips due to
1408 // low battery.
1409 log_failure_code(kLowBattery, update_package);
1410 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001411 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001412 // Skip update-on-reboot when bootreason is kernel_panic or similar
1413 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1414 log_failure_code(kBootreasonInBlacklist, update_package);
1415 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001416 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001417 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1418 // identify the interrupted update due to unexpected reboots.
1419 if (retry_count == 0) {
1420 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001421 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001422
Tao Bao641fa972018-04-25 18:59:40 -07001423 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001424 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1425 wipe_cache(false, device);
1426 }
1427 if (status != INSTALL_SUCCESS) {
1428 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001429
1430 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1431 // RETRY_LIMIT times before we abandon this OTA update.
1432 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001433 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
1434 copy_logs();
1435 retry_count += 1;
1436 set_retry_bootloader_message(retry_count, args);
1437 // Print retry count on screen.
1438 ui->Print("Retry attempt %d\n", retry_count);
1439
1440 // Reboot and retry the update
1441 if (!reboot("reboot,recovery")) {
1442 ui->Print("Reboot failed\n");
1443 } else {
1444 while (true) {
1445 pause();
1446 }
1447 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001448 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001449 // If this is an eng or userdebug build, then automatically
1450 // turn the text display on if the script fails so the error
1451 // message is visible.
1452 if (is_ro_debuggable()) {
1453 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001454 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001455 }
Doug Zongker8674a722010-09-15 11:08:23 -07001456 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001457 } else if (should_wipe_data) {
1458 if (!wipe_data(device)) {
1459 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001460 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001461 } else if (should_prompt_and_wipe_data) {
1462 ui->ShowText(true);
1463 ui->SetBackground(RecoveryUI::ERROR);
1464 if (!prompt_and_wipe_data(device)) {
1465 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001466 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001467 ui->ShowText(false);
1468 } else if (should_wipe_cache) {
1469 if (!wipe_cache(false, device)) {
1470 status = INSTALL_ERROR;
1471 }
1472 } else if (should_wipe_ab) {
1473 if (!wipe_ab_device(wipe_package_size)) {
1474 status = INSTALL_ERROR;
1475 }
1476 } else if (sideload) {
1477 // 'adb reboot sideload' acts the same as user presses key combinations
1478 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1479 // display will NOT be turned on by default. And it will reboot after
1480 // sideload finishes even if there are errors. Unless one turns on the
1481 // text display during the installation. This is to enable automated
1482 // testing.
1483 if (!sideload_auto_reboot) {
1484 ui->ShowText(true);
1485 }
Tao Bao641fa972018-04-25 18:59:40 -07001486 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001487 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1488 if (!wipe_cache(false, device)) {
1489 status = INSTALL_ERROR;
1490 }
1491 }
1492 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1493 if (sideload_auto_reboot) {
1494 ui->Print("Rebooting automatically.\n");
1495 }
1496 } else if (!just_exit) {
1497 // If this is an eng or userdebug build, automatically turn on the text display if no command
1498 // is specified. Note that this should be called before setting the background to avoid
1499 // flickering the background image.
1500 if (is_ro_debuggable()) {
1501 ui->ShowText(true);
1502 }
1503 status = INSTALL_NONE; // No command specified
1504 ui->SetBackground(RecoveryUI::NO_COMMAND);
1505 }
1506
1507 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1508 ui->SetBackground(RecoveryUI::ERROR);
1509 if (!ui->IsTextVisible()) {
1510 sleep(5);
1511 }
1512 }
1513
1514 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1515 // 1. If the recovery menu is visible, prompt and wait for commands.
1516 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1517 // recovery to sideload a package.)
1518 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1519 // without waiting.
1520 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1521 // reboot after it shows the "error" screen for 5s.
1522 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1523 Device::BuiltinAction temp = prompt_and_wait(device, status);
1524 if (temp != Device::NO_ACTION) {
1525 after = temp;
1526 }
1527 }
1528
1529 // Save logs and clean up before rebooting or shutting down.
1530 finish_recovery();
1531
1532 switch (after) {
1533 case Device::SHUTDOWN:
1534 ui->Print("Shutting down...\n");
1535 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1536 break;
1537
1538 case Device::REBOOT_BOOTLOADER:
1539 ui->Print("Rebooting to bootloader...\n");
1540 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
1541 break;
1542
1543 default:
1544 ui->Print("Rebooting...\n");
1545 reboot("reboot,");
1546 break;
1547 }
1548 while (true) {
1549 pause();
1550 }
1551 // Should be unreachable.
1552 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001553}