blob: 9fbdd8c66b785a0bc9cd2b438a5a12782eeb595e [file] [log] [blame]
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070018#include <dirent.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080019#include <errno.h>
20#include <fcntl.h>
21#include <getopt.h>
Tao Bao862a4c12016-06-02 11:16:50 -070022#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080023#include <limits.h>
Tao Bao862a4c12016-06-02 11:16:50 -070024#include <linux/fs.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080025#include <linux/input.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070026#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080027#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
Patrick Tjincd055ee2014-12-09 11:26:40 -080030#include <sys/klog.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070031#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080032#include <sys/types.h>
Tao Baocdcf28f2016-01-13 15:05:20 -080033#include <sys/wait.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080034#include <time.h>
35#include <unistd.h>
36
Tao Bao04ca4262015-09-10 15:32:24 -070037#include <chrono>
Tao Bao862a4c12016-06-02 11:16:50 -070038#include <string>
39#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070040
Tao Bao75238632015-05-27 14:46:17 -070041#include <adb.h>
Mark Salyzyna4f701a2016-03-09 14:58:16 -080042#include <android/log.h> /* Android Log Priority Tags */
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/file.h>
Tianjie Xu3c62b672016-02-05 18:25:58 -080044#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/stringprintf.h>
Tao Bao862a4c12016-06-02 11:16:50 -070046#include <android-base/strings.h>
47#include <android-base/unique_fd.h>
Tao Bao75238632015-05-27 14:46:17 -070048#include <cutils/android_reboot.h>
49#include <cutils/properties.h>
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070050#include <healthd/BatteryMonitor.h>
Mark Salyzyna4f701a2016-03-09 14:58:16 -080051#include <log/logger.h> /* Android Log packet format */
52#include <private/android_logger.h> /* private pmsg functions */
Elliott Hughes4bbd5bf2016-04-01 18:24:39 -070053#include <selinux/label.h>
54#include <selinux/selinux.h>
Yabin Cui99281df2016-02-17 12:21:52 -080055
Tao Bao75238632015-05-27 14:46:17 -070056#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080057#include "bootloader.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080058#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070059#include "device.h"
Tianjie Xu16255832016-04-30 11:49:59 -070060#include "error_code.h"
Tao Bao75238632015-05-27 14:46:17 -070061#include "fuse_sdcard_provider.h"
62#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080063#include "install.h"
Josh Gaoacb2a2f2016-08-26 18:24:34 -070064#include "minadbd/minadbd.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080065#include "minui/minui.h"
66#include "minzip/DirUtil.h"
67#include "roots.h"
Doug Zongker28ce47c2011-10-28 10:33:05 -070068#include "ui.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070069#include "screen_ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080070
Stephen Smalley779701d2012-02-09 14:13:23 -050071struct selabel_handle *sehandle;
72
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080073static const struct option OPTIONS[] = {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080074 { "update_package", required_argument, NULL, 'u' },
Tianjie Xu3c62b672016-02-05 18:25:58 -080075 { "retry_count", required_argument, NULL, 'n' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080076 { "wipe_data", no_argument, NULL, 'w' },
77 { "wipe_cache", no_argument, NULL, 'c' },
Doug Zongker4bc98062010-09-03 11:00:13 -070078 { "show_text", no_argument, NULL, 't' },
Tao Baoc679f932015-03-30 09:43:49 -070079 { "sideload", no_argument, NULL, 's' },
80 { "sideload_auto_reboot", no_argument, NULL, 'a' },
Doug Zongkere5d5ac72012-04-12 11:01:22 -070081 { "just_exit", no_argument, NULL, 'x' },
Doug Zongker02ec6b82012-08-22 17:26:40 -070082 { "locale", required_argument, NULL, 'l' },
Doug Zongkerc87bab12013-11-25 13:53:25 -080083 { "stages", required_argument, NULL, 'g' },
Doug Zongkerb1d12632014-03-18 10:32:12 -070084 { "shutdown_after", no_argument, NULL, 'p' },
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -070085 { "reason", required_argument, NULL, 'r' },
Tianjie Xu35926c42016-04-28 18:06:26 -070086 { "security", no_argument, NULL, 'e'},
Tao Bao862a4c12016-06-02 11:16:50 -070087 { "brick", no_argument, NULL, 0 },
Doug Zongker988500b2009-10-06 14:41:38 -070088 { NULL, 0, NULL, 0 },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080089};
90
Doug Zongker6d0d7ac2013-07-09 13:34:55 -070091static const char *CACHE_LOG_DIR = "/cache/recovery";
Doug Zongkerd4208f92010-09-20 12:16:13 -070092static const char *COMMAND_FILE = "/cache/recovery/command";
Doug Zongkerd4208f92010-09-20 12:16:13 -070093static const char *LOG_FILE = "/cache/recovery/log";
Doug Zongkerd0181b82011-10-19 10:51:12 -070094static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
Doug Zongker8b240cc2012-08-29 15:19:29 -070095static const char *LOCALE_FILE = "/cache/recovery/last_locale";
Paul Lawrence661f8a62016-02-25 12:42:19 -080096static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
97static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
Michael Ward9d2629c2011-06-23 22:14:24 -070098static const char *CACHE_ROOT = "/cache";
Paul Lawrenced0db3372015-11-05 13:38:40 -080099static const char *DATA_ROOT = "/data";
Doug Zongkerd4208f92010-09-20 12:16:13 -0700100static const char *SDCARD_ROOT = "/sdcard";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800101static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
Doug Zongkerd0181b82011-10-19 10:51:12 -0700102static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
Tao Baof0124322015-04-11 02:04:11 +0000103static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
Tao Baobef39712015-05-04 18:50:27 -0700104static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
105static const int KEEP_LOG_COUNT = 10;
Tianjie Xuc37c5c32016-06-23 16:52:17 -0700106// We will try to apply the update package 5 times at most in case of an I/O error.
107static const int EIO_RETRY_COUNT = 4;
Yabin Cui99281df2016-02-17 12:21:52 -0800108static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
109// GmsCore enters recovery mode to install package when having enough battery
110// percentage. Normally, the threshold is 40% without charger and 20% with charger.
111// So we should check battery with a slightly lower limitation.
112static const int BATTERY_OK_PERCENTAGE = 20;
113static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
Tao Bao862a4c12016-06-02 11:16:50 -0700114constexpr const char* RECOVERY_BRICK = "/etc/recovery.brick";
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700115
Doug Zongker211aebc2011-10-28 15:13:10 -0700116RecoveryUI* ui = NULL;
Elliott Hughes498cda62016-04-14 16:49:04 -0700117static const char* locale = "en_US";
Doug Zongkerc87bab12013-11-25 13:53:25 -0800118char* stage = NULL;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -0700119char* reason = NULL;
Tao Bao682c34b2015-04-07 17:16:35 -0700120bool modified_flash = false;
Tao Bao26112e52016-02-25 12:29:40 -0800121static bool has_cache = false;
Doug Zongker211aebc2011-10-28 15:13:10 -0700122
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800123/*
124 * The recovery tool communicates with the main system through /cache files.
125 * /cache/recovery/command - INPUT - command line for tool, one arg per line
126 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800127 *
128 * The arguments which may be supplied in the recovery.command file:
Doug Zongkerd4208f92010-09-20 12:16:13 -0700129 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800130 * --wipe_data - erase user data (and cache), then reboot
131 * --wipe_cache - wipe cache (but not user data), then reboot
Oscar Montemayor05231562009-11-30 08:40:57 -0800132 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700133 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800134 *
135 * After completing, we remove /cache/recovery/command and reboot.
136 * Arguments may also be supplied in the bootloader control block (BCB).
137 * These important scenarios must be safely restartable at any point:
138 *
139 * FACTORY RESET
140 * 1. user selects "factory reset"
141 * 2. main system writes "--wipe_data" to /cache/recovery/command
142 * 3. main system reboots into recovery
143 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
144 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700145 * 5. erase_volume() reformats /data
146 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800147 * 7. finish_recovery() erases BCB
148 * -- after this, rebooting will restart the main system --
149 * 8. main() calls reboot() to boot main system
150 *
151 * OTA INSTALL
152 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700153 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800154 * 3. main system reboots into recovery
155 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
156 * -- after this, rebooting will attempt to reinstall the update --
157 * 5. install_package() attempts to install the update
158 * NOTE: the package install must itself be restartable from any point
159 * 6. finish_recovery() erases BCB
160 * -- after this, rebooting will (try to) restart the main system --
161 * 7. ** if install failed **
162 * 7a. prompt_and_wait() shows an error icon and waits for the user
163 * 7b; the user reboots (pulling the battery, etc) into the main system
164 * 8. main() calls maybe_install_firmware_update()
165 * ** if the update contained radio/hboot firmware **:
166 * 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
167 * -- after this, rebooting will reformat cache & restart main system --
168 * 8b. m_i_f_u() writes firmware image into raw cache partition
169 * 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
170 * -- after this, rebooting will attempt to reinstall firmware --
171 * 8d. bootloader tries to flash firmware
172 * 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
173 * -- after this, rebooting will reformat cache & restart main system --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700174 * 8f. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800175 * 8g. finish_recovery() erases BCB
176 * -- after this, rebooting will (try to) restart the main system --
177 * 9. main() calls reboot() to boot main system
178 */
179
180static const int MAX_ARG_LENGTH = 4096;
181static const int MAX_ARGS = 100;
182
Doug Zongkerd4208f92010-09-20 12:16:13 -0700183// open a given path, mounting partitions as necessary
Tao Bao04ca4262015-09-10 15:32:24 -0700184FILE* fopen_path(const char *path, const char *mode) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700185 if (ensure_path_mounted(path) != 0) {
186 LOGE("Can't mount %s\n", path);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800187 return NULL;
188 }
189
190 // When writing, try to create the containing directory, if necessary.
191 // Use generous permissions, the system (init.rc) will reset them.
Stephen Smalley779701d2012-02-09 14:13:23 -0500192 if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1, sehandle);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800193
194 FILE *fp = fopen(path, mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800195 return fp;
196}
197
Tao Bao04ca4262015-09-10 15:32:24 -0700198// close a file, log an error if the error indicator is set
199static void check_and_fclose(FILE *fp, const char *name) {
200 fflush(fp);
201 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
202 fclose(fp);
203}
204
Elliott Hughesf14af802015-02-10 14:46:14 -0800205bool is_ro_debuggable() {
206 char value[PROPERTY_VALUE_MAX+1];
207 return (property_get("ro.debuggable", value, NULL) == 1 && value[0] == '1');
208}
209
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700210static void redirect_stdio(const char* filename) {
Tao Bao04ca4262015-09-10 15:32:24 -0700211 int pipefd[2];
212 if (pipe(pipefd) == -1) {
213 LOGE("pipe failed: %s\n", strerror(errno));
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700214
Tao Bao04ca4262015-09-10 15:32:24 -0700215 // Fall back to traditional logging mode without timestamps.
216 // If these fail, there's not really anywhere to complain...
217 freopen(filename, "a", stdout); setbuf(stdout, NULL);
218 freopen(filename, "a", stderr); setbuf(stderr, NULL);
219
220 return;
221 }
222
223 pid_t pid = fork();
224 if (pid == -1) {
225 LOGE("fork failed: %s\n", strerror(errno));
226
227 // Fall back to traditional logging mode without timestamps.
228 // If these fail, there's not really anywhere to complain...
229 freopen(filename, "a", stdout); setbuf(stdout, NULL);
230 freopen(filename, "a", stderr); setbuf(stderr, NULL);
231
232 return;
233 }
234
235 if (pid == 0) {
236 /// Close the unused write end.
237 close(pipefd[1]);
238
239 auto start = std::chrono::steady_clock::now();
240
241 // Child logger to actually write to the log file.
242 FILE* log_fp = fopen(filename, "a");
243 if (log_fp == nullptr) {
244 LOGE("fopen \"%s\" failed: %s\n", filename, strerror(errno));
245 close(pipefd[0]);
246 _exit(1);
247 }
248
249 FILE* pipe_fp = fdopen(pipefd[0], "r");
250 if (pipe_fp == nullptr) {
251 LOGE("fdopen failed: %s\n", strerror(errno));
252 check_and_fclose(log_fp, filename);
253 close(pipefd[0]);
254 _exit(1);
255 }
256
257 char* line = nullptr;
258 size_t len = 0;
259 while (getline(&line, &len, pipe_fp) != -1) {
260 auto now = std::chrono::steady_clock::now();
261 double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
262 now - start).count();
263 if (line[0] == '\n') {
264 fprintf(log_fp, "[%12.6lf]\n", duration);
265 } else {
266 fprintf(log_fp, "[%12.6lf] %s", duration, line);
267 }
268 fflush(log_fp);
269 }
270
271 LOGE("getline failed: %s\n", strerror(errno));
272
273 free(line);
274 check_and_fclose(log_fp, filename);
275 close(pipefd[0]);
276 _exit(1);
277 } else {
278 // Redirect stdout/stderr to the logger process.
279 // Close the unused read end.
280 close(pipefd[0]);
281
282 setbuf(stdout, nullptr);
283 setbuf(stderr, nullptr);
284
285 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
286 LOGE("dup2 stdout failed: %s\n", strerror(errno));
287 }
288 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
289 LOGE("dup2 stderr failed: %s\n", strerror(errno));
290 }
291
292 close(pipefd[1]);
293 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800294}
295
296// command line args come from, in decreasing precedence:
297// - the actual command line
298// - the bootloader control block (one per line, after "recovery")
299// - the contents of COMMAND_FILE (one per line)
300static void
301get_args(int *argc, char ***argv) {
302 struct bootloader_message boot;
303 memset(&boot, 0, sizeof(boot));
304 get_bootloader_message(&boot); // this may fail, leaving a zeroed structure
Doug Zongkerc87bab12013-11-25 13:53:25 -0800305 stage = strndup(boot.stage, sizeof(boot.stage));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800306
307 if (boot.command[0] != 0 && boot.command[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700308 LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800309 }
310
311 if (boot.status[0] != 0 && boot.status[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700312 LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800313 }
314
315 // --- if arguments weren't supplied, look in the bootloader control block
316 if (*argc <= 1) {
317 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
318 const char *arg = strtok(boot.recovery, "\n");
319 if (arg != NULL && !strcmp(arg, "recovery")) {
320 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
321 (*argv)[0] = strdup(arg);
322 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
323 if ((arg = strtok(NULL, "\n")) == NULL) break;
324 (*argv)[*argc] = strdup(arg);
325 }
326 LOGI("Got arguments from boot message\n");
327 } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
328 LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
329 }
330 }
331
Tao Bao26112e52016-02-25 12:29:40 -0800332 // --- if that doesn't work, try the command file (if we have /cache).
333 if (*argc <= 1 && has_cache) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700334 FILE *fp = fopen_path(COMMAND_FILE, "r");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800335 if (fp != NULL) {
Jin Feng93ffa752013-06-04 17:46:24 +0800336 char *token;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800337 char *argv0 = (*argv)[0];
338 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
339 (*argv)[0] = argv0; // use the same program name
340
341 char buf[MAX_ARG_LENGTH];
342 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
343 if (!fgets(buf, sizeof(buf), fp)) break;
Jin Feng93ffa752013-06-04 17:46:24 +0800344 token = strtok(buf, "\r\n");
345 if (token != NULL) {
346 (*argv)[*argc] = strdup(token); // Strip newline.
347 } else {
348 --*argc;
349 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800350 }
351
352 check_and_fclose(fp, COMMAND_FILE);
353 LOGI("Got arguments from %s\n", COMMAND_FILE);
354 }
355 }
356
357 // --> write the arguments we have back into the bootloader control block
358 // always boot into recovery after this (until finish_recovery() is called)
359 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
360 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
361 int i;
362 for (i = 1; i < *argc; ++i) {
363 strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
364 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
365 }
366 set_bootloader_message(&boot);
367}
368
Doug Zongker34c98df2009-08-18 12:05:45 -0700369static void
Oscar Montemayor05231562009-11-30 08:40:57 -0800370set_sdcard_update_bootloader_message() {
Doug Zongker34c98df2009-08-18 12:05:45 -0700371 struct bootloader_message boot;
372 memset(&boot, 0, sizeof(boot));
373 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
374 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
375 set_bootloader_message(&boot);
376}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800377
Tao Baobef39712015-05-04 18:50:27 -0700378// Read from kernel log into buffer and write out to file.
379static void save_kernel_log(const char* destination) {
380 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800381 if (klog_buf_len <= 0) {
Tao Baobef39712015-05-04 18:50:27 -0700382 LOGE("Error getting klog size: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800383 return;
384 }
385
Tao Baobef39712015-05-04 18:50:27 -0700386 std::string buffer(klog_buf_len, 0);
387 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
388 if (n == -1) {
389 LOGE("Error in reading klog: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800390 return;
391 }
Tao Baobef39712015-05-04 18:50:27 -0700392 buffer.resize(n);
393 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800394}
395
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800396// write content to the current pmsg session.
397static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
398 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
399 filename, buf, len);
400}
401
402static void copy_log_file_to_pmsg(const char* source, const char* destination) {
403 std::string content;
404 android::base::ReadFileToString(source, &content);
405 __pmsg_write(destination, content.c_str(), content.length());
406}
407
Tao Baof0124322015-04-11 02:04:11 +0000408// How much of the temp log we have copied to the copy in cache.
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700409static off_t tmplog_offset = 0;
Tao Baof0124322015-04-11 02:04:11 +0000410
Tao Baobef39712015-05-04 18:50:27 -0700411static void copy_log_file(const char* source, const char* destination, bool append) {
412 FILE* dest_fp = fopen_path(destination, append ? "a" : "w");
413 if (dest_fp == nullptr) {
Doug Zongker2c3539e2010-09-29 13:21:30 -0700414 LOGE("Can't open %s\n", destination);
415 } else {
Tao Baobef39712015-05-04 18:50:27 -0700416 FILE* source_fp = fopen(source, "r");
417 if (source_fp != nullptr) {
Tao Baof0124322015-04-11 02:04:11 +0000418 if (append) {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700419 fseeko(source_fp, tmplog_offset, SEEK_SET); // Since last write
Doug Zongker2c3539e2010-09-29 13:21:30 -0700420 }
421 char buf[4096];
Tao Baobef39712015-05-04 18:50:27 -0700422 size_t bytes;
423 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
424 fwrite(buf, 1, bytes, dest_fp);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700425 }
Tao Baobef39712015-05-04 18:50:27 -0700426 if (append) {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -0700427 tmplog_offset = ftello(source_fp);
Tao Baobef39712015-05-04 18:50:27 -0700428 }
429 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700430 }
Tao Baobef39712015-05-04 18:50:27 -0700431 check_and_fclose(dest_fp, destination);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700432 }
433}
434
Tao Baobef39712015-05-04 18:50:27 -0700435// Rename last_log -> last_log.1 -> last_log.2 -> ... -> last_log.$max.
436// Similarly rename last_kmsg -> last_kmsg.1 -> ... -> last_kmsg.$max.
437// Overwrite any existing last_log.$max and last_kmsg.$max.
438static void rotate_logs(int max) {
Tao Bao682c34b2015-04-07 17:16:35 -0700439 // Logs should only be rotated once.
440 static bool rotated = false;
441 if (rotated) {
442 return;
443 }
444 rotated = true;
445 ensure_path_mounted(LAST_LOG_FILE);
Tao Baobef39712015-05-04 18:50:27 -0700446 ensure_path_mounted(LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700447
Tao Bao682c34b2015-04-07 17:16:35 -0700448 for (int i = max-1; i >= 0; --i) {
Tao Bao80e46e02015-06-03 10:49:29 -0700449 std::string old_log = android::base::StringPrintf("%s", LAST_LOG_FILE);
450 if (i > 0) {
451 old_log += "." + std::to_string(i);
452 }
Tao Baobef39712015-05-04 18:50:27 -0700453 std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
454 // Ignore errors if old_log doesn't exist.
455 rename(old_log.c_str(), new_log.c_str());
456
Tao Bao80e46e02015-06-03 10:49:29 -0700457 std::string old_kmsg = android::base::StringPrintf("%s", LAST_KMSG_FILE);
458 if (i > 0) {
459 old_kmsg += "." + std::to_string(i);
460 }
Tao Baobef39712015-05-04 18:50:27 -0700461 std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
462 rename(old_kmsg.c_str(), new_kmsg.c_str());
Doug Zongkerda1ebae2013-05-16 11:23:48 -0700463 }
464}
Doug Zongker2c3539e2010-09-29 13:21:30 -0700465
Tao Bao682c34b2015-04-07 17:16:35 -0700466static void copy_logs() {
467 // We only rotate and record the log of the current session if there are
468 // actual attempts to modify the flash, such as wipes, installs from BCB
469 // or menu selections. This is to avoid unnecessary rotation (and
470 // possible deletion) of log files, if it does not do anything loggable.
471 if (!modified_flash) {
472 return;
473 }
474
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800475 // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
476 copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
477 copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
478
479 // We can do nothing for now if there's no /cache partition.
480 if (!has_cache) {
481 return;
482 }
483
Tao Baobef39712015-05-04 18:50:27 -0700484 rotate_logs(KEEP_LOG_COUNT);
Tao Bao682c34b2015-04-07 17:16:35 -0700485
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700486 // Copy logs to cache so the system can find out what happened.
Tao Baof0124322015-04-11 02:04:11 +0000487 copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
488 copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
489 copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
490 save_kernel_log(LAST_KMSG_FILE);
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700491 chmod(LOG_FILE, 0600);
492 chown(LOG_FILE, 1000, 1000); // system user
Tao Baof0124322015-04-11 02:04:11 +0000493 chmod(LAST_KMSG_FILE, 0600);
494 chown(LAST_KMSG_FILE, 1000, 1000); // system user
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700495 chmod(LAST_LOG_FILE, 0640);
496 chmod(LAST_INSTALL_FILE, 0644);
497 sync();
498}
499
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800500// clear the recovery command and prepare to boot a (hopefully working) system,
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700501// copy our log file to cache as well (for the system to read). This function is
502// idempotent: call it as many times as you like.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800503static void
Tianjie Xuc14d95d2016-03-24 11:50:34 -0700504finish_recovery() {
Doug Zongker4f33e552012-08-23 13:16:12 -0700505 // Save the locale to cache, so if recovery is next started up
506 // without a --locale argument (eg, directly from the bootloader)
507 // it will use the last-known locale.
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800508 if (locale != NULL) {
509 size_t len = strlen(locale);
510 __pmsg_write(LOCALE_FILE, locale, len);
511 if (has_cache) {
512 LOGI("Saving locale \"%s\"\n", locale);
513 FILE* fp = fopen_path(LOCALE_FILE, "w");
Johan Harvyl85691422016-08-05 15:42:59 +0200514 if (fp != NULL) {
515 fwrite(locale, 1, len, fp);
516 fflush(fp);
517 fsync(fileno(fp));
518 check_and_fclose(fp, LOCALE_FILE);
519 }
Mark Salyzyna4f701a2016-03-09 14:58:16 -0800520 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700521 }
522
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700523 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800524
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700525 // Reset to normal system boot so recovery won't cycle indefinitely.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800526 struct bootloader_message boot;
527 memset(&boot, 0, sizeof(boot));
528 set_bootloader_message(&boot);
529
530 // Remove the command file, so recovery won't repeat indefinitely.
Tao Bao26112e52016-02-25 12:29:40 -0800531 if (has_cache) {
532 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
533 LOGW("Can't unlink %s\n", COMMAND_FILE);
534 }
535 ensure_path_unmounted(CACHE_ROOT);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800536 }
537
538 sync(); // For good measure.
539}
540
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700541typedef struct _saved_log_file {
542 char* name;
543 struct stat st;
544 unsigned char* data;
545 struct _saved_log_file* next;
546} saved_log_file;
547
Elliott Hughes945548e2015-06-05 17:59:56 -0700548static bool erase_volume(const char* volume) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700549 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800550 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700551
Doug Zongker02ec6b82012-08-22 17:26:40 -0700552 ui->SetBackground(RecoveryUI::ERASING);
Doug Zongker211aebc2011-10-28 15:13:10 -0700553 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700554
555 saved_log_file* head = NULL;
556
557 if (is_cache) {
Tao Baobef39712015-05-04 18:50:27 -0700558 // If we're reformatting /cache, we load any past logs
559 // (i.e. "/cache/recovery/last_*") and the current log
560 // ("/cache/recovery/log") into memory, so we can restore them after
561 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700562
563 ensure_path_mounted(volume);
564
565 DIR* d;
566 struct dirent* de;
567 d = opendir(CACHE_LOG_DIR);
568 if (d) {
569 char path[PATH_MAX];
570 strcpy(path, CACHE_LOG_DIR);
571 strcat(path, "/");
572 int path_len = strlen(path);
573 while ((de = readdir(d)) != NULL) {
Tao Baobef39712015-05-04 18:50:27 -0700574 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700575 saved_log_file* p = (saved_log_file*) malloc(sizeof(saved_log_file));
576 strcpy(path+path_len, de->d_name);
577 p->name = strdup(path);
578 if (stat(path, &(p->st)) == 0) {
579 // truncate files to 512kb
580 if (p->st.st_size > (1 << 19)) {
581 p->st.st_size = 1 << 19;
582 }
583 p->data = (unsigned char*) malloc(p->st.st_size);
584 FILE* f = fopen(path, "rb");
585 fread(p->data, 1, p->st.st_size, f);
586 fclose(f);
587 p->next = head;
588 head = p;
589 } else {
590 free(p);
591 }
592 }
593 }
594 closedir(d);
595 } else {
596 if (errno != ENOENT) {
597 printf("opendir failed: %s\n", strerror(errno));
598 }
599 }
600 }
601
Doug Zongker211aebc2011-10-28 15:13:10 -0700602 ui->Print("Formatting %s...\n", volume);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700603
Doug Zongkerd0181b82011-10-19 10:51:12 -0700604 ensure_path_unmounted(volume);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800605
606 int result;
607
608 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
609 // Create convert_fbe breadcrumb file to signal to init
610 // to convert to file based encryption, not full disk encryption
Paul Lawrence661f8a62016-02-25 12:42:19 -0800611 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
612 ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
613 return true;
614 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800615 FILE* f = fopen(CONVERT_FBE_FILE, "wb");
616 if (!f) {
Paul Lawrence661f8a62016-02-25 12:42:19 -0800617 ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
Paul Lawrenced0db3372015-11-05 13:38:40 -0800618 return true;
619 }
620 fclose(f);
621 result = format_volume(volume, CONVERT_FBE_DIR);
622 remove(CONVERT_FBE_FILE);
623 rmdir(CONVERT_FBE_DIR);
624 } else {
625 result = format_volume(volume);
626 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700627
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700628 if (is_cache) {
629 while (head) {
630 FILE* f = fopen_path(head->name, "wb");
631 if (f) {
632 fwrite(head->data, 1, head->st.st_size, f);
633 fclose(f);
634 chmod(head->name, head->st.st_mode);
635 chown(head->name, head->st.st_uid, head->st.st_gid);
636 }
637 free(head->name);
638 free(head->data);
639 saved_log_file* temp = head->next;
640 free(head);
641 head = temp;
642 }
643
Tao Baof0124322015-04-11 02:04:11 +0000644 // Any part of the log we'd copied to cache is now gone.
645 // Reset the pointer so we copy from the beginning of the temp
646 // log.
647 tmplog_offset = 0;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700648 copy_logs();
Doug Zongker2c3539e2010-09-29 13:21:30 -0700649 }
650
Elliott Hughes945548e2015-06-05 17:59:56 -0700651 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800652}
653
Doug Zongkerf93d8162009-09-22 15:16:02 -0700654static int
Doug Zongker28ce47c2011-10-28 10:33:05 -0700655get_menu_selection(const char* const * headers, const char* const * items,
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700656 int menu_only, int initial_selection, Device* device) {
Doug Zongkerf93d8162009-09-22 15:16:02 -0700657 // throw away keys pressed previously, so user doesn't
658 // accidentally trigger menu items.
Doug Zongker211aebc2011-10-28 15:13:10 -0700659 ui->FlushKeys();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700660
Doug Zongker211aebc2011-10-28 15:13:10 -0700661 ui->StartMenu(headers, items, initial_selection);
Doug Zongker8674a722010-09-15 11:08:23 -0700662 int selected = initial_selection;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800663 int chosen_item = -1;
664
Doug Zongkerf93d8162009-09-22 15:16:02 -0700665 while (chosen_item < 0) {
Doug Zongker211aebc2011-10-28 15:13:10 -0700666 int key = ui->WaitKey();
667 int visible = ui->IsTextVisible();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800668
Doug Zongker5cae4452011-01-25 13:15:30 -0800669 if (key == -1) { // ui_wait_key() timed out
Doug Zongker211aebc2011-10-28 15:13:10 -0700670 if (ui->WasTextEverVisible()) {
Doug Zongker5cae4452011-01-25 13:15:30 -0800671 continue;
672 } else {
673 LOGI("timed out waiting for key input; rebooting.\n");
Doug Zongker211aebc2011-10-28 15:13:10 -0700674 ui->EndMenu();
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700675 return 0; // XXX fixme
Doug Zongker5cae4452011-01-25 13:15:30 -0800676 }
677 }
678
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700679 int action = device->HandleMenuKey(key, visible);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700680
681 if (action < 0) {
682 switch (action) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700683 case Device::kHighlightUp:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700684 selected = ui->SelectMenu(--selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700685 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700686 case Device::kHighlightDown:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700687 selected = ui->SelectMenu(++selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700688 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700689 case Device::kInvokeItem:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700690 chosen_item = selected;
691 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700692 case Device::kNoAction:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700693 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800694 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700695 } else if (!menu_only) {
Doug Zongkerddd6a282009-06-09 12:22:33 -0700696 chosen_item = action;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800697 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700698 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800699
Doug Zongker211aebc2011-10-28 15:13:10 -0700700 ui->EndMenu();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700701 return chosen_item;
702}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800703
Doug Zongker8674a722010-09-15 11:08:23 -0700704static int compare_string(const void* a, const void* b) {
705 return strcmp(*(const char**)a, *(const char**)b);
706}
707
Doug Zongker93950222014-07-08 14:10:23 -0700708// Returns a malloc'd path, or NULL.
Elliott Hughes30694c92015-03-25 15:16:51 -0700709static char* browse_directory(const char* path, Device* device) {
Michael Ward9d2629c2011-06-23 22:14:24 -0700710 ensure_path_mounted(path);
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700711
Elliott Hughes30694c92015-03-25 15:16:51 -0700712 DIR* d = opendir(path);
Doug Zongker8674a722010-09-15 11:08:23 -0700713 if (d == NULL) {
714 LOGE("error opening %s: %s\n", path, strerror(errno));
Doug Zongker93950222014-07-08 14:10:23 -0700715 return NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700716 }
717
Doug Zongker8674a722010-09-15 11:08:23 -0700718 int d_size = 0;
719 int d_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700720 char** dirs = (char**)malloc(d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700721 int z_size = 1;
722 int z_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700723 char** zips = (char**)malloc(z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700724 zips[0] = strdup("../");
725
Elliott Hughes30694c92015-03-25 15:16:51 -0700726 struct dirent* de;
Doug Zongker8674a722010-09-15 11:08:23 -0700727 while ((de = readdir(d)) != NULL) {
728 int name_len = strlen(de->d_name);
729
730 if (de->d_type == DT_DIR) {
731 // skip "." and ".." entries
732 if (name_len == 1 && de->d_name[0] == '.') continue;
733 if (name_len == 2 && de->d_name[0] == '.' &&
734 de->d_name[1] == '.') continue;
735
736 if (d_size >= d_alloc) {
737 d_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700738 dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700739 }
Doug Zongker28ce47c2011-10-28 10:33:05 -0700740 dirs[d_size] = (char*)malloc(name_len + 2);
Doug Zongker8674a722010-09-15 11:08:23 -0700741 strcpy(dirs[d_size], de->d_name);
742 dirs[d_size][name_len] = '/';
743 dirs[d_size][name_len+1] = '\0';
744 ++d_size;
745 } else if (de->d_type == DT_REG &&
746 name_len >= 4 &&
747 strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
748 if (z_size >= z_alloc) {
749 z_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700750 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700751 }
752 zips[z_size++] = strdup(de->d_name);
753 }
754 }
755 closedir(d);
756
757 qsort(dirs, d_size, sizeof(char*), compare_string);
758 qsort(zips, z_size, sizeof(char*), compare_string);
759
760 // append dirs to the zips list
761 if (d_size + z_size + 1 > z_alloc) {
762 z_alloc = d_size + z_size + 1;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700763 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700764 }
765 memcpy(zips + z_size, dirs, d_size * sizeof(char*));
766 free(dirs);
767 z_size += d_size;
768 zips[z_size] = NULL;
769
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700770 const char* headers[] = { "Choose a package to install:", path, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700771
Doug Zongker93950222014-07-08 14:10:23 -0700772 char* result;
Doug Zongker8674a722010-09-15 11:08:23 -0700773 int chosen_item = 0;
Doug Zongker93950222014-07-08 14:10:23 -0700774 while (true) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700775 chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
Doug Zongker8674a722010-09-15 11:08:23 -0700776
777 char* item = zips[chosen_item];
778 int item_len = strlen(item);
779 if (chosen_item == 0) { // item 0 is always "../"
Michael Ward9d2629c2011-06-23 22:14:24 -0700780 // go up but continue browsing (if the caller is update_directory)
Doug Zongker93950222014-07-08 14:10:23 -0700781 result = NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700782 break;
783 }
Doug Zongker93950222014-07-08 14:10:23 -0700784
785 char new_path[PATH_MAX];
786 strlcpy(new_path, path, PATH_MAX);
787 strlcat(new_path, "/", PATH_MAX);
788 strlcat(new_path, item, PATH_MAX);
789
790 if (item[item_len-1] == '/') {
791 // recurse down into a subdirectory
792 new_path[strlen(new_path)-1] = '\0'; // truncate the trailing '/'
793 result = browse_directory(new_path, device);
794 if (result) break;
795 } else {
796 // selected a zip file: return the malloc'd path to the caller.
797 result = strdup(new_path);
798 break;
799 }
800 }
Doug Zongker8674a722010-09-15 11:08:23 -0700801
Elliott Hughes30694c92015-03-25 15:16:51 -0700802 for (int i = 0; i < z_size; ++i) free(zips[i]);
Doug Zongker8674a722010-09-15 11:08:23 -0700803 free(zips);
Doug Zongker8674a722010-09-15 11:08:23 -0700804
805 return result;
806}
807
Elliott Hughes30694c92015-03-25 15:16:51 -0700808static bool yes_no(Device* device, const char* question1, const char* question2) {
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700809 const char* headers[] = { question1, question2, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700810 const char* items[] = { " No", " Yes", NULL };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700811
Elliott Hughes30694c92015-03-25 15:16:51 -0700812 int chosen_item = get_menu_selection(headers, items, 1, 0, device);
813 return (chosen_item == 1);
814}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800815
Tao Baoe39a9bc2015-03-31 12:19:05 -0700816// Return true on success.
817static bool wipe_data(int should_confirm, Device* device) {
818 if (should_confirm && !yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!")) {
819 return false;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700820 }
Doug Zongker1066d2c2009-04-01 13:57:40 -0700821
Tao Bao682c34b2015-04-07 17:16:35 -0700822 modified_flash = true;
823
Doug Zongker211aebc2011-10-28 15:13:10 -0700824 ui->Print("\n-- Wiping data...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700825 bool success =
826 device->PreWipeData() &&
827 erase_volume("/data") &&
Tao Bao26112e52016-02-25 12:29:40 -0800828 (has_cache ? erase_volume("/cache") : true) &&
Elliott Hughes945548e2015-06-05 17:59:56 -0700829 device->PostWipeData();
830 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
831 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700832}
833
Tao Baoe39a9bc2015-03-31 12:19:05 -0700834// Return true on success.
835static bool wipe_cache(bool should_confirm, Device* device) {
Tao Bao26112e52016-02-25 12:29:40 -0800836 if (!has_cache) {
837 ui->Print("No /cache partition found.\n");
838 return false;
839 }
840
Elliott Hughes30694c92015-03-25 15:16:51 -0700841 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700842 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700843 }
844
Tao Bao682c34b2015-04-07 17:16:35 -0700845 modified_flash = true;
846
Elliott Hughes30694c92015-03-25 15:16:51 -0700847 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700848 bool success = erase_volume("/cache");
849 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
850 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700851}
852
Tao Bao862a4c12016-06-02 11:16:50 -0700853// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported.
854// Otherwise, it goes with BLKDISCARD (if device supports BLKDISCARDZEROES) or
855// BLKZEROOUT.
856static bool secure_wipe_partition(const std::string& partition) {
857 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
858 if (fd == -1) {
859 LOGE("failed to open \"%s\": %s\n", partition.c_str(), strerror(errno));
860 return false;
861 }
862
863 uint64_t range[2] = {0, 0};
864 if (ioctl(fd, BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
865 LOGE("failed to get partition size: %s\n", strerror(errno));
866 return false;
867 }
868 printf("Secure-wiping \"%s\" from %" PRIu64 " to %" PRIu64 ".\n",
869 partition.c_str(), range[0], range[1]);
870
871 printf("Trying BLKSECDISCARD...\t");
872 if (ioctl(fd, BLKSECDISCARD, &range) == -1) {
873 printf("failed: %s\n", strerror(errno));
874
875 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
876 unsigned int zeroes;
877 if (ioctl(fd, BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
878 printf("Trying BLKDISCARD...\t");
879 if (ioctl(fd, BLKDISCARD, &range) == -1) {
880 printf("failed: %s\n", strerror(errno));
881 return false;
882 }
883 } else {
884 printf("Trying BLKZEROOUT...\t");
885 if (ioctl(fd, BLKZEROOUT, &range) == -1) {
886 printf("failed: %s\n", strerror(errno));
887 return false;
888 }
889 }
890 }
891
892 printf("done\n");
893 return true;
894}
895
896// Brick the current device, with a secure wipe of all the partitions in
897// RECOVERY_BRICK.
898static bool brick_device() {
899 ui->SetBackground(RecoveryUI::ERASING);
900 ui->SetProgressType(RecoveryUI::INDETERMINATE);
901
902 std::string partition_list;
903 if (!android::base::ReadFileToString(RECOVERY_BRICK, &partition_list)) {
904 LOGE("failed to read \"%s\".\n", RECOVERY_BRICK);
905 return false;
906 }
907
908 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
909 for (const std::string& line : lines) {
910 std::string partition = android::base::Trim(line);
911 // Ignore '#' comment or empty lines.
912 if (android::base::StartsWith(partition, "#") || partition.empty()) {
913 continue;
914 }
915
916 // Proceed anyway even if it fails to wipe some partition.
917 secure_wipe_partition(partition);
918 }
919 return true;
920}
921
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700922static void choose_recovery_file(Device* device) {
Elliott Hughesc0491632015-05-06 12:40:05 -0700923 // "Back" + KEEP_LOG_COUNT * 2 + terminating nullptr entry
924 char* entries[1 + KEEP_LOG_COUNT * 2 + 1];
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700925 memset(entries, 0, sizeof(entries));
926
Tao Baobef39712015-05-04 18:50:27 -0700927 unsigned int n = 0;
Patrick Tjincd055ee2014-12-09 11:26:40 -0800928
Tianjie Xua54f75e2016-08-17 12:02:46 -0700929 if (has_cache) {
930 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
931 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
932 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
933 char* log_file;
934 int ret;
935 ret = (i == 0) ? asprintf(&log_file, "%s", LAST_LOG_FILE) :
936 asprintf(&log_file, "%s.%d", LAST_LOG_FILE, i);
937 if (ret == -1) {
938 // memory allocation failure - return early. Should never happen.
939 return;
940 }
941 if ((ensure_path_mounted(log_file) != 0) || (access(log_file, R_OK) == -1)) {
942 free(log_file);
943 } else {
944 entries[n++] = log_file;
945 }
Tao Baobef39712015-05-04 18:50:27 -0700946
Tianjie Xua54f75e2016-08-17 12:02:46 -0700947 char* kmsg_file;
948 ret = (i == 0) ? asprintf(&kmsg_file, "%s", LAST_KMSG_FILE) :
949 asprintf(&kmsg_file, "%s.%d", LAST_KMSG_FILE, i);
950 if (ret == -1) {
951 // memory allocation failure - return early. Should never happen.
952 return;
953 }
954 if ((ensure_path_mounted(kmsg_file) != 0) || (access(kmsg_file, R_OK) == -1)) {
955 free(kmsg_file);
956 } else {
957 entries[n++] = kmsg_file;
958 }
Tao Baobef39712015-05-04 18:50:27 -0700959 }
Tianjie Xua54f75e2016-08-17 12:02:46 -0700960 } else {
961 // If cache partition is not found, view /tmp/recovery.log instead.
962 ui->Print("No /cache partition found.\n");
963 if (access(TEMPORARY_LOG_FILE, R_OK) == -1) {
964 return;
965 } else{
966 entries[n++] = strdup(TEMPORARY_LOG_FILE);
Tao Baobef39712015-05-04 18:50:27 -0700967 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700968 }
969
Elliott Hughesc0491632015-05-06 12:40:05 -0700970 entries[n++] = strdup("Back");
971
Tao Baobef39712015-05-04 18:50:27 -0700972 const char* headers[] = { "Select file to view", nullptr };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700973
Elliott Hughes8de52072015-04-08 20:06:50 -0700974 while (true) {
Elliott Hughes30694c92015-03-25 15:16:51 -0700975 int chosen_item = get_menu_selection(headers, entries, 1, 0, device);
Elliott Hughesc0491632015-05-06 12:40:05 -0700976 if (strcmp(entries[chosen_item], "Back") == 0) break;
Elliott Hughes8de52072015-04-08 20:06:50 -0700977
Elliott Hughes8de52072015-04-08 20:06:50 -0700978 ui->ShowFile(entries[chosen_item]);
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700979 }
980
Tao Baobef39712015-05-04 18:50:27 -0700981 for (size_t i = 0; i < (sizeof(entries) / sizeof(*entries)); i++) {
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700982 free(entries[i]);
983 }
984}
985
Elliott Hughes498cda62016-04-14 16:49:04 -0700986static void run_graphics_test(Device* device) {
987 // Switch to graphics screen.
988 ui->ShowText(false);
989
990 ui->SetProgressType(RecoveryUI::INDETERMINATE);
991 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
992 sleep(1);
993
994 ui->SetBackground(RecoveryUI::ERROR);
995 sleep(1);
996
997 ui->SetBackground(RecoveryUI::NO_COMMAND);
998 sleep(1);
999
1000 ui->SetBackground(RecoveryUI::ERASING);
1001 sleep(1);
1002
1003 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
1004
1005 ui->SetProgressType(RecoveryUI::DETERMINATE);
1006 ui->ShowProgress(1.0, 10.0);
1007 float fraction = 0.0;
1008 for (size_t i = 0; i < 100; ++i) {
1009 fraction += .01;
1010 ui->SetProgress(fraction);
1011 usleep(100000);
1012 }
1013
1014 ui->ShowText(true);
1015}
1016
Tao Baocdcf28f2016-01-13 15:05:20 -08001017// How long (in seconds) we wait for the fuse-provided package file to
1018// appear, before timing out.
1019#define SDCARD_INSTALL_TIMEOUT 10
1020
Tao Bao145d8612015-03-25 15:51:15 -07001021static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -07001022 modified_flash = true;
1023
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001024 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
1025 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
1026 return INSTALL_ERROR;
1027 }
1028
1029 char* path = browse_directory(SDCARD_ROOT, device);
1030 if (path == NULL) {
Elliott Hughes018ed312015-04-08 16:51:36 -07001031 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +08001032 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001033 return INSTALL_ERROR;
1034 }
1035
1036 ui->Print("\n-- Install %s ...\n", path);
1037 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001038
Tao Baocdcf28f2016-01-13 15:05:20 -08001039 // We used to use fuse in a thread as opposed to a process. Since accessing
1040 // through fuse involves going from kernel to userspace to kernel, it leads
1041 // to deadlock when a page fault occurs. (Bug: 26313124)
1042 pid_t child;
1043 if ((child = fork()) == 0) {
1044 bool status = start_sdcard_fuse(path);
1045
1046 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
1047 }
1048
1049 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
1050 // process is ready.
1051 int result = INSTALL_ERROR;
1052 int status;
1053 bool waited = false;
1054 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
1055 if (waitpid(child, &status, WNOHANG) == -1) {
1056 result = INSTALL_ERROR;
1057 waited = true;
1058 break;
1059 }
1060
1061 struct stat sb;
1062 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
1063 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
1064 sleep(1);
1065 continue;
1066 } else {
1067 LOGE("Timed out waiting for the fuse-provided package.\n");
1068 result = INSTALL_ERROR;
1069 kill(child, SIGKILL);
1070 break;
1071 }
1072 }
1073
1074 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
Tianjie Xu16255832016-04-30 11:49:59 -07001075 TEMPORARY_INSTALL_FILE, false, 0/*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -08001076 break;
1077 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001078
Tao Baocdcf28f2016-01-13 15:05:20 -08001079 if (!waited) {
1080 // Calling stat() on this magic filename signals the fuse
1081 // filesystem to shut down.
1082 struct stat sb;
1083 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
1084
1085 waitpid(child, &status, 0);
1086 }
1087
1088 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1089 LOGE("Error exit from the fuse process: %d\n", WEXITSTATUS(status));
1090 }
1091
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001092 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -08001093 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001094}
1095
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001096// Return REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION
1097// means to take the default, which is to reboot or shutdown depending
1098// on if the --shutdown_after flag was passed to recovery.
1099static Device::BuiltinAction
Doug Zongker6c8553d2012-09-24 10:40:47 -07001100prompt_and_wait(Device* device, int status) {
Doug Zongkerf93d8162009-09-22 15:16:02 -07001101 for (;;) {
Tianjie Xuc14d95d2016-03-24 11:50:34 -07001102 finish_recovery();
Doug Zongker6c8553d2012-09-24 10:40:47 -07001103 switch (status) {
1104 case INSTALL_SUCCESS:
1105 case INSTALL_NONE:
1106 ui->SetBackground(RecoveryUI::NO_COMMAND);
1107 break;
1108
1109 case INSTALL_ERROR:
1110 case INSTALL_CORRUPT:
1111 ui->SetBackground(RecoveryUI::ERROR);
1112 break;
1113 }
Doug Zongker211aebc2011-10-28 15:13:10 -07001114 ui->SetProgressType(RecoveryUI::EMPTY);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001115
Elliott Hughes8fd86d72015-04-13 14:36:02 -07001116 int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), 0, 0, device);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001117
1118 // device-specific code may take some action here. It may
1119 // return one of the core actions handled in the switch
1120 // statement below.
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001121 Device::BuiltinAction chosen_action = device->InvokeMenuItem(chosen_item);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001122
Elliott Hughes30694c92015-03-25 15:16:51 -07001123 bool should_wipe_cache = false;
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001124 switch (chosen_action) {
1125 case Device::NO_ACTION:
1126 break;
1127
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001128 case Device::REBOOT:
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001129 case Device::SHUTDOWN:
1130 case Device::REBOOT_BOOTLOADER:
1131 return chosen_action;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001132
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001133 case Device::WIPE_DATA:
1134 wipe_data(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001135 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001136 break;
1137
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001138 case Device::WIPE_CACHE:
Elliott Hughes30694c92015-03-25 15:16:51 -07001139 wipe_cache(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001140 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001141 break;
1142
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001143 case Device::APPLY_ADB_SIDELOAD:
Elliott Hughesec283402015-04-10 10:01:53 -07001144 case Device::APPLY_SDCARD:
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001145 {
1146 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
1147 if (adb) {
Elliott Hughes30694c92015-03-25 15:16:51 -07001148 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001149 } else {
Elliott Hughes30694c92015-03-25 15:16:51 -07001150 status = apply_from_sdcard(device, &should_wipe_cache);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001151 }
Doug Zongker945fc682014-07-10 10:50:39 -07001152
Elliott Hughes30694c92015-03-25 15:16:51 -07001153 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001154 if (!wipe_cache(false, device)) {
1155 status = INSTALL_ERROR;
1156 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001157 }
1158
Tao Baoc679f932015-03-30 09:43:49 -07001159 if (status != INSTALL_SUCCESS) {
1160 ui->SetBackground(RecoveryUI::ERROR);
1161 ui->Print("Installation aborted.\n");
1162 copy_logs();
1163 } else if (!ui->IsTextVisible()) {
1164 return Device::NO_ACTION; // reboot if logs aren't visible
1165 } else {
1166 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
Doug Zongker8674a722010-09-15 11:08:23 -07001167 }
Doug Zongkerf93d8162009-09-22 15:16:02 -07001168 }
1169 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001170
Elliott Hughesec283402015-04-10 10:01:53 -07001171 case Device::VIEW_RECOVERY_LOGS:
1172 choose_recovery_file(device);
Michael Ward9d2629c2011-06-23 22:14:24 -07001173 break;
Doug Zongker9270a202012-01-09 15:16:13 -08001174
Elliott Hughes498cda62016-04-14 16:49:04 -07001175 case Device::RUN_GRAPHICS_TEST:
1176 run_graphics_test(device);
1177 break;
1178
Elliott Hughesec283402015-04-10 10:01:53 -07001179 case Device::MOUNT_SYSTEM:
Tao Baoabb8f772015-07-30 14:43:27 -07001180 char system_root_image[PROPERTY_VALUE_MAX];
1181 property_get("ro.build.system_root_image", system_root_image, "");
1182
1183 // For a system image built with the root directory (i.e.
1184 // system_root_image == "true"), we mount it to /system_root, and symlink /system
1185 // to /system_root/system to make adb shell work (the symlink is created through
1186 // the build system).
1187 // Bug: 22855115
1188 if (strcmp(system_root_image, "true") == 0) {
1189 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1190 ui->Print("Mounted /system.\n");
1191 }
1192 } else {
1193 if (ensure_path_mounted("/system") != -1) {
1194 ui->Print("Mounted /system.\n");
1195 }
Elliott Hughesec283402015-04-10 10:01:53 -07001196 }
Tao Baoabb8f772015-07-30 14:43:27 -07001197
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001198 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001199 }
1200 }
1201}
1202
1203static void
Oscar Montemayor05231562009-11-30 08:40:57 -08001204print_property(const char *key, const char *name, void *cookie) {
Doug Zongker56c51052010-07-01 09:18:44 -07001205 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001206}
1207
Doug Zongker02ec6b82012-08-22 17:26:40 -07001208static void
1209load_locale_from_cache() {
1210 FILE* fp = fopen_path(LOCALE_FILE, "r");
1211 char buffer[80];
1212 if (fp != NULL) {
1213 fgets(buffer, sizeof(buffer), fp);
1214 int j = 0;
Doug Zongker5fa8c232012-09-18 12:37:02 -07001215 unsigned int i;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001216 for (i = 0; i < sizeof(buffer) && buffer[i]; ++i) {
1217 if (!isspace(buffer[i])) {
1218 buffer[j++] = buffer[i];
1219 }
1220 }
1221 buffer[j] = 0;
1222 locale = strdup(buffer);
Devin Kim6016d082012-10-08 09:47:37 -07001223 check_and_fclose(fp, LOCALE_FILE);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001224 }
1225}
1226
Doug Zongker7c3ae452013-05-14 11:03:02 -07001227static RecoveryUI* gCurrentUI = NULL;
1228
1229void
1230ui_print(const char* format, ...) {
1231 char buffer[256];
1232
1233 va_list ap;
1234 va_start(ap, format);
1235 vsnprintf(buffer, sizeof(buffer), format, ap);
1236 va_end(ap);
1237
1238 if (gCurrentUI != NULL) {
1239 gCurrentUI->Print("%s", buffer);
1240 } else {
1241 fputs(buffer, stdout);
1242 }
1243}
1244
Yabin Cui99281df2016-02-17 12:21:52 -08001245static bool is_battery_ok() {
1246 struct healthd_config healthd_config = {
1247 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1248 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1249 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1250 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1251 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1252 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1253 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1254 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1255 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1256 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1257 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1258 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1259 .energyCounter = NULL,
1260 .boot_min_cap = 0,
1261 .screen_on = NULL
1262 };
1263 healthd_board_init(&healthd_config);
1264
1265 android::BatteryMonitor monitor;
1266 monitor.init(&healthd_config);
1267
1268 int wait_second = 0;
1269 while (true) {
1270 int charge_status = monitor.getChargeStatus();
1271 // Treat unknown status as charged.
1272 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1273 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1274 android::BatteryProperty capacity;
1275 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1276 ui_print("charge_status %d, charged %d, status %d, capacity %lld\n", charge_status,
1277 charged, status, capacity.valueInt64);
1278 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1279 // the battery profile. Before the load finishes, it reports value 50 as a fake
1280 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1281 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1282 if (status == 0 && capacity.valueInt64 == 50) {
1283 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1284 sleep(1);
1285 wait_second++;
1286 continue;
1287 }
1288 }
1289 // If we can't read battery percentage, it may be a device without battery. In this
1290 // situation, use 100 as a fake battery percentage.
1291 if (status != 0) {
1292 capacity.valueInt64 = 100;
1293 }
1294 return (charged && capacity.valueInt64 >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
1295 (!charged && capacity.valueInt64 >= BATTERY_OK_PERCENTAGE);
1296 }
1297}
1298
Tianjie Xu3c62b672016-02-05 18:25:58 -08001299static void set_retry_bootloader_message(int retry_count, int argc, char** argv) {
1300 struct bootloader_message boot {};
1301 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
1302 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
1303
1304 for (int i = 1; i < argc; ++i) {
1305 if (strstr(argv[i], "retry_count") == nullptr) {
1306 strlcat(boot.recovery, argv[i], sizeof(boot.recovery));
1307 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
1308 }
1309 }
1310
1311 // Initialize counter to 1 if it's not in BCB, otherwise increment it by 1.
1312 if (retry_count == 0) {
1313 strlcat(boot.recovery, "--retry_count=1\n", sizeof(boot.recovery));
1314 } else {
1315 char buffer[20];
1316 snprintf(buffer, sizeof(buffer), "--retry_count=%d\n", retry_count+1);
1317 strlcat(boot.recovery, buffer, sizeof(boot.recovery));
1318 }
1319 set_bootloader_message(&boot);
1320}
1321
Mark Salyzyna4f701a2016-03-09 14:58:16 -08001322static ssize_t logbasename(
1323 log_id_t /* logId */,
1324 char /* prio */,
1325 const char *filename,
1326 const char * /* buf */, size_t len,
1327 void *arg) {
1328 if (strstr(LAST_KMSG_FILE, filename) ||
1329 strstr(LAST_LOG_FILE, filename)) {
1330 bool *doRotate = reinterpret_cast<bool *>(arg);
1331 *doRotate = true;
1332 }
1333 return len;
1334}
1335
1336static ssize_t logrotate(
1337 log_id_t logId,
1338 char prio,
1339 const char *filename,
1340 const char *buf, size_t len,
1341 void *arg) {
1342 bool *doRotate = reinterpret_cast<bool *>(arg);
1343 if (!*doRotate) {
1344 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1345 }
1346
1347 std::string name(filename);
Chih-Hung Hsieh23abfd32016-07-27 10:19:47 -07001348 size_t dot = name.find_last_of('.');
Mark Salyzyna4f701a2016-03-09 14:58:16 -08001349 std::string sub = name.substr(0, dot);
1350
1351 if (!strstr(LAST_KMSG_FILE, sub.c_str()) &&
1352 !strstr(LAST_LOG_FILE, sub.c_str())) {
1353 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1354 }
1355
1356 // filename rotation
1357 if (dot == std::string::npos) {
1358 name += ".1";
1359 } else {
1360 std::string number = name.substr(dot + 1);
1361 if (!isdigit(number.data()[0])) {
1362 name += ".1";
1363 } else {
Chih-Hung Hsieh54a27472016-04-18 11:30:55 -07001364 auto i = std::stoull(number);
Mark Salyzyna4f701a2016-03-09 14:58:16 -08001365 name = sub + "." + std::to_string(i + 1);
1366 }
1367 }
1368
1369 return __android_log_pmsg_file_write(logId, prio, name.c_str(), buf, len);
1370}
1371
Yabin Cui99281df2016-02-17 12:21:52 -08001372int main(int argc, char **argv) {
Mark Salyzyna4f701a2016-03-09 14:58:16 -08001373 // Take last pmsg contents and rewrite it to the current pmsg session.
1374 static const char filter[] = "recovery/";
1375 // Do we need to rotate?
1376 bool doRotate = false;
1377 __android_log_pmsg_file_read(
1378 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1379 logbasename, &doRotate);
1380 // Take action to refresh pmsg contents
1381 __android_log_pmsg_file_read(
1382 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1383 logrotate, &doRotate);
1384
Doug Zongker9270a202012-01-09 15:16:13 -08001385 // If this binary is started with the single argument "--adbd",
1386 // instead of being the normal recovery binary, it turns into kind
1387 // of a stripped-down version of adbd that only supports the
1388 // 'sideload' command. Note this must be a real argument, not
1389 // anything in the command file or bootloader control block; the
1390 // only way recovery should be run with this argument is when it
1391 // starts a copy of itself from the apply_from_adb() function.
1392 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
Josh Gaoacb2a2f2016-08-26 18:24:34 -07001393 minadbd_main();
Doug Zongker9270a202012-01-09 15:16:13 -08001394 return 0;
1395 }
1396
Tao Bao04ca4262015-09-10 15:32:24 -07001397 time_t start = time(NULL);
1398
1399 // redirect_stdio should be called only in non-sideload mode. Otherwise
1400 // we may have two logger instances with different timestamps.
1401 redirect_stdio(TEMPORARY_LOG_FILE);
1402
Doug Zongker19a8e242014-01-21 09:25:41 -08001403 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001404
Doug Zongkerd4208f92010-09-20 12:16:13 -07001405 load_volume_table();
Tao Bao26112e52016-02-25 12:29:40 -08001406 has_cache = volume_for_path(CACHE_ROOT) != nullptr;
1407
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001408 get_args(&argc, &argv);
1409
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001410 const char *update_package = NULL;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001411 bool should_wipe_data = false;
Tao Baoc679f932015-03-30 09:43:49 -07001412 bool should_wipe_cache = false;
Tao Bao862a4c12016-06-02 11:16:50 -07001413 bool should_brick = false;
Tao Bao145d8612015-03-25 15:51:15 -07001414 bool show_text = false;
Tao Baoc679f932015-03-30 09:43:49 -07001415 bool sideload = false;
1416 bool sideload_auto_reboot = false;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001417 bool just_exit = false;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001418 bool shutdown_after = false;
Tianjie Xu3c62b672016-02-05 18:25:58 -08001419 int retry_count = 0;
Tianjie Xu35926c42016-04-28 18:06:26 -07001420 bool security_update = false;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001421
1422 int arg;
Tao Bao862a4c12016-06-02 11:16:50 -07001423 int option_index;
1424 while ((arg = getopt_long(argc, argv, "", OPTIONS, &option_index)) != -1) {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001425 switch (arg) {
Tianjie Xu3c62b672016-02-05 18:25:58 -08001426 case 'n': android::base::ParseInt(optarg, &retry_count, 0); break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001427 case 'u': update_package = optarg; break;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001428 case 'w': should_wipe_data = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001429 case 'c': should_wipe_cache = true; break;
Tao Bao145d8612015-03-25 15:51:15 -07001430 case 't': show_text = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001431 case 's': sideload = true; break;
1432 case 'a': sideload = true; sideload_auto_reboot = true; break;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001433 case 'x': just_exit = true; break;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001434 case 'l': locale = optarg; break;
Doug Zongkerc87bab12013-11-25 13:53:25 -08001435 case 'g': {
1436 if (stage == NULL || *stage == '\0') {
1437 char buffer[20] = "1/";
1438 strncat(buffer, optarg, sizeof(buffer)-3);
1439 stage = strdup(buffer);
1440 }
1441 break;
1442 }
Doug Zongkerb1d12632014-03-18 10:32:12 -07001443 case 'p': shutdown_after = true; break;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001444 case 'r': reason = optarg; break;
Tianjie Xu35926c42016-04-28 18:06:26 -07001445 case 'e': security_update = true; break;
Tao Bao862a4c12016-06-02 11:16:50 -07001446 case 0: {
1447 if (strcmp(OPTIONS[option_index].name, "brick") == 0) {
1448 should_brick = true;
1449 break;
1450 }
1451 break;
1452 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001453 case '?':
1454 LOGE("Invalid command argument\n");
1455 continue;
1456 }
1457 }
1458
Tao Bao26112e52016-02-25 12:29:40 -08001459 if (locale == nullptr && has_cache) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001460 load_locale_from_cache();
1461 }
1462 printf("locale is [%s]\n", locale);
Doug Zongker0d32f252014-02-13 15:07:56 -08001463 printf("stage is [%s]\n", stage);
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001464 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001465
1466 Device* device = make_device();
1467 ui = device->GetUI();
Doug Zongker7c3ae452013-05-14 11:03:02 -07001468 gCurrentUI = ui;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001469
Doug Zongker5fa8c232012-09-18 12:37:02 -07001470 ui->SetLocale(locale);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001471 ui->Init();
Tianjie Xu35926c42016-04-28 18:06:26 -07001472 // Set background string to "installing security update" for security update,
1473 // otherwise set it to "installing system update".
1474 ui->SetSystemUpdateText(security_update);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001475
1476 int st_cur, st_max;
1477 if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
1478 ui->SetStage(st_cur, st_max);
1479 }
1480
Doug Zongker02ec6b82012-08-22 17:26:40 -07001481 ui->SetBackground(RecoveryUI::NONE);
1482 if (show_text) ui->ShowText(true);
1483
Stephen Smalley779701d2012-02-09 14:13:23 -05001484 struct selinux_opt seopts[] = {
1485 { SELABEL_OPT_PATH, "/file_contexts" }
1486 };
1487
1488 sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
1489
1490 if (!sehandle) {
Doug Zongkerfafc85b2013-07-09 12:29:45 -07001491 ui->Print("Warning: No file_contexts\n");
Stephen Smalley779701d2012-02-09 14:13:23 -05001492 }
Stephen Smalley779701d2012-02-09 14:13:23 -05001493
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001494 device->StartRecovery();
Doug Zongkerefa1bab2010-02-01 15:59:12 -08001495
Doug Zongker56c51052010-07-01 09:18:44 -07001496 printf("Command:");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001497 for (arg = 0; arg < argc; arg++) {
Doug Zongker56c51052010-07-01 09:18:44 -07001498 printf(" \"%s\"", argv[arg]);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001499 }
Doug Zongker9b125b02010-09-22 12:01:37 -07001500 printf("\n");
1501
1502 if (update_package) {
1503 // For backwards compatibility on the cache partition only, if
1504 // we're given an old 'root' path "CACHE:foo", change it to
1505 // "/cache/foo".
1506 if (strncmp(update_package, "CACHE:", 6) == 0) {
1507 int len = strlen(update_package) + 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -07001508 char* modified_path = (char*)malloc(len);
Jeremy Compostella1b7d9b72015-07-29 17:17:03 +02001509 if (modified_path) {
1510 strlcpy(modified_path, "/cache/", len);
1511 strlcat(modified_path, update_package+6, len);
1512 printf("(replacing path \"%s\" with \"%s\")\n",
1513 update_package, modified_path);
1514 update_package = modified_path;
1515 }
1516 else
1517 printf("modified_path allocation failed\n");
Doug Zongker9b125b02010-09-22 12:01:37 -07001518 }
1519 }
1520 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001521
1522 property_list(print_property, NULL);
Doug Zongker56c51052010-07-01 09:18:44 -07001523 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001524
Elliott Hughesbb78d622015-04-09 20:51:08 -07001525 ui->Print("Supported API: %d\n", RECOVERY_API_VERSION);
1526
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001527 int status = INSTALL_SUCCESS;
1528
Doug Zongker540d57f2011-01-18 13:36:58 -08001529 if (update_package != NULL) {
Tao Bao56870012016-04-29 15:37:05 -07001530 // It's not entirely true that we will modify the flash. But we want
1531 // to log the update attempt since update_package is non-NULL.
1532 modified_flash = true;
1533
Yabin Cui99281df2016-02-17 12:21:52 -08001534 if (!is_battery_ok()) {
1535 ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
1536 BATTERY_OK_PERCENTAGE);
Tianjie Xu16255832016-04-30 11:49:59 -07001537 // Log the error code to last_install when installation skips due to
1538 // low battery.
1539 FILE* install_log = fopen_path(LAST_INSTALL_FILE, "w");
1540 if (install_log != nullptr) {
1541 fprintf(install_log, "%s\n", update_package);
1542 fprintf(install_log, "0\n");
1543 fprintf(install_log, "error: %d\n", kLowBattery);
1544 fclose(install_log);
1545 } else {
1546 LOGE("failed to open last_install: %s\n", strerror(errno));
1547 }
Yabin Cui99281df2016-02-17 12:21:52 -08001548 status = INSTALL_SKIPPED;
1549 } else {
1550 status = install_package(update_package, &should_wipe_cache,
Tianjie Xu16255832016-04-30 11:49:59 -07001551 TEMPORARY_INSTALL_FILE, true, retry_count);
Yabin Cui99281df2016-02-17 12:21:52 -08001552 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1553 wipe_cache(false, device);
1554 }
1555 if (status != INSTALL_SUCCESS) {
1556 ui->Print("Installation aborted.\n");
Tianjie Xu3c62b672016-02-05 18:25:58 -08001557 // When I/O error happens, reboot and retry installation EIO_RETRY_COUNT
1558 // times before we abandon this OTA update.
1559 if (status == INSTALL_RETRY && retry_count < EIO_RETRY_COUNT) {
1560 copy_logs();
1561 set_retry_bootloader_message(retry_count, argc, argv);
1562 // Print retry count on screen.
1563 ui->Print("Retry attempt %d\n", retry_count);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001564
Tianjie Xu3c62b672016-02-05 18:25:58 -08001565 // Reboot and retry the update
1566 int ret = property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
1567 if (ret < 0) {
1568 ui->Print("Reboot failed\n");
1569 } else {
1570 while (true) {
1571 pause();
1572 }
1573 }
1574 }
Yabin Cui99281df2016-02-17 12:21:52 -08001575 // If this is an eng or userdebug build, then automatically
1576 // turn the text display on if the script fails so the error
1577 // message is visible.
1578 if (is_ro_debuggable()) {
1579 ui->ShowText(true);
1580 }
Doug Zongker7c3ae452013-05-14 11:03:02 -07001581 }
1582 }
Tao Baoe39a9bc2015-03-31 12:19:05 -07001583 } else if (should_wipe_data) {
1584 if (!wipe_data(false, device)) {
1585 status = INSTALL_ERROR;
1586 }
Tao Baoc679f932015-03-30 09:43:49 -07001587 } else if (should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001588 if (!wipe_cache(false, device)) {
1589 status = INSTALL_ERROR;
1590 }
Tao Bao862a4c12016-06-02 11:16:50 -07001591 } else if (should_brick) {
1592 if (!brick_device()) {
1593 status = INSTALL_ERROR;
1594 }
Tao Baoc679f932015-03-30 09:43:49 -07001595 } else if (sideload) {
1596 // 'adb reboot sideload' acts the same as user presses key combinations
1597 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1598 // display will NOT be turned on by default. And it will reboot after
1599 // sideload finishes even if there are errors. Unless one turns on the
1600 // text display during the installation. This is to enable automated
1601 // testing.
1602 if (!sideload_auto_reboot) {
1603 ui->ShowText(true);
1604 }
1605 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
1606 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001607 if (!wipe_cache(false, device)) {
1608 status = INSTALL_ERROR;
1609 }
Tao Baoc679f932015-03-30 09:43:49 -07001610 }
1611 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1612 if (sideload_auto_reboot) {
1613 ui->Print("Rebooting automatically.\n");
1614 }
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001615 } else if (!just_exit) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001616 status = INSTALL_NONE; // No command specified
1617 ui->SetBackground(RecoveryUI::NO_COMMAND);
Tao Bao785d22c2015-05-04 09:34:29 -07001618
1619 // http://b/17489952
1620 // If this is an eng or userdebug build, automatically turn on the
1621 // text display if no command is specified.
1622 if (is_ro_debuggable()) {
1623 ui->ShowText(true);
1624 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001625 }
1626
Tao Baoc679f932015-03-30 09:43:49 -07001627 if (!sideload_auto_reboot && (status == INSTALL_ERROR || status == INSTALL_CORRUPT)) {
Doug Zongkerf24fd7e2013-07-02 11:43:25 -07001628 copy_logs();
Doug Zongker02ec6b82012-08-22 17:26:40 -07001629 ui->SetBackground(RecoveryUI::ERROR);
1630 }
Tao Baoc679f932015-03-30 09:43:49 -07001631
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001632 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
Yabin Cui99281df2016-02-17 12:21:52 -08001633 if ((status != INSTALL_SUCCESS && status != INSTALL_SKIPPED && !sideload_auto_reboot) ||
1634 ui->IsTextVisible()) {
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001635 Device::BuiltinAction temp = prompt_and_wait(device, status);
Tao Baoc679f932015-03-30 09:43:49 -07001636 if (temp != Device::NO_ACTION) {
1637 after = temp;
1638 }
Doug Zongker8674a722010-09-15 11:08:23 -07001639 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001640
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001641 // Save logs and clean up before rebooting or shutting down.
Tianjie Xuc14d95d2016-03-24 11:50:34 -07001642 finish_recovery();
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001643
1644 switch (after) {
1645 case Device::SHUTDOWN:
1646 ui->Print("Shutting down...\n");
1647 property_set(ANDROID_RB_PROPERTY, "shutdown,");
1648 break;
1649
1650 case Device::REBOOT_BOOTLOADER:
1651 ui->Print("Rebooting to bootloader...\n");
1652 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
1653 break;
1654
1655 default:
1656 ui->Print("Rebooting...\n");
1657 property_set(ANDROID_RB_PROPERTY, "reboot,");
1658 break;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001659 }
Tao Bao75238632015-05-27 14:46:17 -07001660 while (true) {
1661 pause();
1662 }
1663 // Should be unreachable.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001664 return EXIT_SUCCESS;
1665}