blob: 9873f976c552d1b9773a504b6471bbbdb68c1360 [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>
22#include <limits.h>
23#include <linux/input.h>
Doug Zongker7c3ae452013-05-14 11:03:02 -070024#include <stdarg.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080025#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Patrick Tjincd055ee2014-12-09 11:26:40 -080028#include <sys/klog.h>
Doug Zongker23ceeea2010-07-08 17:27:55 -070029#include <sys/stat.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080030#include <sys/types.h>
Tao Baocdcf28f2016-01-13 15:05:20 -080031#include <sys/wait.h>
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080032#include <time.h>
33#include <unistd.h>
34
Tao Bao04ca4262015-09-10 15:32:24 -070035#include <chrono>
36
Tao Bao75238632015-05-27 14:46:17 -070037#include <adb.h>
Mark Salyzyn13aca592016-03-09 14:58:16 -080038#include <android/log.h> /* Android Log Priority Tags */
Elliott Hughes4b166f02015-12-04 15:30:20 -080039#include <android-base/file.h>
Tianjie Xufa12b972016-02-05 18:25:58 -080040#include <android-base/parseint.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/stringprintf.h>
Tao Bao75238632015-05-27 14:46:17 -070042#include <cutils/android_reboot.h>
43#include <cutils/properties.h>
Mark Salyzyn13aca592016-03-09 14:58:16 -080044#include <log/logger.h> /* Android Log packet format */
45#include <private/android_logger.h> /* private pmsg functions */
Tao Baobef39712015-05-04 18:50:27 -070046
Yabin Cui99281df2016-02-17 12:21:52 -080047#include <healthd/BatteryMonitor.h>
48
Tao Bao75238632015-05-27 14:46:17 -070049#include "adb_install.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080050#include "bootloader.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080051#include "common.h"
Tao Bao75238632015-05-27 14:46:17 -070052#include "device.h"
53#include "fuse_sdcard_provider.h"
54#include "fuse_sideload.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080055#include "install.h"
56#include "minui/minui.h"
57#include "minzip/DirUtil.h"
58#include "roots.h"
Doug Zongker28ce47c2011-10-28 10:33:05 -070059#include "ui.h"
Doug Zongker211aebc2011-10-28 15:13:10 -070060#include "screen_ui.h"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080061
Stephen Smalley779701d2012-02-09 14:13:23 -050062struct selabel_handle *sehandle;
63
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080064static const struct option OPTIONS[] = {
Tao Baoc679f932015-03-30 09:43:49 -070065 { "send_intent", required_argument, NULL, 'i' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080066 { "update_package", required_argument, NULL, 'u' },
Tianjie Xufa12b972016-02-05 18:25:58 -080067 { "retry_count", required_argument, NULL, 'n' },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080068 { "wipe_data", no_argument, NULL, 'w' },
69 { "wipe_cache", no_argument, NULL, 'c' },
Doug Zongker4bc98062010-09-03 11:00:13 -070070 { "show_text", no_argument, NULL, 't' },
Tao Baoc679f932015-03-30 09:43:49 -070071 { "sideload", no_argument, NULL, 's' },
72 { "sideload_auto_reboot", no_argument, NULL, 'a' },
Doug Zongkere5d5ac72012-04-12 11:01:22 -070073 { "just_exit", no_argument, NULL, 'x' },
Doug Zongker02ec6b82012-08-22 17:26:40 -070074 { "locale", required_argument, NULL, 'l' },
Doug Zongkerc87bab12013-11-25 13:53:25 -080075 { "stages", required_argument, NULL, 'g' },
Doug Zongkerb1d12632014-03-18 10:32:12 -070076 { "shutdown_after", no_argument, NULL, 'p' },
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -070077 { "reason", required_argument, NULL, 'r' },
Tianjie Xu35926c42016-04-28 18:06:26 -070078 { "security", no_argument, NULL, 'e'},
Doug Zongker988500b2009-10-06 14:41:38 -070079 { NULL, 0, NULL, 0 },
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080080};
81
Doug Zongker6d0d7ac2013-07-09 13:34:55 -070082static const char *CACHE_LOG_DIR = "/cache/recovery";
Doug Zongkerd4208f92010-09-20 12:16:13 -070083static const char *COMMAND_FILE = "/cache/recovery/command";
84static const char *INTENT_FILE = "/cache/recovery/intent";
85static const char *LOG_FILE = "/cache/recovery/log";
Doug Zongkerd0181b82011-10-19 10:51:12 -070086static const char *LAST_INSTALL_FILE = "/cache/recovery/last_install";
Doug Zongker8b240cc2012-08-29 15:19:29 -070087static const char *LOCALE_FILE = "/cache/recovery/last_locale";
Paul Lawrence661f8a62016-02-25 12:42:19 -080088static const char *CONVERT_FBE_DIR = "/tmp/convert_fbe";
89static const char *CONVERT_FBE_FILE = "/tmp/convert_fbe/convert_fbe";
Michael Ward9d2629c2011-06-23 22:14:24 -070090static const char *CACHE_ROOT = "/cache";
Paul Lawrenced0db3372015-11-05 13:38:40 -080091static const char *DATA_ROOT = "/data";
Doug Zongkerd4208f92010-09-20 12:16:13 -070092static const char *SDCARD_ROOT = "/sdcard";
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -080093static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log";
Doug Zongkerd0181b82011-10-19 10:51:12 -070094static const char *TEMPORARY_INSTALL_FILE = "/tmp/last_install";
Tao Baof0124322015-04-11 02:04:11 +000095static const char *LAST_KMSG_FILE = "/cache/recovery/last_kmsg";
Tao Baobef39712015-05-04 18:50:27 -070096static const char *LAST_LOG_FILE = "/cache/recovery/last_log";
97static const int KEEP_LOG_COUNT = 10;
Tianjie Xufa12b972016-02-05 18:25:58 -080098static const int EIO_RETRY_COUNT = 2;
Yabin Cui99281df2016-02-17 12:21:52 -080099static const int BATTERY_READ_TIMEOUT_IN_SEC = 10;
100// GmsCore enters recovery mode to install package when having enough battery
101// percentage. Normally, the threshold is 40% without charger and 20% with charger.
102// So we should check battery with a slightly lower limitation.
103static const int BATTERY_OK_PERCENTAGE = 20;
104static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700105
Doug Zongker211aebc2011-10-28 15:13:10 -0700106RecoveryUI* ui = NULL;
Elliott Hughes498cda62016-04-14 16:49:04 -0700107static const char* locale = "en_US";
Doug Zongkerc87bab12013-11-25 13:53:25 -0800108char* stage = NULL;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -0700109char* reason = NULL;
Tao Bao682c34b2015-04-07 17:16:35 -0700110bool modified_flash = false;
Tao Baoae6408d2016-02-25 12:29:40 -0800111static bool has_cache = false;
Doug Zongker211aebc2011-10-28 15:13:10 -0700112
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800113/*
114 * The recovery tool communicates with the main system through /cache files.
115 * /cache/recovery/command - INPUT - command line for tool, one arg per line
116 * /cache/recovery/log - OUTPUT - combined log file from recovery run(s)
117 * /cache/recovery/intent - OUTPUT - intent that was passed in
118 *
119 * The arguments which may be supplied in the recovery.command file:
120 * --send_intent=anystring - write the text out to recovery.intent
Doug Zongkerd4208f92010-09-20 12:16:13 -0700121 * --update_package=path - verify install an OTA package file
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800122 * --wipe_data - erase user data (and cache), then reboot
123 * --wipe_cache - wipe cache (but not user data), then reboot
Oscar Montemayor05231562009-11-30 08:40:57 -0800124 * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700125 * --just_exit - do nothing; exit and reboot
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800126 *
127 * After completing, we remove /cache/recovery/command and reboot.
128 * Arguments may also be supplied in the bootloader control block (BCB).
129 * These important scenarios must be safely restartable at any point:
130 *
131 * FACTORY RESET
132 * 1. user selects "factory reset"
133 * 2. main system writes "--wipe_data" to /cache/recovery/command
134 * 3. main system reboots into recovery
135 * 4. get_args() writes BCB with "boot-recovery" and "--wipe_data"
136 * -- after this, rebooting will restart the erase --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700137 * 5. erase_volume() reformats /data
138 * 6. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800139 * 7. finish_recovery() erases BCB
140 * -- after this, rebooting will restart the main system --
141 * 8. main() calls reboot() to boot main system
142 *
143 * OTA INSTALL
144 * 1. main system downloads OTA package to /cache/some-filename.zip
Doug Zongker9b125b02010-09-22 12:01:37 -0700145 * 2. main system writes "--update_package=/cache/some-filename.zip"
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800146 * 3. main system reboots into recovery
147 * 4. get_args() writes BCB with "boot-recovery" and "--update_package=..."
148 * -- after this, rebooting will attempt to reinstall the update --
149 * 5. install_package() attempts to install the update
150 * NOTE: the package install must itself be restartable from any point
151 * 6. finish_recovery() erases BCB
152 * -- after this, rebooting will (try to) restart the main system --
153 * 7. ** if install failed **
154 * 7a. prompt_and_wait() shows an error icon and waits for the user
155 * 7b; the user reboots (pulling the battery, etc) into the main system
156 * 8. main() calls maybe_install_firmware_update()
157 * ** if the update contained radio/hboot firmware **:
158 * 8a. m_i_f_u() writes BCB with "boot-recovery" and "--wipe_cache"
159 * -- after this, rebooting will reformat cache & restart main system --
160 * 8b. m_i_f_u() writes firmware image into raw cache partition
161 * 8c. m_i_f_u() writes BCB with "update-radio/hboot" and "--wipe_cache"
162 * -- after this, rebooting will attempt to reinstall firmware --
163 * 8d. bootloader tries to flash firmware
164 * 8e. bootloader writes BCB with "boot-recovery" (keeping "--wipe_cache")
165 * -- after this, rebooting will reformat cache & restart main system --
Doug Zongkerd4208f92010-09-20 12:16:13 -0700166 * 8f. erase_volume() reformats /cache
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800167 * 8g. finish_recovery() erases BCB
168 * -- after this, rebooting will (try to) restart the main system --
169 * 9. main() calls reboot() to boot main system
170 */
171
172static const int MAX_ARG_LENGTH = 4096;
173static const int MAX_ARGS = 100;
174
Doug Zongkerd4208f92010-09-20 12:16:13 -0700175// open a given path, mounting partitions as necessary
Tao Bao04ca4262015-09-10 15:32:24 -0700176FILE* fopen_path(const char *path, const char *mode) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700177 if (ensure_path_mounted(path) != 0) {
178 LOGE("Can't mount %s\n", path);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800179 return NULL;
180 }
181
182 // When writing, try to create the containing directory, if necessary.
183 // Use generous permissions, the system (init.rc) will reset them.
Stephen Smalley779701d2012-02-09 14:13:23 -0500184 if (strchr("wa", mode[0])) dirCreateHierarchy(path, 0777, NULL, 1, sehandle);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800185
186 FILE *fp = fopen(path, mode);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800187 return fp;
188}
189
Tao Bao04ca4262015-09-10 15:32:24 -0700190// close a file, log an error if the error indicator is set
191static void check_and_fclose(FILE *fp, const char *name) {
192 fflush(fp);
193 if (ferror(fp)) LOGE("Error in %s\n(%s)\n", name, strerror(errno));
194 fclose(fp);
195}
196
Elliott Hughesf14af802015-02-10 14:46:14 -0800197bool is_ro_debuggable() {
198 char value[PROPERTY_VALUE_MAX+1];
199 return (property_get("ro.debuggable", value, NULL) == 1 && value[0] == '1');
200}
201
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700202static void redirect_stdio(const char* filename) {
Tao Bao04ca4262015-09-10 15:32:24 -0700203 int pipefd[2];
204 if (pipe(pipefd) == -1) {
205 LOGE("pipe failed: %s\n", strerror(errno));
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700206
Tao Bao04ca4262015-09-10 15:32:24 -0700207 // Fall back to traditional logging mode without timestamps.
208 // If these fail, there's not really anywhere to complain...
209 freopen(filename, "a", stdout); setbuf(stdout, NULL);
210 freopen(filename, "a", stderr); setbuf(stderr, NULL);
211
212 return;
213 }
214
215 pid_t pid = fork();
216 if (pid == -1) {
217 LOGE("fork failed: %s\n", strerror(errno));
218
219 // Fall back to traditional logging mode without timestamps.
220 // If these fail, there's not really anywhere to complain...
221 freopen(filename, "a", stdout); setbuf(stdout, NULL);
222 freopen(filename, "a", stderr); setbuf(stderr, NULL);
223
224 return;
225 }
226
227 if (pid == 0) {
228 /// Close the unused write end.
229 close(pipefd[1]);
230
231 auto start = std::chrono::steady_clock::now();
232
233 // Child logger to actually write to the log file.
234 FILE* log_fp = fopen(filename, "a");
235 if (log_fp == nullptr) {
236 LOGE("fopen \"%s\" failed: %s\n", filename, strerror(errno));
237 close(pipefd[0]);
238 _exit(1);
239 }
240
241 FILE* pipe_fp = fdopen(pipefd[0], "r");
242 if (pipe_fp == nullptr) {
243 LOGE("fdopen failed: %s\n", strerror(errno));
244 check_and_fclose(log_fp, filename);
245 close(pipefd[0]);
246 _exit(1);
247 }
248
249 char* line = nullptr;
250 size_t len = 0;
251 while (getline(&line, &len, pipe_fp) != -1) {
252 auto now = std::chrono::steady_clock::now();
253 double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
254 now - start).count();
255 if (line[0] == '\n') {
256 fprintf(log_fp, "[%12.6lf]\n", duration);
257 } else {
258 fprintf(log_fp, "[%12.6lf] %s", duration, line);
259 }
260 fflush(log_fp);
261 }
262
263 LOGE("getline failed: %s\n", strerror(errno));
264
265 free(line);
266 check_and_fclose(log_fp, filename);
267 close(pipefd[0]);
268 _exit(1);
269 } else {
270 // Redirect stdout/stderr to the logger process.
271 // Close the unused read end.
272 close(pipefd[0]);
273
274 setbuf(stdout, nullptr);
275 setbuf(stderr, nullptr);
276
277 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
278 LOGE("dup2 stdout failed: %s\n", strerror(errno));
279 }
280 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
281 LOGE("dup2 stderr failed: %s\n", strerror(errno));
282 }
283
284 close(pipefd[1]);
285 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800286}
287
288// command line args come from, in decreasing precedence:
289// - the actual command line
290// - the bootloader control block (one per line, after "recovery")
291// - the contents of COMMAND_FILE (one per line)
292static void
293get_args(int *argc, char ***argv) {
294 struct bootloader_message boot;
295 memset(&boot, 0, sizeof(boot));
296 get_bootloader_message(&boot); // this may fail, leaving a zeroed structure
Doug Zongkerc87bab12013-11-25 13:53:25 -0800297 stage = strndup(boot.stage, sizeof(boot.stage));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800298
299 if (boot.command[0] != 0 && boot.command[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700300 LOGI("Boot command: %.*s\n", (int)sizeof(boot.command), boot.command);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800301 }
302
303 if (boot.status[0] != 0 && boot.status[0] != 255) {
Mark Salyzynf3bb31c2014-03-14 09:39:48 -0700304 LOGI("Boot status: %.*s\n", (int)sizeof(boot.status), boot.status);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800305 }
306
307 // --- if arguments weren't supplied, look in the bootloader control block
308 if (*argc <= 1) {
309 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
310 const char *arg = strtok(boot.recovery, "\n");
311 if (arg != NULL && !strcmp(arg, "recovery")) {
312 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
313 (*argv)[0] = strdup(arg);
314 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
315 if ((arg = strtok(NULL, "\n")) == NULL) break;
316 (*argv)[*argc] = strdup(arg);
317 }
318 LOGI("Got arguments from boot message\n");
319 } else if (boot.recovery[0] != 0 && boot.recovery[0] != 255) {
320 LOGE("Bad boot message\n\"%.20s\"\n", boot.recovery);
321 }
322 }
323
Tao Baoae6408d2016-02-25 12:29:40 -0800324 // --- if that doesn't work, try the command file (if we have /cache).
325 if (*argc <= 1 && has_cache) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700326 FILE *fp = fopen_path(COMMAND_FILE, "r");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800327 if (fp != NULL) {
Jin Feng93ffa752013-06-04 17:46:24 +0800328 char *token;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800329 char *argv0 = (*argv)[0];
330 *argv = (char **) malloc(sizeof(char *) * MAX_ARGS);
331 (*argv)[0] = argv0; // use the same program name
332
333 char buf[MAX_ARG_LENGTH];
334 for (*argc = 1; *argc < MAX_ARGS; ++*argc) {
335 if (!fgets(buf, sizeof(buf), fp)) break;
Jin Feng93ffa752013-06-04 17:46:24 +0800336 token = strtok(buf, "\r\n");
337 if (token != NULL) {
338 (*argv)[*argc] = strdup(token); // Strip newline.
339 } else {
340 --*argc;
341 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800342 }
343
344 check_and_fclose(fp, COMMAND_FILE);
345 LOGI("Got arguments from %s\n", COMMAND_FILE);
346 }
347 }
348
349 // --> write the arguments we have back into the bootloader control block
350 // always boot into recovery after this (until finish_recovery() is called)
351 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
352 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
353 int i;
354 for (i = 1; i < *argc; ++i) {
355 strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
356 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
357 }
358 set_bootloader_message(&boot);
359}
360
Doug Zongker34c98df2009-08-18 12:05:45 -0700361static void
Oscar Montemayor05231562009-11-30 08:40:57 -0800362set_sdcard_update_bootloader_message() {
Doug Zongker34c98df2009-08-18 12:05:45 -0700363 struct bootloader_message boot;
364 memset(&boot, 0, sizeof(boot));
365 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
366 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
367 set_bootloader_message(&boot);
368}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800369
Tao Baobef39712015-05-04 18:50:27 -0700370// Read from kernel log into buffer and write out to file.
371static void save_kernel_log(const char* destination) {
372 int klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800373 if (klog_buf_len <= 0) {
Tao Baobef39712015-05-04 18:50:27 -0700374 LOGE("Error getting klog size: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800375 return;
376 }
377
Tao Baobef39712015-05-04 18:50:27 -0700378 std::string buffer(klog_buf_len, 0);
379 int n = klogctl(KLOG_READ_ALL, &buffer[0], klog_buf_len);
380 if (n == -1) {
381 LOGE("Error in reading klog: %s\n", strerror(errno));
Patrick Tjincd055ee2014-12-09 11:26:40 -0800382 return;
383 }
Tao Baobef39712015-05-04 18:50:27 -0700384 buffer.resize(n);
385 android::base::WriteStringToFile(buffer, destination);
Patrick Tjincd055ee2014-12-09 11:26:40 -0800386}
387
Mark Salyzyn13aca592016-03-09 14:58:16 -0800388// write content to the current pmsg session.
389static ssize_t __pmsg_write(const char *filename, const char *buf, size_t len) {
390 return __android_log_pmsg_file_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
391 filename, buf, len);
392}
393
394static void copy_log_file_to_pmsg(const char* source, const char* destination) {
395 std::string content;
396 android::base::ReadFileToString(source, &content);
397 __pmsg_write(destination, content.c_str(), content.length());
398}
399
Tao Baof0124322015-04-11 02:04:11 +0000400// How much of the temp log we have copied to the copy in cache.
401static long tmplog_offset = 0;
402
Tao Baobef39712015-05-04 18:50:27 -0700403static void copy_log_file(const char* source, const char* destination, bool append) {
404 FILE* dest_fp = fopen_path(destination, append ? "a" : "w");
405 if (dest_fp == nullptr) {
Doug Zongker2c3539e2010-09-29 13:21:30 -0700406 LOGE("Can't open %s\n", destination);
407 } else {
Tao Baobef39712015-05-04 18:50:27 -0700408 FILE* source_fp = fopen(source, "r");
409 if (source_fp != nullptr) {
Tao Baof0124322015-04-11 02:04:11 +0000410 if (append) {
Tao Baobef39712015-05-04 18:50:27 -0700411 fseek(source_fp, tmplog_offset, SEEK_SET); // Since last write
Doug Zongker2c3539e2010-09-29 13:21:30 -0700412 }
413 char buf[4096];
Tao Baobef39712015-05-04 18:50:27 -0700414 size_t bytes;
415 while ((bytes = fread(buf, 1, sizeof(buf), source_fp)) != 0) {
416 fwrite(buf, 1, bytes, dest_fp);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700417 }
Tao Baobef39712015-05-04 18:50:27 -0700418 if (append) {
419 tmplog_offset = ftell(source_fp);
420 }
421 check_and_fclose(source_fp, source);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700422 }
Tao Baobef39712015-05-04 18:50:27 -0700423 check_and_fclose(dest_fp, destination);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700424 }
425}
426
Tao Baobef39712015-05-04 18:50:27 -0700427// Rename last_log -> last_log.1 -> last_log.2 -> ... -> last_log.$max.
428// Similarly rename last_kmsg -> last_kmsg.1 -> ... -> last_kmsg.$max.
429// Overwrite any existing last_log.$max and last_kmsg.$max.
430static void rotate_logs(int max) {
Tao Bao682c34b2015-04-07 17:16:35 -0700431 // Logs should only be rotated once.
432 static bool rotated = false;
433 if (rotated) {
434 return;
435 }
436 rotated = true;
437 ensure_path_mounted(LAST_LOG_FILE);
Tao Baobef39712015-05-04 18:50:27 -0700438 ensure_path_mounted(LAST_KMSG_FILE);
Tao Bao682c34b2015-04-07 17:16:35 -0700439
Tao Bao682c34b2015-04-07 17:16:35 -0700440 for (int i = max-1; i >= 0; --i) {
Tao Bao80e46e02015-06-03 10:49:29 -0700441 std::string old_log = android::base::StringPrintf("%s", LAST_LOG_FILE);
442 if (i > 0) {
443 old_log += "." + std::to_string(i);
444 }
Tao Baobef39712015-05-04 18:50:27 -0700445 std::string new_log = android::base::StringPrintf("%s.%d", LAST_LOG_FILE, i+1);
446 // Ignore errors if old_log doesn't exist.
447 rename(old_log.c_str(), new_log.c_str());
448
Tao Bao80e46e02015-06-03 10:49:29 -0700449 std::string old_kmsg = android::base::StringPrintf("%s", LAST_KMSG_FILE);
450 if (i > 0) {
451 old_kmsg += "." + std::to_string(i);
452 }
Tao Baobef39712015-05-04 18:50:27 -0700453 std::string new_kmsg = android::base::StringPrintf("%s.%d", LAST_KMSG_FILE, i+1);
454 rename(old_kmsg.c_str(), new_kmsg.c_str());
Doug Zongkerda1ebae2013-05-16 11:23:48 -0700455 }
456}
Doug Zongker2c3539e2010-09-29 13:21:30 -0700457
Tao Bao682c34b2015-04-07 17:16:35 -0700458static void copy_logs() {
459 // We only rotate and record the log of the current session if there are
460 // actual attempts to modify the flash, such as wipes, installs from BCB
461 // or menu selections. This is to avoid unnecessary rotation (and
462 // possible deletion) of log files, if it does not do anything loggable.
463 if (!modified_flash) {
464 return;
465 }
466
Mark Salyzyn13aca592016-03-09 14:58:16 -0800467 // Always write to pmsg, this allows the OTA logs to be caught in logcat -L
468 copy_log_file_to_pmsg(TEMPORARY_LOG_FILE, LAST_LOG_FILE);
469 copy_log_file_to_pmsg(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE);
470
471 // We can do nothing for now if there's no /cache partition.
472 if (!has_cache) {
473 return;
474 }
475
Tao Baobef39712015-05-04 18:50:27 -0700476 rotate_logs(KEEP_LOG_COUNT);
Tao Bao682c34b2015-04-07 17:16:35 -0700477
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700478 // Copy logs to cache so the system can find out what happened.
Tao Baof0124322015-04-11 02:04:11 +0000479 copy_log_file(TEMPORARY_LOG_FILE, LOG_FILE, true);
480 copy_log_file(TEMPORARY_LOG_FILE, LAST_LOG_FILE, false);
481 copy_log_file(TEMPORARY_INSTALL_FILE, LAST_INSTALL_FILE, false);
482 save_kernel_log(LAST_KMSG_FILE);
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700483 chmod(LOG_FILE, 0600);
484 chown(LOG_FILE, 1000, 1000); // system user
Tao Baof0124322015-04-11 02:04:11 +0000485 chmod(LAST_KMSG_FILE, 0600);
486 chown(LAST_KMSG_FILE, 1000, 1000); // system user
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700487 chmod(LAST_LOG_FILE, 0640);
488 chmod(LAST_INSTALL_FILE, 0644);
489 sync();
490}
491
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800492// clear the recovery command and prepare to boot a (hopefully working) system,
493// copy our log file to cache as well (for the system to read), and
494// record any intent we were asked to communicate back to the system.
495// this function is idempotent: call it as many times as you like.
496static void
Oscar Montemayor05231562009-11-30 08:40:57 -0800497finish_recovery(const char *send_intent) {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800498 // By this point, we're ready to return to the main system...
Tao Baoae6408d2016-02-25 12:29:40 -0800499 if (send_intent != NULL && has_cache) {
Doug Zongkerd4208f92010-09-20 12:16:13 -0700500 FILE *fp = fopen_path(INTENT_FILE, "w");
Jay Freeman (saurik)619ec2f2008-11-17 01:56:05 +0000501 if (fp == NULL) {
502 LOGE("Can't open %s\n", INTENT_FILE);
503 } else {
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800504 fputs(send_intent, fp);
505 check_and_fclose(fp, INTENT_FILE);
506 }
507 }
508
Doug Zongker4f33e552012-08-23 13:16:12 -0700509 // Save the locale to cache, so if recovery is next started up
510 // without a --locale argument (eg, directly from the bootloader)
511 // it will use the last-known locale.
Mark Salyzyn13aca592016-03-09 14:58:16 -0800512 if (locale != NULL) {
513 size_t len = strlen(locale);
514 __pmsg_write(LOCALE_FILE, locale, len);
515 if (has_cache) {
516 LOGI("Saving locale \"%s\"\n", locale);
517 FILE* fp = fopen_path(LOCALE_FILE, "w");
518 fwrite(locale, 1, len, fp);
519 fflush(fp);
520 fsync(fileno(fp));
521 check_and_fclose(fp, LOCALE_FILE);
522 }
Doug Zongker4f33e552012-08-23 13:16:12 -0700523 }
524
Doug Zongkerf24fd7e2013-07-02 11:43:25 -0700525 copy_logs();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800526
Doug Zongkere5d5ac72012-04-12 11:01:22 -0700527 // Reset to normal system boot so recovery won't cycle indefinitely.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800528 struct bootloader_message boot;
529 memset(&boot, 0, sizeof(boot));
530 set_bootloader_message(&boot);
531
532 // Remove the command file, so recovery won't repeat indefinitely.
Tao Baoae6408d2016-02-25 12:29:40 -0800533 if (has_cache) {
534 if (ensure_path_mounted(COMMAND_FILE) != 0 || (unlink(COMMAND_FILE) && errno != ENOENT)) {
535 LOGW("Can't unlink %s\n", COMMAND_FILE);
536 }
537 ensure_path_unmounted(CACHE_ROOT);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800538 }
539
540 sync(); // For good measure.
541}
542
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700543typedef struct _saved_log_file {
544 char* name;
545 struct stat st;
546 unsigned char* data;
547 struct _saved_log_file* next;
548} saved_log_file;
549
Elliott Hughes945548e2015-06-05 17:59:56 -0700550static bool erase_volume(const char* volume) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700551 bool is_cache = (strcmp(volume, CACHE_ROOT) == 0);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800552 bool is_data = (strcmp(volume, DATA_ROOT) == 0);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700553
Doug Zongker02ec6b82012-08-22 17:26:40 -0700554 ui->SetBackground(RecoveryUI::ERASING);
Doug Zongker211aebc2011-10-28 15:13:10 -0700555 ui->SetProgressType(RecoveryUI::INDETERMINATE);
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700556
557 saved_log_file* head = NULL;
558
559 if (is_cache) {
Tao Baobef39712015-05-04 18:50:27 -0700560 // If we're reformatting /cache, we load any past logs
561 // (i.e. "/cache/recovery/last_*") and the current log
562 // ("/cache/recovery/log") into memory, so we can restore them after
563 // the reformat.
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700564
565 ensure_path_mounted(volume);
566
567 DIR* d;
568 struct dirent* de;
569 d = opendir(CACHE_LOG_DIR);
570 if (d) {
571 char path[PATH_MAX];
572 strcpy(path, CACHE_LOG_DIR);
573 strcat(path, "/");
574 int path_len = strlen(path);
575 while ((de = readdir(d)) != NULL) {
Tao Baobef39712015-05-04 18:50:27 -0700576 if (strncmp(de->d_name, "last_", 5) == 0 || strcmp(de->d_name, "log") == 0) {
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700577 saved_log_file* p = (saved_log_file*) malloc(sizeof(saved_log_file));
578 strcpy(path+path_len, de->d_name);
579 p->name = strdup(path);
580 if (stat(path, &(p->st)) == 0) {
581 // truncate files to 512kb
582 if (p->st.st_size > (1 << 19)) {
583 p->st.st_size = 1 << 19;
584 }
585 p->data = (unsigned char*) malloc(p->st.st_size);
586 FILE* f = fopen(path, "rb");
587 fread(p->data, 1, p->st.st_size, f);
588 fclose(f);
589 p->next = head;
590 head = p;
591 } else {
592 free(p);
593 }
594 }
595 }
596 closedir(d);
597 } else {
598 if (errno != ENOENT) {
599 printf("opendir failed: %s\n", strerror(errno));
600 }
601 }
602 }
603
Doug Zongker211aebc2011-10-28 15:13:10 -0700604 ui->Print("Formatting %s...\n", volume);
Doug Zongker2c3539e2010-09-29 13:21:30 -0700605
Doug Zongkerd0181b82011-10-19 10:51:12 -0700606 ensure_path_unmounted(volume);
Paul Lawrenced0db3372015-11-05 13:38:40 -0800607
608 int result;
609
610 if (is_data && reason && strcmp(reason, "convert_fbe") == 0) {
611 // Create convert_fbe breadcrumb file to signal to init
612 // to convert to file based encryption, not full disk encryption
Paul Lawrence661f8a62016-02-25 12:42:19 -0800613 if (mkdir(CONVERT_FBE_DIR, 0700) != 0) {
614 ui->Print("Failed to make convert_fbe dir %s\n", strerror(errno));
615 return true;
616 }
Paul Lawrenced0db3372015-11-05 13:38:40 -0800617 FILE* f = fopen(CONVERT_FBE_FILE, "wb");
618 if (!f) {
Paul Lawrence661f8a62016-02-25 12:42:19 -0800619 ui->Print("Failed to convert to file encryption %s\n", strerror(errno));
Paul Lawrenced0db3372015-11-05 13:38:40 -0800620 return true;
621 }
622 fclose(f);
623 result = format_volume(volume, CONVERT_FBE_DIR);
624 remove(CONVERT_FBE_FILE);
625 rmdir(CONVERT_FBE_DIR);
626 } else {
627 result = format_volume(volume);
628 }
Doug Zongkerd0181b82011-10-19 10:51:12 -0700629
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700630 if (is_cache) {
631 while (head) {
632 FILE* f = fopen_path(head->name, "wb");
633 if (f) {
634 fwrite(head->data, 1, head->st.st_size, f);
635 fclose(f);
636 chmod(head->name, head->st.st_mode);
637 chown(head->name, head->st.st_uid, head->st.st_gid);
638 }
639 free(head->name);
640 free(head->data);
641 saved_log_file* temp = head->next;
642 free(head);
643 head = temp;
644 }
645
Tao Baof0124322015-04-11 02:04:11 +0000646 // Any part of the log we'd copied to cache is now gone.
647 // Reset the pointer so we copy from the beginning of the temp
648 // log.
649 tmplog_offset = 0;
Doug Zongker6d0d7ac2013-07-09 13:34:55 -0700650 copy_logs();
Doug Zongker2c3539e2010-09-29 13:21:30 -0700651 }
652
Elliott Hughes945548e2015-06-05 17:59:56 -0700653 return (result == 0);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800654}
655
Doug Zongkerf93d8162009-09-22 15:16:02 -0700656static int
Doug Zongker28ce47c2011-10-28 10:33:05 -0700657get_menu_selection(const char* const * headers, const char* const * items,
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700658 int menu_only, int initial_selection, Device* device) {
Doug Zongkerf93d8162009-09-22 15:16:02 -0700659 // throw away keys pressed previously, so user doesn't
660 // accidentally trigger menu items.
Doug Zongker211aebc2011-10-28 15:13:10 -0700661 ui->FlushKeys();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700662
Doug Zongker211aebc2011-10-28 15:13:10 -0700663 ui->StartMenu(headers, items, initial_selection);
Doug Zongker8674a722010-09-15 11:08:23 -0700664 int selected = initial_selection;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800665 int chosen_item = -1;
666
Doug Zongkerf93d8162009-09-22 15:16:02 -0700667 while (chosen_item < 0) {
Doug Zongker211aebc2011-10-28 15:13:10 -0700668 int key = ui->WaitKey();
669 int visible = ui->IsTextVisible();
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800670
Doug Zongker5cae4452011-01-25 13:15:30 -0800671 if (key == -1) { // ui_wait_key() timed out
Doug Zongker211aebc2011-10-28 15:13:10 -0700672 if (ui->WasTextEverVisible()) {
Doug Zongker5cae4452011-01-25 13:15:30 -0800673 continue;
674 } else {
675 LOGI("timed out waiting for key input; rebooting.\n");
Doug Zongker211aebc2011-10-28 15:13:10 -0700676 ui->EndMenu();
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700677 return 0; // XXX fixme
Doug Zongker5cae4452011-01-25 13:15:30 -0800678 }
679 }
680
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700681 int action = device->HandleMenuKey(key, visible);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700682
683 if (action < 0) {
684 switch (action) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700685 case Device::kHighlightUp:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700686 selected = ui->SelectMenu(--selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700687 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700688 case Device::kHighlightDown:
Elliott Hughes642aaa72015-04-10 12:47:46 -0700689 selected = ui->SelectMenu(++selected);
Doug Zongkerddd6a282009-06-09 12:22:33 -0700690 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700691 case Device::kInvokeItem:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700692 chosen_item = selected;
693 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700694 case Device::kNoAction:
Doug Zongkerddd6a282009-06-09 12:22:33 -0700695 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800696 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700697 } else if (!menu_only) {
Doug Zongkerddd6a282009-06-09 12:22:33 -0700698 chosen_item = action;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800699 }
Doug Zongkerf93d8162009-09-22 15:16:02 -0700700 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800701
Doug Zongker211aebc2011-10-28 15:13:10 -0700702 ui->EndMenu();
Doug Zongkerf93d8162009-09-22 15:16:02 -0700703 return chosen_item;
704}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800705
Doug Zongker8674a722010-09-15 11:08:23 -0700706static int compare_string(const void* a, const void* b) {
707 return strcmp(*(const char**)a, *(const char**)b);
708}
709
Doug Zongker93950222014-07-08 14:10:23 -0700710// Returns a malloc'd path, or NULL.
Elliott Hughes30694c92015-03-25 15:16:51 -0700711static char* browse_directory(const char* path, Device* device) {
Michael Ward9d2629c2011-06-23 22:14:24 -0700712 ensure_path_mounted(path);
Doug Zongkerc18eeb82010-09-21 16:49:26 -0700713
Elliott Hughes30694c92015-03-25 15:16:51 -0700714 DIR* d = opendir(path);
Doug Zongker8674a722010-09-15 11:08:23 -0700715 if (d == NULL) {
716 LOGE("error opening %s: %s\n", path, strerror(errno));
Doug Zongker93950222014-07-08 14:10:23 -0700717 return NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700718 }
719
Doug Zongker8674a722010-09-15 11:08:23 -0700720 int d_size = 0;
721 int d_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700722 char** dirs = (char**)malloc(d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700723 int z_size = 1;
724 int z_alloc = 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700725 char** zips = (char**)malloc(z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700726 zips[0] = strdup("../");
727
Elliott Hughes30694c92015-03-25 15:16:51 -0700728 struct dirent* de;
Doug Zongker8674a722010-09-15 11:08:23 -0700729 while ((de = readdir(d)) != NULL) {
730 int name_len = strlen(de->d_name);
731
732 if (de->d_type == DT_DIR) {
733 // skip "." and ".." entries
734 if (name_len == 1 && de->d_name[0] == '.') continue;
735 if (name_len == 2 && de->d_name[0] == '.' &&
736 de->d_name[1] == '.') continue;
737
738 if (d_size >= d_alloc) {
739 d_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700740 dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700741 }
Doug Zongker28ce47c2011-10-28 10:33:05 -0700742 dirs[d_size] = (char*)malloc(name_len + 2);
Doug Zongker8674a722010-09-15 11:08:23 -0700743 strcpy(dirs[d_size], de->d_name);
744 dirs[d_size][name_len] = '/';
745 dirs[d_size][name_len+1] = '\0';
746 ++d_size;
747 } else if (de->d_type == DT_REG &&
748 name_len >= 4 &&
749 strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
750 if (z_size >= z_alloc) {
751 z_alloc *= 2;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700752 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700753 }
754 zips[z_size++] = strdup(de->d_name);
755 }
756 }
757 closedir(d);
758
759 qsort(dirs, d_size, sizeof(char*), compare_string);
760 qsort(zips, z_size, sizeof(char*), compare_string);
761
762 // append dirs to the zips list
763 if (d_size + z_size + 1 > z_alloc) {
764 z_alloc = d_size + z_size + 1;
Doug Zongker28ce47c2011-10-28 10:33:05 -0700765 zips = (char**)realloc(zips, z_alloc * sizeof(char*));
Doug Zongker8674a722010-09-15 11:08:23 -0700766 }
767 memcpy(zips + z_size, dirs, d_size * sizeof(char*));
768 free(dirs);
769 z_size += d_size;
770 zips[z_size] = NULL;
771
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700772 const char* headers[] = { "Choose a package to install:", path, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700773
Doug Zongker93950222014-07-08 14:10:23 -0700774 char* result;
Doug Zongker8674a722010-09-15 11:08:23 -0700775 int chosen_item = 0;
Doug Zongker93950222014-07-08 14:10:23 -0700776 while (true) {
Doug Zongkerdaefc1d2011-10-31 09:34:15 -0700777 chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
Doug Zongker8674a722010-09-15 11:08:23 -0700778
779 char* item = zips[chosen_item];
780 int item_len = strlen(item);
781 if (chosen_item == 0) { // item 0 is always "../"
Michael Ward9d2629c2011-06-23 22:14:24 -0700782 // go up but continue browsing (if the caller is update_directory)
Doug Zongker93950222014-07-08 14:10:23 -0700783 result = NULL;
Doug Zongker8674a722010-09-15 11:08:23 -0700784 break;
785 }
Doug Zongker93950222014-07-08 14:10:23 -0700786
787 char new_path[PATH_MAX];
788 strlcpy(new_path, path, PATH_MAX);
789 strlcat(new_path, "/", PATH_MAX);
790 strlcat(new_path, item, PATH_MAX);
791
792 if (item[item_len-1] == '/') {
793 // recurse down into a subdirectory
794 new_path[strlen(new_path)-1] = '\0'; // truncate the trailing '/'
795 result = browse_directory(new_path, device);
796 if (result) break;
797 } else {
798 // selected a zip file: return the malloc'd path to the caller.
799 result = strdup(new_path);
800 break;
801 }
802 }
Doug Zongker8674a722010-09-15 11:08:23 -0700803
Elliott Hughes30694c92015-03-25 15:16:51 -0700804 for (int i = 0; i < z_size; ++i) free(zips[i]);
Doug Zongker8674a722010-09-15 11:08:23 -0700805 free(zips);
Doug Zongker8674a722010-09-15 11:08:23 -0700806
807 return result;
808}
809
Elliott Hughes30694c92015-03-25 15:16:51 -0700810static bool yes_no(Device* device, const char* question1, const char* question2) {
Elliott Hughes8fd86d72015-04-13 14:36:02 -0700811 const char* headers[] = { question1, question2, NULL };
Elliott Hughes30694c92015-03-25 15:16:51 -0700812 const char* items[] = { " No", " Yes", NULL };
Doug Zongkerddd6a282009-06-09 12:22:33 -0700813
Elliott Hughes30694c92015-03-25 15:16:51 -0700814 int chosen_item = get_menu_selection(headers, items, 1, 0, device);
815 return (chosen_item == 1);
816}
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -0800817
Tao Baoe39a9bc2015-03-31 12:19:05 -0700818// Return true on success.
819static bool wipe_data(int should_confirm, Device* device) {
820 if (should_confirm && !yes_no(device, "Wipe all user data?", " THIS CAN NOT BE UNDONE!")) {
821 return false;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700822 }
Doug Zongker1066d2c2009-04-01 13:57:40 -0700823
Tao Bao682c34b2015-04-07 17:16:35 -0700824 modified_flash = true;
825
Doug Zongker211aebc2011-10-28 15:13:10 -0700826 ui->Print("\n-- Wiping data...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700827 bool success =
828 device->PreWipeData() &&
829 erase_volume("/data") &&
Tao Baoae6408d2016-02-25 12:29:40 -0800830 (has_cache ? erase_volume("/cache") : true) &&
Elliott Hughes945548e2015-06-05 17:59:56 -0700831 device->PostWipeData();
832 ui->Print("Data wipe %s.\n", success ? "complete" : "failed");
833 return success;
Doug Zongkerf93d8162009-09-22 15:16:02 -0700834}
835
Tao Baoe39a9bc2015-03-31 12:19:05 -0700836// Return true on success.
837static bool wipe_cache(bool should_confirm, Device* device) {
Tao Baoae6408d2016-02-25 12:29:40 -0800838 if (!has_cache) {
839 ui->Print("No /cache partition found.\n");
840 return false;
841 }
842
Elliott Hughes30694c92015-03-25 15:16:51 -0700843 if (should_confirm && !yes_no(device, "Wipe cache?", " THIS CAN NOT BE UNDONE!")) {
Tao Baoe39a9bc2015-03-31 12:19:05 -0700844 return false;
Elliott Hughes30694c92015-03-25 15:16:51 -0700845 }
846
Tao Bao682c34b2015-04-07 17:16:35 -0700847 modified_flash = true;
848
Elliott Hughes30694c92015-03-25 15:16:51 -0700849 ui->Print("\n-- Wiping cache...\n");
Elliott Hughes945548e2015-06-05 17:59:56 -0700850 bool success = erase_volume("/cache");
851 ui->Print("Cache wipe %s.\n", success ? "complete" : "failed");
852 return success;
Elliott Hughes30694c92015-03-25 15:16:51 -0700853}
854
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700855static void choose_recovery_file(Device* device) {
Tao Baoae6408d2016-02-25 12:29:40 -0800856 if (!has_cache) {
857 ui->Print("No /cache partition found.\n");
858 return;
859 }
860
Elliott Hughesc0491632015-05-06 12:40:05 -0700861 // "Back" + KEEP_LOG_COUNT * 2 + terminating nullptr entry
862 char* entries[1 + KEEP_LOG_COUNT * 2 + 1];
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700863 memset(entries, 0, sizeof(entries));
864
Tao Baobef39712015-05-04 18:50:27 -0700865 unsigned int n = 0;
Patrick Tjincd055ee2014-12-09 11:26:40 -0800866
Patrick Tjincd055ee2014-12-09 11:26:40 -0800867 // Add LAST_LOG_FILE + LAST_LOG_FILE.x
Tao Baobef39712015-05-04 18:50:27 -0700868 // Add LAST_KMSG_FILE + LAST_KMSG_FILE.x
869 for (int i = 0; i < KEEP_LOG_COUNT; i++) {
870 char* log_file;
Tao Bao80e46e02015-06-03 10:49:29 -0700871 int ret;
872 ret = (i == 0) ? asprintf(&log_file, "%s", LAST_LOG_FILE) :
873 asprintf(&log_file, "%s.%d", LAST_LOG_FILE, i);
874 if (ret == -1) {
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700875 // memory allocation failure - return early. Should never happen.
876 return;
877 }
Tao Baobef39712015-05-04 18:50:27 -0700878 if ((ensure_path_mounted(log_file) != 0) || (access(log_file, R_OK) == -1)) {
879 free(log_file);
880 } else {
881 entries[n++] = log_file;
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700882 }
Tao Baobef39712015-05-04 18:50:27 -0700883
884 char* kmsg_file;
Tao Bao80e46e02015-06-03 10:49:29 -0700885 ret = (i == 0) ? asprintf(&kmsg_file, "%s", LAST_KMSG_FILE) :
886 asprintf(&kmsg_file, "%s.%d", LAST_KMSG_FILE, i);
887 if (ret == -1) {
Tao Baobef39712015-05-04 18:50:27 -0700888 // memory allocation failure - return early. Should never happen.
889 return;
890 }
891 if ((ensure_path_mounted(kmsg_file) != 0) || (access(kmsg_file, R_OK) == -1)) {
892 free(kmsg_file);
893 } else {
894 entries[n++] = kmsg_file;
895 }
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700896 }
897
Elliott Hughesc0491632015-05-06 12:40:05 -0700898 entries[n++] = strdup("Back");
899
Tao Baobef39712015-05-04 18:50:27 -0700900 const char* headers[] = { "Select file to view", nullptr };
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700901
Elliott Hughes8de52072015-04-08 20:06:50 -0700902 while (true) {
Elliott Hughes30694c92015-03-25 15:16:51 -0700903 int chosen_item = get_menu_selection(headers, entries, 1, 0, device);
Elliott Hughesc0491632015-05-06 12:40:05 -0700904 if (strcmp(entries[chosen_item], "Back") == 0) break;
Elliott Hughes8de52072015-04-08 20:06:50 -0700905
Elliott Hughes8de52072015-04-08 20:06:50 -0700906 ui->ShowFile(entries[chosen_item]);
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700907 }
908
Tao Baobef39712015-05-04 18:50:27 -0700909 for (size_t i = 0; i < (sizeof(entries) / sizeof(*entries)); i++) {
Nick Kralevicha9ad0322014-10-22 18:38:48 -0700910 free(entries[i]);
911 }
912}
913
Elliott Hughes498cda62016-04-14 16:49:04 -0700914static void run_graphics_test(Device* device) {
915 // Switch to graphics screen.
916 ui->ShowText(false);
917
918 ui->SetProgressType(RecoveryUI::INDETERMINATE);
919 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
920 sleep(1);
921
922 ui->SetBackground(RecoveryUI::ERROR);
923 sleep(1);
924
925 ui->SetBackground(RecoveryUI::NO_COMMAND);
926 sleep(1);
927
928 ui->SetBackground(RecoveryUI::ERASING);
929 sleep(1);
930
931 ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
932
933 ui->SetProgressType(RecoveryUI::DETERMINATE);
934 ui->ShowProgress(1.0, 10.0);
935 float fraction = 0.0;
936 for (size_t i = 0; i < 100; ++i) {
937 fraction += .01;
938 ui->SetProgress(fraction);
939 usleep(100000);
940 }
941
942 ui->ShowText(true);
943}
944
Tao Baocdcf28f2016-01-13 15:05:20 -0800945// How long (in seconds) we wait for the fuse-provided package file to
946// appear, before timing out.
947#define SDCARD_INSTALL_TIMEOUT 10
948
Tao Bao145d8612015-03-25 15:51:15 -0700949static int apply_from_sdcard(Device* device, bool* wipe_cache) {
Tao Bao682c34b2015-04-07 17:16:35 -0700950 modified_flash = true;
951
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000952 if (ensure_path_mounted(SDCARD_ROOT) != 0) {
953 ui->Print("\n-- Couldn't mount %s.\n", SDCARD_ROOT);
954 return INSTALL_ERROR;
955 }
956
957 char* path = browse_directory(SDCARD_ROOT, device);
958 if (path == NULL) {
Elliott Hughes018ed312015-04-08 16:51:36 -0700959 ui->Print("\n-- No package file selected.\n");
caozhiyuanb4effb92015-06-10 16:46:38 +0800960 ensure_path_unmounted(SDCARD_ROOT);
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000961 return INSTALL_ERROR;
962 }
963
964 ui->Print("\n-- Install %s ...\n", path);
965 set_sdcard_update_bootloader_message();
Christian Poetzsch4ec58a42015-02-19 10:42:39 +0000966
Tao Baocdcf28f2016-01-13 15:05:20 -0800967 // We used to use fuse in a thread as opposed to a process. Since accessing
968 // through fuse involves going from kernel to userspace to kernel, it leads
969 // to deadlock when a page fault occurs. (Bug: 26313124)
970 pid_t child;
971 if ((child = fork()) == 0) {
972 bool status = start_sdcard_fuse(path);
973
974 _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
975 }
976
977 // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the fuse in child
978 // process is ready.
979 int result = INSTALL_ERROR;
980 int status;
981 bool waited = false;
982 for (int i = 0; i < SDCARD_INSTALL_TIMEOUT; ++i) {
983 if (waitpid(child, &status, WNOHANG) == -1) {
984 result = INSTALL_ERROR;
985 waited = true;
986 break;
987 }
988
989 struct stat sb;
990 if (stat(FUSE_SIDELOAD_HOST_PATHNAME, &sb) == -1) {
991 if (errno == ENOENT && i < SDCARD_INSTALL_TIMEOUT-1) {
992 sleep(1);
993 continue;
994 } else {
995 LOGE("Timed out waiting for the fuse-provided package.\n");
996 result = INSTALL_ERROR;
997 kill(child, SIGKILL);
998 break;
999 }
1000 }
1001
1002 result = install_package(FUSE_SIDELOAD_HOST_PATHNAME, wipe_cache,
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001003 TEMPORARY_INSTALL_FILE, false);
Tao Baocdcf28f2016-01-13 15:05:20 -08001004 break;
1005 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001006
Tao Baocdcf28f2016-01-13 15:05:20 -08001007 if (!waited) {
1008 // Calling stat() on this magic filename signals the fuse
1009 // filesystem to shut down.
1010 struct stat sb;
1011 stat(FUSE_SIDELOAD_HOST_EXIT_PATHNAME, &sb);
1012
1013 waitpid(child, &status, 0);
1014 }
1015
1016 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1017 LOGE("Error exit from the fuse process: %d\n", WEXITSTATUS(status));
1018 }
1019
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001020 ensure_path_unmounted(SDCARD_ROOT);
Tao Baocdcf28f2016-01-13 15:05:20 -08001021 return result;
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001022}
1023
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001024// Return REBOOT, SHUTDOWN, or REBOOT_BOOTLOADER. Returning NO_ACTION
1025// means to take the default, which is to reboot or shutdown depending
1026// on if the --shutdown_after flag was passed to recovery.
1027static Device::BuiltinAction
Doug Zongker6c8553d2012-09-24 10:40:47 -07001028prompt_and_wait(Device* device, int status) {
Doug Zongkerf93d8162009-09-22 15:16:02 -07001029 for (;;) {
1030 finish_recovery(NULL);
Doug Zongker6c8553d2012-09-24 10:40:47 -07001031 switch (status) {
1032 case INSTALL_SUCCESS:
1033 case INSTALL_NONE:
1034 ui->SetBackground(RecoveryUI::NO_COMMAND);
1035 break;
1036
1037 case INSTALL_ERROR:
1038 case INSTALL_CORRUPT:
1039 ui->SetBackground(RecoveryUI::ERROR);
1040 break;
1041 }
Doug Zongker211aebc2011-10-28 15:13:10 -07001042 ui->SetProgressType(RecoveryUI::EMPTY);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001043
Elliott Hughes8fd86d72015-04-13 14:36:02 -07001044 int chosen_item = get_menu_selection(nullptr, device->GetMenuItems(), 0, 0, device);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001045
1046 // device-specific code may take some action here. It may
1047 // return one of the core actions handled in the switch
1048 // statement below.
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001049 Device::BuiltinAction chosen_action = device->InvokeMenuItem(chosen_item);
Doug Zongkerf93d8162009-09-22 15:16:02 -07001050
Elliott Hughes30694c92015-03-25 15:16:51 -07001051 bool should_wipe_cache = false;
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001052 switch (chosen_action) {
1053 case Device::NO_ACTION:
1054 break;
1055
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001056 case Device::REBOOT:
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001057 case Device::SHUTDOWN:
1058 case Device::REBOOT_BOOTLOADER:
1059 return chosen_action;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001060
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001061 case Device::WIPE_DATA:
1062 wipe_data(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001063 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001064 break;
1065
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001066 case Device::WIPE_CACHE:
Elliott Hughes30694c92015-03-25 15:16:51 -07001067 wipe_cache(ui->IsTextVisible(), device);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001068 if (!ui->IsTextVisible()) return Device::NO_ACTION;
Doug Zongkerf93d8162009-09-22 15:16:02 -07001069 break;
1070
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001071 case Device::APPLY_ADB_SIDELOAD:
Elliott Hughesec283402015-04-10 10:01:53 -07001072 case Device::APPLY_SDCARD:
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001073 {
1074 bool adb = (chosen_action == Device::APPLY_ADB_SIDELOAD);
1075 if (adb) {
Elliott Hughes30694c92015-03-25 15:16:51 -07001076 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001077 } else {
Elliott Hughes30694c92015-03-25 15:16:51 -07001078 status = apply_from_sdcard(device, &should_wipe_cache);
Doug Zongkerd0181b82011-10-19 10:51:12 -07001079 }
Doug Zongker945fc682014-07-10 10:50:39 -07001080
Elliott Hughes30694c92015-03-25 15:16:51 -07001081 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001082 if (!wipe_cache(false, device)) {
1083 status = INSTALL_ERROR;
1084 }
Christian Poetzsch4ec58a42015-02-19 10:42:39 +00001085 }
1086
Tao Baoc679f932015-03-30 09:43:49 -07001087 if (status != INSTALL_SUCCESS) {
1088 ui->SetBackground(RecoveryUI::ERROR);
1089 ui->Print("Installation aborted.\n");
1090 copy_logs();
1091 } else if (!ui->IsTextVisible()) {
1092 return Device::NO_ACTION; // reboot if logs aren't visible
1093 } else {
1094 ui->Print("\nInstall from %s complete.\n", adb ? "ADB" : "SD card");
Doug Zongker8674a722010-09-15 11:08:23 -07001095 }
Doug Zongkerf93d8162009-09-22 15:16:02 -07001096 }
1097 break;
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001098
Elliott Hughesec283402015-04-10 10:01:53 -07001099 case Device::VIEW_RECOVERY_LOGS:
1100 choose_recovery_file(device);
Michael Ward9d2629c2011-06-23 22:14:24 -07001101 break;
Doug Zongker9270a202012-01-09 15:16:13 -08001102
Elliott Hughes498cda62016-04-14 16:49:04 -07001103 case Device::RUN_GRAPHICS_TEST:
1104 run_graphics_test(device);
1105 break;
1106
Elliott Hughesec283402015-04-10 10:01:53 -07001107 case Device::MOUNT_SYSTEM:
Tao Baoabb8f772015-07-30 14:43:27 -07001108 char system_root_image[PROPERTY_VALUE_MAX];
1109 property_get("ro.build.system_root_image", system_root_image, "");
1110
1111 // For a system image built with the root directory (i.e.
1112 // system_root_image == "true"), we mount it to /system_root, and symlink /system
1113 // to /system_root/system to make adb shell work (the symlink is created through
1114 // the build system).
1115 // Bug: 22855115
1116 if (strcmp(system_root_image, "true") == 0) {
1117 if (ensure_path_mounted_at("/", "/system_root") != -1) {
1118 ui->Print("Mounted /system.\n");
1119 }
1120 } else {
1121 if (ensure_path_mounted("/system") != -1) {
1122 ui->Print("Mounted /system.\n");
1123 }
Elliott Hughesec283402015-04-10 10:01:53 -07001124 }
Tao Baoabb8f772015-07-30 14:43:27 -07001125
Nick Kralevicha9ad0322014-10-22 18:38:48 -07001126 break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001127 }
1128 }
1129}
1130
1131static void
Oscar Montemayor05231562009-11-30 08:40:57 -08001132print_property(const char *key, const char *name, void *cookie) {
Doug Zongker56c51052010-07-01 09:18:44 -07001133 printf("%s=%s\n", key, name);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001134}
1135
Doug Zongker02ec6b82012-08-22 17:26:40 -07001136static void
1137load_locale_from_cache() {
1138 FILE* fp = fopen_path(LOCALE_FILE, "r");
1139 char buffer[80];
1140 if (fp != NULL) {
1141 fgets(buffer, sizeof(buffer), fp);
1142 int j = 0;
Doug Zongker5fa8c232012-09-18 12:37:02 -07001143 unsigned int i;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001144 for (i = 0; i < sizeof(buffer) && buffer[i]; ++i) {
1145 if (!isspace(buffer[i])) {
1146 buffer[j++] = buffer[i];
1147 }
1148 }
1149 buffer[j] = 0;
1150 locale = strdup(buffer);
Devin Kim6016d082012-10-08 09:47:37 -07001151 check_and_fclose(fp, LOCALE_FILE);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001152 }
1153}
1154
Doug Zongker7c3ae452013-05-14 11:03:02 -07001155static RecoveryUI* gCurrentUI = NULL;
1156
1157void
1158ui_print(const char* format, ...) {
1159 char buffer[256];
1160
1161 va_list ap;
1162 va_start(ap, format);
1163 vsnprintf(buffer, sizeof(buffer), format, ap);
1164 va_end(ap);
1165
1166 if (gCurrentUI != NULL) {
1167 gCurrentUI->Print("%s", buffer);
1168 } else {
1169 fputs(buffer, stdout);
1170 }
1171}
1172
Yabin Cui99281df2016-02-17 12:21:52 -08001173static bool is_battery_ok() {
1174 struct healthd_config healthd_config = {
1175 .batteryStatusPath = android::String8(android::String8::kEmptyString),
1176 .batteryHealthPath = android::String8(android::String8::kEmptyString),
1177 .batteryPresentPath = android::String8(android::String8::kEmptyString),
1178 .batteryCapacityPath = android::String8(android::String8::kEmptyString),
1179 .batteryVoltagePath = android::String8(android::String8::kEmptyString),
1180 .batteryTemperaturePath = android::String8(android::String8::kEmptyString),
1181 .batteryTechnologyPath = android::String8(android::String8::kEmptyString),
1182 .batteryCurrentNowPath = android::String8(android::String8::kEmptyString),
1183 .batteryCurrentAvgPath = android::String8(android::String8::kEmptyString),
1184 .batteryChargeCounterPath = android::String8(android::String8::kEmptyString),
1185 .batteryFullChargePath = android::String8(android::String8::kEmptyString),
1186 .batteryCycleCountPath = android::String8(android::String8::kEmptyString),
1187 .energyCounter = NULL,
1188 .boot_min_cap = 0,
1189 .screen_on = NULL
1190 };
1191 healthd_board_init(&healthd_config);
1192
1193 android::BatteryMonitor monitor;
1194 monitor.init(&healthd_config);
1195
1196 int wait_second = 0;
1197 while (true) {
1198 int charge_status = monitor.getChargeStatus();
1199 // Treat unknown status as charged.
1200 bool charged = (charge_status != android::BATTERY_STATUS_DISCHARGING &&
1201 charge_status != android::BATTERY_STATUS_NOT_CHARGING);
1202 android::BatteryProperty capacity;
1203 android::status_t status = monitor.getProperty(android::BATTERY_PROP_CAPACITY, &capacity);
1204 ui_print("charge_status %d, charged %d, status %d, capacity %lld\n", charge_status,
1205 charged, status, capacity.valueInt64);
1206 // At startup, the battery drivers in devices like N5X/N6P take some time to load
1207 // the battery profile. Before the load finishes, it reports value 50 as a fake
1208 // capacity. BATTERY_READ_TIMEOUT_IN_SEC is set that the battery drivers are expected
1209 // to finish loading the battery profile earlier than 10 seconds after kernel startup.
1210 if (status == 0 && capacity.valueInt64 == 50) {
1211 if (wait_second < BATTERY_READ_TIMEOUT_IN_SEC) {
1212 sleep(1);
1213 wait_second++;
1214 continue;
1215 }
1216 }
1217 // If we can't read battery percentage, it may be a device without battery. In this
1218 // situation, use 100 as a fake battery percentage.
1219 if (status != 0) {
1220 capacity.valueInt64 = 100;
1221 }
1222 return (charged && capacity.valueInt64 >= BATTERY_WITH_CHARGER_OK_PERCENTAGE) ||
1223 (!charged && capacity.valueInt64 >= BATTERY_OK_PERCENTAGE);
1224 }
1225}
1226
Tianjie Xufa12b972016-02-05 18:25:58 -08001227static void set_retry_bootloader_message(int retry_count, int argc, char** argv) {
1228 struct bootloader_message boot {};
1229 strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
1230 strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
1231
1232 for (int i = 1; i < argc; ++i) {
1233 if (strstr(argv[i], "retry_count") == nullptr) {
1234 strlcat(boot.recovery, argv[i], sizeof(boot.recovery));
1235 strlcat(boot.recovery, "\n", sizeof(boot.recovery));
1236 }
1237 }
1238
1239 // Initialize counter to 1 if it's not in BCB, otherwise increment it by 1.
1240 if (retry_count == 0) {
1241 strlcat(boot.recovery, "--retry_count=1\n", sizeof(boot.recovery));
1242 } else {
1243 char buffer[20];
1244 snprintf(buffer, sizeof(buffer), "--retry_count=%d\n", retry_count+1);
1245 strlcat(boot.recovery, buffer, sizeof(boot.recovery));
1246 }
1247 set_bootloader_message(&boot);
1248}
1249
Mark Salyzyn13aca592016-03-09 14:58:16 -08001250static ssize_t logbasename(
1251 log_id_t /* logId */,
1252 char /* prio */,
1253 const char *filename,
1254 const char * /* buf */, size_t len,
1255 void *arg) {
1256 if (strstr(LAST_KMSG_FILE, filename) ||
1257 strstr(LAST_LOG_FILE, filename)) {
1258 bool *doRotate = reinterpret_cast<bool *>(arg);
1259 *doRotate = true;
1260 }
1261 return len;
1262}
1263
1264static ssize_t logrotate(
1265 log_id_t logId,
1266 char prio,
1267 const char *filename,
1268 const char *buf, size_t len,
1269 void *arg) {
1270 bool *doRotate = reinterpret_cast<bool *>(arg);
1271 if (!*doRotate) {
1272 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1273 }
1274
1275 std::string name(filename);
1276 size_t dot = name.find_last_of(".");
1277 std::string sub = name.substr(0, dot);
1278
1279 if (!strstr(LAST_KMSG_FILE, sub.c_str()) &&
1280 !strstr(LAST_LOG_FILE, sub.c_str())) {
1281 return __android_log_pmsg_file_write(logId, prio, filename, buf, len);
1282 }
1283
1284 // filename rotation
1285 if (dot == std::string::npos) {
1286 name += ".1";
1287 } else {
1288 std::string number = name.substr(dot + 1);
1289 if (!isdigit(number.data()[0])) {
1290 name += ".1";
1291 } else {
1292 unsigned long long i = std::stoull(number);
1293 name = sub + "." + std::to_string(i + 1);
1294 }
1295 }
1296
1297 return __android_log_pmsg_file_write(logId, prio, name.c_str(), buf, len);
1298}
1299
Yabin Cui99281df2016-02-17 12:21:52 -08001300int main(int argc, char **argv) {
Mark Salyzyn13aca592016-03-09 14:58:16 -08001301 // Take last pmsg contents and rewrite it to the current pmsg session.
1302 static const char filter[] = "recovery/";
1303 // Do we need to rotate?
1304 bool doRotate = false;
1305 __android_log_pmsg_file_read(
1306 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1307 logbasename, &doRotate);
1308 // Take action to refresh pmsg contents
1309 __android_log_pmsg_file_read(
1310 LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter,
1311 logrotate, &doRotate);
1312
Doug Zongker9270a202012-01-09 15:16:13 -08001313 // If this binary is started with the single argument "--adbd",
1314 // instead of being the normal recovery binary, it turns into kind
1315 // of a stripped-down version of adbd that only supports the
1316 // 'sideload' command. Note this must be a real argument, not
1317 // anything in the command file or bootloader control block; the
1318 // only way recovery should be run with this argument is when it
1319 // starts a copy of itself from the apply_from_adb() function.
1320 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
Elliott Hughes9f4fdb32015-11-20 13:03:24 -08001321 adb_server_main(0, DEFAULT_ADB_PORT, -1);
Doug Zongker9270a202012-01-09 15:16:13 -08001322 return 0;
1323 }
1324
Tao Bao04ca4262015-09-10 15:32:24 -07001325 time_t start = time(NULL);
1326
1327 // redirect_stdio should be called only in non-sideload mode. Otherwise
1328 // we may have two logger instances with different timestamps.
1329 redirect_stdio(TEMPORARY_LOG_FILE);
1330
Doug Zongker19a8e242014-01-21 09:25:41 -08001331 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001332
Doug Zongkerd4208f92010-09-20 12:16:13 -07001333 load_volume_table();
Tao Baoae6408d2016-02-25 12:29:40 -08001334 has_cache = volume_for_path(CACHE_ROOT) != nullptr;
1335
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001336 get_args(&argc, &argv);
1337
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001338 const char *send_intent = NULL;
1339 const char *update_package = NULL;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001340 bool should_wipe_data = false;
Tao Baoc679f932015-03-30 09:43:49 -07001341 bool should_wipe_cache = false;
Tao Bao145d8612015-03-25 15:51:15 -07001342 bool show_text = false;
Tao Baoc679f932015-03-30 09:43:49 -07001343 bool sideload = false;
1344 bool sideload_auto_reboot = false;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001345 bool just_exit = false;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001346 bool shutdown_after = false;
Tianjie Xufa12b972016-02-05 18:25:58 -08001347 int retry_count = 0;
Tianjie Xu35926c42016-04-28 18:06:26 -07001348 bool security_update = false;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001349
1350 int arg;
1351 while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
1352 switch (arg) {
Tao Baoc679f932015-03-30 09:43:49 -07001353 case 'i': send_intent = optarg; break;
Tianjie Xufa12b972016-02-05 18:25:58 -08001354 case 'n': android::base::ParseInt(optarg, &retry_count, 0); break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001355 case 'u': update_package = optarg; break;
Tao Baoe39a9bc2015-03-31 12:19:05 -07001356 case 'w': should_wipe_data = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001357 case 'c': should_wipe_cache = true; break;
Tao Bao145d8612015-03-25 15:51:15 -07001358 case 't': show_text = true; break;
Tao Baoc679f932015-03-30 09:43:49 -07001359 case 's': sideload = true; break;
1360 case 'a': sideload = true; sideload_auto_reboot = true; break;
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001361 case 'x': just_exit = true; break;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001362 case 'l': locale = optarg; break;
Doug Zongkerc87bab12013-11-25 13:53:25 -08001363 case 'g': {
1364 if (stage == NULL || *stage == '\0') {
1365 char buffer[20] = "1/";
1366 strncat(buffer, optarg, sizeof(buffer)-3);
1367 stage = strdup(buffer);
1368 }
1369 break;
1370 }
Doug Zongkerb1d12632014-03-18 10:32:12 -07001371 case 'p': shutdown_after = true; break;
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001372 case 'r': reason = optarg; break;
Tianjie Xu35926c42016-04-28 18:06:26 -07001373 case 'e': security_update = true; break;
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001374 case '?':
1375 LOGE("Invalid command argument\n");
1376 continue;
1377 }
1378 }
1379
Tao Baoae6408d2016-02-25 12:29:40 -08001380 if (locale == nullptr && has_cache) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001381 load_locale_from_cache();
1382 }
1383 printf("locale is [%s]\n", locale);
Doug Zongker0d32f252014-02-13 15:07:56 -08001384 printf("stage is [%s]\n", stage);
Jeff Sharkeya6e13ae2014-09-24 11:46:17 -07001385 printf("reason is [%s]\n", reason);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001386
1387 Device* device = make_device();
1388 ui = device->GetUI();
Doug Zongker7c3ae452013-05-14 11:03:02 -07001389 gCurrentUI = ui;
Doug Zongker02ec6b82012-08-22 17:26:40 -07001390
Doug Zongker5fa8c232012-09-18 12:37:02 -07001391 ui->SetLocale(locale);
Doug Zongker02ec6b82012-08-22 17:26:40 -07001392 ui->Init();
Tianjie Xu35926c42016-04-28 18:06:26 -07001393 // Set background string to "installing security update" for security update,
1394 // otherwise set it to "installing system update".
1395 ui->SetSystemUpdateText(security_update);
Doug Zongkerc87bab12013-11-25 13:53:25 -08001396
1397 int st_cur, st_max;
1398 if (stage != NULL && sscanf(stage, "%d/%d", &st_cur, &st_max) == 2) {
1399 ui->SetStage(st_cur, st_max);
1400 }
1401
Doug Zongker02ec6b82012-08-22 17:26:40 -07001402 ui->SetBackground(RecoveryUI::NONE);
1403 if (show_text) ui->ShowText(true);
1404
Stephen Smalley779701d2012-02-09 14:13:23 -05001405 struct selinux_opt seopts[] = {
1406 { SELABEL_OPT_PATH, "/file_contexts" }
1407 };
1408
1409 sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);
1410
1411 if (!sehandle) {
Doug Zongkerfafc85b2013-07-09 12:29:45 -07001412 ui->Print("Warning: No file_contexts\n");
Stephen Smalley779701d2012-02-09 14:13:23 -05001413 }
Stephen Smalley779701d2012-02-09 14:13:23 -05001414
Doug Zongkerdaefc1d2011-10-31 09:34:15 -07001415 device->StartRecovery();
Doug Zongkerefa1bab2010-02-01 15:59:12 -08001416
Doug Zongker56c51052010-07-01 09:18:44 -07001417 printf("Command:");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001418 for (arg = 0; arg < argc; arg++) {
Doug Zongker56c51052010-07-01 09:18:44 -07001419 printf(" \"%s\"", argv[arg]);
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001420 }
Doug Zongker9b125b02010-09-22 12:01:37 -07001421 printf("\n");
1422
1423 if (update_package) {
1424 // For backwards compatibility on the cache partition only, if
1425 // we're given an old 'root' path "CACHE:foo", change it to
1426 // "/cache/foo".
1427 if (strncmp(update_package, "CACHE:", 6) == 0) {
1428 int len = strlen(update_package) + 10;
Doug Zongker28ce47c2011-10-28 10:33:05 -07001429 char* modified_path = (char*)malloc(len);
Jeremy Compostella1b7d9b72015-07-29 17:17:03 +02001430 if (modified_path) {
1431 strlcpy(modified_path, "/cache/", len);
1432 strlcat(modified_path, update_package+6, len);
1433 printf("(replacing path \"%s\" with \"%s\")\n",
1434 update_package, modified_path);
1435 update_package = modified_path;
1436 }
1437 else
1438 printf("modified_path allocation failed\n");
Doug Zongker9b125b02010-09-22 12:01:37 -07001439 }
1440 }
1441 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001442
1443 property_list(print_property, NULL);
Doug Zongker56c51052010-07-01 09:18:44 -07001444 printf("\n");
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001445
Elliott Hughesbb78d622015-04-09 20:51:08 -07001446 ui->Print("Supported API: %d\n", RECOVERY_API_VERSION);
1447
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001448 int status = INSTALL_SUCCESS;
1449
Doug Zongker540d57f2011-01-18 13:36:58 -08001450 if (update_package != NULL) {
Tao Bao56870012016-04-29 15:37:05 -07001451 // It's not entirely true that we will modify the flash. But we want
1452 // to log the update attempt since update_package is non-NULL.
1453 modified_flash = true;
1454
Yabin Cui99281df2016-02-17 12:21:52 -08001455 if (!is_battery_ok()) {
1456 ui->Print("battery capacity is not enough for installing package, needed is %d%%\n",
1457 BATTERY_OK_PERCENTAGE);
1458 status = INSTALL_SKIPPED;
1459 } else {
1460 status = install_package(update_package, &should_wipe_cache,
1461 TEMPORARY_INSTALL_FILE, true);
1462 if (status == INSTALL_SUCCESS && should_wipe_cache) {
1463 wipe_cache(false, device);
1464 }
1465 if (status != INSTALL_SUCCESS) {
1466 ui->Print("Installation aborted.\n");
Tianjie Xufa12b972016-02-05 18:25:58 -08001467 // When I/O error happens, reboot and retry installation EIO_RETRY_COUNT
1468 // times before we abandon this OTA update.
1469 if (status == INSTALL_RETRY && retry_count < EIO_RETRY_COUNT) {
1470 copy_logs();
1471 set_retry_bootloader_message(retry_count, argc, argv);
1472 // Print retry count on screen.
1473 ui->Print("Retry attempt %d\n", retry_count);
Doug Zongker7c3ae452013-05-14 11:03:02 -07001474
Tianjie Xufa12b972016-02-05 18:25:58 -08001475 // Reboot and retry the update
1476 int ret = property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
1477 if (ret < 0) {
1478 ui->Print("Reboot failed\n");
1479 } else {
1480 while (true) {
1481 pause();
1482 }
1483 }
1484 }
Yabin Cui99281df2016-02-17 12:21:52 -08001485 // If this is an eng or userdebug build, then automatically
1486 // turn the text display on if the script fails so the error
1487 // message is visible.
1488 if (is_ro_debuggable()) {
1489 ui->ShowText(true);
1490 }
Doug Zongker7c3ae452013-05-14 11:03:02 -07001491 }
1492 }
Tao Baoe39a9bc2015-03-31 12:19:05 -07001493 } else if (should_wipe_data) {
1494 if (!wipe_data(false, device)) {
1495 status = INSTALL_ERROR;
1496 }
Tao Baoc679f932015-03-30 09:43:49 -07001497 } else if (should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001498 if (!wipe_cache(false, device)) {
1499 status = INSTALL_ERROR;
1500 }
Tao Baoc679f932015-03-30 09:43:49 -07001501 } else if (sideload) {
1502 // 'adb reboot sideload' acts the same as user presses key combinations
1503 // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
1504 // display will NOT be turned on by default. And it will reboot after
1505 // sideload finishes even if there are errors. Unless one turns on the
1506 // text display during the installation. This is to enable automated
1507 // testing.
1508 if (!sideload_auto_reboot) {
1509 ui->ShowText(true);
1510 }
1511 status = apply_from_adb(ui, &should_wipe_cache, TEMPORARY_INSTALL_FILE);
1512 if (status == INSTALL_SUCCESS && should_wipe_cache) {
Tao Baoe39a9bc2015-03-31 12:19:05 -07001513 if (!wipe_cache(false, device)) {
1514 status = INSTALL_ERROR;
1515 }
Tao Baoc679f932015-03-30 09:43:49 -07001516 }
1517 ui->Print("\nInstall from ADB complete (status: %d).\n", status);
1518 if (sideload_auto_reboot) {
1519 ui->Print("Rebooting automatically.\n");
1520 }
Doug Zongkere5d5ac72012-04-12 11:01:22 -07001521 } else if (!just_exit) {
Doug Zongker02ec6b82012-08-22 17:26:40 -07001522 status = INSTALL_NONE; // No command specified
1523 ui->SetBackground(RecoveryUI::NO_COMMAND);
Tao Bao785d22c2015-05-04 09:34:29 -07001524
1525 // http://b/17489952
1526 // If this is an eng or userdebug build, automatically turn on the
1527 // text display if no command is specified.
1528 if (is_ro_debuggable()) {
1529 ui->ShowText(true);
1530 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001531 }
1532
Tao Baoc679f932015-03-30 09:43:49 -07001533 if (!sideload_auto_reboot && (status == INSTALL_ERROR || status == INSTALL_CORRUPT)) {
Doug Zongkerf24fd7e2013-07-02 11:43:25 -07001534 copy_logs();
Doug Zongker02ec6b82012-08-22 17:26:40 -07001535 ui->SetBackground(RecoveryUI::ERROR);
1536 }
Tao Baoc679f932015-03-30 09:43:49 -07001537
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001538 Device::BuiltinAction after = shutdown_after ? Device::SHUTDOWN : Device::REBOOT;
Yabin Cui99281df2016-02-17 12:21:52 -08001539 if ((status != INSTALL_SUCCESS && status != INSTALL_SKIPPED && !sideload_auto_reboot) ||
1540 ui->IsTextVisible()) {
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001541 Device::BuiltinAction temp = prompt_and_wait(device, status);
Tao Baoc679f932015-03-30 09:43:49 -07001542 if (temp != Device::NO_ACTION) {
1543 after = temp;
1544 }
Doug Zongker8674a722010-09-15 11:08:23 -07001545 }
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001546
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001547 // Save logs and clean up before rebooting or shutting down.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001548 finish_recovery(send_intent);
Doug Zongker8d9d3d52014-04-01 13:20:23 -07001549
1550 switch (after) {
1551 case Device::SHUTDOWN:
1552 ui->Print("Shutting down...\n");
1553 property_set(ANDROID_RB_PROPERTY, "shutdown,");
1554 break;
1555
1556 case Device::REBOOT_BOOTLOADER:
1557 ui->Print("Rebooting to bootloader...\n");
1558 property_set(ANDROID_RB_PROPERTY, "reboot,bootloader");
1559 break;
1560
1561 default:
1562 ui->Print("Rebooting...\n");
1563 property_set(ANDROID_RB_PROPERTY, "reboot,");
1564 break;
Doug Zongkerb1d12632014-03-18 10:32:12 -07001565 }
Tao Bao75238632015-05-27 14:46:17 -07001566 while (true) {
1567 pause();
1568 }
1569 // Should be unreachable.
The Android Open Source Projectc24a8e62009-03-03 19:28:42 -08001570 return EXIT_SUCCESS;
1571}