blob: 7219771cb7540382de5a51f56190a60fe168d575 [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 Bao3aec6962018-04-20 09:24:58 -070040#include <functional>
Tao Baoc4a18ef2017-02-10 00:13:30 -080041#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070042#include <string>
43#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070044
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070046#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080047#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070048#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080049#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070050#include <android-base/strings.h>
51#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070052#include <bootloader_message/bootloader_message.h>
Tao Bao75238632015-05-27 14:46:17 -070053#include <cutils/android_reboot.h>
Elliott Hughescb220402016-09-23 15:30:55 -070054#include <cutils/properties.h> /* for property_list */
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070055#include <healthd/BatteryMonitor.h>
Tao Baoe1905ad2017-03-22 14:57:04 -070056#include <private/android_filesystem_config.h> /* for AID_SYSTEM */
Tao Bao6d99d4b2018-04-25 16:47:04 -070057#include <private/android_logger.h> /* private pmsg functions */
Jeff Vander Stoepe35926e2017-06-14 15:30:39 -070058#include <selinux/android.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070059#include <selinux/label.h>
60#include <selinux/selinux.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070061#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080062
Tao Bao75238632015-05-27 14:46:17 -070063#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080064#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070065#include "device.h"
66#include "fuse_sdcard_provider.h"
67#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080068#include "install.h"
69#include "minui/minui.h"
Tao Bao17054c02018-05-03 22:41:23 -070070#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070071#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070072#include "otautil/paths.h"
Tao Bao2c526392018-05-03 23:01:13 -070073#include "otautil/sysutil.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080074#include "roots.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070075#include "rotate_logs.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070076#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080077#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070078#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080079
Tao Baoaac9d9f2018-04-29 23:38:59 -070080static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
81static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
82static constexpr const char* LOG_FILE = "/cache/recovery/log";
83static constexpr const char* LAST_INSTALL_FILE = "/cache/recovery/last_install";
84static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
85static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
86static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070087
Tao Baoaac9d9f2018-04-29 23:38:59 -070088static constexpr const char* CACHE_ROOT = "/cache";
89static constexpr const char* DATA_ROOT = "/data";
90static constexpr const char* METADATA_ROOT = "/metadata";
91static constexpr const char* SDCARD_ROOT = "/sdcard";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070092
Tao Baobd0ddcd2017-05-04 13:03:18 -070093// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
94// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
95static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
96
Tao Baoac9d94d2016-11-03 11:37:15 -070097static std::string locale;
Dan Albert8584fcf2016-10-27 03:08:08 +000098static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -070099
Tao Baoac9d94d2016-11-03 11:37:15 -0700100RecoveryUI* ui = nullptr;
101bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -0800102std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -0700103const char* reason = nullptr;
104struct selabel_handle* sehandle;
105
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800106/*
107 * The recovery tool communicates with the main system through /cache files.
108 * /cache/recovery/command - INPUT - command line for tool, one arg per line
109 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800110 *
111 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700112 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700114 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
115 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800116 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700117 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -0800118 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700119 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800120 *
121 * After completing, we remove /cache/recovery/command and reboot.
122 * Arguments may also be supplied in the bootloader control block (BCB).
123 * These important scenarios must be safely restartable at any point:
124 *
125 * FACTORY RESET
126 * 1. user selects "factory reset"
127 * 2. main system writes "--wipe_data" to /cache/recovery/command
128 * 3. main system reboots into recovery
129 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
130 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700131 * 5. erase_volume() reformats /data
132 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800133 * 7. finish_recovery() erases BCB
134 * -- after this, rebooting will restart the main system --
135 * 8. main() calls reboot() to boot main system
136 *
137 * OTA INSTALL
138 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700139 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800140 * 3. main system reboots into recovery
141 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
142 * -- after this, rebooting will attempt to reinstall the update --
143 * 5. install_package() attempts to install the update
144 * NOTE: the package install must itself be restartable from any point
145 * 6. finish_recovery() erases BCB
146 * -- after this, rebooting will (try to) restart the main system --
147 * 7. ** if install failed **
148 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800149 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800150 */
151
Tao Bao641fa972018-04-25 18:59:40 -0700152FILE* fopen_path(const std::string& path, const char* mode) {
153 if (ensure_path_mounted(path.c_str()) != 0) {
Tao Baoac3d1ed2017-07-23 00:01:02 -0700154 LOG(ERROR) << "Can't mount " << path;
155 return nullptr;
156 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800157
Tao Baoac3d1ed2017-07-23 00:01:02 -0700158 // When writing, try to create the containing directory, if necessary. Use generous permissions,
159 // the system (init.rc) will reset them.
160 if (strchr("wa", mode[0])) {
161 mkdir_recursively(path, 0777, true, sehandle);
162 }
Tao Bao641fa972018-04-25 18:59:40 -0700163 return fopen(path.c_str(), mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800164}
165
Tao Bao6d99d4b2018-04-25 16:47:04 -0700166void check_and_fclose(FILE* fp, const std::string& name) {
Tao Bao641fa972018-04-25 18:59:40 -0700167 fflush(fp);
168 if (fsync(fileno(fp)) == -1) {
169 PLOG(ERROR) << "Failed to fsync " << name;
170 }
171 if (ferror(fp)) {
172 PLOG(ERROR) << "Error in " << name;
173 }
174 fclose(fp);
Tao Bao04ca4262015-09-10 15:32:24 -0700175}
176
Elliott Hughesf14af802015-02-10 14:46:14 -0800177bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700178 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800179}
180
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800181// command line args come from, in decreasing precedence:
182// - the actual command line
183// - the bootloader control block (one per line, after "recovery")
184// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800185static std::vector<std::string> get_args(const int argc, char** const argv) {
186 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800187
Tao Baof0ed1592016-12-02 11:32:19 -0800188 bootloader_message boot = {};
189 std::string err;
190 if (!read_bootloader_message(&boot, &err)) {
191 LOG(ERROR) << err;
192 // If fails, leave a zeroed bootloader_message.
193 boot = {};
194 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800195 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800196
Tao Baof0ed1592016-12-02 11:32:19 -0800197 if (boot.command[0] != 0) {
198 std::string boot_command = std::string(boot.command, sizeof(boot.command));
199 LOG(INFO) << "Boot command: " << boot_command;
200 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800201
Tao Baof0ed1592016-12-02 11:32:19 -0800202 if (boot.status[0] != 0) {
203 std::string boot_status = std::string(boot.status, sizeof(boot.status));
204 LOG(INFO) << "Boot status: " << boot_status;
205 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800206
Tao Baof0ed1592016-12-02 11:32:19 -0800207 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800208
Tao Baof0ed1592016-12-02 11:32:19 -0800209 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800210 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800211 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
212 std::string boot_recovery(boot.recovery);
213 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
214 if (!tokens.empty() && tokens[0] == "recovery") {
215 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
216 // Skip empty and '\0'-filled tokens.
217 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
218 }
219 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
220 } else if (boot.recovery[0] != 0) {
221 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
222 }
223 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800224
Tao Baof0ed1592016-12-02 11:32:19 -0800225 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800226 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800227 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800228 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
229 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800230 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800231 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
232 // COMMAND_FILE doesn't use filename as the first argument).
233 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800234 // Skip empty and '\0'-filled tokens.
235 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
236 }
237 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800238 }
Tao Baof0ed1592016-12-02 11:32:19 -0800239 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800240
Tao Baof0ed1592016-12-02 11:32:19 -0800241 // Write the arguments (excluding the filename in args[0]) back into the
242 // bootloader control block. So the device will always boot into recovery to
243 // finish the pending work, until finish_recovery() is called.
244 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800245 if (!update_bootloader_message(options, &err)) {
246 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800247 }
248
249 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800250}
251
Tao Bao2292db82016-12-13 21:53:31 -0800252// Set the BCB to reboot back into recovery (it won't resume the install from
253// sdcard though).
254static void set_sdcard_update_bootloader_message() {
255 std::vector<std::string> options;
256 std::string err;
257 if (!update_bootloader_message(options, &err)) {
258 LOG(ERROR) << "Failed to set BCB message: " << err;
259 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700260}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800261
Tao Baobef39712015-05-04 18:50:27 -0700262// Read from kernel log into buffer and write out to file.
263static void save_kernel_log(const char* destination) {
264 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800265 if (klog_buf_len <= 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700266 PLOG(ERROR) << "Error getting klog size";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800267 return;
268 }
269
Tao Baobef39712015-05-04 18:50:27 -0700270 std::string buffer(klog_buf_len, 0);
271 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
272 if (n == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700273 PLOG(ERROR) << "Error in reading klog";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800274 return;
275 }
Tao Baobef39712015-05-04 18:50:27 -0700276 buffer.resize(n);
277 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800278}
279
Tao Bao641fa972018-04-25 18:59:40 -0700280// Writes content to the current pmsg session.
281static ssize_t __pmsg_write(const std::string& filename, const std::string& buf) {
282 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filename.c_str(),
283 buf.data(), buf.size());
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800284}
285
Tao Bao641fa972018-04-25 18:59:40 -0700286static void copy_log_file_to_pmsg(const std::string& source, const std::string& destination) {
287 std::string content;
288 android::base::ReadFileToString(source, &content);
289 __pmsg_write(destination, content);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800290}
291
Tao Baof0124322015-04-11 02:04:11 +0000292// How much of the temp log we have copied to the copy in cache.
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700293static off_t tmplog_offset = 0;
Tao Baof0124322015-04-11 02:04:11 +0000294
Tao Bao641fa972018-04-25 18:59:40 -0700295static void copy_log_file(const std::string& source, const std::string& destination, bool append) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700296 FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
297 if (dest_fp == nullptr) {
298 PLOG(ERROR) << "Can't open " << destination;
299 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700300 FILE* source_fp = fopen(source.c_str(), "re");
Tianjie Xude6735e2017-07-10 15:13:33 -0700301 if (source_fp != nullptr) {
302 if (append) {
303 fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
304 }
305 char buf[4096];
306 size_t bytes;
307 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
308 fwrite(buf, 1, bytes, dest_fp);
309 }
310 if (append) {
311 tmplog_offset = ftello(source_fp);
312 }
313 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700314 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700315 check_and_fclose(dest_fp, destination);
316 }
Doug Zongker2c3539e2010-09-29 13:21:30 -0700317}
318
Tao Bao682c34b2015-04-07 17:16:35 -0700319static void copy_logs() {
Tao Bao641fa972018-04-25 18:59:40 -0700320 // We only rotate and record the log of the current session if there are actual attempts to modify
321 // the flash, such as wipes, installs from BCB or menu selections. This is to avoid unnecessary
322 // rotation (and possible deletion) of log files, if it does not do anything loggable.
323 if (!modified_flash) {
324 return;
325 }
Tao Bao682c34b2015-04-07 17:16:35 -0700326
Tao Bao641fa972018-04-25 18:59:40 -0700327 // Always write to pmsg, this allows the OTA logs to be caught in `logcat -L`.
328 copy_log_file_to_pmsg(Paths::Get().temporary_log_file(), LAST_LOG_FILE);
329 copy_log_file_to_pmsg(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800330
Tao Bao641fa972018-04-25 18:59:40 -0700331 // We can do nothing for now if there's no /cache partition.
332 if (!has_cache) {
333 return;
334 }
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800335
Tao Bao641fa972018-04-25 18:59:40 -0700336 ensure_path_mounted(LAST_LOG_FILE);
337 ensure_path_mounted(LAST_KMSG_FILE);
338 rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700339
Tao Bao641fa972018-04-25 18:59:40 -0700340 // Copy logs to cache so the system can find out what happened.
341 copy_log_file(Paths::Get().temporary_log_file(), LOG_FILE, true);
342 copy_log_file(Paths::Get().temporary_log_file(), LAST_LOG_FILE, false);
343 copy_log_file(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE, false);
344 save_kernel_log(LAST_KMSG_FILE);
345 chmod(LOG_FILE, 0600);
346 chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
347 chmod(LAST_KMSG_FILE, 0600);
348 chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
349 chmod(LAST_LOG_FILE, 0640);
350 chmod(LAST_INSTALL_FILE, 0644);
351 sync();
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700352}
353
Tao Baoec579032017-07-21 12:13:15 -0700354// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700355// copy our log file to cache as well (for the system to read). This function is
356// idempotent: call it as many times as you like.
Tao Baoac9d94d2016-11-03 11:37:15 -0700357static void finish_recovery() {
Tao Baoec579032017-07-21 12:13:15 -0700358 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
359 // (e.g., directly from the bootloader) it will use the last-known locale.
360 if (!locale.empty() && has_cache) {
361 LOG(INFO) << "Saving locale \"" << locale << "\"";
362 if (ensure_path_mounted(LOCALE_FILE) != 0) {
363 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
364 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
365 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700366 }
Tao Baoec579032017-07-21 12:13:15 -0700367 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700368
Tao Baoec579032017-07-21 12:13:15 -0700369 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800370
Tao Baoec579032017-07-21 12:13:15 -0700371 // Reset to normal system boot so recovery won't cycle indefinitely.
372 std::string err;
373 if (!clear_bootloader_message(&err)) {
374 LOG(ERROR) << "Failed to clear BCB message: " << err;
375 }
376
377 // Remove the command file, so recovery won't repeat indefinitely.
378 if (has_cache) {
379 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
380 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700381 }
Tao Baoec579032017-07-21 12:13:15 -0700382 ensure_path_unmounted(CACHE_ROOT);
383 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800384
Tao Baoec579032017-07-21 12:13:15 -0700385 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800386}
387
Tao Bao3f5a3822016-12-13 11:14:37 -0800388struct saved_log_file {
389 std::string name;
390 struct stat sb;
391 std::string data;
392};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700393
Elliott Hughes945548e2015-06-05 17:59:56 -0700394static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800395 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
396 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700397
Tao Bao3f5a3822016-12-13 11:14:37 -0800398 ui->SetBackground(RecoveryUI::ERASING);
399 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700400
Tao Bao3f5a3822016-12-13 11:14:37 -0800401 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700402
Tao Bao3f5a3822016-12-13 11:14:37 -0800403 if (is_cache) {
404 // If we're reformatting /cache, we load any past logs
405 // (i.e. "/cache/recovery/last_*") and the current log
406 // ("/cache/recovery/log") into memory, so we can restore them after
407 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700408
Tao Bao3f5a3822016-12-13 11:14:37 -0800409 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700410
Tao Bao3f5a3822016-12-13 11:14:37 -0800411 struct dirent* de;
412 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
413 if (d) {
414 while ((de = readdir(d.get())) != nullptr) {
415 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
416 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
417
418 struct stat sb;
419 if (stat(path.c_str(), &sb) == 0) {
420 // truncate files to 512kb
421 if (sb.st_size > (1 << 19)) {
422 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700423 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800424
425 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700426 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800427 fread(&data[0], 1, data.size(), f);
428 fclose(f);
429
430 log_files.emplace_back(saved_log_file{ path, sb, data });
431 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700432 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800433 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800434 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800435 if (errno != ENOENT) {
436 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
437 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800438 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800439 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700440
Tao Bao3f5a3822016-12-13 11:14:37 -0800441 ui->Print("Formatting %s...\n", volume);
442
443 ensure_path_unmounted(volume);
444
445 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800446 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700447 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
448 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
449 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
450 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800451 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700452 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
453 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800454 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700455 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800456 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700457 PLOG(ERROR) << "Failed to convert to file encryption";
458 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800459 }
460 fclose(f);
461 result = format_volume(volume, CONVERT_FBE_DIR);
462 remove(CONVERT_FBE_FILE);
463 rmdir(CONVERT_FBE_DIR);
464 } else {
465 result = format_volume(volume);
466 }
467
468 if (is_cache) {
469 // Re-create the log dir and write back the log entries.
470 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700471 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800472 for (const auto& log : log_files) {
473 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
474 log.sb.st_gid)) {
475 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700476 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800477 }
478 } else {
479 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700480 }
481
Tao Bao3f5a3822016-12-13 11:14:37 -0800482 // Any part of the log we'd copied to cache is now gone.
483 // Reset the pointer so we copy from the beginning of the temp
484 // log.
485 tmplog_offset = 0;
486 copy_logs();
487 }
488
489 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800490}
491
Tao Baoc4a18ef2017-02-10 00:13:30 -0800492// Returns the selected filename, or an empty string.
493static std::string browse_directory(const std::string& path, Device* device) {
494 ensure_path_mounted(path.c_str());
Doug Zongker8674a722010-09-15 11:08:23 -0700495
Tao Baoc4a18ef2017-02-10 00:13:30 -0800496 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
497 if (!d) {
498 PLOG(ERROR) << "error opening " << path;
499 return "";
500 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700501
Tao Baoc4a18ef2017-02-10 00:13:30 -0800502 std::vector<std::string> dirs;
Tao Bao1fe1afe2018-05-01 15:56:05 -0700503 std::vector<std::string> entries{ "../" }; // "../" is always the first entry.
Tao Baoc4a18ef2017-02-10 00:13:30 -0800504
505 dirent* de;
506 while ((de = readdir(d.get())) != nullptr) {
507 std::string name(de->d_name);
508
509 if (de->d_type == DT_DIR) {
510 // Skip "." and ".." entries.
511 if (name == "." || name == "..") continue;
512 dirs.push_back(name + "/");
513 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700514 entries.push_back(name);
Tao Baoc4a18ef2017-02-10 00:13:30 -0800515 }
516 }
517
518 std::sort(dirs.begin(), dirs.end());
Tao Bao1fe1afe2018-05-01 15:56:05 -0700519 std::sort(entries.begin(), entries.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800520
Tao Bao1fe1afe2018-05-01 15:56:05 -0700521 // Append dirs to the entries list.
522 entries.insert(entries.end(), dirs.begin(), dirs.end());
Tao Baoc4a18ef2017-02-10 00:13:30 -0800523
Tao Bao1fe1afe2018-05-01 15:56:05 -0700524 std::vector<std::string> headers{ "Choose a package to install:", path };
Tao Baoc4a18ef2017-02-10 00:13:30 -0800525
Tao Bao1fe1afe2018-05-01 15:56:05 -0700526 size_t chosen_item = 0;
Tao Baoc4a18ef2017-02-10 00:13:30 -0800527 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700528 chosen_item = ui->ShowMenu(
529 headers, entries, chosen_item, true,
530 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baoc4a18ef2017-02-10 00:13:30 -0800531
Tao Bao1fe1afe2018-05-01 15:56:05 -0700532 const std::string& item = entries[chosen_item];
Tao Baoc4a18ef2017-02-10 00:13:30 -0800533 if (chosen_item == 0) {
534 // Go up but continue browsing (if the caller is browse_directory).
535 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700536 }
537
Tao Baoc4a18ef2017-02-10 00:13:30 -0800538 std::string new_path = path + "/" + item;
539 if (new_path.back() == '/') {
540 // Recurse down into a subdirectory.
541 new_path.pop_back();
542 std::string result = browse_directory(new_path, device);
543 if (!result.empty()) return result;
544 } else {
545 // Selected a zip file: return the path to the caller.
546 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700547 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800548 }
Doug Zongker8674a722010-09-15 11:08:23 -0700549
Tao Baoc4a18ef2017-02-10 00:13:30 -0800550 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700551}
552
Elliott Hughes30694c92015-03-25 15:16:51 -0700553static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700554 std::vector<std::string> headers{ question1, question2 };
555 std::vector<std::string> items{ " No", " Yes" };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700556
Tao Bao1fe1afe2018-05-01 15:56:05 -0700557 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700558 headers, items, 0, true,
559 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
560 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700561}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800562
Paul Crowley08404b42016-12-19 13:04:23 -0800563static bool ask_to_wipe_data(Device* device) {
Tao Bao3aec6962018-04-20 09:24:58 -0700564 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
Paul Crowley08404b42016-12-19 13:04:23 -0800565}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700566
Paul Crowley08404b42016-12-19 13:04:23 -0800567// Return true on success.
568static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700569 modified_flash = true;
570
Doug Zongker211aebc2011-10-28 15:13:10 -0700571 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700572 bool success = device->PreWipeData();
573 if (success) {
574 success &= erase_volume(DATA_ROOT);
575 if (has_cache) {
576 success &= erase_volume(CACHE_ROOT);
577 }
578 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
579 success &= erase_volume(METADATA_ROOT);
580 }
581 }
582 if (success) {
583 success &= device->PostWipeData();
584 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700585 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
586 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700587}
588
Paul Crowley08404b42016-12-19 13:04:23 -0800589static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700590 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700591 std::vector<std::string> headers{
Tao Bao2bbc6d62017-08-13 23:48:55 -0700592 "Can't load Android system. Your data may be corrupt. "
593 "If you continue to get this message, you may need to "
594 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700595 "stored on this device.",
Tao Baofc5499f2017-02-23 19:06:53 -0800596 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700597 // clang-format off
598 std::vector<std::string> items {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700599 "Try again",
600 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800601 };
Tao Bao1fe1afe2018-05-01 15:56:05 -0700602 // clang-format on
Tao Baofc5499f2017-02-23 19:06:53 -0800603 for (;;) {
Tao Bao1fe1afe2018-05-01 15:56:05 -0700604 size_t chosen_item = ui->ShowMenu(
Tao Bao3aec6962018-04-20 09:24:58 -0700605 headers, items, 0, true,
606 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baofc5499f2017-02-23 19:06:53 -0800607 if (chosen_item != 1) {
608 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800609 }
Tao Baofc5499f2017-02-23 19:06:53 -0800610 if (ask_to_wipe_data(device)) {
611 return wipe_data(device);
612 }
613 }
Paul Crowley08404b42016-12-19 13:04:23 -0800614}
615
Tao Baoe39a9bc2015-03-31 12:19:05 -0700616// Return true on success.
617static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800618 if (!has_cache) {
619 ui->Print("No /cache partition found.\n");
620 return false;
621 }
622
Elliott Hughes30694c92015-03-25 15:16:51 -0700623 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700624 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700625 }
626
Tao Bao682c34b2015-04-07 17:16:35 -0700627 modified_flash = true;
628
Elliott Hughes30694c92015-03-25 15:16:51 -0700629 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700630 bool success = erase_volume("/cache");
631 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
632 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700633}
634
Tao Bao1b2a98b2017-03-24 10:45:34 -0700635// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
636// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700637static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700638 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
639 if (fd == -1) {
640 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
641 return false;
642 }
643
644 uint64_t range[2] = { 0, 0 };
645 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
646 PLOG(ERROR) << "Failed to get partition size";
647 return false;
648 }
649 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
650
651 LOG(INFO) << " Trying BLKSECDISCARD...";
652 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
653 PLOG(WARNING) << " Failed";
654
655 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
656 unsigned int zeroes;
657 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
658 LOG(INFO) << " Trying BLKDISCARD...";
659 if (ioctl(fd, BLKDISCARD, &range) == -1) {
660 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700661 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700662 }
663 } else {
664 LOG(INFO) << " Trying BLKZEROOUT...";
665 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
666 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700667 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700668 }
Tao Bao862a4c12016-06-02 11:16:50 -0700669 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700670 }
Tao Bao862a4c12016-06-02 11:16:50 -0700671
Tao Bao1b2a98b2017-03-24 10:45:34 -0700672 LOG(INFO) << " Done";
673 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700674}
675
Yabin Cuifd99a312016-06-09 14:09:39 -0700676// Check if the wipe package matches expectation:
677// 1. verify the package.
678// 2. check metadata (ota-type, pre-device and serial number if having one).
679static bool check_wipe_package(size_t wipe_package_size) {
680 if (wipe_package_size == 0) {
681 LOG(ERROR) << "wipe_package_size is zero";
682 return false;
683 }
684 std::string wipe_package;
685 std::string err_str;
686 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
687 PLOG(ERROR) << "Failed to read wipe package";
688 return false;
689 }
690 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
691 wipe_package.size())) {
692 LOG(ERROR) << "Failed to verify package";
693 return false;
694 }
695
696 // Extract metadata
697 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -0800698 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
699 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -0700700 if (err != 0) {
701 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
702 return false;
703 }
704 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700705 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -0700706 CloseArchive(zip);
707 return false;
708 }
709 CloseArchive(zip);
710
711 // Check metadata
712 std::vector<std::string> lines = android::base::Split(metadata, "\n");
713 bool ota_type_matched = false;
714 bool device_type_matched = false;
715 bool has_serial_number = false;
716 bool serial_number_matched = false;
717 for (const auto& line : lines) {
718 if (line == "ota-type=BRICK") {
719 ota_type_matched = true;
720 } else if (android::base::StartsWith(line, "pre-device=")) {
721 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -0800722 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700723 device_type_matched = (device_type == real_device_type);
724 } else if (android::base::StartsWith(line, "serialno=")) {
725 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -0800726 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700727 has_serial_number = true;
728 serial_number_matched = (serial_no == real_serial_no);
729 }
730 }
731 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
732}
733
Tao Baoaac9d9f2018-04-29 23:38:59 -0700734// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700735static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700736 ui->SetBackground(RecoveryUI::ERASING);
737 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700738
Tao Baoaac9d9f2018-04-29 23:38:59 -0700739 if (!check_wipe_package(wipe_package_size)) {
740 LOG(ERROR) << "Failed to verify wipe package";
741 return false;
742 }
743 static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
744 std::string partition_list;
745 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
746 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
747 return false;
748 }
749
750 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
751 for (const std::string& line : lines) {
752 std::string partition = android::base::Trim(line);
753 // Ignore '#' comment or empty lines.
754 if (android::base::StartsWith(partition, "#") || partition.empty()) {
755 continue;
Tao Bao862a4c12016-06-02 11:16:50 -0700756 }
757
Tao Baoaac9d9f2018-04-29 23:38:59 -0700758 // Proceed anyway even if it fails to wipe some partition.
759 secure_wipe_partition(partition);
760 }
761 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700762}
763
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700764static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800765 std::vector<std::string> entries;
766 if (has_cache) {
767 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
768 auto add_to_entries = [&](const char* filename) {
769 std::string log_file(filename);
770 if (i > 0) {
771 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700772 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800773
774 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
775 entries.push_back(std::move(log_file));
776 }
777 };
778
779 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
780 add_to_entries(LAST_LOG_FILE);
781
782 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
783 add_to_entries(LAST_KMSG_FILE);
784 }
785 } else {
786 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700787 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800788 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700789 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700790 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700791 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800792 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700793
Tao Bao08fc6be2017-03-07 00:56:27 -0800794 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700795
Tao Bao1fe1afe2018-05-01 15:56:05 -0700796 std::vector<std::string> headers{ "Select file to view" };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700797
Tao Bao1fe1afe2018-05-01 15:56:05 -0700798 size_t chosen_item = 0;
Tao Bao08fc6be2017-03-07 00:56:27 -0800799 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700800 chosen_item = ui->ShowMenu(
Tao Bao1fe1afe2018-05-01 15:56:05 -0700801 headers, entries, chosen_item, true,
Tao Bao3aec6962018-04-20 09:24:58 -0700802 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao08fc6be2017-03-07 00:56:27 -0800803 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700804
Tao Bao1d156b92018-05-02 12:43:18 -0700805 ui->ShowFile(entries[chosen_item]);
Tao Bao08fc6be2017-03-07 00:56:27 -0800806 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700807}
808
Tao Baodb7e8982017-03-06 23:53:16 -0800809static void run_graphics_test() {
810 // Switch to graphics screen.
811 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700812
Tao Baodb7e8982017-03-06 23:53:16 -0800813 ui->SetProgressType(RecoveryUI::INDETERMINATE);
814 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
815 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700816
Tao Baodb7e8982017-03-06 23:53:16 -0800817 ui->SetBackground(RecoveryUI::ERROR);
818 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700819
Tao Baodb7e8982017-03-06 23:53:16 -0800820 ui->SetBackground(RecoveryUI::NO_COMMAND);
821 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700822
Tao Baodb7e8982017-03-06 23:53:16 -0800823 ui->SetBackground(RecoveryUI::ERASING);
824 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700825
Tao Baodb7e8982017-03-06 23:53:16 -0800826 // Calling SetBackground() after SetStage() to trigger a redraw.
827 ui->SetStage(1, 3);
828 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
829 sleep(1);
830 ui->SetStage(2, 3);
831 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
832 sleep(1);
833 ui->SetStage(3, 3);
834 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
835 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700836
Tao Baodb7e8982017-03-06 23:53:16 -0800837 ui->SetStage(-1, -1);
838 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700839
Tao Baodb7e8982017-03-06 23:53:16 -0800840 ui->SetProgressType(RecoveryUI::DETERMINATE);
841 ui->ShowProgress(1.0, 10.0);
842 float fraction = 0.0;
843 for (size_t i = 0; i < 100; ++i) {
844 fraction += .01;
845 ui->SetProgress(fraction);
846 usleep(100000);
847 }
848
849 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700850}
851
Tao Baocdcf28f2016-01-13 15:05:20 -0800852// How long (in seconds) we wait for the fuse-provided package file to
853// appear, before timing out.
854#define SDCARD_INSTALL_TIMEOUT 10
855
Tao Bao145d8612015-03-25 15:51:15 -0700856static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700857 modified_flash = true;
858
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000859 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
860 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
861 return INSTALL_ERROR;
862 }
863
Tao Baoc4a18ef2017-02-10 00:13:30 -0800864 std::string path = browse_directory(SDCARD_ROOT, device);
865 if (path.empty()) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700866 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800867 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000868 return INSTALL_ERROR;
869 }
870
Tao Baoc4a18ef2017-02-10 00:13:30 -0800871 ui->Print("\n-- Install %s ...\n", path.c_str());
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000872 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000873
Tao Baocdcf28f2016-01-13 15:05:20 -0800874 // We used to use fuse in a thread as opposed to a process. Since accessing
875 // through fuse involves going from kernel to userspace to kernel, it leads
876 // to deadlock when a page fault occurs. (Bug: 26313124)
877 pid_t child;
878 if ((child = fork()) == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800879 bool status = start_sdcard_fuse(path.c_str());
Tao Baocdcf28f2016-01-13 15:05:20 -0800880
881 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
882 }
883
884 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
885 // process is ready.
886 int result = INSTALL_ERROR;
887 int status;
888 bool waited = false;
889 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
890 if (waitpid(child, &status, WNOHANG) == -1) {
891 result = INSTALL_ERROR;
892 waited = true;
893 break;
894 }
895
896 struct stat sb;
897 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
898 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
899 sleep(1);
900 continue;
901 } else {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700902 LOG(ERROR) << "Timed out waiting for the fuse-provided package.";
Tao Baocdcf28f2016-01-13 15:05:20 -0800903 result = INSTALL_ERROR;
904 kill(child, SIGKILL);
905 break;
906 }
907 }
908
Tao Bao641fa972018-04-25 18:59:40 -0700909 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -0800910 break;
911 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000912
Tao Baocdcf28f2016-01-13 15:05:20 -0800913 if (!waited) {
914 // Calling stat() on this magic filename signals the fuse
915 // filesystem to shut down.
916 struct stat sb;
917 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
918
919 waitpid(child, &status, 0);
920 }
921
922 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700923 LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status);
Tao Baocdcf28f2016-01-13 15:05:20 -0800924 }
925
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000926 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -0800927 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000928}
929
Tao Bao50dd5322017-03-07 14:57:04 -0800930// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
931// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
932static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
933 for (;;) {
934 finish_recovery();
935 switch (status) {
936 case INSTALL_SUCCESS:
937 case INSTALL_NONE:
938 ui->SetBackground(RecoveryUI::NO_COMMAND);
939 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700940
Tao Bao50dd5322017-03-07 14:57:04 -0800941 case INSTALL_ERROR:
942 case INSTALL_CORRUPT:
943 ui->SetBackground(RecoveryUI::ERROR);
944 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800945 }
Tao Bao50dd5322017-03-07 14:57:04 -0800946 ui->SetProgressType(RecoveryUI::EMPTY);
947
Tao Bao1fe1afe2018-05-01 15:56:05 -0700948 size_t chosen_item = ui->ShowMenu(
949 {}, device->GetMenuItems(), 0, false,
Tao Bao3aec6962018-04-20 09:24:58 -0700950 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao50dd5322017-03-07 14:57:04 -0800951
952 // Device-specific code may take some action here. It may return one of the core actions
953 // handled in the switch statement below.
Tao Bao1fe1afe2018-05-01 15:56:05 -0700954 Device::BuiltinAction chosen_action = (chosen_item == static_cast<size_t>(-1))
955 ? Device::REBOOT
956 : device->InvokeMenuItem(chosen_item);
Tao Bao50dd5322017-03-07 14:57:04 -0800957
958 bool should_wipe_cache = false;
959 switch (chosen_action) {
960 case Device::NO_ACTION:
961 break;
962
963 case Device::REBOOT:
964 case Device::SHUTDOWN:
965 case Device::REBOOT_BOOTLOADER:
966 return chosen_action;
967
968 case Device::WIPE_DATA:
969 if (ui->IsTextVisible()) {
970 if (ask_to_wipe_data(device)) {
971 wipe_data(device);
972 }
973 } else {
974 wipe_data(device);
975 return Device::NO_ACTION;
976 }
977 break;
978
979 case Device::WIPE_CACHE:
980 wipe_cache(ui->IsTextVisible(), device);
981 if (!ui->IsTextVisible()) return Device::NO_ACTION;
982 break;
983
984 case Device::APPLY_ADB_SIDELOAD:
985 case Device::APPLY_SDCARD:
986 {
987 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
988 if (adb) {
Tao Bao641fa972018-04-25 18:59:40 -0700989 status = apply_from_adb(&should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -0800990 } else {
991 status = apply_from_sdcard(device, &should_wipe_cache);
992 }
993
994 if (status == INSTALL_SUCCESS && should_wipe_cache) {
995 if (!wipe_cache(false, device)) {
996 status = INSTALL_ERROR;
997 }
998 }
999
1000 if (status != INSTALL_SUCCESS) {
1001 ui->SetBackground(RecoveryUI::ERROR);
1002 ui->Print("Installation aborted.\n");
1003 copy_logs();
1004 } else if (!ui->IsTextVisible()) {
1005 return Device::NO_ACTION; // reboot if logs aren't visible
1006 } else {
1007 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
1008 }
1009 }
1010 break;
1011
1012 case Device::VIEW_RECOVERY_LOGS:
1013 choose_recovery_file(device);
1014 break;
1015
1016 case Device::RUN_GRAPHICS_TEST:
1017 run_graphics_test();
1018 break;
1019
Tianjie Xu29d55752017-09-20 17:53:46 -07001020 case Device::RUN_LOCALE_TEST: {
1021 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
1022 screen_ui->CheckBackgroundTextImages(locale);
1023 break;
1024 }
Tao Bao50dd5322017-03-07 14:57:04 -08001025 case Device::MOUNT_SYSTEM:
1026 // For a system image built with the root directory (i.e. system_root_image == "true"), we
1027 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
1028 // work (the symlink is created through the build system). (Bug: 22855115)
1029 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
1030 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1031 ui->Print("Mounted /system.\n");
1032 }
1033 } else {
1034 if (ensure_path_mounted("/system") != -1) {
1035 ui->Print("Mounted /system.\n");
1036 }
1037 }
1038 break;
1039 }
1040 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001041}
1042
Tao Bao99f0d9e2016-10-13 12:46:38 -07001043static void print_property(const char* key, const char* name, void* /* cookie */) {
1044 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001045}
1046
Tao Baoac9d94d2016-11-03 11:37:15 -07001047static std::string load_locale_from_cache() {
1048 if (ensure_path_mounted(LOCALE_FILE) != 0) {
1049 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
1050 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -07001051 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001052
1053 std::string content;
1054 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
1055 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
1056 return "";
1057 }
1058
1059 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001060}
1061
Tao Baoac9d94d2016-11-03 11:37:15 -07001062void ui_print(const char* format, ...) {
1063 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -07001064 va_list ap;
1065 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -07001066 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001067 va_end(ap);
1068
Tao Baoac9d94d2016-11-03 11:37:15 -07001069 if (ui != nullptr) {
1070 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -07001071 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -07001072 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001073 }
1074}
1075
Tao Baof2ea6d72018-04-26 10:40:36 -07001076static bool is_battery_ok(int* required_battery_level) {
1077 struct healthd_config healthd_config = {
1078 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1079 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1080 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1081 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1082 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1083 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1084 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1085 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1086 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1087 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1088 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1089 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1090 .energyCounter = nullptr,
1091 .boot_min_cap = 0,
1092 .screen_on = nullptr
1093 };
1094 healthd_board_init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001095
Tao Baof2ea6d72018-04-26 10:40:36 -07001096 android::BatteryMonitor monitor;
1097 monitor.init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001098
Tao Baof2ea6d72018-04-26 10:40:36 -07001099 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
1100 int wait_second = 0;
1101 while (true) {
1102 int charge_status = monitor.getChargeStatus();
1103 // Treat unknown status as charged.
1104 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1105 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1106 android::BatteryProperty capacity;
1107 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1108 ui_print("charge_status %d, charged %d, status %d, capacity %" PRId64 "\n", charge_status,
1109 charged, status, capacity.valueInt64);
1110 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1111 // the battery profile. Before the load finishes, it reports value 50 as a fake
1112 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1113 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1114 if (status == 0 && capacity.valueInt64 == 50) {
1115 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1116 sleep(1);
1117 wait_second++;
1118 continue;
1119 }
Yabin Cui99281df2016-02-17 12:21:52 -08001120 }
Tao Baof2ea6d72018-04-26 10:40:36 -07001121 // If we can't read battery percentage, it may be a device without battery. In this situation,
1122 // use 100 as a fake battery percentage.
1123 if (status != 0) {
1124 capacity.valueInt64 = 100;
1125 }
1126
1127 // GmsCore enters recovery mode to install package when having enough battery percentage.
1128 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
1129 // battery with a slightly lower limitation.
1130 static constexpr int BATTERY_OK_PERCENTAGE = 20;
1131 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
1132 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
1133 return capacity.valueInt64 >= *required_battery_level;
1134 }
Yabin Cui99281df2016-02-17 12:21:52 -08001135}
1136
Tianjie Xu99b73be2017-11-28 17:23:06 -08001137// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001138static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1139 std::vector<std::string> options;
1140 for (const auto& arg : args) {
1141 if (!android::base::StartsWith(arg, "--retry_count")) {
1142 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001143 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001144 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001145
Tianjie Xu99b73be2017-11-28 17:23:06 -08001146 // Update the retry counter in BCB.
1147 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001148 std::string err;
1149 if (!update_bootloader_message(options, &err)) {
1150 LOG(ERROR) << err;
1151 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001152}
1153
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001154static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001155 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1156 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001157 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
1158 static const std::vector<std::string> kBootreasonBlacklist{
1159 "kernel_panic",
1160 "Panic",
1161 };
1162 for (const auto& str : kBootreasonBlacklist) {
1163 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001164 }
Tao Baoefc35592017-01-08 22:45:47 -08001165 }
1166 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001167}
1168
Tao Bao641fa972018-04-25 18:59:40 -07001169static void log_failure_code(ErrorCode code, const std::string& update_package) {
1170 std::vector<std::string> log_buffer = {
1171 update_package,
1172 "0", // install result
1173 "error: " + std::to_string(code),
1174 };
1175 std::string log_content = android::base::Join(log_buffer, "\n");
1176 const std::string& install_file = Paths::Get().temporary_install_file();
1177 if (!android::base::WriteStringToFile(log_content, install_file)) {
1178 PLOG(ERROR) << "Failed to write " << install_file;
1179 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001180
Tao Bao641fa972018-04-25 18:59:40 -07001181 // Also write the info into last_log.
1182 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001183}
1184
Tao Bao6d99d4b2018-04-25 16:47:04 -07001185int start_recovery(int argc, char** argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001186 time_t start = time(nullptr);
1187
Tianjie Xu99b73be2017-11-28 17:23:06 -08001188 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1189
1190 load_volume_table();
1191 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1192
1193 std::vector<std::string> args = get_args(argc, argv);
1194 std::vector<char*> args_to_parse(args.size());
1195 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1196 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1197
Tao Baof9f17342018-04-27 10:44:04 -07001198 static constexpr struct option OPTIONS[] = {
1199 { "just_exit", no_argument, nullptr, 'x' },
1200 { "locale", required_argument, nullptr, 0 },
1201 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
1202 { "reason", required_argument, nullptr, 0 },
1203 { "retry_count", required_argument, nullptr, 0 },
1204 { "security", no_argument, nullptr, 0 },
1205 { "show_text", no_argument, nullptr, 't' },
1206 { "shutdown_after", no_argument, nullptr, 0 },
1207 { "sideload", no_argument, nullptr, 0 },
1208 { "sideload_auto_reboot", no_argument, nullptr, 0 },
1209 { "update_package", required_argument, nullptr, 0 },
1210 { "wipe_ab", no_argument, nullptr, 0 },
1211 { "wipe_cache", no_argument, nullptr, 0 },
1212 { "wipe_data", no_argument, nullptr, 0 },
1213 { "wipe_package_size", required_argument, nullptr, 0 },
1214 { nullptr, 0, nullptr, 0 },
1215 };
1216
Tianjie Xu99b73be2017-11-28 17:23:06 -08001217 const char* update_package = nullptr;
1218 bool should_wipe_data = false;
1219 bool should_prompt_and_wipe_data = false;
1220 bool should_wipe_cache = false;
1221 bool should_wipe_ab = false;
1222 size_t wipe_package_size = 0;
1223 bool show_text = false;
1224 bool sideload = false;
1225 bool sideload_auto_reboot = false;
1226 bool just_exit = false;
1227 bool shutdown_after = false;
1228 int retry_count = 0;
1229 bool security_update = false;
1230
1231 int arg;
1232 int option_index;
1233 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1234 &option_index)) != -1) {
1235 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001236 case 't':
1237 show_text = true;
1238 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001239 case 'x':
1240 just_exit = true;
1241 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001242 case 0: {
1243 std::string option = OPTIONS[option_index].name;
Tao Baof9f17342018-04-27 10:44:04 -07001244 if (option == "locale") {
1245 locale = optarg;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001246 } else if (option == "prompt_and_wipe_data") {
1247 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -07001248 } else if (option == "reason") {
1249 reason = optarg;
1250 } else if (option == "retry_count") {
1251 android::base::ParseInt(optarg, &retry_count, 0);
1252 } else if (option == "security") {
1253 security_update = true;
1254 } else if (option == "sideload") {
1255 sideload = true;
1256 } else if (option == "sideload_auto_reboot") {
1257 sideload = true;
1258 sideload_auto_reboot = true;
1259 } else if (option == "shutdown_after") {
1260 shutdown_after = true;
1261 } else if (option == "update_package") {
1262 update_package = optarg;
1263 } else if (option == "wipe_ab") {
1264 should_wipe_ab = true;
1265 } else if (option == "wipe_cache") {
1266 should_wipe_cache = true;
1267 } else if (option == "wipe_data") {
1268 should_wipe_data = true;
1269 } else if (option == "wipe_package_size") {
1270 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001271 }
1272 break;
1273 }
1274 case '?':
1275 LOG(ERROR) << "Invalid command argument";
1276 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001277 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001278 }
Doug Zongker9270a202012-01-09 15:16:13 -08001279
Tianjie Xu99b73be2017-11-28 17:23:06 -08001280 if (locale.empty()) {
1281 if (has_cache) {
1282 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001283 }
1284
Tao Baoac9d94d2016-11-03 11:37:15 -07001285 if (locale.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001286 static constexpr const char* DEFAULT_LOCALE = "en-US";
Tianjie Xu99b73be2017-11-28 17:23:06 -08001287 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001288 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001289 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001290
Tianjie Xu99b73be2017-11-28 17:23:06 -08001291 printf("locale is [%s]\n", locale.c_str());
1292 printf("stage is [%s]\n", stage.c_str());
1293 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001294
Tianjie Xu99b73be2017-11-28 17:23:06 -08001295 Device* device = make_device();
1296 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1297 printf("Quiescent recovery mode.\n");
1298 ui = new StubRecoveryUI();
1299 } else {
1300 ui = device->GetUI();
1301
1302 if (!ui->Init(locale)) {
1303 printf("Failed to initialize UI, use stub UI instead.\n");
1304 ui = new StubRecoveryUI();
1305 }
1306 }
1307
1308 // Set background string to "installing security update" for security update,
1309 // otherwise set it to "installing system update".
1310 ui->SetSystemUpdateText(security_update);
1311
1312 int st_cur, st_max;
1313 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1314 ui->SetStage(st_cur, st_max);
1315 }
1316
1317 ui->SetBackground(RecoveryUI::NONE);
1318 if (show_text) ui->ShowText(true);
1319
1320 sehandle = selinux_android_file_context_handle();
1321 selinux_android_set_sehandle(sehandle);
1322 if (!sehandle) {
1323 ui->Print("Warning: No file_contexts\n");
1324 }
1325
1326 device->StartRecovery();
1327
1328 printf("Command:");
1329 for (const auto& arg : args) {
1330 printf(" \"%s\"", arg.c_str());
1331 }
1332 printf("\n\n");
1333
1334 property_list(print_property, nullptr);
1335 printf("\n");
1336
1337 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1338
1339 int status = INSTALL_SUCCESS;
1340
1341 if (update_package != nullptr) {
1342 // It's not entirely true that we will modify the flash. But we want
1343 // to log the update attempt since update_package is non-NULL.
1344 modified_flash = true;
1345
Tao Baof2ea6d72018-04-26 10:40:36 -07001346 int required_battery_level;
1347 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1348 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1349 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001350 // Log the error code to last_install when installation skips due to
1351 // low battery.
1352 log_failure_code(kLowBattery, update_package);
1353 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001354 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001355 // Skip update-on-reboot when bootreason is kernel_panic or similar
1356 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1357 log_failure_code(kBootreasonInBlacklist, update_package);
1358 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001359 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001360 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1361 // identify the interrupted update due to unexpected reboots.
1362 if (retry_count == 0) {
1363 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001364 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001365
Tao Bao641fa972018-04-25 18:59:40 -07001366 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001367 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1368 wipe_cache(false, device);
1369 }
1370 if (status != INSTALL_SUCCESS) {
1371 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001372
1373 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1374 // RETRY_LIMIT times before we abandon this OTA update.
1375 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001376 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
1377 copy_logs();
1378 retry_count += 1;
1379 set_retry_bootloader_message(retry_count, args);
1380 // Print retry count on screen.
1381 ui->Print("Retry attempt %d\n", retry_count);
1382
1383 // Reboot and retry the update
1384 if (!reboot("reboot,recovery")) {
1385 ui->Print("Reboot failed\n");
1386 } else {
1387 while (true) {
1388 pause();
1389 }
1390 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001391 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001392 // If this is an eng or userdebug build, then automatically
1393 // turn the text display on if the script fails so the error
1394 // message is visible.
1395 if (is_ro_debuggable()) {
1396 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001397 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001398 }
Doug Zongker8674a722010-09-15 11:08:23 -07001399 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001400 } else if (should_wipe_data) {
1401 if (!wipe_data(device)) {
1402 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001403 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001404 } else if (should_prompt_and_wipe_data) {
1405 ui->ShowText(true);
1406 ui->SetBackground(RecoveryUI::ERROR);
1407 if (!prompt_and_wipe_data(device)) {
1408 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001409 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001410 ui->ShowText(false);
1411 } else if (should_wipe_cache) {
1412 if (!wipe_cache(false, device)) {
1413 status = INSTALL_ERROR;
1414 }
1415 } else if (should_wipe_ab) {
1416 if (!wipe_ab_device(wipe_package_size)) {
1417 status = INSTALL_ERROR;
1418 }
1419 } else if (sideload) {
1420 // 'adb reboot sideload' acts the same as user presses key combinations
1421 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1422 // display will NOT be turned on by default. And it will reboot after
1423 // sideload finishes even if there are errors. Unless one turns on the
1424 // text display during the installation. This is to enable automated
1425 // testing.
1426 if (!sideload_auto_reboot) {
1427 ui->ShowText(true);
1428 }
Tao Bao641fa972018-04-25 18:59:40 -07001429 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001430 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1431 if (!wipe_cache(false, device)) {
1432 status = INSTALL_ERROR;
1433 }
1434 }
1435 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1436 if (sideload_auto_reboot) {
1437 ui->Print("Rebooting automatically.\n");
1438 }
1439 } else if (!just_exit) {
1440 // If this is an eng or userdebug build, automatically turn on the text display if no command
1441 // is specified. Note that this should be called before setting the background to avoid
1442 // flickering the background image.
1443 if (is_ro_debuggable()) {
1444 ui->ShowText(true);
1445 }
1446 status = INSTALL_NONE; // No command specified
1447 ui->SetBackground(RecoveryUI::NO_COMMAND);
1448 }
1449
1450 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1451 ui->SetBackground(RecoveryUI::ERROR);
1452 if (!ui->IsTextVisible()) {
1453 sleep(5);
1454 }
1455 }
1456
1457 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1458 // 1. If the recovery menu is visible, prompt and wait for commands.
1459 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1460 // recovery to sideload a package.)
1461 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1462 // without waiting.
1463 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1464 // reboot after it shows the "error" screen for 5s.
1465 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1466 Device::BuiltinAction temp = prompt_and_wait(device, status);
1467 if (temp != Device::NO_ACTION) {
1468 after = temp;
1469 }
1470 }
1471
1472 // Save logs and clean up before rebooting or shutting down.
1473 finish_recovery();
1474
1475 switch (after) {
1476 case Device::SHUTDOWN:
1477 ui->Print("Shutting down...\n");
1478 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1479 break;
1480
1481 case Device::REBOOT_BOOTLOADER:
1482 ui->Print("Rebooting to bootloader...\n");
1483 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
1484 break;
1485
1486 default:
1487 ui->Print("Rebooting...\n");
1488 reboot("reboot,");
1489 break;
1490 }
1491 while (true) {
1492 pause();
1493 }
1494 // Should be unreachable.
1495 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001496}