blob: 2eead17b52c8ed57ed6b4766b77956221ee0fc0f [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
Steve Kondikf96dc5e2013-10-19 19:49:20 -07003 * Copyright (C) 2019 The LineageOS Project
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#include <ctype.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070019#include <dirent.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080020#include <errno.h>
21#include <fcntl.h>
22#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070023#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080024#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070025#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080026#include <linux/input.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070027#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080028#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Patrick Tjincd055ee2014-12-09 11:26:40 -080031#include <sys/klog.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070032#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080033#include <sys/types.h>
34#include <time.h>
35#include <unistd.h>
36
Tao Baoc4a18ef2017-02-10 00:13:30 -080037#include <algorithm>
Tao Bao04ca4262015-09-10 15:32:24 -070038#include <chrono>
Tao Baoc4a18ef2017-02-10 00:13:30 -080039#include <memory>
Tao Bao862a4c12016-06-02 11:16:50 -070040#include <string>
41#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070042
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/file.h>
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -070044#include <android-base/logging.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080045#include <android-base/parseint.h>
Elliott Hughescb220402016-09-23 15:30:55 -070046#include <android-base/properties.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080047#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070048#include <android-base/strings.h>
49#include <android-base/unique_fd.h>
Yabin Cui8b309f62016-06-24 18:22:02 -070050#include <bootloader_message/bootloader_message.h>
Tao Bao75238632015-05-27 14:46:17 -070051#include <cutils/android_reboot.h>
Elliott Hughescb220402016-09-23 15:30:55 -070052#include <cutils/properties.h> /* for property_list */
Yifan Honge8e4c402017-11-08 14:56:03 -080053#include <health2/Health.h>
54#include <private/android_filesystem_config.h> /* for AID_SYSTEM */
55#include <private/android_logger.h> /* private pmsg functions */
Jeff Vander Stoepe35926e2017-06-14 15:30:39 -070056#include <selinux/android.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070057#include <selinux/label.h>
58#include <selinux/selinux.h>
Tom Marshalla08c6f12019-01-04 14:37:31 -080059#include <volume_manager/VolumeManager.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070060#include <ziparchive/zip_archive.h>
Yabin Cui99281df2016-02-17 12:21:52 -080061
Tao Bao75238632015-05-27 14:46:17 -070062#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080063#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070064#include "device.h"
65#include "fuse_sdcard_provider.h"
66#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080067#include "install.h"
Josh Gaoacb2a2f2016-08-26 18:24:34 -070068#include "minadbd/minadbd.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080069#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"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080072#include "roots.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070073#include "rotate_logs.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070074#include "screen_ui.h"
Sen Jiangd5304492016-12-09 16:20:49 -080075#include "stub_ui.h"
Tianjie Xue113e4d2016-10-21 17:46:13 -070076#include "ui.h"
Tom Marshalla08c6f12019-01-04 14:37:31 -080077#include "volclient.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080078
Tom Marshallad82f482019-01-17 16:05:59 -080079// For e2fsprogs
80extern "C" {
81const char* program_name = "fstools";
82}
83
Steve Kondikf96dc5e2013-10-19 19:49:20 -070084#include "recovery_cmds.h"
85
86struct recovery_cmd {
87 const char* name;
88 int (*main_func)(int argc, char** argv);
89};
90
91static const struct recovery_cmd recovery_cmds[] = {
92 { "reboot", reboot_main },
93 { "poweroff", reboot_main },
Tom Marshall766ed032019-01-07 14:21:34 -080094 { "gunzip", pigz_main },
95 { "gzip", pigz_main },
96 { "unzip", miniunz_main },
97 { "zip", minizip_main },
Steve Kondikf96dc5e2013-10-19 19:49:20 -070098 { "sh", mksh_main },
Tom Marshallbed81712019-01-07 14:31:55 -080099 { "awk", awk_main },
Tom Marshallad82f482019-01-17 16:05:59 -0800100
101 /* Filesystem tools */
102 { "e2fsdroid", e2fsdroid_main },
103 { "e2fsdroid_static", e2fsdroid_main },
104 { "sload.f2fs", fsck_f2fs_main },
105
106 { "mke2fs", mke2fs_main },
107 { "mke2fs_static", mke2fs_main },
108 { "e2fsck", e2fsck_main },
109 { "fsck.ext4", e2fsck_main },
110 { "mkfs.ext4", mke2fs_main },
Tom Marshall635a0bf2019-01-17 16:21:01 -0800111 { "resize2fs", resize2fs_main },
112 { "tune2fs", tune2fs_main },
Tom Marshallad82f482019-01-17 16:05:59 -0800113
114 { "mkfs.f2fs", mkfs_f2fs_main },
115 { "fsck.f2fs", fsck_f2fs_main },
116
117 { "fsck_msdos", fsck_msdos_main },
118
119 { "mkfs.exfat", mkfs_exfat_main },
120 { "fsck.exfat", fsck_exfat_main },
121
122 { "fsck.ntfs", fsck_ntfs_main },
123 { "mkfs.ntfs", mkfs_ntfs_main },
124 { "mount.ntfs", mount_ntfs_main },
125
126 { "sgdisk", sgdisk_main },
127
Steve Kondikf96dc5e2013-10-19 19:49:20 -0700128 { nullptr, nullptr },
129};
130
131struct recovery_cmd get_command(char* command) {
132 int i;
133
134 for (i = 0; recovery_cmds[i].name; i++) {
135 if (strcmp(command, recovery_cmds[i].name) == 0) {
136 break;
137 }
138 }
139
140 return recovery_cmds[i];
141}
142
Tom Marshalla08c6f12019-01-04 14:37:31 -0800143using android::volmgr::VolumeInfo;
144using android::volmgr::VolumeManager;
145
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800146static const struct option OPTIONS[] = {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800147 { "update_package", required_argument, NULL, 'u' },
Tianjie Xu3c62b672016-02-05 18:25:58 -0800148 { "retry_count", required_argument, NULL, 'n' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800149 { "wipe_data", no_argument, NULL, 'w' },
150 { "wipe_cache", no_argument, NULL, 'c' },
Doug Zongker4bc98062010-09-03 11:00:13 -0700151 { "show_text", no_argument, NULL, 't' },
Tao Baoc679f932015-03-30 09:43:49 -0700152 { "sideload", no_argument, NULL, 's' },
153 { "sideload_auto_reboot", no_argument, NULL, 'a' },
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700154 { "just_exit", no_argument, NULL, 'x' },
Doug Zongker02ec6b82012-08-22 17:26:40 -0700155 { "locale", required_argument, NULL, 'l' },
Doug Zongkerb1d12632014-03-18 10:32:12 -0700156 { "shutdown_after", no_argument, NULL, 'p' },
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -0700157 { "reason", required_argument, NULL, 'r' },
Tianjie Xu35926c42016-04-28 18:06:26 -0700158 { "security", no_argument, NULL, 'e'},
Yabin Cui8b309f62016-06-24 18:22:02 -0700159 { "wipe_ab", no_argument, NULL, 0 },
Yabin Cuifd99a312016-06-09 14:09:39 -0700160 { "wipe_package_size", required_argument, NULL, 0 },
Paul Crowley08404b42016-12-19 13:04:23 -0800161 { "prompt_and_wipe_data", no_argument, NULL, 0 },
Doug Zongker988500b2009-10-06 14:41:38 -0700162 { NULL, 0, NULL, 0 },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800163};
164
Tianjie Xu06e57ac2016-07-11 14:04:08 -0700165// More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
166static const std::vector<std::string> bootreason_blacklist {
167 "kernel_panic",
168 "Panic",
169};
170
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700171static const char *CACHE_LOG_DIR = "/cache/recovery";
Doug Zongkerd4208f92010-09-20 12:16:13 -0700172static const char *COMMAND_FILE = "/cache/recovery/command";
Doug Zongkerd4208f92010-09-20 12:16:13 -0700173static const char *LOG_FILE = "/cache/recovery/log";
Doug Zongkerd0181b82011-10-19 10:51:12 -0700174static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
Doug Zongker8b240cc2012-08-29 15:19:29 -0700175static const char *LOCALE_FILE = "/cache/recovery/last_locale";
Paul Lawrence661f8a62016-02-25 12:42:19 -0800176static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
177static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
Michael Ward9d2629c2011-06-23 22:14:24 -0700178static const char *CACHE_ROOT = "/cache";
Paul Lawrenced0db3372015-11-05 13:38:40 -0800179static const char *DATA_ROOT = "/data";
Paul Crowley723056a2016-06-08 13:51:41 -0700180static const char* METADATA_ROOT = "/metadata";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800181static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
Doug Zongkerd0181b82011-10-19 10:51:12 -0700182static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
Tao Baof0124322015-04-11 02:04:11 +0000183static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
Tao Baobef39712015-05-04 18:50:27 -0700184static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
Tianjie Xu69575552017-05-16 15:51:46 -0700185// We will try to apply the update package 5 times at most in case of an I/O error or
186// bspatch | imgpatch error.
187static const int RETRY_LIMIT = 4;
Yabin Cui99281df2016-02-17 12:21:52 -0800188static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
189// GmsCore enters recovery mode to install package when having enough battery
190// percentage. Normally, the threshold is 40% without charger and 20% with charger.
191// So we should check battery with a slightly lower limitation.
192static const int BATTERY_OK_PERCENTAGE = 20;
193static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
Tao Baoac9d94d2016-11-03 11:37:15 -0700194static constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
Tianjie Xu2078b222017-03-22 12:27:26 -0700195static constexpr const char* DEFAULT_LOCALE = "en-US";
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700196
Tao Baobd0ddcd2017-05-04 13:03:18 -0700197// We define RECOVERY_API_VERSION in Android.mk, which will be picked up by build system and packed
198// into target_files.zip. Assert the version defined in code and in Android.mk are consistent.
199static_assert(kRecoveryApiVersion == RECOVERY_API_VERSION, "Mismatching recovery API versions.");
200
Tao Baoac9d94d2016-11-03 11:37:15 -0700201static std::string locale;
Dan Albert8584fcf2016-10-27 03:08:08 +0000202static bool has_cache = false;
Tao Baoc0319b62016-10-13 15:17:04 -0700203
Tom Marshalle65875b2019-01-07 14:42:42 -0800204static const char* fbe_key_version = "/data/unencrypted/key/version";
Steve Kondikf96dc5e2013-10-19 19:49:20 -0700205static const char* adb_keys_data = "/data/misc/adb/adb_keys";
206static const char* adb_keys_root = "/adb_keys";
207
Tao Baoac9d94d2016-11-03 11:37:15 -0700208RecoveryUI* ui = nullptr;
209bool modified_flash = false;
Tao Baoa8d72bc2016-12-25 18:46:50 -0800210std::string stage;
Tao Baoac9d94d2016-11-03 11:37:15 -0700211const char* reason = nullptr;
212struct selabel_handle* sehandle;
213
Tom Marshalle65875b2019-01-07 14:42:42 -0800214bool userdata_mountable = false;
215bool userdata_encrypted = true;
216
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800217/*
218 * The recovery tool communicates with the main system through /cache files.
219 * /cache/recovery/command - INPUT - command line for tool, one arg per line
220 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800221 *
222 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700223 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800224 * --wipe_data - erase user data (and cache), then reboot
Paul Crowley08404b42016-12-19 13:04:23 -0800225 * --prompt_and_wipe_data - prompt the user that data is corrupt,
226 * with their consent erase user data (and cache), then reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800227 * --wipe_cache - wipe cache (but not user data), then reboot
Oscar Montemayor05231562009-11-30 08:40:57 -0800228 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700229 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800230 *
231 * After completing, we remove /cache/recovery/command and reboot.
232 * Arguments may also be supplied in the bootloader control block (BCB).
233 * These important scenarios must be safely restartable at any point:
234 *
235 * FACTORY RESET
236 * 1. user selects "factory reset"
237 * 2. main system writes "--wipe_data" to /cache/recovery/command
238 * 3. main system reboots into recovery
239 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
240 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700241 * 5. erase_volume() reformats /data
242 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800243 * 7. finish_recovery() erases BCB
244 * -- after this, rebooting will restart the main system --
245 * 8. main() calls reboot() to boot main system
246 *
247 * OTA INSTALL
248 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700249 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800250 * 3. main system reboots into recovery
251 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
252 * -- after this, rebooting will attempt to reinstall the update --
253 * 5. install_package() attempts to install the update
254 * NOTE: the package install must itself be restartable from any point
255 * 6. finish_recovery() erases BCB
256 * -- after this, rebooting will (try to) restart the main system --
257 * 7. ** if install failed **
258 * 7a. prompt_and_wait() shows an error icon and waits for the user
Tao Baoc0336392016-12-13 22:29:49 -0800259 * 7b. the user reboots (pulling the battery, etc) into the main system
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800260 */
261
Tao Baoac3d1ed2017-07-23 00:01:02 -0700262// Open a given path, mounting partitions as necessary.
263FILE* fopen_path(const char* path, const char* mode) {
264 if (ensure_path_mounted(path) != 0) {
265 LOG(ERROR) << "Can't mount " << path;
266 return nullptr;
267 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800268
Tao Baoac3d1ed2017-07-23 00:01:02 -0700269 // When writing, try to create the containing directory, if necessary. Use generous permissions,
270 // the system (init.rc) will reset them.
271 if (strchr("wa", mode[0])) {
272 mkdir_recursively(path, 0777, true, sehandle);
273 }
274 return fopen(path, mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800275}
276
Tao Bao04ca4262015-09-10 15:32:24 -0700277// close a file, log an error if the error indicator is set
278static void check_and_fclose(FILE *fp, const char *name) {
279 fflush(fp);
Tao Baoac9d94d2016-11-03 11:37:15 -0700280 if (fsync(fileno(fp)) == -1) {
281 PLOG(ERROR) << "Failed to fsync " << name;
282 }
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700283 if (ferror(fp)) {
284 PLOG(ERROR) << "Error in " << name;
285 }
Tao Bao04ca4262015-09-10 15:32:24 -0700286 fclose(fp);
287}
288
Steve Kondikf96dc5e2013-10-19 19:49:20 -0700289static bool file_copy(const char* src, const char* dst) {
290 bool ret = false;
291 char tmpdst[PATH_MAX];
292 FILE* sfp;
293 FILE* dfp;
294
295 snprintf(tmpdst, sizeof(tmpdst), "%s.tmp", dst);
296 sfp = fopen(src, "r");
297 dfp = fopen(tmpdst, "w");
298 if (sfp && dfp) {
299 char buf[4096];
300 size_t nr, nw;
301 while ((nr = fread(buf, 1, sizeof(buf), sfp)) != 0) {
302 nw = fwrite(buf, 1, nr, dfp);
303 if (nr != nw) break;
304 }
305 ret = (!ferror(sfp) && !ferror(dfp));
306 }
307 if (dfp) fclose(dfp);
308 if (sfp) fclose(sfp);
309
310 if (ret) {
311 ret = (rename(tmpdst, dst) == 0);
312 } else {
313 unlink(tmpdst);
314 }
315
316 return ret;
317}
318
Elliott Hughesf14af802015-02-10 14:46:14 -0800319bool is_ro_debuggable() {
Elliott Hughescb220402016-09-23 15:30:55 -0700320 return android::base::GetBoolProperty("ro.debuggable", false);
Elliott Hughesf14af802015-02-10 14:46:14 -0800321}
322
Dmitri Plotnikov8706a982017-04-18 08:28:26 -0700323bool reboot(const std::string& command) {
324 std::string cmd = command;
325 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
326 cmd += ",quiescent";
327 }
328 return android::base::SetProperty(ANDROID_RB_PROPERTY, cmd);
329}
330
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700331static void redirect_stdio(const char* filename) {
Tao Bao04ca4262015-09-10 15:32:24 -0700332 int pipefd[2];
333 if (pipe(pipefd) == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700334 PLOG(ERROR) << "pipe failed";
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700335
Tao Bao04ca4262015-09-10 15:32:24 -0700336 // Fall back to traditional logging mode without timestamps.
337 // If these fail, there's not really anywhere to complain...
338 freopen(filename, "a", stdout); setbuf(stdout, NULL);
339 freopen(filename, "a", stderr); setbuf(stderr, NULL);
340
341 return;
342 }
343
344 pid_t pid = fork();
345 if (pid == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700346 PLOG(ERROR) << "fork failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700347
348 // Fall back to traditional logging mode without timestamps.
349 // If these fail, there's not really anywhere to complain...
350 freopen(filename, "a", stdout); setbuf(stdout, NULL);
351 freopen(filename, "a", stderr); setbuf(stderr, NULL);
352
353 return;
354 }
355
356 if (pid == 0) {
357 /// Close the unused write end.
358 close(pipefd[1]);
359
360 auto start = std::chrono::steady_clock::now();
361
362 // Child logger to actually write to the log file.
Tianjie Xude6735e2017-07-10 15:13:33 -0700363 FILE* log_fp = fopen(filename, "ae");
Tao Bao04ca4262015-09-10 15:32:24 -0700364 if (log_fp == nullptr) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700365 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700366 close(pipefd[0]);
Tao Bao3da88012017-02-03 13:09:23 -0800367 _exit(EXIT_FAILURE);
Tao Bao04ca4262015-09-10 15:32:24 -0700368 }
369
370 FILE* pipe_fp = fdopen(pipefd[0], "r");
371 if (pipe_fp == nullptr) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700372 PLOG(ERROR) << "fdopen failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700373 check_and_fclose(log_fp, filename);
374 close(pipefd[0]);
Tao Bao3da88012017-02-03 13:09:23 -0800375 _exit(EXIT_FAILURE);
Tao Bao04ca4262015-09-10 15:32:24 -0700376 }
377
378 char* line = nullptr;
379 size_t len = 0;
380 while (getline(&line, &len, pipe_fp) != -1) {
381 auto now = std::chrono::steady_clock::now();
382 double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
383 now - start).count();
384 if (line[0] == '\n') {
385 fprintf(log_fp, "[%12.6lf]\n", duration);
386 } else {
387 fprintf(log_fp, "[%12.6lf] %s", duration, line);
388 }
389 fflush(log_fp);
390 }
391
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700392 PLOG(ERROR) << "getline failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700393
394 free(line);
395 check_and_fclose(log_fp, filename);
396 close(pipefd[0]);
Tao Bao3da88012017-02-03 13:09:23 -0800397 _exit(EXIT_FAILURE);
Tao Bao04ca4262015-09-10 15:32:24 -0700398 } else {
399 // Redirect stdout/stderr to the logger process.
400 // Close the unused read end.
401 close(pipefd[0]);
402
403 setbuf(stdout, nullptr);
404 setbuf(stderr, nullptr);
405
406 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700407 PLOG(ERROR) << "dup2 stdout failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700408 }
409 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700410 PLOG(ERROR) << "dup2 stderr failed";
Tao Bao04ca4262015-09-10 15:32:24 -0700411 }
412
413 close(pipefd[1]);
414 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800415}
416
417// command line args come from, in decreasing precedence:
418// - the actual command line
419// - the bootloader control block (one per line, after "recovery")
420// - the contents of COMMAND_FILE (one per line)
Tao Baof0ed1592016-12-02 11:32:19 -0800421static std::vector<std::string> get_args(const int argc, char** const argv) {
422 CHECK_GT(argc, 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800423
Tao Baof0ed1592016-12-02 11:32:19 -0800424 bootloader_message boot = {};
425 std::string err;
426 if (!read_bootloader_message(&boot, &err)) {
427 LOG(ERROR) << err;
428 // If fails, leave a zeroed bootloader_message.
429 boot = {};
430 }
Tao Baoa8d72bc2016-12-25 18:46:50 -0800431 stage = std::string(boot.stage);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800432
Tao Baof0ed1592016-12-02 11:32:19 -0800433 if (boot.command[0] != 0) {
434 std::string boot_command = std::string(boot.command, sizeof(boot.command));
435 LOG(INFO) << "Boot command: " << boot_command;
436 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800437
Tao Baof0ed1592016-12-02 11:32:19 -0800438 if (boot.status[0] != 0) {
439 std::string boot_status = std::string(boot.status, sizeof(boot.status));
440 LOG(INFO) << "Boot status: " << boot_status;
441 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800442
Tao Baof0ed1592016-12-02 11:32:19 -0800443 std::vector<std::string> args(argv, argv + argc);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800444
Tao Baof0ed1592016-12-02 11:32:19 -0800445 // --- if arguments weren't supplied, look in the bootloader control block
Tao Bao570af9d2017-01-09 10:29:59 -0800446 if (args.size() == 1) {
Tao Baof0ed1592016-12-02 11:32:19 -0800447 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
448 std::string boot_recovery(boot.recovery);
449 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
450 if (!tokens.empty() && tokens[0] == "recovery") {
451 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
452 // Skip empty and '\0'-filled tokens.
453 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
454 }
455 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
456 } else if (boot.recovery[0] != 0) {
457 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
458 }
459 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800460
Tao Baof0ed1592016-12-02 11:32:19 -0800461 // --- if that doesn't work, try the command file (if we have /cache).
Tao Bao570af9d2017-01-09 10:29:59 -0800462 if (args.size() == 1 && has_cache) {
Tao Baof0ed1592016-12-02 11:32:19 -0800463 std::string content;
Tao Bao7d34fa12016-12-08 18:10:48 -0800464 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
465 android::base::ReadFileToString(COMMAND_FILE, &content)) {
Tao Baof0ed1592016-12-02 11:32:19 -0800466 std::vector<std::string> tokens = android::base::Split(content, "\n");
Tao Bao7d34fa12016-12-08 18:10:48 -0800467 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
468 // COMMAND_FILE doesn't use filename as the first argument).
469 for (auto it = tokens.begin(); it != tokens.end(); it++) {
Tao Baof0ed1592016-12-02 11:32:19 -0800470 // Skip empty and '\0'-filled tokens.
471 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
472 }
473 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800474 }
Tao Baof0ed1592016-12-02 11:32:19 -0800475 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800476
Tao Baof0ed1592016-12-02 11:32:19 -0800477 // Write the arguments (excluding the filename in args[0]) back into the
478 // bootloader control block. So the device will always boot into recovery to
479 // finish the pending work, until finish_recovery() is called.
480 std::vector<std::string> options(args.cbegin() + 1, args.cend());
Tao Bao2292db82016-12-13 21:53:31 -0800481 if (!update_bootloader_message(options, &err)) {
482 LOG(ERROR) << "Failed to set BCB message: " << err;
Tao Baof0ed1592016-12-02 11:32:19 -0800483 }
484
485 return args;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800486}
487
Tao Bao2292db82016-12-13 21:53:31 -0800488// Set the BCB to reboot back into recovery (it won't resume the install from
489// sdcard though).
490static void set_sdcard_update_bootloader_message() {
491 std::vector<std::string> options;
492 std::string err;
493 if (!update_bootloader_message(options, &err)) {
494 LOG(ERROR) << "Failed to set BCB message: " << err;
495 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700496}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800497
Tao Baobef39712015-05-04 18:50:27 -0700498// Read from kernel log into buffer and write out to file.
499static void save_kernel_log(const char* destination) {
500 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800501 if (klog_buf_len <= 0) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700502 PLOG(ERROR) << "Error getting klog size";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800503 return;
504 }
505
Tao Baobef39712015-05-04 18:50:27 -0700506 std::string buffer(klog_buf_len, 0);
507 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
508 if (n == -1) {
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -0700509 PLOG(ERROR) << "Error in reading klog";
Patrick Tjincd055ee2014-12-09 11:26:40 -0800510 return;
511 }
Tao Baobef39712015-05-04 18:50:27 -0700512 buffer.resize(n);
513 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800514}
515
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800516// write content to the current pmsg session.
517static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
518 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
519 filename, buf, len);
520}
521
522static void copy_log_file_to_pmsg(const char* source, const char* destination) {
523 std::string content;
524 android::base::ReadFileToString(source, &content);
525 __pmsg_write(destination, content.c_str(), content.length());
526}
527
Tao Baof0124322015-04-11 02:04:11 +0000528// How much of the temp log we have copied to the copy in cache.
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700529static off_t tmplog_offset = 0;
Tao Baof0124322015-04-11 02:04:11 +0000530
Tao Baobef39712015-05-04 18:50:27 -0700531static void copy_log_file(const char* source, const char* destination, bool append) {
Tianjie Xude6735e2017-07-10 15:13:33 -0700532 FILE* dest_fp = fopen_path(destination, append ? "ae" : "we");
533 if (dest_fp == nullptr) {
534 PLOG(ERROR) << "Can't open " << destination;
535 } else {
536 FILE* source_fp = fopen(source, "re");
537 if (source_fp != nullptr) {
538 if (append) {
539 fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
540 }
541 char buf[4096];
542 size_t bytes;
543 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
544 fwrite(buf, 1, bytes, dest_fp);
545 }
546 if (append) {
547 tmplog_offset = ftello(source_fp);
548 }
549 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700550 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700551 check_and_fclose(dest_fp, destination);
552 }
Doug Zongker2c3539e2010-09-29 13:21:30 -0700553}
554
Tao Bao682c34b2015-04-07 17:16:35 -0700555static void copy_logs() {
556 // We only rotate and record the log of the current session if there are
557 // actual attempts to modify the flash, such as wipes, installs from BCB
558 // or menu selections. This is to avoid unnecessary rotation (and
559 // possible deletion) of log files, if it does not do anything loggable.
560 if (!modified_flash) {
561 return;
562 }
563
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800564 // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
565 copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
566 copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
567
568 // We can do nothing for now if there's no /cache partition.
569 if (!has_cache) {
570 return;
571 }
572
Tianjie Xue113e4d2016-10-21 17:46:13 -0700573 ensure_path_mounted(LAST_LOG_FILE);
574 ensure_path_mounted(LAST_KMSG_FILE);
575 rotate_logs(LAST_LOG_FILE, LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700576
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700577 // Copy logs to cache so the system can find out what happened.
Tao Baof0124322015-04-11 02:04:11 +0000578 copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
579 copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
580 copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
581 save_kernel_log(LAST_KMSG_FILE);
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700582 chmod(LOG_FILE, 0600);
Tao Baoe1905ad2017-03-22 14:57:04 -0700583 chown(LOG_FILE, AID_SYSTEM, AID_SYSTEM);
Tao Baof0124322015-04-11 02:04:11 +0000584 chmod(LAST_KMSG_FILE, 0600);
Tao Baoe1905ad2017-03-22 14:57:04 -0700585 chown(LAST_KMSG_FILE, AID_SYSTEM, AID_SYSTEM);
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700586 chmod(LAST_LOG_FILE, 0640);
587 chmod(LAST_INSTALL_FILE, 0644);
588 sync();
589}
590
Tao Baoec579032017-07-21 12:13:15 -0700591// Clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700592// copy our log file to cache as well (for the system to read). This function is
593// idempotent: call it as many times as you like.
Tao Baoac9d94d2016-11-03 11:37:15 -0700594static void finish_recovery() {
Tao Baoec579032017-07-21 12:13:15 -0700595 // Save the locale to cache, so if recovery is next started up without a '--locale' argument
596 // (e.g., directly from the bootloader) it will use the last-known locale.
597 if (!locale.empty() && has_cache) {
598 LOG(INFO) << "Saving locale \"" << locale << "\"";
599 if (ensure_path_mounted(LOCALE_FILE) != 0) {
600 LOG(ERROR) << "Failed to mount " << LOCALE_FILE;
601 } else if (!android::base::WriteStringToFile(locale, LOCALE_FILE)) {
602 PLOG(ERROR) << "Failed to save locale to " << LOCALE_FILE;
Doug Zongker4f33e552012-08-23 13:16:12 -0700603 }
Tao Baoec579032017-07-21 12:13:15 -0700604 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700605
Tao Baoec579032017-07-21 12:13:15 -0700606 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800607
Tao Baoec579032017-07-21 12:13:15 -0700608 // Reset to normal system boot so recovery won't cycle indefinitely.
609 std::string err;
610 if (!clear_bootloader_message(&err)) {
611 LOG(ERROR) << "Failed to clear BCB message: " << err;
612 }
613
614 // Remove the command file, so recovery won't repeat indefinitely.
615 if (has_cache) {
616 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
617 LOG(WARNING) << "Can't unlink " << COMMAND_FILE;
Yabin Cui8b309f62016-06-24 18:22:02 -0700618 }
Tao Baoec579032017-07-21 12:13:15 -0700619 ensure_path_unmounted(CACHE_ROOT);
620 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800621
Tao Baoec579032017-07-21 12:13:15 -0700622 sync(); // For good measure.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800623}
624
Tao Bao3f5a3822016-12-13 11:14:37 -0800625struct saved_log_file {
626 std::string name;
627 struct stat sb;
628 std::string data;
629};
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700630
Elliott Hughes945548e2015-06-05 17:59:56 -0700631static bool erase_volume(const char* volume) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800632 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
633 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700634
Tao Bao3f5a3822016-12-13 11:14:37 -0800635 std::vector<saved_log_file> log_files;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700636
Tao Bao3f5a3822016-12-13 11:14:37 -0800637 if (is_cache) {
638 // If we're reformatting /cache, we load any past logs
639 // (i.e. "/cache/recovery/last_*") and the current log
640 // ("/cache/recovery/log") into memory, so we can restore them after
641 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700642
Tao Bao3f5a3822016-12-13 11:14:37 -0800643 ensure_path_mounted(volume);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700644
Tao Bao3f5a3822016-12-13 11:14:37 -0800645 struct dirent* de;
646 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(CACHE_LOG_DIR), closedir);
647 if (d) {
648 while ((de = readdir(d.get())) != nullptr) {
649 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
650 std::string path = android::base::StringPrintf("%s/%s", CACHE_LOG_DIR, de->d_name);
651
652 struct stat sb;
653 if (stat(path.c_str(), &sb) == 0) {
654 // truncate files to 512kb
655 if (sb.st_size > (1 << 19)) {
656 sb.st_size = 1 << 19;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700657 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800658
659 std::string data(sb.st_size, '\0');
Tianjie Xude6735e2017-07-10 15:13:33 -0700660 FILE* f = fopen(path.c_str(), "rbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800661 fread(&data[0], 1, data.size(), f);
662 fclose(f);
663
664 log_files.emplace_back(saved_log_file{ path, sb, data });
665 }
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700666 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800667 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800668 } else {
Tao Bao3f5a3822016-12-13 11:14:37 -0800669 if (errno != ENOENT) {
670 PLOG(ERROR) << "Failed to opendir " << CACHE_LOG_DIR;
671 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800672 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800673 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700674
Tao Bao3f5a3822016-12-13 11:14:37 -0800675 ui->Print("Formatting %s...\n", volume);
676
Steve Kondik17b88b02014-09-12 18:52:28 -0700677 ui->SetBackground(RecoveryUI::ERASING);
678 ui->SetProgressType(RecoveryUI::INDETERMINATE);
679
Tao Bao3f5a3822016-12-13 11:14:37 -0800680 ensure_path_unmounted(volume);
681
682 int result;
683
684 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
685 // Create convert_fbe breadcrumb file to signal to init
686 // to convert to file based encryption, not full disk encryption
687 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
688 ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
689 return true;
690 }
Tianjie Xude6735e2017-07-10 15:13:33 -0700691 FILE* f = fopen(CONVERT_FBE_FILE, "wbe");
Tao Bao3f5a3822016-12-13 11:14:37 -0800692 if (!f) {
693 ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
694 return true;
695 }
696 fclose(f);
697 result = format_volume(volume, CONVERT_FBE_DIR);
698 remove(CONVERT_FBE_FILE);
699 rmdir(CONVERT_FBE_DIR);
700 } else {
701 result = format_volume(volume);
702 }
703
704 if (is_cache) {
705 // Re-create the log dir and write back the log entries.
706 if (ensure_path_mounted(CACHE_LOG_DIR) == 0 &&
Tao Baoac3d1ed2017-07-23 00:01:02 -0700707 mkdir_recursively(CACHE_LOG_DIR, 0777, false, sehandle) == 0) {
Tao Bao3f5a3822016-12-13 11:14:37 -0800708 for (const auto& log : log_files) {
709 if (!android::base::WriteStringToFile(log.data, log.name, log.sb.st_mode, log.sb.st_uid,
710 log.sb.st_gid)) {
711 PLOG(ERROR) << "Failed to write to " << log.name;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700712 }
Tao Bao3f5a3822016-12-13 11:14:37 -0800713 }
714 } else {
715 PLOG(ERROR) << "Failed to mount / create " << CACHE_LOG_DIR;
Doug Zongker2c3539e2010-09-29 13:21:30 -0700716 }
717
Tao Bao3f5a3822016-12-13 11:14:37 -0800718 // Any part of the log we'd copied to cache is now gone.
719 // Reset the pointer so we copy from the beginning of the temp
720 // log.
721 tmplog_offset = 0;
722 copy_logs();
723 }
724
725 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800726}
727
Tao Baofc5499f2017-02-23 19:06:53 -0800728// Display a menu with the specified 'headers' and 'items'. Device specific HandleMenuKey() may
729// return a positive number beyond the given range. Caller sets 'menu_only' to true to ensure only
Tao Bao50dd5322017-03-07 14:57:04 -0800730// a menu item gets selected. 'initial_selection' controls the initial cursor location. Returns the
731// (non-negative) chosen item number, or -1 if timed out waiting for input.
Tom Marshall820517b2019-01-14 14:28:55 -0800732int get_menu_selection(bool menu_is_main, menu_type_t menu_type, const char* const* headers,
733 const MenuItemVector& menu_items, bool menu_only, int initial_selection,
Alessandro Astonee5004ac2019-03-29 21:49:20 +0100734 Device* device, bool refreshable = false) {
Tao Baofc5499f2017-02-23 19:06:53 -0800735 // Throw away keys pressed previously, so user doesn't accidentally trigger menu items.
736 ui->FlushKeys();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700737
Tom Marshall820517b2019-01-14 14:28:55 -0800738 ui->StartMenu(menu_is_main, menu_type, headers, menu_items, initial_selection);
Tao Bao50dd5322017-03-07 14:57:04 -0800739
Tao Baofc5499f2017-02-23 19:06:53 -0800740 int selected = initial_selection;
741 int chosen_item = -1;
Tao Baofc5499f2017-02-23 19:06:53 -0800742 while (chosen_item < 0) {
Tom Marshall820517b2019-01-14 14:28:55 -0800743 RecoveryUI::InputEvent evt = ui->WaitInputEvent();
744 if (evt.type() == RecoveryUI::EVENT_TYPE_NONE) { // WaitKey() timed out.
Tao Baofc5499f2017-02-23 19:06:53 -0800745 if (ui->WasTextEverVisible()) {
746 continue;
747 } else {
Tao Bao50dd5322017-03-07 14:57:04 -0800748 LOG(INFO) << "Timed out waiting for key input; rebooting.";
Tao Baofc5499f2017-02-23 19:06:53 -0800749 ui->EndMenu();
Tao Bao50dd5322017-03-07 14:57:04 -0800750 return -1;
Tao Baofc5499f2017-02-23 19:06:53 -0800751 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700752 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800753
Tom Marshall820517b2019-01-14 14:28:55 -0800754 int action = Device::kNoAction;
755 if (evt.type() == RecoveryUI::EVENT_TYPE_TOUCH) {
756 int touch_sel = ui->SelectMenu(evt.pos());
757 if (touch_sel < 0) {
758 action = touch_sel;
759 } else {
760 action = Device::kInvokeItem;
761 selected = touch_sel;
762 }
763 } else {
764 bool visible = ui->IsTextVisible();
765 action = device->HandleMenuKey(evt.key(), visible);
766 }
Tao Baofc5499f2017-02-23 19:06:53 -0800767
768 if (action < 0) {
769 switch (action) {
770 case Device::kHighlightUp:
771 selected = ui->SelectMenu(--selected);
772 break;
773 case Device::kHighlightDown:
774 selected = ui->SelectMenu(++selected);
775 break;
Alessandro Astoned6eb74e2019-03-28 22:02:02 +0100776 case Device::kScrollUp:
777 selected = ui->ScrollMenu(-1);
778 break;
779 case Device::kScrollDown:
780 selected = ui->ScrollMenu(1);
781 break;
Tao Baofc5499f2017-02-23 19:06:53 -0800782 case Device::kInvokeItem:
783 chosen_item = selected;
Tom Marshall820517b2019-01-14 14:28:55 -0800784 if (chosen_item < 0) {
785 chosen_item = Device::kGoBack;
786 }
Tao Baofc5499f2017-02-23 19:06:53 -0800787 break;
788 case Device::kNoAction:
789 break;
Tom Marshall74f48242017-08-24 13:50:01 +0000790 case Device::kGoBack:
791 chosen_item = Device::kGoBack;
792 break;
793 case Device::kGoHome:
794 chosen_item = Device::kGoHome;
795 break;
Tom Marshalla08c6f12019-01-04 14:37:31 -0800796 case Device::kRefresh:
Alessandro Astonee5004ac2019-03-29 21:49:20 +0100797 if (refreshable) {
798 chosen_item = Device::kRefresh;
799 }
Tom Marshalla08c6f12019-01-04 14:37:31 -0800800 break;
Tao Baofc5499f2017-02-23 19:06:53 -0800801 }
802 } else if (!menu_only) {
803 chosen_item = action;
804 }
Tom Marshalla08c6f12019-01-04 14:37:31 -0800805 if (chosen_item == Device::kGoBack || chosen_item == Device::kGoHome ||
806 chosen_item == Device::kRefresh) {
Tom Marshall74f48242017-08-24 13:50:01 +0000807 break;
808 }
Tao Baofc5499f2017-02-23 19:06:53 -0800809 }
810
811 ui->EndMenu();
Tom Marshall820517b2019-01-14 14:28:55 -0800812 if (chosen_item == Device::kGoHome) {
813 device->GoHome();
814 }
Tao Baofc5499f2017-02-23 19:06:53 -0800815 return chosen_item;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700816}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800817
Tao Baoc4a18ef2017-02-10 00:13:30 -0800818// Returns the selected filename, or an empty string.
819static std::string browse_directory(const std::string& path, Device* device) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800820 std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
821 if (!d) {
822 PLOG(ERROR) << "error opening " << path;
823 return "";
824 }
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700825
Tao Baoc4a18ef2017-02-10 00:13:30 -0800826 std::vector<std::string> dirs;
827 std::vector<std::string> zips = { "../" }; // "../" is always the first entry.
828
829 dirent* de;
830 while ((de = readdir(d.get())) != nullptr) {
831 std::string name(de->d_name);
832
833 if (de->d_type == DT_DIR) {
834 // Skip "." and ".." entries.
835 if (name == "." || name == "..") continue;
836 dirs.push_back(name + "/");
837 } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
838 zips.push_back(name);
839 }
840 }
841
842 std::sort(dirs.begin(), dirs.end());
843 std::sort(zips.begin(), zips.end());
844
845 // Append dirs to the zips list.
846 zips.insert(zips.end(), dirs.begin(), dirs.end());
847
Tom Marshall820517b2019-01-14 14:28:55 -0800848 MenuItemVector items;
Tao Baoc4a18ef2017-02-10 00:13:30 -0800849 for (size_t i = 0; i < zips.size(); i++) {
Tom Marshall820517b2019-01-14 14:28:55 -0800850 items.push_back(MenuItem(zips[i]));
Tao Baoc4a18ef2017-02-10 00:13:30 -0800851 }
852
853 const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
854
855 int chosen_item = 0;
856 while (true) {
Tom Marshall820517b2019-01-14 14:28:55 -0800857 chosen_item = get_menu_selection(false, MT_LIST, headers, items, true, chosen_item, device);
Tom Marshall74f48242017-08-24 13:50:01 +0000858 if (chosen_item == Device::kGoHome) {
859 return "@";
860 }
861 if (chosen_item == Device::kGoBack || chosen_item == 0) {
Tao Baoc4a18ef2017-02-10 00:13:30 -0800862 // Go up but continue browsing (if the caller is browse_directory).
863 return "";
Doug Zongker8674a722010-09-15 11:08:23 -0700864 }
Tom Marshalla08c6f12019-01-04 14:37:31 -0800865 if (chosen_item == Device::kRefresh) {
Alessandro Astonee5004ac2019-03-29 21:49:20 +0100866 continue;
Tom Marshalla08c6f12019-01-04 14:37:31 -0800867 }
Doug Zongker8674a722010-09-15 11:08:23 -0700868
Tom Marshall74f48242017-08-24 13:50:01 +0000869 const std::string& item = zips[chosen_item];
870
Tao Baoc4a18ef2017-02-10 00:13:30 -0800871 std::string new_path = path + "/" + item;
872 if (new_path.back() == '/') {
873 // Recurse down into a subdirectory.
874 new_path.pop_back();
875 std::string result = browse_directory(new_path, device);
876 if (!result.empty()) return result;
877 } else {
878 // Selected a zip file: return the path to the caller.
879 return new_path;
Doug Zongker8674a722010-09-15 11:08:23 -0700880 }
Tao Baoc4a18ef2017-02-10 00:13:30 -0800881 }
Doug Zongker8674a722010-09-15 11:08:23 -0700882
Tao Baoc4a18ef2017-02-10 00:13:30 -0800883 // Unreachable.
Doug Zongker8674a722010-09-15 11:08:23 -0700884}
885
Elliott Hughes30694c92015-03-25 15:16:51 -0700886static bool yes_no(Device* device, const char* question1, const char* question2) {
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700887 const char* headers[] = { question1, question2, NULL };
Tom Marshall820517b2019-01-14 14:28:55 -0800888 const MenuItemVector items = {
889 MenuItem(" No"),
890 MenuItem(" Yes"),
891 };
Tom Marshalla08c6f12019-01-04 14:37:31 -0800892 int chosen_item;
893 do {
Tom Marshall820517b2019-01-14 14:28:55 -0800894 chosen_item = get_menu_selection(false, MT_LIST, headers, items, true, 0, device);
Tom Marshalla08c6f12019-01-04 14:37:31 -0800895 } while (chosen_item == Device::kRefresh);
Elliott Hughes30694c92015-03-25 15:16:51 -0700896 return (chosen_item == 1);
897}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800898
Tom Marshalle2b6a972018-06-21 00:57:24 +0200899static bool ask_to_continue_unverified_install(Device* device) {
900#ifdef RELEASE_BUILD
901 return false;
902#else
903 ui->SetProgressType(RecoveryUI::EMPTY);
904 return yes_no(device, "Signature verification failed", "Install anyway?");
905#endif
906}
907
Paul Crowley08404b42016-12-19 13:04:23 -0800908static bool ask_to_wipe_data(Device* device) {
909 return yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!");
910}
Doug Zongker1066d2c2009-04-01 13:57:40 -0700911
Paul Crowley08404b42016-12-19 13:04:23 -0800912// Return true on success.
913static bool wipe_data(Device* device) {
Tao Bao682c34b2015-04-07 17:16:35 -0700914 modified_flash = true;
915
Doug Zongker211aebc2011-10-28 15:13:10 -0700916 ui->Print("\n-- Wiping data...\n");
Paul Crowley723056a2016-06-08 13:51:41 -0700917 bool success = device->PreWipeData();
918 if (success) {
919 success &= erase_volume(DATA_ROOT);
920 if (has_cache) {
921 success &= erase_volume(CACHE_ROOT);
922 }
923 if (volume_for_mount_point(METADATA_ROOT) != nullptr) {
924 success &= erase_volume(METADATA_ROOT);
925 }
926 }
927 if (success) {
928 success &= device->PostWipeData();
929 }
Elliott Hughes945548e2015-06-05 17:59:56 -0700930 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
931 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700932}
933
Paul Crowley08404b42016-12-19 13:04:23 -0800934static bool prompt_and_wipe_data(Device* device) {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700935 // Use a single string and let ScreenRecoveryUI handles the wrapping.
Tao Baofc5499f2017-02-23 19:06:53 -0800936 const char* const headers[] = {
Tao Bao2bbc6d62017-08-13 23:48:55 -0700937 "Can't load Android system. Your data may be corrupt. "
938 "If you continue to get this message, you may need to "
939 "perform a factory data reset and erase all user data "
Paul Crowley31ac0c62017-03-23 12:32:40 -0700940 "stored on this device.",
Tao Bao2bbc6d62017-08-13 23:48:55 -0700941 nullptr
Tao Baofc5499f2017-02-23 19:06:53 -0800942 };
Tom Marshall820517b2019-01-14 14:28:55 -0800943 const MenuItemVector items = {
944 MenuItem("Try again"),
945 MenuItem("Factory data reset"),
Tao Baofc5499f2017-02-23 19:06:53 -0800946 };
Tom Marshall820517b2019-01-14 14:28:55 -0800947
Tao Baofc5499f2017-02-23 19:06:53 -0800948 for (;;) {
Tom Marshall820517b2019-01-14 14:28:55 -0800949 int chosen_item = get_menu_selection(false, MT_LIST, headers, items, true, 0, device);
Tao Baofc5499f2017-02-23 19:06:53 -0800950 if (chosen_item != 1) {
951 return true; // Just reboot, no wipe; not a failure, user asked for it
Paul Crowley08404b42016-12-19 13:04:23 -0800952 }
Tao Baofc5499f2017-02-23 19:06:53 -0800953 if (ask_to_wipe_data(device)) {
954 return wipe_data(device);
955 }
956 }
Paul Crowley08404b42016-12-19 13:04:23 -0800957}
958
Tao Baoe39a9bc2015-03-31 12:19:05 -0700959// Return true on success.
960static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800961 if (!has_cache) {
962 ui->Print("No /cache partition found.\n");
963 return false;
964 }
965
Elliott Hughes30694c92015-03-25 15:16:51 -0700966 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700967 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700968 }
969
Tao Bao682c34b2015-04-07 17:16:35 -0700970 modified_flash = true;
971
Elliott Hughes30694c92015-03-25 15:16:51 -0700972 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700973 bool success = erase_volume("/cache");
974 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
975 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700976}
977
Dan Pasanendc95db82017-04-04 13:40:19 -0500978static bool ask_to_wipe_system(Device* device) {
979 return yes_no(device, "Wipe system?", " THIS CAN NOT BE UNDONE!");
980}
981
982// Return true on success.
983static bool wipe_system() {
984 modified_flash = true;
985
986 ui->Print("\n-- Wiping system...\n");
987 bool success = erase_volume("/system");
988 ui->Print("System wipe %s.\n", success ? "complete" : "failed");
989 return success;
990}
991
Tao Bao1b2a98b2017-03-24 10:45:34 -0700992// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported. Otherwise, it goes with
993// BLKDISCARD (if device supports BLKDISCARDZEROES) or BLKZEROOUT.
Tao Bao862a4c12016-06-02 11:16:50 -0700994static bool secure_wipe_partition(const std::string& partition) {
Tao Bao1b2a98b2017-03-24 10:45:34 -0700995 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
996 if (fd == -1) {
997 PLOG(ERROR) << "Failed to open \"" << partition << "\"";
998 return false;
999 }
1000
1001 uint64_t range[2] = { 0, 0 };
1002 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
1003 PLOG(ERROR) << "Failed to get partition size";
1004 return false;
1005 }
1006 LOG(INFO) << "Secure-wiping \"" << partition << "\" from " << range[0] << " to " << range[1];
1007
1008 LOG(INFO) << " Trying BLKSECDISCARD...";
1009 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
1010 PLOG(WARNING) << " Failed";
1011
1012 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
1013 unsigned int zeroes;
1014 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
1015 LOG(INFO) << " Trying BLKDISCARD...";
1016 if (ioctl(fd, BLKDISCARD, &range) == -1) {
1017 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -07001018 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -07001019 }
1020 } else {
1021 LOG(INFO) << " Trying BLKZEROOUT...";
1022 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
1023 PLOG(ERROR) << " Failed";
Tao Bao862a4c12016-06-02 11:16:50 -07001024 return false;
Tao Bao1b2a98b2017-03-24 10:45:34 -07001025 }
Tao Bao862a4c12016-06-02 11:16:50 -07001026 }
Tao Bao1b2a98b2017-03-24 10:45:34 -07001027 }
Tao Bao862a4c12016-06-02 11:16:50 -07001028
Tao Bao1b2a98b2017-03-24 10:45:34 -07001029 LOG(INFO) << " Done";
1030 return true;
Tao Bao862a4c12016-06-02 11:16:50 -07001031}
1032
Yabin Cuifd99a312016-06-09 14:09:39 -07001033// Check if the wipe package matches expectation:
1034// 1. verify the package.
1035// 2. check metadata (ota-type, pre-device and serial number if having one).
1036static bool check_wipe_package(size_t wipe_package_size) {
1037 if (wipe_package_size == 0) {
1038 LOG(ERROR) << "wipe_package_size is zero";
1039 return false;
1040 }
1041 std::string wipe_package;
1042 std::string err_str;
1043 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
1044 PLOG(ERROR) << "Failed to read wipe package";
1045 return false;
1046 }
1047 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
1048 wipe_package.size())) {
1049 LOG(ERROR) << "Failed to verify package";
1050 return false;
1051 }
1052
1053 // Extract metadata
1054 ZipArchiveHandle zip;
Tao Baoefc35592017-01-08 22:45:47 -08001055 int err = OpenArchiveFromMemory(static_cast<void*>(&wipe_package[0]), wipe_package.size(),
1056 "wipe_package", &zip);
Yabin Cuifd99a312016-06-09 14:09:39 -07001057 if (err != 0) {
1058 LOG(ERROR) << "Can't open wipe package : " << ErrorCodeString(err);
1059 return false;
1060 }
1061 std::string metadata;
Tao Bao1b2a98b2017-03-24 10:45:34 -07001062 if (!read_metadata_from_package(zip, &metadata)) {
Yabin Cuifd99a312016-06-09 14:09:39 -07001063 CloseArchive(zip);
1064 return false;
1065 }
1066 CloseArchive(zip);
1067
1068 // Check metadata
1069 std::vector<std::string> lines = android::base::Split(metadata, "\n");
1070 bool ota_type_matched = false;
1071 bool device_type_matched = false;
1072 bool has_serial_number = false;
1073 bool serial_number_matched = false;
1074 for (const auto& line : lines) {
1075 if (line == "ota-type=BRICK") {
1076 ota_type_matched = true;
1077 } else if (android::base::StartsWith(line, "pre-device=")) {
1078 std::string device_type = line.substr(strlen("pre-device="));
Tao Baoefc35592017-01-08 22:45:47 -08001079 std::string real_device_type = android::base::GetProperty("ro.build.product", "");
Yabin Cuifd99a312016-06-09 14:09:39 -07001080 device_type_matched = (device_type == real_device_type);
1081 } else if (android::base::StartsWith(line, "serialno=")) {
1082 std::string serial_no = line.substr(strlen("serialno="));
Tao Baoefc35592017-01-08 22:45:47 -08001083 std::string real_serial_no = android::base::GetProperty("ro.serialno", "");
Yabin Cuifd99a312016-06-09 14:09:39 -07001084 has_serial_number = true;
1085 serial_number_matched = (serial_no == real_serial_no);
1086 }
1087 }
1088 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
1089}
1090
Yabin Cui8b309f62016-06-24 18:22:02 -07001091// Wipe the current A/B device, with a secure wipe of all the partitions in
1092// RECOVERY_WIPE.
Yabin Cuifd99a312016-06-09 14:09:39 -07001093static bool wipe_ab_device(size_t wipe_package_size) {
Tao Bao862a4c12016-06-02 11:16:50 -07001094 ui->SetBackground(RecoveryUI::ERASING);
1095 ui->SetProgressType(RecoveryUI::INDETERMINATE);
1096
Yabin Cuifd99a312016-06-09 14:09:39 -07001097 if (!check_wipe_package(wipe_package_size)) {
1098 LOG(ERROR) << "Failed to verify wipe package";
1099 return false;
1100 }
Tao Bao862a4c12016-06-02 11:16:50 -07001101 std::string partition_list;
Yabin Cui8b309f62016-06-24 18:22:02 -07001102 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
1103 LOG(ERROR) << "failed to read \"" << RECOVERY_WIPE << "\"";
Tao Bao862a4c12016-06-02 11:16:50 -07001104 return false;
1105 }
1106
1107 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
1108 for (const std::string& line : lines) {
1109 std::string partition = android::base::Trim(line);
1110 // Ignore '#' comment or empty lines.
1111 if (android::base::StartsWith(partition, "#") || partition.empty()) {
1112 continue;
1113 }
1114
1115 // Proceed anyway even if it fails to wipe some partition.
1116 secure_wipe_partition(partition);
1117 }
1118 return true;
1119}
1120
Tom Marshall820517b2019-01-14 14:28:55 -08001121static int choose_recovery_file(Device* device) {
Tao Bao08fc6be2017-03-07 00:56:27 -08001122 std::vector<std::string> entries;
Tom Marshall820517b2019-01-14 14:28:55 -08001123 if (access(TEMPORARY_LOG_FILE, R_OK) != -1) {
1124 entries.push_back(TEMPORARY_LOG_FILE);
1125 }
Tao Bao08fc6be2017-03-07 00:56:27 -08001126 if (has_cache) {
1127 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
1128 auto add_to_entries = [&](const char* filename) {
1129 std::string log_file(filename);
1130 if (i > 0) {
1131 log_file += "." + std::to_string(i);
Tao Baobef39712015-05-04 18:50:27 -07001132 }
Tao Bao08fc6be2017-03-07 00:56:27 -08001133
1134 if (ensure_path_mounted(log_file.c_str()) == 0 && access(log_file.c_str(), R_OK) == 0) {
1135 entries.push_back(std::move(log_file));
1136 }
1137 };
1138
1139 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
1140 add_to_entries(LAST_LOG_FILE);
1141
1142 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
1143 add_to_entries(LAST_KMSG_FILE);
1144 }
Tom Marshall820517b2019-01-14 14:28:55 -08001145 }
1146 if (entries.empty()) {
1147 // Should never happen
1148 return Device::kNoAction;
Tao Bao08fc6be2017-03-07 00:56:27 -08001149 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001150
Tom Marshall820517b2019-01-14 14:28:55 -08001151 MenuItemVector items(entries.size());
1152 std::transform(entries.cbegin(), entries.cend(), items.begin(),
1153 [](const std::string& entry) { return MenuItem(entry.c_str()); });
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001154
Tao Bao08fc6be2017-03-07 00:56:27 -08001155 const char* headers[] = { "Select file to view", nullptr };
Elliott Hughes8de52072015-04-08 20:06:50 -07001156
Tao Bao08fc6be2017-03-07 00:56:27 -08001157 int chosen_item = 0;
1158 while (true) {
Tom Marshall820517b2019-01-14 14:28:55 -08001159 chosen_item = get_menu_selection(false, MT_LIST, headers, items, true, chosen_item, device);
1160 if (chosen_item == Device::kGoHome || chosen_item == Device::kGoBack) {
Tom Marshall74f48242017-08-24 13:50:01 +00001161 break;
1162 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001163
Tom Marshall820517b2019-01-14 14:28:55 -08001164 int key = ui->ShowFile(entries[chosen_item].c_str());
1165 if (key == KEY_HOME || key == KEY_HOMEPAGE) {
1166 chosen_item = Device::kGoHome;
1167 break;
1168 }
Tao Bao08fc6be2017-03-07 00:56:27 -08001169 }
Tom Marshall820517b2019-01-14 14:28:55 -08001170 return chosen_item;
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001171}
1172
Tao Baodb7e8982017-03-06 23:53:16 -08001173static void run_graphics_test() {
Tao Baodb7e8982017-03-06 23:53:16 -08001174 ui->SetBackground(RecoveryUI::ERROR);
Tom Marshallf780f1c2018-03-01 23:51:51 +01001175 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001176 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -07001177
Tom Marshallf780f1c2018-03-01 23:51:51 +01001178 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
1179 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001180 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -07001181
Tao Baodb7e8982017-03-06 23:53:16 -08001182 ui->SetBackground(RecoveryUI::ERASING);
Tom Marshallf780f1c2018-03-01 23:51:51 +01001183 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001184 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -07001185
Tao Baodb7e8982017-03-06 23:53:16 -08001186 ui->SetStage(1, 3);
Tom Marshallf780f1c2018-03-01 23:51:51 +01001187 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001188 sleep(1);
1189 ui->SetStage(2, 3);
Tom Marshallf780f1c2018-03-01 23:51:51 +01001190 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001191 sleep(1);
1192 ui->SetStage(3, 3);
Tom Marshallf780f1c2018-03-01 23:51:51 +01001193 ui->Redraw();
Tao Baodb7e8982017-03-06 23:53:16 -08001194 sleep(1);
Elliott Hughes498cda62016-04-14 16:49:04 -07001195
Tao Baodb7e8982017-03-06 23:53:16 -08001196 ui->SetStage(-1, -1);
Elliott Hughes498cda62016-04-14 16:49:04 -07001197
Tom Marshallf780f1c2018-03-01 23:51:51 +01001198 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
Tao Baodb7e8982017-03-06 23:53:16 -08001199 ui->SetProgressType(RecoveryUI::DETERMINATE);
1200 ui->ShowProgress(1.0, 10.0);
1201 float fraction = 0.0;
1202 for (size_t i = 0; i < 100; ++i) {
1203 fraction += .01;
1204 ui->SetProgress(fraction);
1205 usleep(100000);
1206 }
Elliott Hughes498cda62016-04-14 16:49:04 -07001207}
1208
Tom Marshalla08c6f12019-01-04 14:37:31 -08001209static int apply_from_storage(Device* device, VolumeInfo& vi, bool* wipe_cache) {
1210 modified_flash = true;
Tao Bao682c34b2015-04-07 17:16:35 -07001211
Tom Marshalla08c6f12019-01-04 14:37:31 -08001212 int status;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001213
Tom Marshalla08c6f12019-01-04 14:37:31 -08001214 if (!VolumeManager::Instance()->volumeMount(vi.mId)) {
1215 return INSTALL_ERROR;
1216 }
Alessandro Astonee5004ac2019-03-29 21:49:20 +01001217 ui->VolumesChanged();
Tom Marshalla08c6f12019-01-04 14:37:31 -08001218
1219 std::string path;
1220 do {
1221 path = browse_directory(vi.mPath, device);
Tom Marshall74f48242017-08-24 13:50:01 +00001222 if (path == "@") {
1223 return INSTALL_NONE;
1224 }
Tom Marshalla08c6f12019-01-04 14:37:31 -08001225 } while (path == "@refresh");
1226
1227 if (path.empty()) {
1228 ui->Print("\n-- No package file selected.\n");
1229 VolumeManager::Instance()->volumeUnmount(vi.mId);
1230 return INSTALL_NONE;
1231 }
1232
1233 ui->Print("\n-- Install %s ...\n", path.c_str());
1234 set_sdcard_update_bootloader_message();
1235 void* token = start_sdcard_fuse(path.c_str());
1236 if (!token) {
1237 LOG(ERROR) << "Failed to start FUSE for sdcard install";
1238 return INSTALL_ERROR;
1239 }
1240
1241 VolumeManager::Instance()->volumeUnmount(vi.mId, true);
1242
Alessandro Astone20c8d412019-04-01 11:11:33 +02001243 ui->UpdateScreenOnPrint(true);
Tom Marshalla08c6f12019-01-04 14:37:31 -08001244 status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, TEMPORARY_INSTALL_FILE, false,
Tom Marshalle2b6a972018-06-21 00:57:24 +02001245 0 /*retry_count*/, true /*verify*/);
1246 if (status == INSTALL_UNVERIFIED && ask_to_continue_unverified_install(device)) {
1247 status = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache, TEMPORARY_INSTALL_FILE, false,
1248 0 /*retry_count*/, false /*verify*/);
1249 }
Alessandro Astone20c8d412019-04-01 11:11:33 +02001250 ui->UpdateScreenOnPrint(false);
Tom Marshalla08c6f12019-01-04 14:37:31 -08001251
1252 finish_sdcard_fuse(token);
1253 return status;
1254}
1255
1256static int show_apply_update_menu(Device* device, bool* wipe_cache) {
Tom Marshall820517b2019-01-14 14:28:55 -08001257 MenuItemVector items;
Tom Marshalla08c6f12019-01-04 14:37:31 -08001258 static const char* headers[] = { "Apply update", nullptr };
Tom Marshalla08c6f12019-01-04 14:37:31 -08001259
1260refresh:
Tom Marshall820517b2019-01-14 14:28:55 -08001261 items.clear();
1262 items.push_back(MenuItem("Apply from ADB")); // Index 0
Tom Marshalla08c6f12019-01-04 14:37:31 -08001263
1264 std::vector<VolumeInfo> volumes;
1265 VolumeManager::Instance()->getVolumeInfo(volumes);
1266
Tom Marshall820517b2019-01-14 14:28:55 -08001267 for (auto& vol : volumes) {
Tom Marshalle65875b2019-01-07 14:42:42 -08001268 if (vol.mLabel == "emulated") {
1269 if (!userdata_mountable || userdata_encrypted) {
1270 continue;
1271 }
1272 }
Tom Marshall820517b2019-01-14 14:28:55 -08001273 items.push_back(MenuItem("Choose from " + vol.mLabel));
Tom Marshalla08c6f12019-01-04 14:37:31 -08001274 }
Tom Marshalla08c6f12019-01-04 14:37:31 -08001275
1276 int status = INSTALL_ERROR;
1277
Alessandro Astonee5004ac2019-03-29 21:49:20 +01001278 int chosen =
1279 get_menu_selection(false, MT_LIST, headers, items, false, 0, device, true /*refreshable*/);
Tom Marshall87c82622014-11-25 12:58:22 -08001280 if (chosen == Device::kRefresh) {
1281 goto refresh;
1282 }
Tom Marshall820517b2019-01-14 14:28:55 -08001283 if (chosen == Device::kGoBack || chosen == Device::kGoHome) {
Tom Marshall87c82622014-11-25 12:58:22 -08001284 return INSTALL_NONE;
1285 }
Tom Marshall820517b2019-01-14 14:28:55 -08001286 if (chosen == 0) {
1287 static const char* s_headers[] = { "ADB Sideload", nullptr };
1288 static const MenuItemVector s_items = { MenuItem("Cancel sideload") };
Tom Marshall5b4a9d82018-12-17 15:57:44 -08001289
Tom Marshall668f1c32018-03-06 22:51:58 +01001290 sideload_start();
Alessandro Astonee5004ac2019-03-29 21:49:20 +01001291 int item = get_menu_selection(false, MT_LIST, s_headers, s_items, false, 0, device,
1292 true /*refreshable*/);
Tom Marshall668f1c32018-03-06 22:51:58 +01001293 if (item == Device::kRefresh) {
1294 sideload_wait(false);
Alessandro Astone20c8d412019-04-01 11:11:33 +02001295 ui->UpdateScreenOnPrint(true);
Tom Marshalle2b6a972018-06-21 00:57:24 +02001296 status = sideload_install(wipe_cache, TEMPORARY_INSTALL_FILE, true);
1297 if (status == INSTALL_UNVERIFIED && ask_to_continue_unverified_install(device)) {
1298 status = sideload_install(wipe_cache, TEMPORARY_INSTALL_FILE, false);
1299 }
Alessandro Astone20c8d412019-04-01 11:11:33 +02001300 ui->UpdateScreenOnPrint(false);
Tom Marshall668f1c32018-03-06 22:51:58 +01001301 } else {
1302 sideload_wait(true);
Tom Marshalle2b6a972018-06-21 00:57:24 +02001303 status = INSTALL_NONE;
Tom Marshalla08c6f12019-01-04 14:37:31 -08001304 }
Tom Marshall668f1c32018-03-06 22:51:58 +01001305 sideload_stop();
Tom Marshall87c82622014-11-25 12:58:22 -08001306 } else {
1307 status = apply_from_storage(device, volumes[chosen - 1], wipe_cache);
Tom Marshalla08c6f12019-01-04 14:37:31 -08001308 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001309
Tom Marshalla08c6f12019-01-04 14:37:31 -08001310 return status;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001311}
1312
Tao Bao50dd5322017-03-07 14:57:04 -08001313// Returns REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION means to take the default,
1314// which is to reboot or shutdown depending on if the --shutdown_after flag was passed to recovery.
1315static Device::BuiltinAction prompt_and_wait(Device* device, int status) {
1316 for (;;) {
1317 finish_recovery();
1318 switch (status) {
1319 case INSTALL_SUCCESS:
1320 case INSTALL_NONE:
1321 ui->SetBackground(RecoveryUI::NO_COMMAND);
1322 break;
Doug Zongker6c8553d2012-09-24 10:40:47 -07001323
Tao Bao50dd5322017-03-07 14:57:04 -08001324 case INSTALL_ERROR:
1325 case INSTALL_CORRUPT:
1326 ui->SetBackground(RecoveryUI::ERROR);
1327 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001328 }
Tao Bao50dd5322017-03-07 14:57:04 -08001329 ui->SetProgressType(RecoveryUI::EMPTY);
1330
Tom Marshall820517b2019-01-14 14:28:55 -08001331 int chosen_item = get_menu_selection(device->IsMainMenu(), device->GetMenuType(), nullptr,
1332 device->GetMenuItems(), false, 0, device);
1333 if (chosen_item == Device::kGoBack || chosen_item == Device::kGoHome) {
1334 device->GoHome();
1335 continue;
1336 }
1337 if (chosen_item == Device::kRefresh) {
Tom Marshall74f48242017-08-24 13:50:01 +00001338 continue;
1339 }
Tao Bao50dd5322017-03-07 14:57:04 -08001340
1341 // Device-specific code may take some action here. It may return one of the core actions
1342 // handled in the switch statement below.
1343 Device::BuiltinAction chosen_action =
1344 (chosen_item == -1) ? Device::REBOOT : device->InvokeMenuItem(chosen_item);
1345
1346 bool should_wipe_cache = false;
1347 switch (chosen_action) {
1348 case Device::NO_ACTION:
Tom Marshall820517b2019-01-14 14:28:55 -08001349 case Device::WIPE_MENU:
1350 case Device::ADVANCED_MENU:
Tao Bao50dd5322017-03-07 14:57:04 -08001351 break;
1352
1353 case Device::REBOOT:
1354 case Device::SHUTDOWN:
1355 case Device::REBOOT_BOOTLOADER:
jrior00125f976d2019-03-24 17:57:07 -04001356 case Device::REBOOT_RECOVERY:
Tao Bao50dd5322017-03-07 14:57:04 -08001357 return chosen_action;
1358
1359 case Device::WIPE_DATA:
1360 if (ui->IsTextVisible()) {
1361 if (ask_to_wipe_data(device)) {
1362 wipe_data(device);
1363 }
1364 } else {
1365 wipe_data(device);
1366 return Device::NO_ACTION;
1367 }
1368 break;
1369
1370 case Device::WIPE_CACHE:
1371 wipe_cache(ui->IsTextVisible(), device);
1372 if (!ui->IsTextVisible()) return Device::NO_ACTION;
1373 break;
1374
Dan Pasanendc95db82017-04-04 13:40:19 -05001375 case Device::WIPE_SYSTEM:
1376 if (ui->IsTextVisible()) {
1377 if (ask_to_wipe_system(device)) {
1378 wipe_system();
1379 }
1380 } else {
1381 wipe_system();
1382 return Device::NO_ACTION;
1383 }
1384 break;
1385
Tom Marshalla08c6f12019-01-04 14:37:31 -08001386 case Device::APPLY_UPDATE: {
1387 status = show_apply_update_menu(device, &should_wipe_cache);
Tao Bao50dd5322017-03-07 14:57:04 -08001388
Tom Marshall820517b2019-01-14 14:28:55 -08001389 if (status != INSTALL_NONE) {
1390 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1391 if (!wipe_cache(false, device)) {
1392 status = INSTALL_ERROR;
1393 }
Tao Bao50dd5322017-03-07 14:57:04 -08001394 }
1395
Tom Marshall5b4a9d82018-12-17 15:57:44 -08001396 if (status != INSTALL_SUCCESS) {
Tom Marshallf780f1c2018-03-01 23:51:51 +01001397 ui->SetProgressType(RecoveryUI::EMPTY);
Tom Marshall5b4a9d82018-12-17 15:57:44 -08001398 ui->SetBackground(RecoveryUI::ERROR);
1399 ui->Print("Installation aborted.\n");
Tom Marshallf780f1c2018-03-01 23:51:51 +01001400 ui->Redraw();
Tom Marshall5b4a9d82018-12-17 15:57:44 -08001401 copy_logs();
Tom Marshallf780f1c2018-03-01 23:51:51 +01001402 ui->FlushKeys();
1403 ui->WaitInputEvent();
Tom Marshall5b4a9d82018-12-17 15:57:44 -08001404 } else if (!ui->IsTextVisible()) {
1405 return Device::NO_ACTION; // reboot if logs aren't visible
1406 } else {
1407 ui->Print("\nInstall complete.\n");
1408 }
Tom Marshalla08c6f12019-01-04 14:37:31 -08001409 }
Tao Bao50dd5322017-03-07 14:57:04 -08001410 }
1411 break;
1412
1413 case Device::VIEW_RECOVERY_LOGS:
1414 choose_recovery_file(device);
Tom Marshall820517b2019-01-14 14:28:55 -08001415 if (chosen_item == Device::kGoHome) {
1416 device->GoHome();
1417 }
Tao Bao50dd5322017-03-07 14:57:04 -08001418 break;
1419
1420 case Device::RUN_GRAPHICS_TEST:
1421 run_graphics_test();
1422 break;
1423
Tianjie Xu29d55752017-09-20 17:53:46 -07001424 case Device::RUN_LOCALE_TEST: {
1425 ScreenRecoveryUI* screen_ui = static_cast<ScreenRecoveryUI*>(ui);
1426 screen_ui->CheckBackgroundTextImages(locale);
1427 break;
1428 }
Tao Bao50dd5322017-03-07 14:57:04 -08001429 case Device::MOUNT_SYSTEM:
1430 // For a system image built with the root directory (i.e. system_root_image == "true"), we
1431 // mount it to /system_root, and symlink /system to /system_root/system to make adb shell
1432 // work (the symlink is created through the build system). (Bug: 22855115)
1433 if (android::base::GetBoolProperty("ro.build.system_root_image", false)) {
1434 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1435 ui->Print("Mounted /system.\n");
1436 }
1437 } else {
1438 if (ensure_path_mounted("/system") != -1) {
1439 ui->Print("Mounted /system.\n");
1440 }
1441 }
1442 break;
1443 }
1444 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001445}
1446
Tao Bao99f0d9e2016-10-13 12:46:38 -07001447static void print_property(const char* key, const char* name, void* /* cookie */) {
1448 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001449}
1450
Tao Baoac9d94d2016-11-03 11:37:15 -07001451static std::string load_locale_from_cache() {
1452 if (ensure_path_mounted(LOCALE_FILE) != 0) {
1453 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
1454 return "";
Doug Zongker02ec6b82012-08-22 17:26:40 -07001455 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001456
1457 std::string content;
1458 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
1459 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
1460 return "";
1461 }
1462
1463 return android::base::Trim(content);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001464}
1465
Tao Baoac9d94d2016-11-03 11:37:15 -07001466void ui_print(const char* format, ...) {
1467 std::string buffer;
Doug Zongker7c3ae452013-05-14 11:03:02 -07001468 va_list ap;
1469 va_start(ap, format);
Tao Baoac9d94d2016-11-03 11:37:15 -07001470 android::base::StringAppendV(&buffer, format, ap);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001471 va_end(ap);
1472
Tao Baoac9d94d2016-11-03 11:37:15 -07001473 if (ui != nullptr) {
1474 ui->Print("%s", buffer.c_str());
Doug Zongker7c3ae452013-05-14 11:03:02 -07001475 } else {
Tao Baoac9d94d2016-11-03 11:37:15 -07001476 fputs(buffer.c_str(), stdout);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001477 }
1478}
1479
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -07001480static constexpr char log_characters[] = "VDIWEF";
1481
Tao Bao99f0d9e2016-10-13 12:46:38 -07001482void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
1483 const char* /* tag */, const char* /* file */, unsigned int /* line */,
1484 const char* message) {
1485 if (severity >= android::base::ERROR && ui != nullptr) {
1486 ui->Print("E:%s\n", message);
1487 } else {
1488 fprintf(stdout, "%c:%s\n", log_characters[severity], message);
1489 }
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -07001490}
1491
Yabin Cui99281df2016-02-17 12:21:52 -08001492static bool is_battery_ok() {
Yifan Honge8e4c402017-11-08 14:56:03 -08001493 using android::hardware::health::V1_0::BatteryStatus;
1494 using android::hardware::health::V2_0::Result;
1495 using android::hardware::health::V2_0::toString;
1496 using android::hardware::health::V2_0::implementation::Health;
Yabin Cui99281df2016-02-17 12:21:52 -08001497
Yifan Honge8e4c402017-11-08 14:56:03 -08001498 struct healthd_config healthd_config = {
1499 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1500 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1501 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1502 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1503 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1504 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1505 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1506 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1507 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1508 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1509 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1510 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1511 .energyCounter = NULL,
1512 .boot_min_cap = 0,
1513 .screen_on = NULL
1514 };
Yabin Cui99281df2016-02-17 12:21:52 -08001515
Yifan Honge8e4c402017-11-08 14:56:03 -08001516 auto health =
1517 android::hardware::health::V2_0::implementation::Health::initInstance(&healthd_config);
1518
1519 int wait_second = 0;
1520 while (true) {
1521 auto charge_status = BatteryStatus::UNKNOWN;
1522 health
1523 ->getChargeStatus([&charge_status](auto res, auto out_status) {
1524 if (res == Result::SUCCESS) {
1525 charge_status = out_status;
1526 }
1527 })
1528 .isOk(); // should not have transport error
1529
1530 // Treat unknown status as charged.
1531 bool charged = (charge_status != BatteryStatus::DISCHARGING &&
1532 charge_status != BatteryStatus::NOT_CHARGING);
1533
1534 Result res = Result::UNKNOWN;
1535 int32_t capacity = INT32_MIN;
1536 health
1537 ->getCapacity([&res, &capacity](auto out_res, auto out_capacity) {
1538 res = out_res;
1539 capacity = out_capacity;
1540 })
1541 .isOk(); // should not have transport error
1542
1543 ui_print("charge_status %d, charged %d, status %s, capacity %" PRId32 "\n", charge_status,
1544 charged, toString(res).c_str(), capacity);
1545 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1546 // the battery profile. Before the load finishes, it reports value 50 as a fake
1547 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1548 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1549 if (res == Result::SUCCESS && capacity == 50) {
1550 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1551 sleep(1);
1552 wait_second++;
1553 continue;
1554 }
1555 }
1556 // If we can't read battery percentage, it may be a device without battery. In this
1557 // situation, use 100 as a fake battery percentage.
1558 if (res != Result::SUCCESS) {
1559 capacity = 100;
1560 }
1561 return (charged && capacity >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
1562 (!charged && capacity >= BATTERY_OK_PERCENTAGE);
Yabin Cui99281df2016-02-17 12:21:52 -08001563 }
1564}
1565
Tianjie Xu99b73be2017-11-28 17:23:06 -08001566// Set the retry count to |retry_count| in BCB.
Tianjie Xu72449c92017-05-16 18:07:31 -07001567static void set_retry_bootloader_message(int retry_count, const std::vector<std::string>& args) {
1568 std::vector<std::string> options;
1569 for (const auto& arg : args) {
1570 if (!android::base::StartsWith(arg, "--retry_count")) {
1571 options.push_back(arg);
Tianjie Xu3c62b672016-02-05 18:25:58 -08001572 }
Tianjie Xu72449c92017-05-16 18:07:31 -07001573 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001574
Tianjie Xu99b73be2017-11-28 17:23:06 -08001575 // Update the retry counter in BCB.
1576 options.push_back(android::base::StringPrintf("--retry_count=%d", retry_count));
Tianjie Xu72449c92017-05-16 18:07:31 -07001577 std::string err;
1578 if (!update_bootloader_message(options, &err)) {
1579 LOG(ERROR) << err;
1580 }
Tianjie Xu3c62b672016-02-05 18:25:58 -08001581}
1582
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001583static bool bootreason_in_blacklist() {
Tao Baoefc35592017-01-08 22:45:47 -08001584 std::string bootreason = android::base::GetProperty("ro.boot.bootreason", "");
1585 if (!bootreason.empty()) {
1586 for (const auto& str : bootreason_blacklist) {
1587 if (strcasecmp(str.c_str(), bootreason.c_str()) == 0) {
1588 return true;
1589 }
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001590 }
Tao Baoefc35592017-01-08 22:45:47 -08001591 }
1592 return false;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001593}
1594
1595static void log_failure_code(ErrorCode code, const char *update_package) {
1596 std::vector<std::string> log_buffer = {
1597 update_package,
1598 "0", // install result
1599 "error: " + std::to_string(code),
1600 };
1601 std::string log_content = android::base::Join(log_buffer, "\n");
1602 if (!android::base::WriteStringToFile(log_content, TEMPORARY_INSTALL_FILE)) {
Tao Baoac9d94d2016-11-03 11:37:15 -07001603 PLOG(ERROR) << "failed to write " << TEMPORARY_INSTALL_FILE;
Tianjie Xu06e57ac2016-07-11 14:04:08 -07001604 }
1605
1606 // Also write the info into last_log.
1607 LOG(INFO) << log_content;
1608}
1609
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001610static void copy_userdata_files() {
1611 if (ensure_path_mounted("/data") == 0) {
Tom Marshalle65875b2019-01-07 14:42:42 -08001612 userdata_mountable = true;
1613 if (access(fbe_key_version, F_OK) != 0) {
1614 userdata_encrypted = false;
1615 }
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001616 if (access(adb_keys_root, F_OK) != 0) {
1617 if (access(adb_keys_data, R_OK) == 0) {
1618 file_copy(adb_keys_data, adb_keys_root);
1619 }
1620 }
1621 ensure_path_unmounted("/data");
1622 }
1623}
1624
1625static void setup_adbd() {
1626 int tries;
1627 for (tries = 0; tries < 5; ++tries) {
1628 if (access(adb_keys_root, F_OK) == 0) {
1629 break;
1630 }
1631 sleep(1);
1632 }
1633
1634 // Trigger (re)start of adb daemon
Hridya Valsaraju37d729b2018-07-27 22:09:12 -07001635 property_set("sys.usb.config", "adb");
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001636 property_set("lineage.service.adb.root", "1");
1637}
1638
Yabin Cui99281df2016-02-17 12:21:52 -08001639int main(int argc, char **argv) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001640 // We don't have logcat yet under recovery; so we'll print error on screen and
1641 // log to stdout (which is redirected to recovery.log) as we used to do.
1642 android::base::InitLogging(argv, &UiLogger);
Tianjie Xu7b0ad9c2016-08-05 18:00:04 -07001643
Tianjie Xu99b73be2017-11-28 17:23:06 -08001644 // Take last pmsg contents and rewrite it to the current pmsg session.
1645 static const char filter[] = "recovery/";
1646 // Do we need to rotate?
1647 bool doRotate = false;
Tianjie Xue113e4d2016-10-21 17:46:13 -07001648
Tianjie Xu99b73be2017-11-28 17:23:06 -08001649 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &doRotate);
1650 // Take action to refresh pmsg contents
1651 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &doRotate);
Mark Salyzyna4f701a2016-03-09 14:58:16 -08001652
Tianjie Xu99b73be2017-11-28 17:23:06 -08001653 // If this binary is started with the single argument "--adbd",
1654 // instead of being the normal recovery binary, it turns into kind
1655 // of a stripped-down version of adbd that only supports the
1656 // 'sideload' command. Note this must be a real argument, not
1657 // anything in the command file or bootloader control block; the
1658 // only way recovery should be run with this argument is when it
1659 // starts a copy of itself from the apply_from_adb() function.
1660 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
1661 minadbd_main();
1662 return 0;
1663 }
1664
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001665 // Handle alternative invocations
1666 char* command = argv[0];
1667 char* stripped = strrchr(argv[0], '/');
1668 if (stripped) {
1669 command = stripped + 1;
1670 }
1671
1672 if (strcmp(command, "recovery") != 0) {
1673 struct recovery_cmd cmd = get_command(command);
1674 if (cmd.name) {
1675 return cmd.main_func(argc, argv);
1676 }
1677
1678 LOG(ERROR) << "Unhandled command " << command;
1679 return 1;
1680 }
1681
Tom Marshall4d361ff2019-03-29 21:17:15 +00001682#ifndef RELEASE_BUILD
1683 // Set SELinux to permissive
1684 security_setenforce(0);
1685#endif
1686
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001687 // Clear umask for packages that copy files out to /tmp and then over
1688 // to /system without properly setting all permissions (eg. gapps).
1689 umask(0);
1690
Tianjie Xu99b73be2017-11-28 17:23:06 -08001691 time_t start = time(nullptr);
1692
1693 // redirect_stdio should be called only in non-sideload mode. Otherwise
1694 // we may have two logger instances with different timestamps.
1695 redirect_stdio(TEMPORARY_LOG_FILE);
1696
1697 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
1698
1699 load_volume_table();
1700 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
1701
Steve Kondikf96dc5e2013-10-19 19:49:20 -07001702 if (is_ro_debuggable()) {
1703 copy_userdata_files();
1704 setup_adbd();
1705 }
1706
Tianjie Xu99b73be2017-11-28 17:23:06 -08001707 std::vector<std::string> args = get_args(argc, argv);
1708 std::vector<char*> args_to_parse(args.size());
1709 std::transform(args.cbegin(), args.cend(), args_to_parse.begin(),
1710 [](const std::string& arg) { return const_cast<char*>(arg.c_str()); });
1711
1712 const char* update_package = nullptr;
1713 bool should_wipe_data = false;
1714 bool should_prompt_and_wipe_data = false;
1715 bool should_wipe_cache = false;
1716 bool should_wipe_ab = false;
1717 size_t wipe_package_size = 0;
1718 bool show_text = false;
1719 bool sideload = false;
1720 bool sideload_auto_reboot = false;
1721 bool just_exit = false;
1722 bool shutdown_after = false;
1723 int retry_count = 0;
1724 bool security_update = false;
1725
1726 int arg;
1727 int option_index;
1728 while ((arg = getopt_long(args_to_parse.size(), args_to_parse.data(), "", OPTIONS,
1729 &option_index)) != -1) {
1730 switch (arg) {
1731 case 'n':
1732 android::base::ParseInt(optarg, &retry_count, 0);
1733 break;
1734 case 'u':
1735 update_package = optarg;
1736 break;
1737 case 'w':
1738 should_wipe_data = true;
1739 break;
1740 case 'c':
1741 should_wipe_cache = true;
1742 break;
1743 case 't':
1744 show_text = true;
1745 break;
1746 case 's':
1747 sideload = true;
1748 break;
1749 case 'a':
1750 sideload = true;
1751 sideload_auto_reboot = true;
1752 break;
1753 case 'x':
1754 just_exit = true;
1755 break;
1756 case 'l':
1757 locale = optarg;
1758 break;
1759 case 'p':
1760 shutdown_after = true;
1761 break;
1762 case 'r':
1763 reason = optarg;
1764 break;
1765 case 'e':
1766 security_update = true;
1767 break;
1768 case 0: {
1769 std::string option = OPTIONS[option_index].name;
1770 if (option == "wipe_ab") {
1771 should_wipe_ab = true;
1772 } else if (option == "wipe_package_size") {
1773 android::base::ParseUint(optarg, &wipe_package_size);
1774 } else if (option == "prompt_and_wipe_data") {
1775 should_prompt_and_wipe_data = true;
1776 }
1777 break;
1778 }
1779 case '?':
1780 LOG(ERROR) << "Invalid command argument";
1781 continue;
Doug Zongker9270a202012-01-09 15:16:13 -08001782 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001783 }
Doug Zongker9270a202012-01-09 15:16:13 -08001784
Tianjie Xu99b73be2017-11-28 17:23:06 -08001785 if (locale.empty()) {
1786 if (has_cache) {
1787 locale = load_locale_from_cache();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001788 }
1789
Tao Baoac9d94d2016-11-03 11:37:15 -07001790 if (locale.empty()) {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001791 locale = DEFAULT_LOCALE;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001792 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001793 }
Tao Baoac9d94d2016-11-03 11:37:15 -07001794
Tianjie Xu99b73be2017-11-28 17:23:06 -08001795 printf("locale is [%s]\n", locale.c_str());
1796 printf("stage is [%s]\n", stage.c_str());
1797 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001798
Tianjie Xu99b73be2017-11-28 17:23:06 -08001799 Device* device = make_device();
1800 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
1801 printf("Quiescent recovery mode.\n");
1802 ui = new StubRecoveryUI();
1803 } else {
1804 ui = device->GetUI();
1805
1806 if (!ui->Init(locale)) {
1807 printf("Failed to initialize UI, use stub UI instead.\n");
1808 ui = new StubRecoveryUI();
1809 }
1810 }
1811
Tom Marshalla08c6f12019-01-04 14:37:31 -08001812 VolumeClient* volclient = new VolumeClient(device);
1813 VolumeManager* volmgr = VolumeManager::Instance();
1814 if (!volmgr->start(volclient)) {
1815 printf("Failed to start volume manager\n");
1816 }
1817
Tianjie Xu99b73be2017-11-28 17:23:06 -08001818 // Set background string to "installing security update" for security update,
1819 // otherwise set it to "installing system update".
1820 ui->SetSystemUpdateText(security_update);
1821
1822 int st_cur, st_max;
1823 if (!stage.empty() && sscanf(stage.c_str(), "%d/%d", &st_cur, &st_max) == 2) {
1824 ui->SetStage(st_cur, st_max);
1825 }
1826
1827 ui->SetBackground(RecoveryUI::NONE);
1828 if (show_text) ui->ShowText(true);
1829
1830 sehandle = selinux_android_file_context_handle();
1831 selinux_android_set_sehandle(sehandle);
1832 if (!sehandle) {
1833 ui->Print("Warning: No file_contexts\n");
1834 }
1835
1836 device->StartRecovery();
1837
1838 printf("Command:");
1839 for (const auto& arg : args) {
1840 printf(" \"%s\"", arg.c_str());
1841 }
1842 printf("\n\n");
1843
1844 property_list(print_property, nullptr);
1845 printf("\n");
1846
Tianjie Xu99b73be2017-11-28 17:23:06 -08001847 int status = INSTALL_SUCCESS;
1848
1849 if (update_package != nullptr) {
1850 // It's not entirely true that we will modify the flash. But we want
1851 // to log the update attempt since update_package is non-NULL.
1852 modified_flash = true;
1853
1854 if (!is_battery_ok()) {
1855 ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
1856 BATTERY_OK_PERCENTAGE);
1857 // Log the error code to last_install when installation skips due to
1858 // low battery.
1859 log_failure_code(kLowBattery, update_package);
1860 status = INSTALL_SKIPPED;
1861 } else if (bootreason_in_blacklist()) {
1862 // Skip update-on-reboot when bootreason is kernel_panic or similar
1863 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1864 log_failure_code(kBootreasonInBlacklist, update_package);
1865 status = INSTALL_SKIPPED;
Dmitri Plotnikov8706a982017-04-18 08:28:26 -07001866 } else {
Tianjie Xu99b73be2017-11-28 17:23:06 -08001867 // It's a fresh update. Initialize the retry_count in the BCB to 1; therefore we can later
1868 // identify the interrupted update due to unexpected reboots.
1869 if (retry_count == 0) {
1870 set_retry_bootloader_message(retry_count + 1, args);
Tao Bao7022f332017-07-25 09:52:36 -07001871 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001872
Tianjie Xu99b73be2017-11-28 17:23:06 -08001873 status = install_package(update_package, &should_wipe_cache, TEMPORARY_INSTALL_FILE, true,
Tom Marshalle2b6a972018-06-21 00:57:24 +02001874 retry_count, true);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001875 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1876 wipe_cache(false, device);
1877 }
1878 if (status != INSTALL_SUCCESS) {
1879 ui->Print("Installation aborted.\n");
1880 // When I/O error happens, reboot and retry installation RETRY_LIMIT
1881 // times before we abandon this OTA update.
1882 if (status == INSTALL_RETRY && retry_count < RETRY_LIMIT) {
1883 copy_logs();
1884 retry_count += 1;
1885 set_retry_bootloader_message(retry_count, args);
1886 // Print retry count on screen.
1887 ui->Print("Retry attempt %d\n", retry_count);
1888
1889 // Reboot and retry the update
1890 if (!reboot("reboot,recovery")) {
1891 ui->Print("Reboot failed\n");
1892 } else {
1893 while (true) {
1894 pause();
1895 }
1896 }
Tianjie Xud9d16292017-04-20 18:08:21 -07001897 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001898 // If this is an eng or userdebug build, then automatically
1899 // turn the text display on if the script fails so the error
1900 // message is visible.
1901 if (is_ro_debuggable()) {
1902 ui->ShowText(true);
Tao Baoc679f932015-03-30 09:43:49 -07001903 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001904 }
Doug Zongker8674a722010-09-15 11:08:23 -07001905 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001906 } else if (should_wipe_data) {
1907 if (!wipe_data(device)) {
1908 status = INSTALL_ERROR;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001909 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001910 } else if (should_prompt_and_wipe_data) {
1911 ui->ShowText(true);
1912 ui->SetBackground(RecoveryUI::ERROR);
1913 if (!prompt_and_wipe_data(device)) {
1914 status = INSTALL_ERROR;
Tao Bao75238632015-05-27 14:46:17 -07001915 }
Tianjie Xu99b73be2017-11-28 17:23:06 -08001916 ui->ShowText(false);
1917 } else if (should_wipe_cache) {
1918 if (!wipe_cache(false, device)) {
1919 status = INSTALL_ERROR;
1920 }
1921 } else if (should_wipe_ab) {
1922 if (!wipe_ab_device(wipe_package_size)) {
1923 status = INSTALL_ERROR;
1924 }
1925 } else if (sideload) {
1926 // 'adb reboot sideload' acts the same as user presses key combinations
1927 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1928 // display will NOT be turned on by default. And it will reboot after
1929 // sideload finishes even if there are errors. Unless one turns on the
1930 // text display during the installation. This is to enable automated
1931 // testing.
1932 if (!sideload_auto_reboot) {
1933 ui->ShowText(true);
1934 }
Tom Marshall668f1c32018-03-06 22:51:58 +01001935 sideload_start();
1936 sideload_wait(false);
Tom Marshalle2b6a972018-06-21 00:57:24 +02001937 status = sideload_install(&should_wipe_cache, TEMPORARY_INSTALL_FILE, true);
Tom Marshall668f1c32018-03-06 22:51:58 +01001938 sideload_stop();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001939 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1940 if (!wipe_cache(false, device)) {
1941 status = INSTALL_ERROR;
1942 }
1943 }
1944 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1945 if (sideload_auto_reboot) {
1946 ui->Print("Rebooting automatically.\n");
1947 }
1948 } else if (!just_exit) {
Pat Erley741e0142016-01-05 16:50:02 -08001949 // Always show menu if no command is specified.
1950 // Note that this should be called before setting the background to avoid
Tianjie Xu99b73be2017-11-28 17:23:06 -08001951 // flickering the background image.
Pat Erley741e0142016-01-05 16:50:02 -08001952 ui->ShowText(true);
Tianjie Xu99b73be2017-11-28 17:23:06 -08001953 status = INSTALL_NONE; // No command specified
1954 ui->SetBackground(RecoveryUI::NO_COMMAND);
1955 }
1956
1957 if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
1958 ui->SetBackground(RecoveryUI::ERROR);
1959 if (!ui->IsTextVisible()) {
Tom Marshallf780f1c2018-03-01 23:51:51 +01001960 ui->Redraw();
Tianjie Xu99b73be2017-11-28 17:23:06 -08001961 sleep(5);
1962 }
1963 }
1964
1965 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
1966 // 1. If the recovery menu is visible, prompt and wait for commands.
1967 // 2. If the state is INSTALL_NONE, wait for commands. (i.e. In user build, manually reboot into
1968 // recovery to sideload a package.)
1969 // 3. sideload_auto_reboot is an option only available in user-debug build, reboot the device
1970 // without waiting.
1971 // 4. In all other cases, reboot the device. Therefore, normal users will observe the device
1972 // reboot after it shows the "error" screen for 5s.
1973 if ((status == INSTALL_NONE && !sideload_auto_reboot) || ui->IsTextVisible()) {
1974 Device::BuiltinAction temp = prompt_and_wait(device, status);
1975 if (temp != Device::NO_ACTION) {
1976 after = temp;
1977 }
1978 }
1979
1980 // Save logs and clean up before rebooting or shutting down.
1981 finish_recovery();
1982
Tom Marshalla08c6f12019-01-04 14:37:31 -08001983 volmgr->unmountAll();
1984 volmgr->stop();
1985 delete volclient;
1986
1987 sync();
1988
Tom Marshallcfcafa12017-09-08 19:48:46 +00001989 ui->Stop();
1990
Tianjie Xu99b73be2017-11-28 17:23:06 -08001991 switch (after) {
1992 case Device::SHUTDOWN:
1993 ui->Print("Shutting down...\n");
1994 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
1995 break;
1996
1997 case Device::REBOOT_BOOTLOADER:
Andreas Blaesius3f011a22015-04-26 02:28:14 +02001998#ifdef DOWNLOAD_MODE
1999 ui->Print("Rebooting to download mode...\n");
2000 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,download");
2001#else
Tianjie Xu99b73be2017-11-28 17:23:06 -08002002 ui->Print("Rebooting to bootloader...\n");
2003 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
Andreas Blaesius3f011a22015-04-26 02:28:14 +02002004#endif
Tianjie Xu99b73be2017-11-28 17:23:06 -08002005 break;
2006
jrior00125f976d2019-03-24 17:57:07 -04002007 case Device::REBOOT_RECOVERY:
2008 ui->Print("Rebooting to recovery...\n");
2009 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,recovery");
2010 break;
Tianjie Xu99b73be2017-11-28 17:23:06 -08002011 default:
2012 ui->Print("Rebooting...\n");
2013 reboot("reboot,");
2014 break;
2015 }
2016 while (true) {
2017 pause();
2018 }
2019 // Should be unreachable.
2020 return EXIT_SUCCESS;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08002021}