blob: 7e539ce3d07257c7749401476849ce50fcce9c9e [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"
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080073#include "roots.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070074#include "rotate_logs.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070075#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080076#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070077#include "ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080078
Tao Baoaac9d9f2018-04-29 23:38:59 -070079static constexpr const char* CACHE_LOG_DIR = "/cache/recovery";
80static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
81static constexpr const char* LOG_FILE = "/cache/recovery/log";
82static constexpr const char* LAST_INSTALL_FILE = "/cache/recovery/last_install";
83static constexpr const char* LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
84static constexpr const char* LAST_LOG_FILE = "/cache/recovery/last_log";
85static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
Tianjie Xu06e57ac2016-07-11 14:04:08 -070086
Tao Baoaac9d9f2018-04-29 23:38:59 -070087static constexpr const char* CACHE_ROOT = "/cache";
88static constexpr const char* DATA_ROOT = "/data";
89static constexpr const char* METADATA_ROOT = "/metadata";
90static constexpr const char* SDCARD_ROOT = "/sdcard";
Nick Kralevicha9ad0322014-10-22 18:38:48 -070091
Tao Baobd0ddcd2017-05-04 13:03:18 -070092// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
93// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
94static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
95
Tao Baoac9d94d2016-11-03 11:37:15 -070096static std::string locale;
Dan Albert8584fcf2016-10-27 03:08:08 +000097static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -070098
Tao Baoac9d94d2016-11-03 11:37:15 -070099RecoveryUI* ui = nullptr;
100bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -0800101std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -0700102const char* reason = nullptr;
103struct selabel_handle* sehandle;
104
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800105/*
106 * The recovery tool communicates with the main system through /cache files.
107 * /cache/recovery/command - INPUT - command line for tool, one arg per line
108 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800109 *
110 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700111 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800112 * --wipe_data - erase user data (and cache), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700113 * --prompt_and_wipe_data - prompt the user that data is corrupt, with their consent erase user
114 * data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800115 * --wipe_cache - wipe cache (but not user data), then reboot
Tao Baof9f17342018-04-27 10:44:04 -0700116 * --show_text - show the recovery text menu, used by some bootloader (e.g. http://b/36872519).
Oscar Montemayor05231562009-11-30 08:40:57 -0800117 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700118 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800119 *
120 * After completing, we remove /cache/recovery/command and reboot.
121 * Arguments may also be supplied in the bootloader control block (BCB).
122 * These important scenarios must be safely restartable at any point:
123 *
124 * FACTORY RESET
125 * 1. user selects "factory reset"
126 * 2. main system writes "--wipe_data" to /cache/recovery/command
127 * 3. main system reboots into recovery
128 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
129 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700130 * 5. erase_volume() reformats /data
131 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800132 * 7. finish_recovery() erases BCB
133 * -- after this, rebooting will restart the main system --
134 * 8. main() calls reboot() to boot main system
135 *
136 * OTA INSTALL
137 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700138 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800139 * 3. main system reboots into recovery
140 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
141 * -- after this, rebooting will attempt to reinstall the update --
142 * 5. install_package() attempts to install the update
143 * NOTE: the package install must itself be restartable from any point
144 * 6. finish_recovery() erases BCB
145 * -- after this, rebooting will (try to) restart the main system --
146 * 7. ** if install failed **
147 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800148 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800149 */
150
Tao Bao641fa972018-04-25 18:59:40 -0700151FILE* fopen_path(const std::string& path, const char* mode) {
152 if (ensure_path_mounted(path.c_str()) != 0) {
Tao Baoac3d1ed2017-07-23 00:01:02 -0700153 LOG(ERROR) << "Can't mount " << path;
154 return nullptr;
155 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800156
Tao Baoac3d1ed2017-07-23 00:01:02 -0700157 // When writing, try to create the containing directory, if necessary. Use generous permissions,
158 // the system (init.rc) will reset them.
159 if (strchr("wa", mode[0])) {
160 mkdir_recursively(path, 0777, true, sehandle);
161 }
Tao Bao641fa972018-04-25 18:59:40 -0700162 return fopen(path.c_str(), mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800163}
164
Tao Bao6d99d4b2018-04-25 16:47:04 -0700165void check_and_fclose(FILE* fp, const std::string& name) {
Tao Bao641fa972018-04-25 18:59:40 -0700166 fflush(fp);
167 if (fsync(fileno(fp)) == -1) {
168 PLOG(ERROR) << "Failed to fsync " << name;
169 }
170 if (ferror(fp)) {
171 PLOG(ERROR) << "Error in " << name;
172 }
173 fclose(fp);
Tao Bao04ca4262015-09-10 15:32:24 -0700174}
175
Elliott Hughesf14af802015-02-10 14:46:14 -0800176bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700177 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800178}
179
Dmitri Plotnikov8706a982017-04-18 08:28:26 -0700180bool reboot(const std::string& command) {
181 std::string cmd = command;
182 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
183 cmd += ",quiescent";
184 }
185 return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
186}
187
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800188// command line args come from, in decreasing precedence:
189// - the actual command line
190// - the bootloader control block (one per line, after "recovery")
191// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800192static std::vector<std::string> get_args(const int argc, char** const argv) {
193 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800194
Tao Baof0ed1592016-12-02 11:32:19 -0800195 bootloader_message boot = {};
196 std::string err;
197 if (!read_bootloader_message(&boot, &err)) {
198 LOG(ERROR) << err;
199 // If fails, leave a zeroed bootloader_message.
200 boot = {};
201 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800202 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800203
Tao Baof0ed1592016-12-02 11:32:19 -0800204 if (boot.command[0] != 0) {
205 std::string boot_command = std::string(boot.command, sizeof(boot.command));
206 LOG(INFO) << "Boot command: " << boot_command;
207 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800208
Tao Baof0ed1592016-12-02 11:32:19 -0800209 if (boot.status[0] != 0) {
210 std::string boot_status = std::string(boot.status, sizeof(boot.status));
211 LOG(INFO) << "Boot status: " << boot_status;
212 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800213
Tao Baof0ed1592016-12-02 11:32:19 -0800214 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800215
Tao Baof0ed1592016-12-02 11:32:19 -0800216 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800217 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800218 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
219 std::string boot_recovery(boot.recovery);
220 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
221 if (!tokens.empty() && tokens[0] == "recovery") {
222 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
223 // Skip empty and '\0'-filled tokens.
224 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
225 }
226 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
227 } else if (boot.recovery[0] != 0) {
228 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
229 }
230 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800231
Tao Baof0ed1592016-12-02 11:32:19 -0800232 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800233 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800234 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800235 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
236 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800237 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800238 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
239 // COMMAND_FILE doesn't use filename as the first argument).
240 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800241 // Skip empty and '\0'-filled tokens.
242 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
243 }
244 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800245 }
Tao Baof0ed1592016-12-02 11:32:19 -0800246 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800247
Tao Baof0ed1592016-12-02 11:32:19 -0800248 // Write the arguments (excluding the filename in args[0]) back into the
249 // bootloader control block. So the device will always boot into recovery to
250 // finish the pending work, until finish_recovery() is called.
251 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800252 if (!update_bootloader_message(options, &err)) {
253 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800254 }
255
256 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800257}
258
Tao Bao2292db82016-12-13 21:53:31 -0800259// Set the BCB to reboot back into recovery (it won't resume the install from
260// sdcard though).
261static void set_sdcard_update_bootloader_message() {
262 std::vector<std::string> options;
263 std::string err;
264 if (!update_bootloader_message(options, &err)) {
265 LOG(ERROR) << "Failed to set BCB message: " << err;
266 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700267}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800268
Tao Baobef39712015-05-04 18:50:27 -0700269// Read from kernel log into buffer and write out to file.
270static void save_kernel_log(const char* destination) {
271 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800272 if (klog_buf_len <= 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700273 PLOG(ERROR) << "Error getting klog size";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800274 return;
275 }
276
Tao Baobef39712015-05-04 18:50:27 -0700277 std::string buffer(klog_buf_len, 0);
278 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
279 if (n == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700280 PLOG(ERROR) << "Error in reading klog";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800281 return;
282 }
Tao Baobef39712015-05-04 18:50:27 -0700283 buffer.resize(n);
284 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800285}
286
Tao Bao641fa972018-04-25 18:59:40 -0700287// Writes content to the current pmsg session.
288static ssize_t __pmsg_write(const std::string& filename, const std::string& buf) {
289 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filename.c_str(),
290 buf.data(), buf.size());
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800291}
292
Tao Bao641fa972018-04-25 18:59:40 -0700293static void copy_log_file_to_pmsg(const std::string& source, const std::string& destination) {
294 std::string content;
295 android::base::ReadFileToString(source, &content);
296 __pmsg_write(destination, content);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800297}
298
Tao Baof0124322015-04-11 02:04:11 +0000299// How much of the temp log we have copied to the copy in cache.
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700300static off_t tmplog_offset = 0;
Tao Baof0124322015-04-11 02:04:11 +0000301
Tao Bao641fa972018-04-25 18:59:40 -0700302static void copy_log_file(const std::string& source, const std::string& destination, bool append) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700303 FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
304 if (dest_fp == nullptr) {
305 PLOG(ERROR) << "Can't open " << destination;
306 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700307 FILE* source_fp = fopen(source.c_str(), "re");
Tianjie Xude6735e2017-07-10 15:13:33 -0700308 if (source_fp != nullptr) {
309 if (append) {
310 fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
311 }
312 char buf[4096];
313 size_t bytes;
314 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
315 fwrite(buf, 1, bytes, dest_fp);
316 }
317 if (append) {
318 tmplog_offset = ftello(source_fp);
319 }
320 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700321 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700322 check_and_fclose(dest_fp, destination);
323 }
Doug Zongker2c3539e2010-09-29 13:21:30 -0700324}
325
Tao Bao682c34b2015-04-07 17:16:35 -0700326static void copy_logs() {
Tao Bao641fa972018-04-25 18:59:40 -0700327 // We only rotate and record the log of the current session if there are actual attempts to modify
328 // the flash, such as wipes, installs from BCB or menu selections. This is to avoid unnecessary
329 // rotation (and possible deletion) of log files, if it does not do anything loggable.
330 if (!modified_flash) {
331 return;
332 }
Tao Bao682c34b2015-04-07 17:16:35 -0700333
Tao Bao641fa972018-04-25 18:59:40 -0700334 // Always write to pmsg, this allows the OTA logs to be caught in `logcat -L`.
335 copy_log_file_to_pmsg(Paths::Get().temporary_log_file(), LAST_LOG_FILE);
336 copy_log_file_to_pmsg(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE);
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800337
Tao Bao641fa972018-04-25 18:59:40 -0700338 // We can do nothing for now if there's no /cache partition.
339 if (!has_cache) {
340 return;
341 }
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800342
Tao Bao641fa972018-04-25 18:59:40 -0700343 ensure_path_mounted(LAST_LOG_FILE);
344 ensure_path_mounted(LAST_KMSG_FILE);
345 rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700346
Tao Bao641fa972018-04-25 18:59:40 -0700347 // Copy logs to cache so the system can find out what happened.
348 copy_log_file(Paths::Get().temporary_log_file(), LOG_FILE, true);
349 copy_log_file(Paths::Get().temporary_log_file(), LAST_LOG_FILE, false);
350 copy_log_file(Paths::Get().temporary_install_file(), LAST_INSTALL_FILE, false);
351 save_kernel_log(LAST_KMSG_FILE);
352 chmod(LOG_FILE, 0600);
353 chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
354 chmod(LAST_KMSG_FILE, 0600);
355 chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
356 chmod(LAST_LOG_FILE, 0640);
357 chmod(LAST_INSTALL_FILE, 0644);
358 sync();
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700359}
360
Tao Baoec579032017-07-21 12:13:15 -0700361// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700362// copy our log file to cache as well (for the system to read). This function is
363// idempotent: call it as many times as you like.
Tao Baoac9d94d2016-11-03 11:37:15 -0700364static void finish_recovery() {
Tao Baoec579032017-07-21 12:13:15 -0700365 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
366 // (e.g., directly from the bootloader) it will use the last-known locale.
367 if (!locale.empty() && has_cache) {
368 LOG(INFO) << "Saving locale \"" << locale << "\"";
369 if (ensure_path_mounted(LOCALE_FILE) != 0) {
370 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
371 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
372 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700373 }
Tao Baoec579032017-07-21 12:13:15 -0700374 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700375
Tao Baoec579032017-07-21 12:13:15 -0700376 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800377
Tao Baoec579032017-07-21 12:13:15 -0700378 // Reset to normal system boot so recovery won't cycle indefinitely.
379 std::string err;
380 if (!clear_bootloader_message(&err)) {
381 LOG(ERROR) << "Failed to clear BCB message: " << err;
382 }
383
384 // Remove the command file, so recovery won't repeat indefinitely.
385 if (has_cache) {
386 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
387 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700388 }
Tao Baoec579032017-07-21 12:13:15 -0700389 ensure_path_unmounted(CACHE_ROOT);
390 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800391
Tao Baoec579032017-07-21 12:13:15 -0700392 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800393}
394
Tao Bao3f5a3822016-12-13 11:14:37 -0800395struct saved_log_file {
396 std::string name;
397 struct stat sb;
398 std::string data;
399};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700400
Elliott Hughes945548e2015-06-05 17:59:56 -0700401static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800402 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
403 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700404
Tao Bao3f5a3822016-12-13 11:14:37 -0800405 ui->SetBackground(RecoveryUI::ERASING);
406 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700407
Tao Bao3f5a3822016-12-13 11:14:37 -0800408 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700409
Tao Bao3f5a3822016-12-13 11:14:37 -0800410 if (is_cache) {
411 // If we're reformatting /cache, we load any past logs
412 // (i.e. "/cache/recovery/last_*") and the current log
413 // ("/cache/recovery/log") into memory, so we can restore them after
414 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700415
Tao Bao3f5a3822016-12-13 11:14:37 -0800416 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700417
Tao Bao3f5a3822016-12-13 11:14:37 -0800418 struct dirent* de;
419 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
420 if (d) {
421 while ((de = readdir(d.get())) != nullptr) {
422 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
423 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
424
425 struct stat sb;
426 if (stat(path.c_str(), &sb) == 0) {
427 // truncate files to 512kb
428 if (sb.st_size > (1 << 19)) {
429 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700430 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800431
432 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700433 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800434 fread(&data[0], 1, data.size(), f);
435 fclose(f);
436
437 log_files.emplace_back(saved_log_file{ path, sb, data });
438 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700439 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800440 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800441 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800442 if (errno != ENOENT) {
443 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
444 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800445 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800446 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700447
Tao Bao3f5a3822016-12-13 11:14:37 -0800448 ui->Print("Formatting %s...\n", volume);
449
450 ensure_path_unmounted(volume);
451
452 int result;
Tao Bao3f5a3822016-12-13 11:14:37 -0800453 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700454 static constexpr const char* CONVERT_FBE_DIR = "/tmp/convert_fbe";
455 static constexpr const char* CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
456 // Create convert_fbe breadcrumb file to signal init to convert to file based encryption, not
457 // full disk encryption.
Tao Bao3f5a3822016-12-13 11:14:37 -0800458 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700459 PLOG(ERROR) << "Failed to mkdir " << CONVERT_FBE_DIR;
460 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800461 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700462 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800463 if (!f) {
Tao Bao406a6ff2018-04-30 10:05:57 -0700464 PLOG(ERROR) << "Failed to convert to file encryption";
465 return false;
Tao Bao3f5a3822016-12-13 11:14:37 -0800466 }
467 fclose(f);
468 result = format_volume(volume, CONVERT_FBE_DIR);
469 remove(CONVERT_FBE_FILE);
470 rmdir(CONVERT_FBE_DIR);
471 } else {
472 result = format_volume(volume);
473 }
474
475 if (is_cache) {
476 // Re-create the log dir and write back the log entries.
477 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700478 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800479 for (const auto& log : log_files) {
480 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
481 log.sb.st_gid)) {
482 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700483 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800484 }
485 } else {
486 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700487 }
488
Tao Bao3f5a3822016-12-13 11:14:37 -0800489 // Any part of the log we'd copied to cache is now gone.
490 // Reset the pointer so we copy from the beginning of the temp
491 // log.
492 tmplog_offset = 0;
493 copy_logs();
494 }
495
496 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800497}
498
Tao Baoc4a18ef2017-02-10 00:13:30 -0800499// Returns the selected filename, or an empty string.
500static std::string browse_directory(const std::string& path, Device* device) {
501 ensure_path_mounted(path.c_str());
Doug Zongker8674a722010-09-15 11:08:23 -0700502
Tao Baoc4a18ef2017-02-10 00:13:30 -0800503 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
504 if (!d) {
505 PLOG(ERROR) << "error opening " << path;
506 return "";
507 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700508
Tao Baoc4a18ef2017-02-10 00:13:30 -0800509 std::vector<std::string> dirs;
510 std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
511
512 dirent* de;
513 while ((de = readdir(d.get())) != nullptr) {
514 std::string name(de->d_name);
515
516 if (de->d_type == DT_DIR) {
517 // Skip "." and ".." entries.
518 if (name == "." || name == "..") continue;
519 dirs.push_back(name + "/");
520 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
521 zips.push_back(name);
522 }
523 }
524
525 std::sort(dirs.begin(), dirs.end());
526 std::sort(zips.begin(), zips.end());
527
528 // Append dirs to the zips list.
529 zips.insert(zips.end(), dirs.begin(), dirs.end());
530
531 const char* entries[zips.size() + 1];
532 entries[zips.size()] = nullptr;
533 for (size_t i = 0; i < zips.size(); i++) {
534 entries[i] = zips[i].c_str();
535 }
536
537 const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
538
539 int chosen_item = 0;
540 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700541 chosen_item = ui->ShowMenu(
542 headers, entries, chosen_item, true,
543 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baoc4a18ef2017-02-10 00:13:30 -0800544
545 const std::string& item = zips[chosen_item];
546 if (chosen_item == 0) {
547 // Go up but continue browsing (if the caller is browse_directory).
548 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700549 }
550
Tao Baoc4a18ef2017-02-10 00:13:30 -0800551 std::string new_path = path + "/" + item;
552 if (new_path.back() == '/') {
553 // Recurse down into a subdirectory.
554 new_path.pop_back();
555 std::string result = browse_directory(new_path, device);
556 if (!result.empty()) return result;
557 } else {
558 // Selected a zip file: return the path to the caller.
559 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700560 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800561 }
Doug Zongker8674a722010-09-15 11:08:23 -0700562
Tao Baoc4a18ef2017-02-10 00:13:30 -0800563 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700564}
565
Elliott Hughes30694c92015-03-25 15:16:51 -0700566static bool yes_no(Device* device, const char* question1, const char* question2) {
Tao Bao3aec6962018-04-20 09:24:58 -0700567 const char* headers[] = { question1, question2, NULL };
568 const char* items[] = { " No", " Yes", NULL };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700569
Tao Bao3aec6962018-04-20 09:24:58 -0700570 int chosen_item = ui->ShowMenu(
571 headers, items, 0, true,
572 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
573 return (chosen_item == 1);
Elliott Hughes30694c92015-03-25 15:16:51 -0700574}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800575
Paul Crowley08404b42016-12-19 13:04:23 -0800576static bool ask_to_wipe_data(Device* device) {
Tao Bao3aec6962018-04-20 09:24:58 -0700577 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
Paul Crowley08404b42016-12-19 13:04:23 -0800578}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700579
Paul Crowley08404b42016-12-19 13:04:23 -0800580// Return true on success.
581static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700582 modified_flash = true;
583
Doug Zongker211aebc2011-10-28 15:13:10 -0700584 ui->Print("\n-- Wiping data...\n");
Paul Crowley3b4d5162016-06-08 13:51:41 -0700585 bool success = device->PreWipeData();
586 if (success) {
587 success &= erase_volume(DATA_ROOT);
588 if (has_cache) {
589 success &= erase_volume(CACHE_ROOT);
590 }
591 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
592 success &= erase_volume(METADATA_ROOT);
593 }
594 }
595 if (success) {
596 success &= device->PostWipeData();
597 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700598 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
599 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700600}
601
Paul Crowley08404b42016-12-19 13:04:23 -0800602static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700603 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Baofc5499f2017-02-23 19:06:53 -0800604 const char* const headers[] = {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700605 "Can't load Android system. Your data may be corrupt. "
606 "If you continue to get this message, you may need to "
607 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700608 "stored on this device.",
Tao Bao2bbc6d62017-08-13 23:48:55 -0700609 nullptr
Tao Baofc5499f2017-02-23 19:06:53 -0800610 };
611 const char* const items[] = {
Paul Crowley31ac0c62017-03-23 12:32:40 -0700612 "Try again",
613 "Factory data reset",
Tao Baofc5499f2017-02-23 19:06:53 -0800614 NULL
615 };
616 for (;;) {
Tao Bao3aec6962018-04-20 09:24:58 -0700617 int chosen_item = ui->ShowMenu(
618 headers, items, 0, true,
619 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Baofc5499f2017-02-23 19:06:53 -0800620 if (chosen_item != 1) {
621 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800622 }
Tao Baofc5499f2017-02-23 19:06:53 -0800623 if (ask_to_wipe_data(device)) {
624 return wipe_data(device);
625 }
626 }
Paul Crowley08404b42016-12-19 13:04:23 -0800627}
628
Tao Baoe39a9bc2015-03-31 12:19:05 -0700629// Return true on success.
630static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800631 if (!has_cache) {
632 ui->Print("No /cache partition found.\n");
633 return false;
634 }
635
Elliott Hughes30694c92015-03-25 15:16:51 -0700636 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700637 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700638 }
639
Tao Bao682c34b2015-04-07 17:16:35 -0700640 modified_flash = true;
641
Elliott Hughes30694c92015-03-25 15:16:51 -0700642 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700643 bool success = erase_volume("/cache");
644 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
645 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700646}
647
Tao Bao1b2a98b2017-03-24 10:45:34 -0700648// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
649// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700650static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700651 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
652 if (fd == -1) {
653 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
654 return false;
655 }
656
657 uint64_t range[2] = { 0, 0 };
658 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
659 PLOG(ERROR) << "Failed to get partition size";
660 return false;
661 }
662 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
663
664 LOG(INFO) << " Trying BLKSECDISCARD...";
665 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
666 PLOG(WARNING) << " Failed";
667
668 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
669 unsigned int zeroes;
670 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
671 LOG(INFO) << " Trying BLKDISCARD...";
672 if (ioctl(fd, BLKDISCARD, &range) == -1) {
673 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700674 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700675 }
676 } else {
677 LOG(INFO) << " Trying BLKZEROOUT...";
678 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
679 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -0700680 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700681 }
Tao Bao862a4c12016-06-02 11:16:50 -0700682 }
Tao Bao1b2a98b2017-03-24 10:45:34 -0700683 }
Tao Bao862a4c12016-06-02 11:16:50 -0700684
Tao Bao1b2a98b2017-03-24 10:45:34 -0700685 LOG(INFO) << " Done";
686 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700687}
688
Yabin Cuifd99a312016-06-09 14:09:39 -0700689// Check if the wipe package matches expectation:
690// 1. verify the package.
691// 2. check metadata (ota-type, pre-device and serial number if having one).
692static bool check_wipe_package(size_t wipe_package_size) {
693 if (wipe_package_size == 0) {
694 LOG(ERROR) << "wipe_package_size is zero";
695 return false;
696 }
697 std::string wipe_package;
698 std::string err_str;
699 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
700 PLOG(ERROR) << "Failed to read wipe package";
701 return false;
702 }
703 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
704 wipe_package.size())) {
705 LOG(ERROR) << "Failed to verify package";
706 return false;
707 }
708
709 // Extract metadata
710 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -0800711 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
712 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -0700713 if (err != 0) {
714 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
715 return false;
716 }
717 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -0700718 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -0700719 CloseArchive(zip);
720 return false;
721 }
722 CloseArchive(zip);
723
724 // Check metadata
725 std::vector<std::string> lines = android::base::Split(metadata, "\n");
726 bool ota_type_matched = false;
727 bool device_type_matched = false;
728 bool has_serial_number = false;
729 bool serial_number_matched = false;
730 for (const auto& line : lines) {
731 if (line == "ota-type=BRICK") {
732 ota_type_matched = true;
733 } else if (android::base::StartsWith(line, "pre-device=")) {
734 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -0800735 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700736 device_type_matched = (device_type == real_device_type);
737 } else if (android::base::StartsWith(line, "serialno=")) {
738 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -0800739 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -0700740 has_serial_number = true;
741 serial_number_matched = (serial_no == real_serial_no);
742 }
743 }
744 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
745}
746
Tao Baoaac9d9f2018-04-29 23:38:59 -0700747// Wipes the current A/B device, with a secure wipe of all the partitions in RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -0700748static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baoaac9d9f2018-04-29 23:38:59 -0700749 ui->SetBackground(RecoveryUI::ERASING);
750 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Tao Bao862a4c12016-06-02 11:16:50 -0700751
Tao Baoaac9d9f2018-04-29 23:38:59 -0700752 if (!check_wipe_package(wipe_package_size)) {
753 LOG(ERROR) << "Failed to verify wipe package";
754 return false;
755 }
756 static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
757 std::string partition_list;
758 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
759 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
760 return false;
761 }
762
763 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
764 for (const std::string& line : lines) {
765 std::string partition = android::base::Trim(line);
766 // Ignore '#' comment or empty lines.
767 if (android::base::StartsWith(partition, "#") || partition.empty()) {
768 continue;
Tao Bao862a4c12016-06-02 11:16:50 -0700769 }
770
Tao Baoaac9d9f2018-04-29 23:38:59 -0700771 // Proceed anyway even if it fails to wipe some partition.
772 secure_wipe_partition(partition);
773 }
774 return true;
Tao Bao862a4c12016-06-02 11:16:50 -0700775}
776
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700777static void choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800778 std::vector<std::string> entries;
779 if (has_cache) {
780 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
781 auto add_to_entries = [&](const char* filename) {
782 std::string log_file(filename);
783 if (i > 0) {
784 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -0700785 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800786
787 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
788 entries.push_back(std::move(log_file));
789 }
790 };
791
792 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
793 add_to_entries(LAST_LOG_FILE);
794
795 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
796 add_to_entries(LAST_KMSG_FILE);
797 }
798 } else {
799 // If cache partition is not found, view /tmp/recovery.log instead.
Tao Bao641fa972018-04-25 18:59:40 -0700800 if (access(Paths::Get().temporary_log_file().c_str(), R_OK) == -1) {
Tao Bao08fc6be2017-03-07 00:56:27 -0800801 return;
Tianjie Xua54f75e2016-08-17 12:02:46 -0700802 } else {
Tao Bao641fa972018-04-25 18:59:40 -0700803 entries.push_back(Paths::Get().temporary_log_file());
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700804 }
Tao Bao08fc6be2017-03-07 00:56:27 -0800805 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700806
Tao Bao08fc6be2017-03-07 00:56:27 -0800807 entries.push_back("Back");
Elliott Hughesc0491632015-05-06 12:40:05 -0700808
Tao Bao08fc6be2017-03-07 00:56:27 -0800809 std::vector<const char*> menu_entries(entries.size());
810 std::transform(entries.cbegin(), entries.cend(), menu_entries.begin(),
811 [](const std::string& entry) { return entry.c_str(); });
812 menu_entries.push_back(nullptr);
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700813
Tao Bao08fc6be2017-03-07 00:56:27 -0800814 const char* headers[] = { "Select file to view", nullptr };
Elliott Hughes8de52072015-04-08 20:06:50 -0700815
Tao Bao08fc6be2017-03-07 00:56:27 -0800816 int chosen_item = 0;
817 while (true) {
Tao Bao3aec6962018-04-20 09:24:58 -0700818 chosen_item = ui->ShowMenu(
819 headers, menu_entries.data(), chosen_item, true,
820 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao08fc6be2017-03-07 00:56:27 -0800821 if (entries[chosen_item] == "Back") break;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700822
Tao Bao08fc6be2017-03-07 00:56:27 -0800823 ui->ShowFile(entries[chosen_item].c_str());
824 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700825}
826
Tao Baodb7e8982017-03-06 23:53:16 -0800827static void run_graphics_test() {
828 // Switch to graphics screen.
829 ui->ShowText(false);
Elliott Hughes498cda62016-04-14 16:49:04 -0700830
Tao Baodb7e8982017-03-06 23:53:16 -0800831 ui->SetProgressType(RecoveryUI::INDETERMINATE);
832 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
833 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700834
Tao Baodb7e8982017-03-06 23:53:16 -0800835 ui->SetBackground(RecoveryUI::ERROR);
836 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700837
Tao Baodb7e8982017-03-06 23:53:16 -0800838 ui->SetBackground(RecoveryUI::NO_COMMAND);
839 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700840
Tao Baodb7e8982017-03-06 23:53:16 -0800841 ui->SetBackground(RecoveryUI::ERASING);
842 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700843
Tao Baodb7e8982017-03-06 23:53:16 -0800844 // Calling SetBackground() after SetStage() to trigger a redraw.
845 ui->SetStage(1, 3);
846 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
847 sleep(1);
848 ui->SetStage(2, 3);
849 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
850 sleep(1);
851 ui->SetStage(3, 3);
852 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
853 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -0700854
Tao Baodb7e8982017-03-06 23:53:16 -0800855 ui->SetStage(-1, -1);
856 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Elliott Hughes498cda62016-04-14 16:49:04 -0700857
Tao Baodb7e8982017-03-06 23:53:16 -0800858 ui->SetProgressType(RecoveryUI::DETERMINATE);
859 ui->ShowProgress(1.0, 10.0);
860 float fraction = 0.0;
861 for (size_t i = 0; i < 100; ++i) {
862 fraction += .01;
863 ui->SetProgress(fraction);
864 usleep(100000);
865 }
866
867 ui->ShowText(true);
Elliott Hughes498cda62016-04-14 16:49:04 -0700868}
869
Tao Baocdcf28f2016-01-13 15:05:20 -0800870// How long (in seconds) we wait for the fuse-provided package file to
871// appear, before timing out.
872#define SDCARD_INSTALL_TIMEOUT 10
873
Tao Bao145d8612015-03-25 15:51:15 -0700874static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700875 modified_flash = true;
876
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000877 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
878 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
879 return INSTALL_ERROR;
880 }
881
Tao Baoc4a18ef2017-02-10 00:13:30 -0800882 std::string path = browse_directory(SDCARD_ROOT, device);
883 if (path.empty()) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700884 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800885 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000886 return INSTALL_ERROR;
887 }
888
Tao Baoc4a18ef2017-02-10 00:13:30 -0800889 ui->Print("\n-- Install %s ...\n", path.c_str());
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000890 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000891
Tao Baocdcf28f2016-01-13 15:05:20 -0800892 // We used to use fuse in a thread as opposed to a process. Since accessing
893 // through fuse involves going from kernel to userspace to kernel, it leads
894 // to deadlock when a page fault occurs. (Bug: 26313124)
895 pid_t child;
896 if ((child = fork()) == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800897 bool status = start_sdcard_fuse(path.c_str());
Tao Baocdcf28f2016-01-13 15:05:20 -0800898
899 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
900 }
901
902 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
903 // process is ready.
904 int result = INSTALL_ERROR;
905 int status;
906 bool waited = false;
907 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
908 if (waitpid(child, &status, WNOHANG) == -1) {
909 result = INSTALL_ERROR;
910 waited = true;
911 break;
912 }
913
914 struct stat sb;
915 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
916 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
917 sleep(1);
918 continue;
919 } else {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700920 LOG(ERROR) << "Timed out waiting for the fuse-provided package.";
Tao Baocdcf28f2016-01-13 15:05:20 -0800921 result = INSTALL_ERROR;
922 kill(child, SIGKILL);
923 break;
924 }
925 }
926
Tao Bao641fa972018-04-25 18:59:40 -0700927 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, false, 0 /*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -0800928 break;
929 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000930
Tao Baocdcf28f2016-01-13 15:05:20 -0800931 if (!waited) {
932 // Calling stat() on this magic filename signals the fuse
933 // filesystem to shut down.
934 struct stat sb;
935 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
936
937 waitpid(child, &status, 0);
938 }
939
940 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700941 LOG(ERROR) << "Error exit from the fuse process: " << WEXITSTATUS(status);
Tao Baocdcf28f2016-01-13 15:05:20 -0800942 }
943
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000944 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -0800945 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000946}
947
Tao Bao50dd5322017-03-07 14:57:04 -0800948// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
949// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
950static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
951 for (;;) {
952 finish_recovery();
953 switch (status) {
954 case INSTALL_SUCCESS:
955 case INSTALL_NONE:
956 ui->SetBackground(RecoveryUI::NO_COMMAND);
957 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -0700958
Tao Bao50dd5322017-03-07 14:57:04 -0800959 case INSTALL_ERROR:
960 case INSTALL_CORRUPT:
961 ui->SetBackground(RecoveryUI::ERROR);
962 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800963 }
Tao Bao50dd5322017-03-07 14:57:04 -0800964 ui->SetProgressType(RecoveryUI::EMPTY);
965
Tao Bao3aec6962018-04-20 09:24:58 -0700966 int chosen_item = ui->ShowMenu(
967 nullptr, device->GetMenuItems(), 0, false,
968 std::bind(&Device::HandleMenuKey, device, std::placeholders::_1, std::placeholders::_2));
Tao Bao50dd5322017-03-07 14:57:04 -0800969
970 // Device-specific code may take some action here. It may return one of the core actions
971 // handled in the switch statement below.
972 Device::BuiltinAction chosen_action =
973 (chosen_item == -1) ? Device::REBOOT : device->InvokeMenuItem(chosen_item);
974
975 bool should_wipe_cache = false;
976 switch (chosen_action) {
977 case Device::NO_ACTION:
978 break;
979
980 case Device::REBOOT:
981 case Device::SHUTDOWN:
982 case Device::REBOOT_BOOTLOADER:
983 return chosen_action;
984
985 case Device::WIPE_DATA:
986 if (ui->IsTextVisible()) {
987 if (ask_to_wipe_data(device)) {
988 wipe_data(device);
989 }
990 } else {
991 wipe_data(device);
992 return Device::NO_ACTION;
993 }
994 break;
995
996 case Device::WIPE_CACHE:
997 wipe_cache(ui->IsTextVisible(), device);
998 if (!ui->IsTextVisible()) return Device::NO_ACTION;
999 break;
1000
1001 case Device::APPLY_ADB_SIDELOAD:
1002 case Device::APPLY_SDCARD:
1003 {
1004 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
1005 if (adb) {
Tao Bao641fa972018-04-25 18:59:40 -07001006 status = apply_from_adb(&should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -08001007 } else {
1008 status = apply_from_sdcard(device, &should_wipe_cache);
1009 }
1010
1011 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1012 if (!wipe_cache(false, device)) {
1013 status = INSTALL_ERROR;
1014 }
1015 }
1016
1017 if (status != INSTALL_SUCCESS) {
1018 ui->SetBackground(RecoveryUI::ERROR);
1019 ui->Print("Installation aborted.\n");
1020 copy_logs();
1021 } else if (!ui->IsTextVisible()) {
1022 return Device::NO_ACTION; // reboot if logs aren't visible
1023 } else {
1024 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
1025 }
1026 }
1027 break;
1028
1029 case Device::VIEW_RECOVERY_LOGS:
1030 choose_recovery_file(device);
1031 break;
1032
1033 case Device::RUN_GRAPHICS_TEST:
1034 run_graphics_test();
1035 break;
1036
Tianjie Xu29d55752017-09-20 17:53:46 -07001037 case Device::RUN_LOCALE_TEST: {
1038 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
1039 screen_ui->CheckBackgroundTextImages(locale);
1040 break;
1041 }
Tao Bao50dd5322017-03-07 14:57:04 -08001042 case Device::MOUNT_SYSTEM:
1043 // For a system image built with the root directory (i.e. system_root_image == "true"), we
1044 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
1045 // work (the symlink is created through the build system). (Bug: 22855115)
1046 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
1047 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1048 ui->Print("Mounted /system.\n");
1049 }
1050 } else {
1051 if (ensure_path_mounted("/system") != -1) {
1052 ui->Print("Mounted /system.\n");
1053 }
1054 }
1055 break;
1056 }
1057 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001058}
1059
Tao Bao99f0d9e2016-10-13 12:46:38 -07001060static void print_property(const char* key, const char* name, void* /* cookie */) {
1061 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001062}
1063
Tao Baoac9d94d2016-11-03 11:37:15 -07001064static std::string load_locale_from_cache() {
1065 if (ensure_path_mounted(LOCALE_FILE) != 0) {
1066 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
1067 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -07001068 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001069
1070 std::string content;
1071 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
1072 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
1073 return "";
1074 }
1075
1076 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001077}
1078
Tao Baoac9d94d2016-11-03 11:37:15 -07001079void ui_print(const char* format, ...) {
1080 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -07001081 va_list ap;
1082 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -07001083 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001084 va_end(ap);
1085
Tao Baoac9d94d2016-11-03 11:37:15 -07001086 if (ui != nullptr) {
1087 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -07001088 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -07001089 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001090 }
1091}
1092
Tao Baof2ea6d72018-04-26 10:40:36 -07001093static bool is_battery_ok(int* required_battery_level) {
1094 struct healthd_config healthd_config = {
1095 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1096 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1097 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1098 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1099 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1100 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1101 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1102 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1103 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1104 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1105 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1106 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1107 .energyCounter = nullptr,
1108 .boot_min_cap = 0,
1109 .screen_on = nullptr
1110 };
1111 healthd_board_init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001112
Tao Baof2ea6d72018-04-26 10:40:36 -07001113 android::BatteryMonitor monitor;
1114 monitor.init(&healthd_config);
Yabin Cui99281df2016-02-17 12:21:52 -08001115
Tao Baof2ea6d72018-04-26 10:40:36 -07001116 static constexpr int BATTERY_READ_TIMEOUT_IN_SEC = 10;
1117 int wait_second = 0;
1118 while (true) {
1119 int charge_status = monitor.getChargeStatus();
1120 // Treat unknown status as charged.
1121 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1122 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1123 android::BatteryProperty capacity;
1124 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1125 ui_print("charge_status %d, charged %d, status %d, capacity %" PRId64 "\n", charge_status,
1126 charged, status, capacity.valueInt64);
1127 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1128 // the battery profile. Before the load finishes, it reports value 50 as a fake
1129 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1130 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1131 if (status == 0 && capacity.valueInt64 == 50) {
1132 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1133 sleep(1);
1134 wait_second++;
1135 continue;
1136 }
Yabin Cui99281df2016-02-17 12:21:52 -08001137 }
Tao Baof2ea6d72018-04-26 10:40:36 -07001138 // If we can't read battery percentage, it may be a device without battery. In this situation,
1139 // use 100 as a fake battery percentage.
1140 if (status != 0) {
1141 capacity.valueInt64 = 100;
1142 }
1143
1144 // GmsCore enters recovery mode to install package when having enough battery percentage.
1145 // Normally, the threshold is 40% without charger and 20% with charger. So we should check
1146 // battery with a slightly lower limitation.
1147 static constexpr int BATTERY_OK_PERCENTAGE = 20;
1148 static constexpr int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
1149 *required_battery_level = charged ? BATTERY_WITH_CHARGER_OK_PERCENTAGE : BATTERY_OK_PERCENTAGE;
1150 return capacity.valueInt64 >= *required_battery_level;
1151 }
Yabin Cui99281df2016-02-17 12:21:52 -08001152}
1153
Tianjie Xu99b73be2017-11-28 17:23:06 -08001154// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001155static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1156 std::vector<std::string> options;
1157 for (const auto& arg : args) {
1158 if (!android::base::StartsWith(arg, "--retry_count")) {
1159 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001160 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001161 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001162
Tianjie Xu99b73be2017-11-28 17:23:06 -08001163 // Update the retry counter in BCB.
1164 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001165 std::string err;
1166 if (!update_bootloader_message(options, &err)) {
1167 LOG(ERROR) << err;
1168 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001169}
1170
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001171static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001172 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1173 if (!bootreason.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001174 // More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
1175 static const std::vector<std::string> kBootreasonBlacklist{
1176 "kernel_panic",
1177 "Panic",
1178 };
1179 for (const auto& str : kBootreasonBlacklist) {
1180 if (android::base::EqualsIgnoreCase(str, bootreason)) return true;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001181 }
Tao Baoefc35592017-01-08 22:45:47 -08001182 }
1183 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001184}
1185
Tao Bao641fa972018-04-25 18:59:40 -07001186static void log_failure_code(ErrorCode code, const std::string& update_package) {
1187 std::vector<std::string> log_buffer = {
1188 update_package,
1189 "0", // install result
1190 "error: " + std::to_string(code),
1191 };
1192 std::string log_content = android::base::Join(log_buffer, "\n");
1193 const std::string& install_file = Paths::Get().temporary_install_file();
1194 if (!android::base::WriteStringToFile(log_content, install_file)) {
1195 PLOG(ERROR) << "Failed to write " << install_file;
1196 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001197
Tao Bao641fa972018-04-25 18:59:40 -07001198 // Also write the info into last_log.
1199 LOG(INFO) << log_content;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001200}
1201
Tao Bao6d99d4b2018-04-25 16:47:04 -07001202int start_recovery(int argc, char** argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001203 time_t start = time(nullptr);
1204
Tianjie Xu99b73be2017-11-28 17:23:06 -08001205 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1206
1207 load_volume_table();
1208 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1209
1210 std::vector<std::string> args = get_args(argc, argv);
1211 std::vector<char*> args_to_parse(args.size());
1212 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1213 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1214
Tao Baof9f17342018-04-27 10:44:04 -07001215 static constexpr struct option OPTIONS[] = {
1216 { "just_exit", no_argument, nullptr, 'x' },
1217 { "locale", required_argument, nullptr, 0 },
1218 { "prompt_and_wipe_data", no_argument, nullptr, 0 },
1219 { "reason", required_argument, nullptr, 0 },
1220 { "retry_count", required_argument, nullptr, 0 },
1221 { "security", no_argument, nullptr, 0 },
1222 { "show_text", no_argument, nullptr, 't' },
1223 { "shutdown_after", no_argument, nullptr, 0 },
1224 { "sideload", no_argument, nullptr, 0 },
1225 { "sideload_auto_reboot", no_argument, nullptr, 0 },
1226 { "update_package", required_argument, nullptr, 0 },
1227 { "wipe_ab", no_argument, nullptr, 0 },
1228 { "wipe_cache", no_argument, nullptr, 0 },
1229 { "wipe_data", no_argument, nullptr, 0 },
1230 { "wipe_package_size", required_argument, nullptr, 0 },
1231 { nullptr, 0, nullptr, 0 },
1232 };
1233
Tianjie Xu99b73be2017-11-28 17:23:06 -08001234 const char* update_package = nullptr;
1235 bool should_wipe_data = false;
1236 bool should_prompt_and_wipe_data = false;
1237 bool should_wipe_cache = false;
1238 bool should_wipe_ab = false;
1239 size_t wipe_package_size = 0;
1240 bool show_text = false;
1241 bool sideload = false;
1242 bool sideload_auto_reboot = false;
1243 bool just_exit = false;
1244 bool shutdown_after = false;
1245 int retry_count = 0;
1246 bool security_update = false;
1247
1248 int arg;
1249 int option_index;
1250 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1251 &option_index)) != -1) {
1252 switch (arg) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001253 case 't':
1254 show_text = true;
1255 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001256 case 'x':
1257 just_exit = true;
1258 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001259 case 0: {
1260 std::string option = OPTIONS[option_index].name;
Tao Baof9f17342018-04-27 10:44:04 -07001261 if (option == "locale") {
1262 locale = optarg;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001263 } else if (option == "prompt_and_wipe_data") {
1264 should_prompt_and_wipe_data = true;
Tao Baof9f17342018-04-27 10:44:04 -07001265 } else if (option == "reason") {
1266 reason = optarg;
1267 } else if (option == "retry_count") {
1268 android::base::ParseInt(optarg, &retry_count, 0);
1269 } else if (option == "security") {
1270 security_update = true;
1271 } else if (option == "sideload") {
1272 sideload = true;
1273 } else if (option == "sideload_auto_reboot") {
1274 sideload = true;
1275 sideload_auto_reboot = true;
1276 } else if (option == "shutdown_after") {
1277 shutdown_after = true;
1278 } else if (option == "update_package") {
1279 update_package = optarg;
1280 } else if (option == "wipe_ab") {
1281 should_wipe_ab = true;
1282 } else if (option == "wipe_cache") {
1283 should_wipe_cache = true;
1284 } else if (option == "wipe_data") {
1285 should_wipe_data = true;
1286 } else if (option == "wipe_package_size") {
1287 android::base::ParseUint(optarg, &wipe_package_size);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001288 }
1289 break;
1290 }
1291 case '?':
1292 LOG(ERROR) << "Invalid command argument";
1293 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001294 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001295 }
Doug Zongker9270a202012-01-09 15:16:13 -08001296
Tianjie Xu99b73be2017-11-28 17:23:06 -08001297 if (locale.empty()) {
1298 if (has_cache) {
1299 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001300 }
1301
Tao Baoac9d94d2016-11-03 11:37:15 -07001302 if (locale.empty()) {
Tao Baoaac9d9f2018-04-29 23:38:59 -07001303 static constexpr const char* DEFAULT_LOCALE = "en-US";
Tianjie Xu99b73be2017-11-28 17:23:06 -08001304 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001305 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001306 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001307
Tianjie Xu99b73be2017-11-28 17:23:06 -08001308 printf("locale is [%s]\n", locale.c_str());
1309 printf("stage is [%s]\n", stage.c_str());
1310 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001311
Tianjie Xu99b73be2017-11-28 17:23:06 -08001312 Device* device = make_device();
1313 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1314 printf("Quiescent recovery mode.\n");
1315 ui = new StubRecoveryUI();
1316 } else {
1317 ui = device->GetUI();
1318
1319 if (!ui->Init(locale)) {
1320 printf("Failed to initialize UI, use stub UI instead.\n");
1321 ui = new StubRecoveryUI();
1322 }
1323 }
1324
1325 // Set background string to "installing security update" for security update,
1326 // otherwise set it to "installing system update".
1327 ui->SetSystemUpdateText(security_update);
1328
1329 int st_cur, st_max;
1330 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1331 ui->SetStage(st_cur, st_max);
1332 }
1333
1334 ui->SetBackground(RecoveryUI::NONE);
1335 if (show_text) ui->ShowText(true);
1336
1337 sehandle = selinux_android_file_context_handle();
1338 selinux_android_set_sehandle(sehandle);
1339 if (!sehandle) {
1340 ui->Print("Warning: No file_contexts\n");
1341 }
1342
1343 device->StartRecovery();
1344
1345 printf("Command:");
1346 for (const auto& arg : args) {
1347 printf(" \"%s\"", arg.c_str());
1348 }
1349 printf("\n\n");
1350
1351 property_list(print_property, nullptr);
1352 printf("\n");
1353
1354 ui->Print("Supported API: %d\n", kRecoveryApiVersion);
1355
1356 int status = INSTALL_SUCCESS;
1357
1358 if (update_package != nullptr) {
1359 // It's not entirely true that we will modify the flash. But we want
1360 // to log the update attempt since update_package is non-NULL.
1361 modified_flash = true;
1362
Tao Baof2ea6d72018-04-26 10:40:36 -07001363 int required_battery_level;
1364 if (retry_count == 0 && !is_battery_ok(&required_battery_level)) {
1365 ui->Print("battery capacity is not enough for installing package: %d%% needed\n",
1366 required_battery_level);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001367 // Log the error code to last_install when installation skips due to
1368 // low battery.
1369 log_failure_code(kLowBattery, update_package);
1370 status = INSTALL_SKIPPED;
Tianjie Xua6f49bd2018-03-26 14:32:11 -07001371 } else if (retry_count == 0 && bootreason_in_blacklist()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001372 // Skip update-on-reboot when bootreason is kernel_panic or similar
1373 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1374 log_failure_code(kBootreasonInBlacklist, update_package);
1375 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001376 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001377 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1378 // identify the interrupted update due to unexpected reboots.
1379 if (retry_count == 0) {
1380 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001381 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001382
Tao Bao641fa972018-04-25 18:59:40 -07001383 status = install_package(update_package, &should_wipe_cache, true, retry_count);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001384 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1385 wipe_cache(false, device);
1386 }
1387 if (status != INSTALL_SUCCESS) {
1388 ui->Print("Installation aborted.\n");
Tao Baoaac9d9f2018-04-29 23:38:59 -07001389
1390 // When I/O error or bspatch/imgpatch error happens, reboot and retry installation
1391 // RETRY_LIMIT times before we abandon this OTA update.
1392 static constexpr int RETRY_LIMIT = 4;
Tianjie Xu99b73be2017-11-28 17:23:06 -08001393 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
1394 copy_logs();
1395 retry_count += 1;
1396 set_retry_bootloader_message(retry_count, args);
1397 // Print retry count on screen.
1398 ui->Print("Retry attempt %d\n", retry_count);
1399
1400 // Reboot and retry the update
1401 if (!reboot("reboot,recovery")) {
1402 ui->Print("Reboot failed\n");
1403 } else {
1404 while (true) {
1405 pause();
1406 }
1407 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001408 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001409 // If this is an eng or userdebug build, then automatically
1410 // turn the text display on if the script fails so the error
1411 // message is visible.
1412 if (is_ro_debuggable()) {
1413 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001414 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001415 }
Doug Zongker8674a722010-09-15 11:08:23 -07001416 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001417 } else if (should_wipe_data) {
1418 if (!wipe_data(device)) {
1419 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001420 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001421 } else if (should_prompt_and_wipe_data) {
1422 ui->ShowText(true);
1423 ui->SetBackground(RecoveryUI::ERROR);
1424 if (!prompt_and_wipe_data(device)) {
1425 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001426 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001427 ui->ShowText(false);
1428 } else if (should_wipe_cache) {
1429 if (!wipe_cache(false, device)) {
1430 status = INSTALL_ERROR;
1431 }
1432 } else if (should_wipe_ab) {
1433 if (!wipe_ab_device(wipe_package_size)) {
1434 status = INSTALL_ERROR;
1435 }
1436 } else if (sideload) {
1437 // 'adb reboot sideload' acts the same as user presses key combinations
1438 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1439 // display will NOT be turned on by default. And it will reboot after
1440 // sideload finishes even if there are errors. Unless one turns on the
1441 // text display during the installation. This is to enable automated
1442 // testing.
1443 if (!sideload_auto_reboot) {
1444 ui->ShowText(true);
1445 }
Tao Bao641fa972018-04-25 18:59:40 -07001446 status = apply_from_adb(&should_wipe_cache);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001447 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1448 if (!wipe_cache(false, device)) {
1449 status = INSTALL_ERROR;
1450 }
1451 }
1452 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1453 if (sideload_auto_reboot) {
1454 ui->Print("Rebooting automatically.\n");
1455 }
1456 } else if (!just_exit) {
1457 // If this is an eng or userdebug build, automatically turn on the text display if no command
1458 // is specified. Note that this should be called before setting the background to avoid
1459 // flickering the background image.
1460 if (is_ro_debuggable()) {
1461 ui->ShowText(true);
1462 }
1463 status = INSTALL_NONE; // No command specified
1464 ui->SetBackground(RecoveryUI::NO_COMMAND);
1465 }
1466
1467 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1468 ui->SetBackground(RecoveryUI::ERROR);
1469 if (!ui->IsTextVisible()) {
1470 sleep(5);
1471 }
1472 }
1473
1474 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1475 // 1. If the recovery menu is visible, prompt and wait for commands.
1476 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1477 // recovery to sideload a package.)
1478 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1479 // without waiting.
1480 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1481 // reboot after it shows the "error" screen for 5s.
1482 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1483 Device::BuiltinAction temp = prompt_and_wait(device, status);
1484 if (temp != Device::NO_ACTION) {
1485 after = temp;
1486 }
1487 }
1488
1489 // Save logs and clean up before rebooting or shutting down.
1490 finish_recovery();
1491
1492 switch (after) {
1493 case Device::SHUTDOWN:
1494 ui->Print("Shutting down...\n");
1495 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1496 break;
1497
1498 case Device::REBOOT_BOOTLOADER:
1499 ui->Print("Rebooting to bootloader...\n");
1500 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
1501 break;
1502
1503 default:
1504 ui->Print("Rebooting...\n");
1505 reboot("reboot,");
1506 break;
1507 }
1508 while (true) {
1509 pause();
1510 }
1511 // Should be unreachable.
1512 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001513}