blob: 1f3091316ea82a80f205539fe319e3f4fa3939bc [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 Baob0838182016-06-02 11:16:50 -070022#include <inttypes.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080023#include <limits.h>
Tao Baob0838182016-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>
Ameya Thakur74e750e2016-08-15 13:16:03 -070034#include <sys/mount.h>
35#include <fs_mgr.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080036#include <time.h>
37#include <unistd.h>
38
Tao Bao04ca4262015-09-10 15:32:24 -070039#include <chrono>
Tao Baob0838182016-06-02 11:16:50 -070040#include <string>
41#include <vector>
Tao Bao04ca4262015-09-10 15:32:24 -070042
Tao Bao75238632015-05-27 14:46:17 -070043#include <adb.h>
Mark Salyzyn13aca592016-03-09 14:58:16 -080044#include <android/log.h> /* Android Log Priority Tags */
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/file.h>
Tianjie Xufa12b972016-02-05 18:25:58 -080046#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080047#include <android-base/stringprintf.h>
Tao Baob0838182016-06-02 11:16:50 -070048#include <android-base/strings.h>
Yabin Cui2f272c02016-06-24 18:22:02 -070049#include <bootloader_message/bootloader_message.h>
Tao Bao75238632015-05-27 14:46:17 -070050#include <cutils/android_reboot.h>
51#include <cutils/properties.h>
Mark Salyzyn13aca592016-03-09 14:58:16 -080052#include <log/logger.h> /* Android Log packet format */
53#include <private/android_logger.h> /* private pmsg functions */
Tao Baobef39712015-05-04 18:50:27 -070054
Yabin Cui99281df2016-02-17 12:21:52 -080055#include <healthd/BatteryMonitor.h>
56
Tao Bao75238632015-05-27 14:46:17 -070057#include "adb_install.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"
64#include "minui/minui.h"
65#include "minzip/DirUtil.h"
Yabin Cui6faf0262016-06-09 14:09:39 -070066#include "minzip/Zip.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080067#include "roots.h"
Doug Zongker28ce47c2011-10-28 10:33:05 -070068#include "ui.h"
Tao Baob0838182016-06-02 11:16:50 -070069#include "unique_fd.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070070#include "screen_ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080071
Ameya Thakur74e750e2016-08-15 13:16:03 -070072#define UFS_DEV_SDCARD_BLK_PATH "/dev/block/mmcblk0p1"
73
Stephen Smalley779701d2012-02-09 14:13:23 -050074struct selabel_handle *sehandle;
75
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080076static const struct option OPTIONS[] = {
Tao Baoc679f932015-03-30 09:43:49 -070077 { "send_intent", required_argument, NULL, 'i' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080078 { "update_package", required_argument, NULL, 'u' },
Tianjie Xufa12b972016-02-05 18:25:58 -080079 { "retry_count", required_argument, NULL, 'n' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080080 { "wipe_data", no_argument, NULL, 'w' },
81 { "wipe_cache", no_argument, NULL, 'c' },
Doug Zongker4bc98062010-09-03 11:00:13 -070082 { "show_text", no_argument, NULL, 't' },
Tao Baoc679f932015-03-30 09:43:49 -070083 { "sideload", no_argument, NULL, 's' },
84 { "sideload_auto_reboot", no_argument, NULL, 'a' },
Doug Zongkere5d5ac72012-04-12 11:01:22 -070085 { "just_exit", no_argument, NULL, 'x' },
Doug Zongker02ec6b82012-08-22 17:26:40 -070086 { "locale", required_argument, NULL, 'l' },
Doug Zongkerc87bab12013-11-25 13:53:25 -080087 { "stages", required_argument, NULL, 'g' },
Doug Zongkerb1d12632014-03-18 10:32:12 -070088 { "shutdown_after", no_argument, NULL, 'p' },
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -070089 { "reason", required_argument, NULL, 'r' },
Tianjie Xu35926c42016-04-28 18:06:26 -070090 { "security", no_argument, NULL, 'e'},
Tao Bao108ab212016-06-10 10:13:32 -070091 { "wipe_ab", no_argument, NULL, 0 },
Yabin Cui6faf0262016-06-09 14:09:39 -070092 { "wipe_package_size", required_argument, NULL, 0 },
Doug Zongker988500b2009-10-06 14:41:38 -070093 { NULL, 0, NULL, 0 },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080094};
95
Tianjie Xu27b9fc82016-07-11 14:04:08 -070096// More bootreasons can be found in "system/core/bootstat/bootstat.cpp".
97static const std::vector<std::string> bootreason_blacklist {
98 "kernel_panic",
99 "Panic",
100};
101
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700102static const char *CACHE_LOG_DIR = "/cache/recovery";
Doug Zongkerd4208f92010-09-20 12:16:13 -0700103static const char *COMMAND_FILE = "/cache/recovery/command";
104static const char *INTENT_FILE = "/cache/recovery/intent";
105static const char *LOG_FILE = "/cache/recovery/log";
Doug Zongkerd0181b82011-10-19 10:51:12 -0700106static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
Doug Zongker8b240cc2012-08-29 15:19:29 -0700107static const char *LOCALE_FILE = "/cache/recovery/last_locale";
Paul Lawrence661f8a62016-02-25 12:42:19 -0800108static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
109static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
Michael Ward9d2629c2011-06-23 22:14:24 -0700110static const char *CACHE_ROOT = "/cache";
Paul Lawrenced0db3372015-11-05 13:38:40 -0800111static const char *DATA_ROOT = "/data";
Doug Zongkerd4208f92010-09-20 12:16:13 -0700112static const char *SDCARD_ROOT = "/sdcard";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
Doug Zongkerd0181b82011-10-19 10:51:12 -0700114static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
Tao Baof0124322015-04-11 02:04:11 +0000115static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
Tao Baobef39712015-05-04 18:50:27 -0700116static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
117static const int KEEP_LOG_COUNT = 10;
Tianjie Xuc37c5c32016-06-23 16:52:17 -0700118// We will try to apply the update package 5 times at most in case of an I/O error.
119static const int EIO_RETRY_COUNT = 4;
Yabin Cui99281df2016-02-17 12:21:52 -0800120static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
121// GmsCore enters recovery mode to install package when having enough battery
122// percentage. Normally, the threshold is 40% without charger and 20% with charger.
123// So we should check battery with a slightly lower limitation.
124static const int BATTERY_OK_PERCENTAGE = 20;
125static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
Tao Bao108ab212016-06-10 10:13:32 -0700126constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700127
Doug Zongker211aebc2011-10-28 15:13:10 -0700128RecoveryUI* ui = NULL;
Elliott Hughes498cda62016-04-14 16:49:04 -0700129static const char* locale = "en_US";
Doug Zongkerc87bab12013-11-25 13:53:25 -0800130char* stage = NULL;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -0700131char* reason = NULL;
Tao Bao682c34b2015-04-07 17:16:35 -0700132bool modified_flash = false;
Tao Baoae6408d2016-02-25 12:29:40 -0800133static bool has_cache = false;
Doug Zongker211aebc2011-10-28 15:13:10 -0700134
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800135/*
136 * The recovery tool communicates with the main system through /cache files.
137 * /cache/recovery/command - INPUT - command line for tool, one arg per line
138 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
139 * /cache/recovery/intent - OUTPUT - intent that was passed in
140 *
141 * The arguments which may be supplied in the recovery.command file:
142 * --send_intent=anystring - write the text out to recovery.intent
Doug Zongkerd4208f92010-09-20 12:16:13 -0700143 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800144 * --wipe_data - erase user data (and cache), then reboot
145 * --wipe_cache - wipe cache (but not user data), then reboot
Oscar Montemayor05231562009-11-30 08:40:57 -0800146 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700147 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800148 *
149 * After completing, we remove /cache/recovery/command and reboot.
150 * Arguments may also be supplied in the bootloader control block (BCB).
151 * These important scenarios must be safely restartable at any point:
152 *
153 * FACTORY RESET
154 * 1. user selects "factory reset"
155 * 2. main system writes "--wipe_data" to /cache/recovery/command
156 * 3. main system reboots into recovery
157 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
158 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700159 * 5. erase_volume() reformats /data
160 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800161 * 7. finish_recovery() erases BCB
162 * -- after this, rebooting will restart the main system --
163 * 8. main() calls reboot() to boot main system
164 *
165 * OTA INSTALL
166 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700167 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800168 * 3. main system reboots into recovery
169 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
170 * -- after this, rebooting will attempt to reinstall the update --
171 * 5. install_package() attempts to install the update
172 * NOTE: the package install must itself be restartable from any point
173 * 6. finish_recovery() erases BCB
174 * -- after this, rebooting will (try to) restart the main system --
175 * 7. ** if install failed **
176 * 7a. prompt_and_wait() shows an error icon and waits for the user
177 * 7b; the user reboots (pulling the battery, etc) into the main system
178 * 8. main() calls maybe_install_firmware_update()
179 * ** if the update contained radio/hboot firmware **:
180 * 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
181 * -- after this, rebooting will reformat cache & restart main system --
182 * 8b. m_i_f_u() writes firmware image into raw cache partition
183 * 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
184 * -- after this, rebooting will attempt to reinstall firmware --
185 * 8d. bootloader tries to flash firmware
186 * 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
187 * -- after this, rebooting will reformat cache & restart main system --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700188 * 8f. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800189 * 8g. finish_recovery() erases BCB
190 * -- after this, rebooting will (try to) restart the main system --
191 * 9. main() calls reboot() to boot main system
192 */
193
194static const int MAX_ARG_LENGTH = 4096;
195static const int MAX_ARGS = 100;
196
Amit Blay5c81cc12016-07-03 23:01:38 +0300197#ifdef USE_MDTP
198
199#define MAX_CMD_LINE_LEN (2048)
200
201static int is_mdtp_activated()
202{
203 char cmdline[MAX_CMD_LINE_LEN];
204 char *ptr;
205 int fd;
206 int mdtp_activated = 0;
207
208 fd = open("/proc/cmdline", O_RDONLY);
209 if (fd >= 0) {
210 int n = read(fd, cmdline, sizeof(cmdline) - 1);
211 if (n < 0)
212 n = 0;
213 /* get rid of trailing newline, it happens */
214 if (n > 0 && cmdline[n-1] == '\n') n--;
215 cmdline[n] = 0;
216 close(fd);
217 } else {
218 cmdline[0] = 0;
219 }
220
221 /* Look for the string "mdtp" in kernel cmdline, indicating that MDTP is activated.*/
222 ptr = cmdline;
223 while (ptr && *ptr) {
224 char *x = strchr(ptr, ' ');
225 if (x != 0)
226 *x++ = 0;
227 if (!strcmp(ptr,"mdtp")) {
228 mdtp_activated = 1;
229 break;
230 }
231
232 ptr = x;
233 }
234
235 return mdtp_activated;
236}
237#endif /* USE_MDTP */
238
Doug Zongkerd4208f92010-09-20 12:16:13 -0700239// open a given path, mounting partitions as necessary
Tao Bao04ca4262015-09-10 15:32:24 -0700240FILE* fopen_path(const char *path, const char *mode) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700241 if (ensure_path_mounted(path) != 0) {
242 LOGE("Can't mount %s\n", path);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800243 return NULL;
244 }
245
246 // When writing, try to create the containing directory, if necessary.
247 // Use generous permissions, the system (init.rc) will reset them.
Stephen Smalley779701d2012-02-09 14:13:23 -0500248 if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1, sehandle);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800249
250 FILE *fp = fopen(path, mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800251 return fp;
252}
253
Tao Bao04ca4262015-09-10 15:32:24 -0700254// close a file, log an error if the error indicator is set
255static void check_and_fclose(FILE *fp, const char *name) {
256 fflush(fp);
257 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
258 fclose(fp);
259}
260
Elliott Hughesf14af802015-02-10 14:46:14 -0800261bool is_ro_debuggable() {
262 char value[PROPERTY_VALUE_MAX+1];
263 return (property_get("ro.debuggable", value, NULL) == 1 && value[0] == '1');
264}
265
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700266static void redirect_stdio(const char* filename) {
Tao Bao04ca4262015-09-10 15:32:24 -0700267 int pipefd[2];
268 if (pipe(pipefd) == -1) {
269 LOGE("pipe failed: %s\n", strerror(errno));
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700270
Tao Bao04ca4262015-09-10 15:32:24 -0700271 // Fall back to traditional logging mode without timestamps.
272 // If these fail, there's not really anywhere to complain...
273 freopen(filename, "a", stdout); setbuf(stdout, NULL);
274 freopen(filename, "a", stderr); setbuf(stderr, NULL);
275
276 return;
277 }
278
279 pid_t pid = fork();
280 if (pid == -1) {
281 LOGE("fork failed: %s\n", strerror(errno));
282
283 // Fall back to traditional logging mode without timestamps.
284 // If these fail, there's not really anywhere to complain...
285 freopen(filename, "a", stdout); setbuf(stdout, NULL);
286 freopen(filename, "a", stderr); setbuf(stderr, NULL);
287
288 return;
289 }
290
291 if (pid == 0) {
292 /// Close the unused write end.
293 close(pipefd[1]);
294
295 auto start = std::chrono::steady_clock::now();
296
297 // Child logger to actually write to the log file.
298 FILE* log_fp = fopen(filename, "a");
299 if (log_fp == nullptr) {
300 LOGE("fopen \"%s\" failed: %s\n", filename, strerror(errno));
301 close(pipefd[0]);
302 _exit(1);
303 }
304
305 FILE* pipe_fp = fdopen(pipefd[0], "r");
306 if (pipe_fp == nullptr) {
307 LOGE("fdopen failed: %s\n", strerror(errno));
308 check_and_fclose(log_fp, filename);
309 close(pipefd[0]);
310 _exit(1);
311 }
312
313 char* line = nullptr;
314 size_t len = 0;
315 while (getline(&line, &len, pipe_fp) != -1) {
316 auto now = std::chrono::steady_clock::now();
317 double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
318 now - start).count();
319 if (line[0] == '\n') {
320 fprintf(log_fp, "[%12.6lf]\n", duration);
321 } else {
322 fprintf(log_fp, "[%12.6lf] %s", duration, line);
323 }
324 fflush(log_fp);
325 }
326
327 LOGE("getline failed: %s\n", strerror(errno));
328
329 free(line);
330 check_and_fclose(log_fp, filename);
331 close(pipefd[0]);
332 _exit(1);
333 } else {
334 // Redirect stdout/stderr to the logger process.
335 // Close the unused read end.
336 close(pipefd[0]);
337
338 setbuf(stdout, nullptr);
339 setbuf(stderr, nullptr);
340
341 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
342 LOGE("dup2 stdout failed: %s\n", strerror(errno));
343 }
344 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
345 LOGE("dup2 stderr failed: %s\n", strerror(errno));
346 }
347
348 close(pipefd[1]);
349 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800350}
351
352// command line args come from, in decreasing precedence:
353// - the actual command line
354// - the bootloader control block (one per line, after "recovery")
355// - the contents of COMMAND_FILE (one per line)
356static void
357get_args(int *argc, char ***argv) {
Yabin Cui2f272c02016-06-24 18:22:02 -0700358 bootloader_message boot = {};
359 std::string err;
360 if (!read_bootloader_message(&boot, &err)) {
361 LOGE("%s\n", err.c_str());
362 // If fails, leave a zeroed bootloader_message.
363 memset(&boot, 0, sizeof(boot));
364 }
Doug Zongkerc87bab12013-11-25 13:53:25 -0800365 stage = strndup(boot.stage, sizeof(boot.stage));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800366
367 if (boot.command[0] != 0 && boot.command[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700368 LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800369 }
370
371 if (boot.status[0] != 0 && boot.status[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700372 LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800373 }
374
375 // --- if arguments weren't supplied, look in the bootloader control block
376 if (*argc <= 1) {
377 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
378 const char *arg = strtok(boot.recovery, "\n");
379 if (arg != NULL && !strcmp(arg, "recovery")) {
380 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
381 (*argv)[0] = strdup(arg);
382 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
383 if ((arg = strtok(NULL, "\n")) == NULL) break;
384 (*argv)[*argc] = strdup(arg);
385 }
386 LOGI("Got arguments from boot message\n");
387 } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
388 LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
389 }
390 }
391
Tao Baoae6408d2016-02-25 12:29:40 -0800392 // --- if that doesn't work, try the command file (if we have /cache).
393 if (*argc <= 1 && has_cache) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700394 FILE *fp = fopen_path(COMMAND_FILE, "r");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800395 if (fp != NULL) {
Jin Feng93ffa752013-06-04 17:46:24 +0800396 char *token;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800397 char *argv0 = (*argv)[0];
398 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
399 (*argv)[0] = argv0; // use the same program name
400
401 char buf[MAX_ARG_LENGTH];
402 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
403 if (!fgets(buf, sizeof(buf), fp)) break;
Jin Feng93ffa752013-06-04 17:46:24 +0800404 token = strtok(buf, "\r\n");
405 if (token != NULL) {
406 (*argv)[*argc] = strdup(token); // Strip newline.
407 } else {
408 --*argc;
409 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800410 }
411
412 check_and_fclose(fp, COMMAND_FILE);
413 LOGI("Got arguments from %s\n", COMMAND_FILE);
414 }
415 }
416
417 // --> write the arguments we have back into the bootloader control block
418 // always boot into recovery after this (until finish_recovery() is called)
419 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
420 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
421 int i;
422 for (i = 1; i < *argc; ++i) {
423 strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
424 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
425 }
Yabin Cui2f272c02016-06-24 18:22:02 -0700426 if (!write_bootloader_message(boot, &err)) {
427 LOGE("%s\n", err.c_str());
428 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800429}
430
Doug Zongker34c98df2009-08-18 12:05:45 -0700431static void
Oscar Montemayor05231562009-11-30 08:40:57 -0800432set_sdcard_update_bootloader_message() {
Yabin Cui2f272c02016-06-24 18:22:02 -0700433 bootloader_message boot = {};
Doug Zongker34c98df2009-08-18 12:05:45 -0700434 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
435 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
Yabin Cui2f272c02016-06-24 18:22:02 -0700436 std::string err;
437 if (!write_bootloader_message(boot, &err)) {
438 LOGE("%s\n", err.c_str());
439 }
Doug Zongker34c98df2009-08-18 12:05:45 -0700440}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800441
Tao Baobef39712015-05-04 18:50:27 -0700442// Read from kernel log into buffer and write out to file.
443static void save_kernel_log(const char* destination) {
444 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800445 if (klog_buf_len <= 0) {
Tao Baobef39712015-05-04 18:50:27 -0700446 LOGE("Error getting klog size: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800447 return;
448 }
449
Tao Baobef39712015-05-04 18:50:27 -0700450 std::string buffer(klog_buf_len, 0);
451 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
452 if (n == -1) {
453 LOGE("Error in reading klog: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800454 return;
455 }
Tao Baobef39712015-05-04 18:50:27 -0700456 buffer.resize(n);
457 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800458}
459
Mark Salyzyn13aca592016-03-09 14:58:16 -0800460// write content to the current pmsg session.
461static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
462 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
463 filename, buf, len);
464}
465
466static void copy_log_file_to_pmsg(const char* source, const char* destination) {
467 std::string content;
468 android::base::ReadFileToString(source, &content);
469 __pmsg_write(destination, content.c_str(), content.length());
470}
471
Tao Baof0124322015-04-11 02:04:11 +0000472// How much of the temp log we have copied to the copy in cache.
473static long tmplog_offset = 0;
474
Tao Baobef39712015-05-04 18:50:27 -0700475static void copy_log_file(const char* source, const char* destination, bool append) {
476 FILE* dest_fp = fopen_path(destination, append ? "a" : "w");
477 if (dest_fp == nullptr) {
Doug Zongker2c3539e2010-09-29 13:21:30 -0700478 LOGE("Can't open %s\n", destination);
479 } else {
Tao Baobef39712015-05-04 18:50:27 -0700480 FILE* source_fp = fopen(source, "r");
481 if (source_fp != nullptr) {
Tao Baof0124322015-04-11 02:04:11 +0000482 if (append) {
Tao Baobef39712015-05-04 18:50:27 -0700483 fseek(source_fp, tmplog_offset, SEEK_SET); // Since last write
Doug Zongker2c3539e2010-09-29 13:21:30 -0700484 }
485 char buf[4096];
Tao Baobef39712015-05-04 18:50:27 -0700486 size_t bytes;
487 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
488 fwrite(buf, 1, bytes, dest_fp);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700489 }
Tao Baobef39712015-05-04 18:50:27 -0700490 if (append) {
491 tmplog_offset = ftell(source_fp);
492 }
493 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700494 }
Tao Baobef39712015-05-04 18:50:27 -0700495 check_and_fclose(dest_fp, destination);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700496 }
497}
498
Tao Baobef39712015-05-04 18:50:27 -0700499// Rename last_log -> last_log.1 -> last_log.2 -> ... -> last_log.$max.
500// Similarly rename last_kmsg -> last_kmsg.1 -> ... -> last_kmsg.$max.
501// Overwrite any existing last_log.$max and last_kmsg.$max.
502static void rotate_logs(int max) {
Tao Bao682c34b2015-04-07 17:16:35 -0700503 // Logs should only be rotated once.
504 static bool rotated = false;
505 if (rotated) {
506 return;
507 }
508 rotated = true;
509 ensure_path_mounted(LAST_LOG_FILE);
Tao Baobef39712015-05-04 18:50:27 -0700510 ensure_path_mounted(LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700511
Tao Bao682c34b2015-04-07 17:16:35 -0700512 for (int i = max-1; i >= 0; --i) {
Tao Bao80e46e02015-06-03 10:49:29 -0700513 std::string old_log = android::base::StringPrintf("%s", LAST_LOG_FILE);
514 if (i > 0) {
515 old_log += "." + std::to_string(i);
516 }
Tao Baobef39712015-05-04 18:50:27 -0700517 std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
518 // Ignore errors if old_log doesn't exist.
519 rename(old_log.c_str(), new_log.c_str());
520
Tao Bao80e46e02015-06-03 10:49:29 -0700521 std::string old_kmsg = android::base::StringPrintf("%s", LAST_KMSG_FILE);
522 if (i > 0) {
523 old_kmsg += "." + std::to_string(i);
524 }
Tao Baobef39712015-05-04 18:50:27 -0700525 std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
526 rename(old_kmsg.c_str(), new_kmsg.c_str());
Doug Zongkerda1ebae2013-05-16 11:23:48 -0700527 }
528}
Doug Zongker2c3539e2010-09-29 13:21:30 -0700529
Tao Bao682c34b2015-04-07 17:16:35 -0700530static void copy_logs() {
531 // We only rotate and record the log of the current session if there are
532 // actual attempts to modify the flash, such as wipes, installs from BCB
533 // or menu selections. This is to avoid unnecessary rotation (and
534 // possible deletion) of log files, if it does not do anything loggable.
535 if (!modified_flash) {
536 return;
537 }
538
Mark Salyzyn13aca592016-03-09 14:58:16 -0800539 // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
540 copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
541 copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
542
543 // We can do nothing for now if there's no /cache partition.
544 if (!has_cache) {
545 return;
546 }
547
Tao Baobef39712015-05-04 18:50:27 -0700548 rotate_logs(KEEP_LOG_COUNT);
Tao Bao682c34b2015-04-07 17:16:35 -0700549
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700550 // Copy logs to cache so the system can find out what happened.
Tao Baof0124322015-04-11 02:04:11 +0000551 copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
552 copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
553 copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
554 save_kernel_log(LAST_KMSG_FILE);
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700555 chmod(LOG_FILE, 0600);
556 chown(LOG_FILE, 1000, 1000); // system user
Tao Baof0124322015-04-11 02:04:11 +0000557 chmod(LAST_KMSG_FILE, 0600);
558 chown(LAST_KMSG_FILE, 1000, 1000); // system user
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700559 chmod(LAST_LOG_FILE, 0640);
560 chmod(LAST_INSTALL_FILE, 0644);
561 sync();
562}
563
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800564// clear the recovery command and prepare to boot a (hopefully working) system,
565// copy our log file to cache as well (for the system to read), and
566// record any intent we were asked to communicate back to the system.
567// this function is idempotent: call it as many times as you like.
568static void
Oscar Montemayor05231562009-11-30 08:40:57 -0800569finish_recovery(const char *send_intent) {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800570 // By this point, we're ready to return to the main system...
Tao Baoae6408d2016-02-25 12:29:40 -0800571 if (send_intent != NULL && has_cache) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700572 FILE *fp = fopen_path(INTENT_FILE, "w");
Jay Freeman (saurik)619ec2f2008-11-17 01:56:05 +0000573 if (fp == NULL) {
574 LOGE("Can't open %s\n", INTENT_FILE);
575 } else {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800576 fputs(send_intent, fp);
577 check_and_fclose(fp, INTENT_FILE);
578 }
579 }
580
Doug Zongker4f33e552012-08-23 13:16:12 -0700581 // Save the locale to cache, so if recovery is next started up
582 // without a --locale argument (eg, directly from the bootloader)
583 // it will use the last-known locale.
Mark Salyzyn13aca592016-03-09 14:58:16 -0800584 if (locale != NULL) {
585 size_t len = strlen(locale);
586 __pmsg_write(LOCALE_FILE, locale, len);
587 if (has_cache) {
588 LOGI("Saving locale \"%s\"\n", locale);
589 FILE* fp = fopen_path(LOCALE_FILE, "w");
590 fwrite(locale, 1, len, fp);
591 fflush(fp);
592 fsync(fileno(fp));
593 check_and_fclose(fp, LOCALE_FILE);
594 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700595 }
596
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700597 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800598
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700599 // Reset to normal system boot so recovery won't cycle indefinitely.
Yabin Cui2f272c02016-06-24 18:22:02 -0700600 bootloader_message boot = {};
601 std::string err;
602 if (!write_bootloader_message(boot, &err)) {
603 LOGE("%s\n", err.c_str());
604 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800605
606 // Remove the command file, so recovery won't repeat indefinitely.
Tao Baoae6408d2016-02-25 12:29:40 -0800607 if (has_cache) {
608 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
609 LOGW("Can't unlink %s\n", COMMAND_FILE);
610 }
611 ensure_path_unmounted(CACHE_ROOT);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800612 }
613
614 sync(); // For good measure.
615}
616
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700617typedef struct _saved_log_file {
618 char* name;
619 struct stat st;
620 unsigned char* data;
621 struct _saved_log_file* next;
622} saved_log_file;
623
Elliott Hughes945548e2015-06-05 17:59:56 -0700624static bool erase_volume(const char* volume) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700625 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800626 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700627
Doug Zongker02ec6b82012-08-22 17:26:40 -0700628 ui->SetBackground(RecoveryUI::ERASING);
Doug Zongker211aebc2011-10-28 15:13:10 -0700629 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700630
631 saved_log_file* head = NULL;
632
633 if (is_cache) {
Tao Baobef39712015-05-04 18:50:27 -0700634 // If we're reformatting /cache, we load any past logs
635 // (i.e. "/cache/recovery/last_*") and the current log
636 // ("/cache/recovery/log") into memory, so we can restore them after
637 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700638
639 ensure_path_mounted(volume);
640
641 DIR* d;
642 struct dirent* de;
643 d = opendir(CACHE_LOG_DIR);
644 if (d) {
645 char path[PATH_MAX];
646 strcpy(path, CACHE_LOG_DIR);
647 strcat(path, "/");
648 int path_len = strlen(path);
649 while ((de = readdir(d)) != NULL) {
Tao Baobef39712015-05-04 18:50:27 -0700650 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700651 saved_log_file* p = (saved_log_file*) malloc(sizeof(saved_log_file));
652 strcpy(path+path_len, de->d_name);
653 p->name = strdup(path);
654 if (stat(path, &(p->st)) == 0) {
655 // truncate files to 512kb
656 if (p->st.st_size > (1 << 19)) {
657 p->st.st_size = 1 << 19;
658 }
659 p->data = (unsigned char*) malloc(p->st.st_size);
660 FILE* f = fopen(path, "rb");
661 fread(p->data, 1, p->st.st_size, f);
662 fclose(f);
663 p->next = head;
664 head = p;
665 } else {
666 free(p);
667 }
668 }
669 }
670 closedir(d);
671 } else {
672 if (errno != ENOENT) {
673 printf("opendir failed: %s\n", strerror(errno));
674 }
675 }
676 }
677
Doug Zongker211aebc2011-10-28 15:13:10 -0700678 ui->Print("Formatting %s...\n", volume);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700679
Doug Zongkerd0181b82011-10-19 10:51:12 -0700680 ensure_path_unmounted(volume);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800681
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
Paul Lawrence661f8a62016-02-25 12:42:19 -0800687 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
688 ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
689 return true;
690 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800691 FILE* f = fopen(CONVERT_FBE_FILE, "wb");
692 if (!f) {
Paul Lawrence661f8a62016-02-25 12:42:19 -0800693 ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
Paul Lawrenced0db3372015-11-05 13:38:40 -0800694 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 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700703
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700704 if (is_cache) {
705 while (head) {
706 FILE* f = fopen_path(head->name, "wb");
707 if (f) {
708 fwrite(head->data, 1, head->st.st_size, f);
709 fclose(f);
710 chmod(head->name, head->st.st_mode);
711 chown(head->name, head->st.st_uid, head->st.st_gid);
712 }
713 free(head->name);
714 free(head->data);
715 saved_log_file* temp = head->next;
716 free(head);
717 head = temp;
718 }
719
Tao Baof0124322015-04-11 02:04:11 +0000720 // Any part of the log we'd copied to cache is now gone.
721 // Reset the pointer so we copy from the beginning of the temp
722 // log.
723 tmplog_offset = 0;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700724 copy_logs();
Doug Zongker2c3539e2010-09-29 13:21:30 -0700725 }
726
Elliott Hughes945548e2015-06-05 17:59:56 -0700727 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800728}
729
Doug Zongkerf93d8162009-09-22 15:16:02 -0700730static int
Doug Zongker28ce47c2011-10-28 10:33:05 -0700731get_menu_selection(const char* const * headers, const char* const * items,
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700732 int menu_only, int initial_selection, Device* device) {
Doug Zongkerf93d8162009-09-22 15:16:02 -0700733 // throw away keys pressed previously, so user doesn't
734 // accidentally trigger menu items.
Doug Zongker211aebc2011-10-28 15:13:10 -0700735 ui->FlushKeys();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700736
Doug Zongker211aebc2011-10-28 15:13:10 -0700737 ui->StartMenu(headers, items, initial_selection);
Doug Zongker8674a722010-09-15 11:08:23 -0700738 int selected = initial_selection;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800739 int chosen_item = -1;
740
Doug Zongkerf93d8162009-09-22 15:16:02 -0700741 while (chosen_item < 0) {
Doug Zongker211aebc2011-10-28 15:13:10 -0700742 int key = ui->WaitKey();
743 int visible = ui->IsTextVisible();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800744
Doug Zongker5cae4452011-01-25 13:15:30 -0800745 if (key == -1) { // ui_wait_key() timed out
Doug Zongker211aebc2011-10-28 15:13:10 -0700746 if (ui->WasTextEverVisible()) {
Doug Zongker5cae4452011-01-25 13:15:30 -0800747 continue;
748 } else {
749 LOGI("timed out waiting for key input; rebooting.\n");
Doug Zongker211aebc2011-10-28 15:13:10 -0700750 ui->EndMenu();
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700751 return 0; // XXX fixme
Doug Zongker5cae4452011-01-25 13:15:30 -0800752 }
753 }
754
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700755 int action = device->HandleMenuKey(key, visible);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700756
757 if (action < 0) {
758 switch (action) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700759 case Device::kHighlightUp:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700760 selected = ui->SelectMenu(--selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700761 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700762 case Device::kHighlightDown:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700763 selected = ui->SelectMenu(++selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700764 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700765 case Device::kInvokeItem:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700766 chosen_item = selected;
767 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700768 case Device::kNoAction:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700769 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800770 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700771 } else if (!menu_only) {
Doug Zongkerddd6a282009-06-09 12:22:33 -0700772 chosen_item = action;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800773 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700774 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800775
Doug Zongker211aebc2011-10-28 15:13:10 -0700776 ui->EndMenu();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700777 return chosen_item;
778}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800779
Doug Zongker8674a722010-09-15 11:08:23 -0700780static int compare_string(const void* a, const void* b) {
781 return strcmp(*(const char**)a, *(const char**)b);
782}
783
Doug Zongker93950222014-07-08 14:10:23 -0700784// Returns a malloc'd path, or NULL.
Elliott Hughes30694c92015-03-25 15:16:51 -0700785static char* browse_directory(const char* path, Device* device) {
Michael Ward9d2629c2011-06-23 22:14:24 -0700786 ensure_path_mounted(path);
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700787
Elliott Hughes30694c92015-03-25 15:16:51 -0700788 DIR* d = opendir(path);
Doug Zongker8674a722010-09-15 11:08:23 -0700789 if (d == NULL) {
790 LOGE("error opening %s: %s\n", path, strerror(errno));
Doug Zongker93950222014-07-08 14:10:23 -0700791 return NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700792 }
793
Doug Zongker8674a722010-09-15 11:08:23 -0700794 int d_size = 0;
795 int d_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700796 char** dirs = (char**)malloc(d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700797 int z_size = 1;
798 int z_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700799 char** zips = (char**)malloc(z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700800 zips[0] = strdup("../");
801
Elliott Hughes30694c92015-03-25 15:16:51 -0700802 struct dirent* de;
Doug Zongker8674a722010-09-15 11:08:23 -0700803 while ((de = readdir(d)) != NULL) {
804 int name_len = strlen(de->d_name);
805
806 if (de->d_type == DT_DIR) {
807 // skip "." and ".." entries
808 if (name_len == 1 && de->d_name[0] == '.') continue;
809 if (name_len == 2 && de->d_name[0] == '.' &&
810 de->d_name[1] == '.') continue;
811
812 if (d_size >= d_alloc) {
813 d_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700814 dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700815 }
Doug Zongker28ce47c2011-10-28 10:33:05 -0700816 dirs[d_size] = (char*)malloc(name_len + 2);
Doug Zongker8674a722010-09-15 11:08:23 -0700817 strcpy(dirs[d_size], de->d_name);
818 dirs[d_size][name_len] = '/';
819 dirs[d_size][name_len+1] = '\0';
820 ++d_size;
821 } else if (de->d_type == DT_REG &&
822 name_len >= 4 &&
823 strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
824 if (z_size >= z_alloc) {
825 z_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700826 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700827 }
828 zips[z_size++] = strdup(de->d_name);
829 }
830 }
831 closedir(d);
832
833 qsort(dirs, d_size, sizeof(char*), compare_string);
834 qsort(zips, z_size, sizeof(char*), compare_string);
835
836 // append dirs to the zips list
837 if (d_size + z_size + 1 > z_alloc) {
838 z_alloc = d_size + z_size + 1;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700839 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700840 }
841 memcpy(zips + z_size, dirs, d_size * sizeof(char*));
842 free(dirs);
843 z_size += d_size;
844 zips[z_size] = NULL;
845
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700846 const char* headers[] = { "Choose a package to install:", path, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700847
Doug Zongker93950222014-07-08 14:10:23 -0700848 char* result;
Doug Zongker8674a722010-09-15 11:08:23 -0700849 int chosen_item = 0;
Doug Zongker93950222014-07-08 14:10:23 -0700850 while (true) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700851 chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
Doug Zongker8674a722010-09-15 11:08:23 -0700852
853 char* item = zips[chosen_item];
854 int item_len = strlen(item);
855 if (chosen_item == 0) { // item 0 is always "../"
Michael Ward9d2629c2011-06-23 22:14:24 -0700856 // go up but continue browsing (if the caller is update_directory)
Doug Zongker93950222014-07-08 14:10:23 -0700857 result = NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700858 break;
859 }
Doug Zongker93950222014-07-08 14:10:23 -0700860
861 char new_path[PATH_MAX];
862 strlcpy(new_path, path, PATH_MAX);
863 strlcat(new_path, "/", PATH_MAX);
864 strlcat(new_path, item, PATH_MAX);
865
866 if (item[item_len-1] == '/') {
867 // recurse down into a subdirectory
868 new_path[strlen(new_path)-1] = '\0'; // truncate the trailing '/'
869 result = browse_directory(new_path, device);
870 if (result) break;
871 } else {
872 // selected a zip file: return the malloc'd path to the caller.
873 result = strdup(new_path);
874 break;
875 }
876 }
Doug Zongker8674a722010-09-15 11:08:23 -0700877
Elliott Hughes30694c92015-03-25 15:16:51 -0700878 for (int i = 0; i < z_size; ++i) free(zips[i]);
Doug Zongker8674a722010-09-15 11:08:23 -0700879 free(zips);
Doug Zongker8674a722010-09-15 11:08:23 -0700880
881 return result;
882}
883
Elliott Hughes30694c92015-03-25 15:16:51 -0700884static bool yes_no(Device* device, const char* question1, const char* question2) {
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700885 const char* headers[] = { question1, question2, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700886 const char* items[] = { " No", " Yes", NULL };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700887
Elliott Hughes30694c92015-03-25 15:16:51 -0700888 int chosen_item = get_menu_selection(headers, items, 1, 0, device);
889 return (chosen_item == 1);
890}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800891
Tao Baoe39a9bc2015-03-31 12:19:05 -0700892// Return true on success.
893static bool wipe_data(int should_confirm, Device* device) {
894 if (should_confirm && !yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!")) {
895 return false;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700896 }
Doug Zongker1066d2c2009-04-01 13:57:40 -0700897
Tao Bao682c34b2015-04-07 17:16:35 -0700898 modified_flash = true;
899
Doug Zongker211aebc2011-10-28 15:13:10 -0700900 ui->Print("\n-- Wiping data...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700901 bool success =
902 device->PreWipeData() &&
903 erase_volume("/data") &&
Tao Baoae6408d2016-02-25 12:29:40 -0800904 (has_cache ? erase_volume("/cache") : true) &&
Elliott Hughes945548e2015-06-05 17:59:56 -0700905 device->PostWipeData();
906 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
907 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700908}
909
Tao Baoe39a9bc2015-03-31 12:19:05 -0700910// Return true on success.
911static bool wipe_cache(bool should_confirm, Device* device) {
Tao Baoae6408d2016-02-25 12:29:40 -0800912 if (!has_cache) {
913 ui->Print("No /cache partition found.\n");
914 return false;
915 }
916
Elliott Hughes30694c92015-03-25 15:16:51 -0700917 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700918 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700919 }
920
Tao Bao682c34b2015-04-07 17:16:35 -0700921 modified_flash = true;
922
Elliott Hughes30694c92015-03-25 15:16:51 -0700923 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700924 bool success = erase_volume("/cache");
925 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
926 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700927}
928
Tao Baob0838182016-06-02 11:16:50 -0700929// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported.
930// Otherwise, it goes with BLKDISCARD (if device supports BLKDISCARDZEROES) or
931// BLKZEROOUT.
932static bool secure_wipe_partition(const std::string& partition) {
933 unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
934 if (fd.get() == -1) {
935 LOGE("failed to open \"%s\": %s\n", partition.c_str(), strerror(errno));
936 return false;
Tao Baoae6408d2016-02-25 12:29:40 -0800937 }
938
Tao Baob0838182016-06-02 11:16:50 -0700939 uint64_t range[2] = {0, 0};
940 if (ioctl(fd.get(), BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
941 LOGE("failed to get partition size: %s\n", strerror(errno));
942 return false;
943 }
944 printf("Secure-wiping \"%s\" from %" PRIu64 " to %" PRIu64 ".\n",
945 partition.c_str(), range[0], range[1]);
946
947 printf("Trying BLKSECDISCARD...\t");
948 if (ioctl(fd.get(), BLKSECDISCARD, &range) == -1) {
949 printf("failed: %s\n", strerror(errno));
950
951 // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
952 unsigned int zeroes;
953 if (ioctl(fd.get(), BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
954 printf("Trying BLKDISCARD...\t");
955 if (ioctl(fd.get(), BLKDISCARD, &range) == -1) {
956 printf("failed: %s\n", strerror(errno));
957 return false;
958 }
959 } else {
960 printf("Trying BLKZEROOUT...\t");
961 if (ioctl(fd.get(), BLKZEROOUT, &range) == -1) {
962 printf("failed: %s\n", strerror(errno));
963 return false;
964 }
965 }
966 }
967
968 printf("done\n");
969 return true;
970}
971
Yabin Cui6faf0262016-06-09 14:09:39 -0700972// Check if the wipe package matches expectation:
973// 1. verify the package.
974// 2. check metadata (ota-type, pre-device and serial number if having one).
975static bool check_wipe_package(size_t wipe_package_size) {
976 if (wipe_package_size == 0) {
977 LOGE("wipe_package_size is zero.\n");
978 return false;
979 }
980 std::string wipe_package;
Yabin Cui2f272c02016-06-24 18:22:02 -0700981 std::string err_str;
982 if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
983 LOGE("Failed to read wipe package: %s\n", err_str.c_str());
Yabin Cui6faf0262016-06-09 14:09:39 -0700984 return false;
985 }
986 if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
987 wipe_package.size())) {
988 LOGE("Failed to verify package.\n");
989 return false;
990 }
991
992 // Extract metadata
993 ZipArchive zip;
994 int err = mzOpenZipArchive(reinterpret_cast<unsigned char*>(&wipe_package[0]),
995 wipe_package.size(), &zip);
996 if (err != 0) {
997 LOGE("Can't open wipe package: %s\n", err != -1 ? strerror(err) : "bad");
998 return false;
999 }
1000 std::string metadata;
1001 if (!read_metadata_from_package(&zip, &metadata)) {
1002 mzCloseZipArchive(&zip);
1003 return false;
1004 }
1005 mzCloseZipArchive(&zip);
1006
1007 // Check metadata
1008 std::vector<std::string> lines = android::base::Split(metadata, "\n");
1009 bool ota_type_matched = false;
1010 bool device_type_matched = false;
1011 bool has_serial_number = false;
1012 bool serial_number_matched = false;
1013 for (const auto& line : lines) {
1014 if (line == "ota-type=BRICK") {
1015 ota_type_matched = true;
1016 } else if (android::base::StartsWith(line, "pre-device=")) {
1017 std::string device_type = line.substr(strlen("pre-device="));
1018 char real_device_type[PROPERTY_VALUE_MAX];
1019 property_get("ro.build.product", real_device_type, "");
1020 device_type_matched = (device_type == real_device_type);
1021 } else if (android::base::StartsWith(line, "serialno=")) {
1022 std::string serial_no = line.substr(strlen("serialno="));
1023 char real_serial_no[PROPERTY_VALUE_MAX];
1024 property_get("ro.serialno", real_serial_no, "");
1025 has_serial_number = true;
1026 serial_number_matched = (serial_no == real_serial_no);
1027 }
1028 }
1029 return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
1030}
1031
Tao Bao108ab212016-06-10 10:13:32 -07001032// Wipe the current A/B device, with a secure wipe of all the partitions in
1033// RECOVERY_WIPE.
Yabin Cui6faf0262016-06-09 14:09:39 -07001034static bool wipe_ab_device(size_t wipe_package_size) {
Tao Baob0838182016-06-02 11:16:50 -07001035 ui->SetBackground(RecoveryUI::ERASING);
1036 ui->SetProgressType(RecoveryUI::INDETERMINATE);
1037
Yabin Cui6faf0262016-06-09 14:09:39 -07001038 if (!check_wipe_package(wipe_package_size)) {
1039 LOGE("Failed to verify wipe package\n");
1040 return false;
1041 }
Tao Baob0838182016-06-02 11:16:50 -07001042 std::string partition_list;
Tao Bao108ab212016-06-10 10:13:32 -07001043 if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
1044 LOGE("failed to read \"%s\".\n", RECOVERY_WIPE);
Tao Baob0838182016-06-02 11:16:50 -07001045 return false;
1046 }
1047
1048 std::vector<std::string> lines = android::base::Split(partition_list, "\n");
1049 for (const std::string& line : lines) {
1050 std::string partition = android::base::Trim(line);
1051 // Ignore '#' comment or empty lines.
1052 if (android::base::StartsWith(partition, "#") || partition.empty()) {
1053 continue;
1054 }
1055
1056 // Proceed anyway even if it fails to wipe some partition.
1057 secure_wipe_partition(partition);
1058 }
1059 return true;
1060}
1061
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001062static void choose_recovery_file(Device* device) {
Elliott Hughesc0491632015-05-06 12:40:05 -07001063 // "Back" + KEEP_LOG_COUNT * 2 + terminating nullptr entry
1064 char* entries[1 + KEEP_LOG_COUNT * 2 + 1];
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001065 memset(entries, 0, sizeof(entries));
1066
Tao Baobef39712015-05-04 18:50:27 -07001067 unsigned int n = 0;
Patrick Tjincd055ee2014-12-09 11:26:40 -08001068
Tianjie Xu62ab2a02016-08-17 12:02:46 -07001069 if (has_cache) {
1070 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
1071 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
1072 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
1073 char* log_file;
1074 int ret;
1075 ret = (i == 0) ? asprintf(&log_file, "%s", LAST_LOG_FILE) :
1076 asprintf(&log_file, "%s.%d", LAST_LOG_FILE, i);
1077 if (ret == -1) {
1078 // memory allocation failure - return early. Should never happen.
1079 return;
1080 }
1081 if ((ensure_path_mounted(log_file) != 0) || (access(log_file, R_OK) == -1)) {
1082 free(log_file);
1083 } else {
1084 entries[n++] = log_file;
1085 }
Tao Baobef39712015-05-04 18:50:27 -07001086
Tianjie Xu62ab2a02016-08-17 12:02:46 -07001087 char* kmsg_file;
1088 ret = (i == 0) ? asprintf(&kmsg_file, "%s", LAST_KMSG_FILE) :
1089 asprintf(&kmsg_file, "%s.%d", LAST_KMSG_FILE, i);
1090 if (ret == -1) {
1091 // memory allocation failure - return early. Should never happen.
1092 return;
1093 }
1094 if ((ensure_path_mounted(kmsg_file) != 0) || (access(kmsg_file, R_OK) == -1)) {
1095 free(kmsg_file);
1096 } else {
1097 entries[n++] = kmsg_file;
1098 }
Tao Baobef39712015-05-04 18:50:27 -07001099 }
Tianjie Xu62ab2a02016-08-17 12:02:46 -07001100 } else {
1101 // If cache partition is not found, view /tmp/recovery.log instead.
1102 ui->Print("No /cache partition found.\n");
1103 if (access(TEMPORARY_LOG_FILE, R_OK) == -1) {
1104 return;
1105 } else{
1106 entries[n++] = strdup(TEMPORARY_LOG_FILE);
Tao Baobef39712015-05-04 18:50:27 -07001107 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001108 }
1109
Elliott Hughesc0491632015-05-06 12:40:05 -07001110 entries[n++] = strdup("Back");
1111
Tao Baobef39712015-05-04 18:50:27 -07001112 const char* headers[] = { "Select file to view", nullptr };
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001113
Elliott Hughes8de52072015-04-08 20:06:50 -07001114 while (true) {
Elliott Hughes30694c92015-03-25 15:16:51 -07001115 int chosen_item = get_menu_selection(headers, entries, 1, 0, device);
Elliott Hughesc0491632015-05-06 12:40:05 -07001116 if (strcmp(entries[chosen_item], "Back") == 0) break;
Elliott Hughes8de52072015-04-08 20:06:50 -07001117
Elliott Hughes8de52072015-04-08 20:06:50 -07001118 ui->ShowFile(entries[chosen_item]);
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001119 }
1120
Tao Baobef39712015-05-04 18:50:27 -07001121 for (size_t i = 0; i < (sizeof(entries) / sizeof(*entries)); i++) {
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001122 free(entries[i]);
1123 }
1124}
1125
Elliott Hughes498cda62016-04-14 16:49:04 -07001126static void run_graphics_test(Device* device) {
1127 // Switch to graphics screen.
1128 ui->ShowText(false);
1129
1130 ui->SetProgressType(RecoveryUI::INDETERMINATE);
1131 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
1132 sleep(1);
1133
1134 ui->SetBackground(RecoveryUI::ERROR);
1135 sleep(1);
1136
1137 ui->SetBackground(RecoveryUI::NO_COMMAND);
1138 sleep(1);
1139
1140 ui->SetBackground(RecoveryUI::ERASING);
1141 sleep(1);
1142
1143 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
1144
1145 ui->SetProgressType(RecoveryUI::DETERMINATE);
1146 ui->ShowProgress(1.0, 10.0);
1147 float fraction = 0.0;
1148 for (size_t i = 0; i < 100; ++i) {
1149 fraction += .01;
1150 ui->SetProgress(fraction);
1151 usleep(100000);
1152 }
1153
1154 ui->ShowText(true);
1155}
1156
Ameya Thakur74e750e2016-08-15 13:16:03 -07001157static int is_ufs_dev()
1158{
1159 char bootdevice[PROPERTY_VALUE_MAX] = {0};
1160 property_get("ro.boot.bootdevice", bootdevice, "N/A");
1161 ui->Print("ro.boot.bootdevice is: %s\n",bootdevice);
1162 if (strlen(bootdevice) < strlen(".ufshc") + 1)
1163 return 0;
1164 return (!strncmp(&bootdevice[strlen(bootdevice) - strlen(".ufshc")],
1165 ".ufshc",
1166 sizeof(".ufshc")));
1167}
1168
1169static int do_sdcard_mount_for_ufs()
1170{
1171 int rc = 0;
1172 ui->Print("Update via sdcard on UFS dev.Mounting card\n");
1173 Volume *v = volume_for_path("/sdcard");
1174 if (v == NULL) {
1175 ui->Print("Unknown volume for /sdcard.Check fstab\n");
1176 goto error;
1177 }
1178 if (strncmp(v->fs_type, "vfat", sizeof("vfat"))) {
1179 ui->Print("Unsupported format on the sdcard: %s\n",
1180 v->fs_type);
1181 goto error;
1182 }
1183 rc = mount(UFS_DEV_SDCARD_BLK_PATH,
1184 v->mount_point,
1185 v->fs_type,
1186 v->flags,
1187 v->fs_options);
1188 if (rc) {
1189 ui->Print("Failed to mount sdcard : %s\n",
1190 strerror(errno));
1191 goto error;
1192 }
1193 ui->Print("Done mounting sdcard\n");
1194 return 0;
1195error:
1196 return -1;
1197}
1198
Tao Baocdcf28f2016-01-13 15:05:20 -08001199// How long (in seconds) we wait for the fuse-provided package file to
1200// appear, before timing out.
1201#define SDCARD_INSTALL_TIMEOUT 10
1202
Tao Bao145d8612015-03-25 15:51:15 -07001203static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -07001204 modified_flash = true;
1205
Ameya Thakur74e750e2016-08-15 13:16:03 -07001206 if (is_ufs_dev()) {
1207 if (do_sdcard_mount_for_ufs() != 0) {
1208 ui->Print("\nFailed to mount sdcard\n");
1209 return INSTALL_ERROR;
1210 }
1211 } else {
1212 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
1213 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
1214 return INSTALL_ERROR;
1215 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001216 }
Ameya Thakurc10391f2016-02-22 16:22:01 -08001217 if (ensure_path_mounted("/cache") != 0 ||
1218 ensure_path_mounted("/tmp") != 0) {
1219 ui->Print("\nFailed to mount cache/tmp partition\n");
1220 return INSTALL_ERROR;
1221 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001222 char* path = browse_directory(SDCARD_ROOT, device);
1223 if (path == NULL) {
Elliott Hughes018ed312015-04-08 16:51:36 -07001224 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +08001225 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001226 return INSTALL_ERROR;
1227 }
1228
1229 ui->Print("\n-- Install %s ...\n", path);
1230 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001231
Tao Baocdcf28f2016-01-13 15:05:20 -08001232 // We used to use fuse in a thread as opposed to a process. Since accessing
1233 // through fuse involves going from kernel to userspace to kernel, it leads
1234 // to deadlock when a page fault occurs. (Bug: 26313124)
1235 pid_t child;
1236 if ((child = fork()) == 0) {
1237 bool status = start_sdcard_fuse(path);
1238
1239 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
1240 }
1241
1242 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
1243 // process is ready.
1244 int result = INSTALL_ERROR;
1245 int status;
1246 bool waited = false;
1247 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
1248 if (waitpid(child, &status, WNOHANG) == -1) {
1249 result = INSTALL_ERROR;
1250 waited = true;
1251 break;
1252 }
1253
1254 struct stat sb;
1255 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
1256 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
1257 sleep(1);
1258 continue;
1259 } else {
1260 LOGE("Timed out waiting for the fuse-provided package.\n");
1261 result = INSTALL_ERROR;
1262 kill(child, SIGKILL);
1263 break;
1264 }
1265 }
1266
1267 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
Tianjie Xu16255832016-04-30 11:49:59 -07001268 TEMPORARY_INSTALL_FILE, false, 0/*retry_count*/);
Tao Baocdcf28f2016-01-13 15:05:20 -08001269 break;
1270 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001271
Tao Baocdcf28f2016-01-13 15:05:20 -08001272 if (!waited) {
1273 // Calling stat() on this magic filename signals the fuse
1274 // filesystem to shut down.
1275 struct stat sb;
1276 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
1277
1278 waitpid(child, &status, 0);
1279 }
1280
1281 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1282 LOGE("Error exit from the fuse process: %d\n", WEXITSTATUS(status));
1283 }
1284
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001285 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -08001286 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001287}
1288
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001289// Return REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION
1290// means to take the default, which is to reboot or shutdown depending
1291// on if the --shutdown_after flag was passed to recovery.
1292static Device::BuiltinAction
Doug Zongker6c8553d2012-09-24 10:40:47 -07001293prompt_and_wait(Device* device, int status) {
Doug Zongkerf93d8162009-09-22 15:16:02 -07001294 for (;;) {
1295 finish_recovery(NULL);
Doug Zongker6c8553d2012-09-24 10:40:47 -07001296 switch (status) {
1297 case INSTALL_SUCCESS:
1298 case INSTALL_NONE:
1299 ui->SetBackground(RecoveryUI::NO_COMMAND);
1300 break;
1301
1302 case INSTALL_ERROR:
1303 case INSTALL_CORRUPT:
1304 ui->SetBackground(RecoveryUI::ERROR);
1305 break;
1306 }
Doug Zongker211aebc2011-10-28 15:13:10 -07001307 ui->SetProgressType(RecoveryUI::EMPTY);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001308
Elliott Hughes8fd86d72015-04-13 14:36:02 -07001309 int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), 0, 0, device);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001310
1311 // device-specific code may take some action here. It may
1312 // return one of the core actions handled in the switch
1313 // statement below.
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001314 Device::BuiltinAction chosen_action = device->InvokeMenuItem(chosen_item);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001315
Elliott Hughes30694c92015-03-25 15:16:51 -07001316 bool should_wipe_cache = false;
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001317 switch (chosen_action) {
1318 case Device::NO_ACTION:
1319 break;
1320
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001321 case Device::REBOOT:
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001322 case Device::SHUTDOWN:
1323 case Device::REBOOT_BOOTLOADER:
1324 return chosen_action;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001325
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001326 case Device::WIPE_DATA:
1327 wipe_data(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001328 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001329 break;
1330
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001331 case Device::WIPE_CACHE:
Elliott Hughes30694c92015-03-25 15:16:51 -07001332 wipe_cache(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001333 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001334 break;
1335
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001336 case Device::APPLY_ADB_SIDELOAD:
Elliott Hughesec283402015-04-10 10:01:53 -07001337 case Device::APPLY_SDCARD:
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001338 {
1339 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
1340 if (adb) {
Elliott Hughes30694c92015-03-25 15:16:51 -07001341 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001342 } else {
Elliott Hughes30694c92015-03-25 15:16:51 -07001343 status = apply_from_sdcard(device, &should_wipe_cache);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001344 }
Doug Zongker945fc682014-07-10 10:50:39 -07001345
Elliott Hughes30694c92015-03-25 15:16:51 -07001346 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001347 if (!wipe_cache(false, device)) {
1348 status = INSTALL_ERROR;
1349 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001350 }
1351
Tao Baoc679f932015-03-30 09:43:49 -07001352 if (status != INSTALL_SUCCESS) {
1353 ui->SetBackground(RecoveryUI::ERROR);
1354 ui->Print("Installation aborted.\n");
1355 copy_logs();
1356 } else if (!ui->IsTextVisible()) {
1357 return Device::NO_ACTION; // reboot if logs aren't visible
1358 } else {
1359 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
Doug Zongker8674a722010-09-15 11:08:23 -07001360 }
Doug Zongkerf93d8162009-09-22 15:16:02 -07001361 }
1362 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001363
Elliott Hughesec283402015-04-10 10:01:53 -07001364 case Device::VIEW_RECOVERY_LOGS:
1365 choose_recovery_file(device);
Michael Ward9d2629c2011-06-23 22:14:24 -07001366 break;
Doug Zongker9270a202012-01-09 15:16:13 -08001367
Elliott Hughes498cda62016-04-14 16:49:04 -07001368 case Device::RUN_GRAPHICS_TEST:
1369 run_graphics_test(device);
1370 break;
1371
Elliott Hughesec283402015-04-10 10:01:53 -07001372 case Device::MOUNT_SYSTEM:
Amit Blay5c81cc12016-07-03 23:01:38 +03001373#ifdef USE_MDTP
1374 if (is_mdtp_activated()) {
1375 ui->Print("Mounting /system forbidden by MDTP.\n");
1376 }
1377 else
1378#endif
1379 {
1380 char system_root_image[PROPERTY_VALUE_MAX];
1381 property_get("ro.build.system_root_image", system_root_image, "");
Tao Baoabb8f772015-07-30 14:43:27 -07001382
Amit Blay5c81cc12016-07-03 23:01:38 +03001383 // For a system image built with the root directory (i.e.
1384 // system_root_image == "true"), we mount it to /system_root, and symlink /system
1385 // to /system_root/system to make adb shell work (the symlink is created through
1386 // the build system).
1387 // Bug: 22855115
1388 if (strcmp(system_root_image, "true") == 0) {
1389 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1390 ui->Print("Mounted /system.\n");
1391 }
1392 } else {
1393 if (ensure_path_mounted("/system") != -1) {
1394 ui->Print("Mounted /system.\n");
1395 }
Tao Baoabb8f772015-07-30 14:43:27 -07001396 }
Elliott Hughesec283402015-04-10 10:01:53 -07001397 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001398 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001399 }
1400 }
1401}
1402
1403static void
Oscar Montemayor05231562009-11-30 08:40:57 -08001404print_property(const char *key, const char *name, void *cookie) {
Doug Zongker56c51052010-07-01 09:18:44 -07001405 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001406}
1407
Doug Zongker02ec6b82012-08-22 17:26:40 -07001408static void
1409load_locale_from_cache() {
1410 FILE* fp = fopen_path(LOCALE_FILE, "r");
1411 char buffer[80];
1412 if (fp != NULL) {
1413 fgets(buffer, sizeof(buffer), fp);
1414 int j = 0;
Doug Zongker5fa8c232012-09-18 12:37:02 -07001415 unsigned int i;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001416 for (i = 0; i < sizeof(buffer) && buffer[i]; ++i) {
1417 if (!isspace(buffer[i])) {
1418 buffer[j++] = buffer[i];
1419 }
1420 }
1421 buffer[j] = 0;
1422 locale = strdup(buffer);
Devin Kim6016d082012-10-08 09:47:37 -07001423 check_and_fclose(fp, LOCALE_FILE);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001424 }
1425}
1426
Doug Zongker7c3ae452013-05-14 11:03:02 -07001427static RecoveryUI* gCurrentUI = NULL;
1428
1429void
1430ui_print(const char* format, ...) {
1431 char buffer[256];
1432
1433 va_list ap;
1434 va_start(ap, format);
1435 vsnprintf(buffer, sizeof(buffer), format, ap);
1436 va_end(ap);
1437
1438 if (gCurrentUI != NULL) {
1439 gCurrentUI->Print("%s", buffer);
1440 } else {
1441 fputs(buffer, stdout);
1442 }
1443}
1444
Yabin Cui99281df2016-02-17 12:21:52 -08001445static bool is_battery_ok() {
1446 struct healthd_config healthd_config = {
1447 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1448 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1449 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1450 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1451 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1452 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1453 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1454 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1455 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1456 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1457 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1458 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1459 .energyCounter = NULL,
1460 .boot_min_cap = 0,
1461 .screen_on = NULL
1462 };
1463 healthd_board_init(&healthd_config);
1464
1465 android::BatteryMonitor monitor;
1466 monitor.init(&healthd_config);
1467
1468 int wait_second = 0;
1469 while (true) {
1470 int charge_status = monitor.getChargeStatus();
1471 // Treat unknown status as charged.
1472 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1473 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1474 android::BatteryProperty capacity;
1475 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1476 ui_print("charge_status %d, charged %d, status %d, capacity %lld\n", charge_status,
1477 charged, status, capacity.valueInt64);
1478 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1479 // the battery profile. Before the load finishes, it reports value 50 as a fake
1480 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1481 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1482 if (status == 0 && capacity.valueInt64 == 50) {
1483 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1484 sleep(1);
1485 wait_second++;
1486 continue;
1487 }
1488 }
1489 // If we can't read battery percentage, it may be a device without battery. In this
1490 // situation, use 100 as a fake battery percentage.
1491 if (status != 0) {
1492 capacity.valueInt64 = 100;
1493 }
1494 return (charged && capacity.valueInt64 >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
1495 (!charged && capacity.valueInt64 >= BATTERY_OK_PERCENTAGE);
1496 }
1497}
1498
Tianjie Xufa12b972016-02-05 18:25:58 -08001499static void set_retry_bootloader_message(int retry_count, int argc, char** argv) {
Yabin Cui2f272c02016-06-24 18:22:02 -07001500 bootloader_message boot = {};
Tianjie Xufa12b972016-02-05 18:25:58 -08001501 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
1502 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
1503
1504 for (int i = 1; i < argc; ++i) {
1505 if (strstr(argv[i], "retry_count") == nullptr) {
1506 strlcat(boot.recovery, argv[i], sizeof(boot.recovery));
1507 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
1508 }
1509 }
1510
1511 // Initialize counter to 1 if it's not in BCB, otherwise increment it by 1.
1512 if (retry_count == 0) {
1513 strlcat(boot.recovery, "--retry_count=1\n", sizeof(boot.recovery));
1514 } else {
1515 char buffer[20];
1516 snprintf(buffer, sizeof(buffer), "--retry_count=%d\n", retry_count+1);
1517 strlcat(boot.recovery, buffer, sizeof(boot.recovery));
1518 }
Yabin Cui2f272c02016-06-24 18:22:02 -07001519 std::string err;
1520 if (!write_bootloader_message(boot, &err)) {
1521 LOGE("%s\n", err.c_str());
1522 }
Tianjie Xufa12b972016-02-05 18:25:58 -08001523}
1524
Tianjie Xu27b9fc82016-07-11 14:04:08 -07001525static bool bootreason_in_blacklist() {
1526 char bootreason[PROPERTY_VALUE_MAX];
1527 if (property_get("ro.boot.bootreason", bootreason, nullptr) > 0) {
1528 for (const auto& str : bootreason_blacklist) {
1529 if (strcasecmp(str.c_str(), bootreason) == 0) {
1530 return true;
1531 }
1532 }
1533 }
1534 return false;
1535}
1536
1537static void log_failure_code(ErrorCode code, const char *update_package) {
Tao Baoa8c0d0b2016-09-26 11:39:14 -07001538 std::vector<std::string> log_buffer = {
1539 update_package,
1540 "0", // install result
1541 "error: " + std::to_string(code),
1542 };
1543 std::string log_content = android::base::Join(log_buffer, "\n");
1544 if (!android::base::WriteStringToFile(log_content, TEMPORARY_INSTALL_FILE)) {
1545 LOGE("failed to write %s: %s\n", TEMPORARY_INSTALL_FILE, strerror(errno));
Tianjie Xu27b9fc82016-07-11 14:04:08 -07001546 }
Tao Baoa8c0d0b2016-09-26 11:39:14 -07001547
1548 // Also write the info into last_log.
1549 LOGI("%s\n", log_content.c_str());
Yabin Cui99281df2016-02-17 12:21:52 -08001550}
1551
Mark Salyzyn13aca592016-03-09 14:58:16 -08001552static ssize_t logbasename(
1553 log_id_t /* logId */,
1554 char /* prio */,
1555 const char *filename,
1556 const char * /* buf */, size_t len,
1557 void *arg) {
1558 if (strstr(LAST_KMSG_FILE, filename) ||
1559 strstr(LAST_LOG_FILE, filename)) {
1560 bool *doRotate = reinterpret_cast<bool *>(arg);
1561 *doRotate = true;
1562 }
1563 return len;
1564}
1565
1566static ssize_t logrotate(
1567 log_id_t logId,
1568 char prio,
1569 const char *filename,
1570 const char *buf, size_t len,
1571 void *arg) {
1572 bool *doRotate = reinterpret_cast<bool *>(arg);
1573 if (!*doRotate) {
1574 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1575 }
1576
1577 std::string name(filename);
1578 size_t dot = name.find_last_of(".");
1579 std::string sub = name.substr(0, dot);
1580
1581 if (!strstr(LAST_KMSG_FILE, sub.c_str()) &&
1582 !strstr(LAST_LOG_FILE, sub.c_str())) {
1583 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1584 }
1585
1586 // filename rotation
1587 if (dot == std::string::npos) {
1588 name += ".1";
1589 } else {
1590 std::string number = name.substr(dot + 1);
1591 if (!isdigit(number.data()[0])) {
1592 name += ".1";
1593 } else {
1594 unsigned long long i = std::stoull(number);
1595 name = sub + "." + std::to_string(i + 1);
1596 }
1597 }
1598
1599 return __android_log_pmsg_file_write(logId, prio, name.c_str(), buf, len);
1600}
1601
Yabin Cui99281df2016-02-17 12:21:52 -08001602int main(int argc, char **argv) {
Mark Salyzyn13aca592016-03-09 14:58:16 -08001603 // Take last pmsg contents and rewrite it to the current pmsg session.
1604 static const char filter[] = "recovery/";
1605 // Do we need to rotate?
1606 bool doRotate = false;
1607 __android_log_pmsg_file_read(
1608 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1609 logbasename, &doRotate);
1610 // Take action to refresh pmsg contents
1611 __android_log_pmsg_file_read(
1612 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1613 logrotate, &doRotate);
1614
Doug Zongker9270a202012-01-09 15:16:13 -08001615 // If this binary is started with the single argument "--adbd",
1616 // instead of being the normal recovery binary, it turns into kind
1617 // of a stripped-down version of adbd that only supports the
1618 // 'sideload' command. Note this must be a real argument, not
1619 // anything in the command file or bootloader control block; the
1620 // only way recovery should be run with this argument is when it
1621 // starts a copy of itself from the apply_from_adb() function.
1622 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
Elliott Hughes9f4fdb32015-11-20 13:03:24 -08001623 adb_server_main(0, DEFAULT_ADB_PORT, -1);
Doug Zongker9270a202012-01-09 15:16:13 -08001624 return 0;
1625 }
1626
Tao Bao04ca4262015-09-10 15:32:24 -07001627 time_t start = time(NULL);
1628
1629 // redirect_stdio should be called only in non-sideload mode. Otherwise
1630 // we may have two logger instances with different timestamps.
1631 redirect_stdio(TEMPORARY_LOG_FILE);
1632
Doug Zongker19a8e242014-01-21 09:25:41 -08001633 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001634
Doug Zongkerd4208f92010-09-20 12:16:13 -07001635 load_volume_table();
Tao Baoae6408d2016-02-25 12:29:40 -08001636 has_cache = volume_for_path(CACHE_ROOT) != nullptr;
1637
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001638 get_args(&argc, &argv);
1639
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001640 const char *send_intent = NULL;
1641 const char *update_package = NULL;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001642 bool should_wipe_data = false;
Tao Baoc679f932015-03-30 09:43:49 -07001643 bool should_wipe_cache = false;
Tao Bao108ab212016-06-10 10:13:32 -07001644 bool should_wipe_ab = false;
Yabin Cui6faf0262016-06-09 14:09:39 -07001645 size_t wipe_package_size = 0;
Tao Bao145d8612015-03-25 15:51:15 -07001646 bool show_text = false;
Tao Baoc679f932015-03-30 09:43:49 -07001647 bool sideload = false;
1648 bool sideload_auto_reboot = false;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001649 bool just_exit = false;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001650 bool shutdown_after = false;
Tianjie Xufa12b972016-02-05 18:25:58 -08001651 int retry_count = 0;
Tianjie Xu35926c42016-04-28 18:06:26 -07001652 bool security_update = false;
Ameya Thakur74e750e2016-08-15 13:16:03 -07001653 int status = INSTALL_SUCCESS;
1654 bool mount_required = true;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001655
1656 int arg;
Tao Baob0838182016-06-02 11:16:50 -07001657 int option_index;
1658 while ((arg = getopt_long(argc, argv, "", OPTIONS, &option_index)) != -1) {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001659 switch (arg) {
Tao Baoc679f932015-03-30 09:43:49 -07001660 case 'i': send_intent = optarg; break;
Tianjie Xufa12b972016-02-05 18:25:58 -08001661 case 'n': android::base::ParseInt(optarg, &retry_count, 0); break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001662 case 'u': update_package = optarg; break;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001663 case 'w': should_wipe_data = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001664 case 'c': should_wipe_cache = true; break;
Tao Bao145d8612015-03-25 15:51:15 -07001665 case 't': show_text = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001666 case 's': sideload = true; break;
1667 case 'a': sideload = true; sideload_auto_reboot = true; break;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001668 case 'x': just_exit = true; break;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001669 case 'l': locale = optarg; break;
Doug Zongkerc87bab12013-11-25 13:53:25 -08001670 case 'g': {
1671 if (stage == NULL || *stage == '\0') {
1672 char buffer[20] = "1/";
1673 strncat(buffer, optarg, sizeof(buffer)-3);
1674 stage = strdup(buffer);
1675 }
1676 break;
1677 }
Doug Zongkerb1d12632014-03-18 10:32:12 -07001678 case 'p': shutdown_after = true; break;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001679 case 'r': reason = optarg; break;
Tianjie Xu35926c42016-04-28 18:06:26 -07001680 case 'e': security_update = true; break;
Tao Baob0838182016-06-02 11:16:50 -07001681 case 0: {
Tao Bao108ab212016-06-10 10:13:32 -07001682 if (strcmp(OPTIONS[option_index].name, "wipe_ab") == 0) {
1683 should_wipe_ab = true;
Tao Baob0838182016-06-02 11:16:50 -07001684 break;
Yabin Cui6faf0262016-06-09 14:09:39 -07001685 } else if (strcmp(OPTIONS[option_index].name, "wipe_package_size") == 0) {
1686 android::base::ParseUint(optarg, &wipe_package_size);
1687 break;
Tao Baob0838182016-06-02 11:16:50 -07001688 }
1689 break;
1690 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001691 case '?':
1692 LOGE("Invalid command argument\n");
1693 continue;
1694 }
1695 }
1696
Tao Baoae6408d2016-02-25 12:29:40 -08001697 if (locale == nullptr && has_cache) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001698 load_locale_from_cache();
1699 }
1700 printf("locale is [%s]\n", locale);
Doug Zongker0d32f252014-02-13 15:07:56 -08001701 printf("stage is [%s]\n", stage);
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001702 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001703
1704 Device* device = make_device();
1705 ui = device->GetUI();
Doug Zongker7c3ae452013-05-14 11:03:02 -07001706 gCurrentUI = ui;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001707
Doug Zongker5fa8c232012-09-18 12:37:02 -07001708 ui->SetLocale(locale);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001709 ui->Init();
Tianjie Xu35926c42016-04-28 18:06:26 -07001710 // Set background string to "installing security update" for security update,
1711 // otherwise set it to "installing system update".
1712 ui->SetSystemUpdateText(security_update);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001713
1714 int st_cur, st_max;
1715 if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
1716 ui->SetStage(st_cur, st_max);
1717 }
1718
Doug Zongker02ec6b82012-08-22 17:26:40 -07001719 ui->SetBackground(RecoveryUI::NONE);
1720 if (show_text) ui->ShowText(true);
1721
Stephen Smalley779701d2012-02-09 14:13:23 -05001722 struct selinux_opt seopts[] = {
1723 { SELABEL_OPT_PATH, "/file_contexts" }
1724 };
1725
1726 sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
1727
1728 if (!sehandle) {
Doug Zongkerfafc85b2013-07-09 12:29:45 -07001729 ui->Print("Warning: No file_contexts\n");
Stephen Smalley779701d2012-02-09 14:13:23 -05001730 }
Stephen Smalley779701d2012-02-09 14:13:23 -05001731
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001732 device->StartRecovery();
Doug Zongkerefa1bab2010-02-01 15:59:12 -08001733
Doug Zongker56c51052010-07-01 09:18:44 -07001734 printf("Command:");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001735 for (arg = 0; arg < argc; arg++) {
Doug Zongker56c51052010-07-01 09:18:44 -07001736 printf(" \"%s\"", argv[arg]);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001737 }
Doug Zongker9b125b02010-09-22 12:01:37 -07001738 printf("\n");
1739
1740 if (update_package) {
1741 // For backwards compatibility on the cache partition only, if
1742 // we're given an old 'root' path "CACHE:foo", change it to
1743 // "/cache/foo".
1744 if (strncmp(update_package, "CACHE:", 6) == 0) {
1745 int len = strlen(update_package) + 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -07001746 char* modified_path = (char*)malloc(len);
Jeremy Compostella1b7d9b72015-07-29 17:17:03 +02001747 if (modified_path) {
1748 strlcpy(modified_path, "/cache/", len);
1749 strlcat(modified_path, update_package+6, len);
1750 printf("(replacing path \"%s\" with \"%s\")\n",
1751 update_package, modified_path);
1752 update_package = modified_path;
1753 }
1754 else
1755 printf("modified_path allocation failed\n");
Doug Zongker9b125b02010-09-22 12:01:37 -07001756 }
Ameya Thakur74e750e2016-08-15 13:16:03 -07001757 if (!strncmp("/sdcard", update_package, 7)) {
1758 //If this is a UFS device lets mount the sdcard ourselves.Depending
1759 //on if the device is UFS or EMMC based the path to the sdcard
1760 //device changes so we cannot rely on the block dev path from
1761 //recovery.fstab
1762 if (is_ufs_dev()) {
1763 if(do_sdcard_mount_for_ufs() != 0) {
1764 status = INSTALL_ERROR;
1765 goto error;
1766 }
Ameya Thakurc10391f2016-02-22 16:22:01 -08001767 if (ensure_path_mounted("/cache") != 0 || ensure_path_mounted("/tmp") != 0) {
1768 ui->Print("\nFailed to mount tmp/cache partition\n");
1769 status = INSTALL_ERROR;
1770 goto error;
1771 }
Ameya Thakur74e750e2016-08-15 13:16:03 -07001772 mount_required = false;
1773 } else {
1774 ui->Print("Update via sdcard on EMMC dev. Using path from fstab\n");
1775 }
1776 }
Doug Zongker9b125b02010-09-22 12:01:37 -07001777 }
1778 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001779 property_list(print_property, NULL);
Doug Zongker56c51052010-07-01 09:18:44 -07001780 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001781
Elliott Hughesbb78d622015-04-09 20:51:08 -07001782 ui->Print("Supported API: %d\n", RECOVERY_API_VERSION);
1783
Doug Zongker540d57f2011-01-18 13:36:58 -08001784 if (update_package != NULL) {
Tao Bao56870012016-04-29 15:37:05 -07001785 // It's not entirely true that we will modify the flash. But we want
1786 // to log the update attempt since update_package is non-NULL.
1787 modified_flash = true;
1788
Yabin Cui99281df2016-02-17 12:21:52 -08001789 if (!is_battery_ok()) {
1790 ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
1791 BATTERY_OK_PERCENTAGE);
Tianjie Xu16255832016-04-30 11:49:59 -07001792 // Log the error code to last_install when installation skips due to
1793 // low battery.
Tianjie Xu27b9fc82016-07-11 14:04:08 -07001794 log_failure_code(kLowBattery, update_package);
1795 status = INSTALL_SKIPPED;
1796 } else if (bootreason_in_blacklist()) {
1797 // Skip update-on-reboot when bootreason is kernel_panic or similar
1798 ui->Print("bootreason is in the blacklist; skip OTA installation\n");
1799 log_failure_code(kBootreasonInBlacklist, update_package);
Yabin Cui99281df2016-02-17 12:21:52 -08001800 status = INSTALL_SKIPPED;
1801 } else {
1802 status = install_package(update_package, &should_wipe_cache,
Ameya Thakur74e750e2016-08-15 13:16:03 -07001803 TEMPORARY_INSTALL_FILE, mount_required, retry_count);
Yabin Cui99281df2016-02-17 12:21:52 -08001804 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1805 wipe_cache(false, device);
1806 }
1807 if (status != INSTALL_SUCCESS) {
1808 ui->Print("Installation aborted.\n");
Tianjie Xufa12b972016-02-05 18:25:58 -08001809 // When I/O error happens, reboot and retry installation EIO_RETRY_COUNT
1810 // times before we abandon this OTA update.
1811 if (status == INSTALL_RETRY && retry_count < EIO_RETRY_COUNT) {
1812 copy_logs();
1813 set_retry_bootloader_message(retry_count, argc, argv);
1814 // Print retry count on screen.
1815 ui->Print("Retry attempt %d\n", retry_count);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001816
Tianjie Xufa12b972016-02-05 18:25:58 -08001817 // Reboot and retry the update
1818 int ret = property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
1819 if (ret < 0) {
1820 ui->Print("Reboot failed\n");
1821 } else {
1822 while (true) {
1823 pause();
1824 }
1825 }
1826 }
Yabin Cui99281df2016-02-17 12:21:52 -08001827 // If this is an eng or userdebug build, then automatically
1828 // turn the text display on if the script fails so the error
1829 // message is visible.
1830 if (is_ro_debuggable()) {
1831 ui->ShowText(true);
1832 }
Doug Zongker7c3ae452013-05-14 11:03:02 -07001833 }
1834 }
Tao Baoe39a9bc2015-03-31 12:19:05 -07001835 } else if (should_wipe_data) {
1836 if (!wipe_data(false, device)) {
1837 status = INSTALL_ERROR;
1838 }
Tao Baoc679f932015-03-30 09:43:49 -07001839 } else if (should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001840 if (!wipe_cache(false, device)) {
1841 status = INSTALL_ERROR;
1842 }
Tao Bao108ab212016-06-10 10:13:32 -07001843 } else if (should_wipe_ab) {
Yabin Cui6faf0262016-06-09 14:09:39 -07001844 if (!wipe_ab_device(wipe_package_size)) {
Tao Baob0838182016-06-02 11:16:50 -07001845 status = INSTALL_ERROR;
1846 }
Tao Baoc679f932015-03-30 09:43:49 -07001847 } else if (sideload) {
1848 // 'adb reboot sideload' acts the same as user presses key combinations
1849 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1850 // display will NOT be turned on by default. And it will reboot after
1851 // sideload finishes even if there are errors. Unless one turns on the
1852 // text display during the installation. This is to enable automated
1853 // testing.
1854 if (!sideload_auto_reboot) {
1855 ui->ShowText(true);
1856 }
1857 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
1858 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001859 if (!wipe_cache(false, device)) {
1860 status = INSTALL_ERROR;
1861 }
Tao Baoc679f932015-03-30 09:43:49 -07001862 }
1863 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1864 if (sideload_auto_reboot) {
1865 ui->Print("Rebooting automatically.\n");
1866 }
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001867 } else if (!just_exit) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001868 status = INSTALL_NONE; // No command specified
1869 ui->SetBackground(RecoveryUI::NO_COMMAND);
Tao Bao785d22c2015-05-04 09:34:29 -07001870
1871 // http://b/17489952
1872 // If this is an eng or userdebug build, automatically turn on the
1873 // text display if no command is specified.
1874 if (is_ro_debuggable()) {
1875 ui->ShowText(true);
1876 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001877 }
Ameya Thakur74e750e2016-08-15 13:16:03 -07001878error:
Tao Baoc679f932015-03-30 09:43:49 -07001879 if (!sideload_auto_reboot && (status == INSTALL_ERROR || status == INSTALL_CORRUPT)) {
Doug Zongkerf24fd7e2013-07-02 11:43:25 -07001880 copy_logs();
Doug Zongker02ec6b82012-08-22 17:26:40 -07001881 ui->SetBackground(RecoveryUI::ERROR);
1882 }
Tao Baoc679f932015-03-30 09:43:49 -07001883
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001884 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
Yabin Cui99281df2016-02-17 12:21:52 -08001885 if ((status != INSTALL_SUCCESS && status != INSTALL_SKIPPED && !sideload_auto_reboot) ||
1886 ui->IsTextVisible()) {
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001887 Device::BuiltinAction temp = prompt_and_wait(device, status);
Tao Baoc679f932015-03-30 09:43:49 -07001888 if (temp != Device::NO_ACTION) {
1889 after = temp;
1890 }
Doug Zongker8674a722010-09-15 11:08:23 -07001891 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001892
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001893 // Save logs and clean up before rebooting or shutting down.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001894 finish_recovery(send_intent);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001895
1896 switch (after) {
1897 case Device::SHUTDOWN:
1898 ui->Print("Shutting down...\n");
1899 property_set(ANDROID_RB_PROPERTY, "shutdown,");
1900 break;
1901
1902 case Device::REBOOT_BOOTLOADER:
1903 ui->Print("Rebooting to bootloader...\n");
1904 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
1905 break;
1906
1907 default:
1908 ui->Print("Rebooting...\n");
1909 property_set(ANDROID_RB_PROPERTY, "reboot,");
1910 break;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001911 }
Tao Bao75238632015-05-27 14:46:17 -07001912 while (true) {
1913 pause();
1914 }
1915 // Should be unreachable.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001916 return EXIT_SUCCESS;
1917}