blob: 7fb46163e487ab46f6c80617711d915e7a918397 [file] [log] [blame]
Tao Bao6d99d4b2018-04-25 16:47:04 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tao Bao42c45e22018-07-31 09:37:12 -070017#include <dlfcn.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070018#include <errno.h>
19#include <fcntl.h>
20#include <getopt.h>
21#include <inttypes.h>
22#include <limits.h>
23#include <linux/fs.h>
24#include <stdarg.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070025#include <stdio.h>
26#include <stdlib.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070027#include <string.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <time.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070031#include <unistd.h>
32
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070033#include <atomic>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070034#include <string>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070035#include <thread>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070036#include <vector>
Tao Bao6d99d4b2018-04-25 16:47:04 -070037
Jerry Zhangf5e319a2018-05-04 11:24:10 -070038#include <android-base/file.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070039#include <android-base/logging.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070040#include <android-base/properties.h>
41#include <android-base/strings.h>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070042#include <android-base/unique_fd.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070043#include <bootloader_message/bootloader_message.h>
44#include <cutils/android_reboot.h>
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070045#include <cutils/sockets.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070046#include <private/android_logger.h> /* private pmsg functions */
Jerry Zhangf5e319a2018-05-04 11:24:10 -070047#include <selinux/android.h>
48#include <selinux/label.h>
49#include <selinux/selinux.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070050
51#include "common.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070052#include "device.h"
Hridya Valsaraju20c81b32018-07-27 22:09:12 -070053#include "fastboot/fastboot.h"
Jerry Zhang152933a2018-05-02 16:56:00 -070054#include "logging.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070055#include "minadbd/minadbd.h"
56#include "otautil/paths.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070057#include "otautil/sysutil.h"
58#include "recovery.h"
59#include "roots.h"
60#include "stub_ui.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070061#include "ui.h"
62
Jerry Zhangf5e319a2018-05-04 11:24:10 -070063static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
64static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
65
66static constexpr const char* CACHE_ROOT = "/cache";
67
68bool has_cache = false;
69
70RecoveryUI* ui = nullptr;
71struct selabel_handle* sehandle;
72
Tao Bao6d99d4b2018-04-25 16:47:04 -070073static void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
74 const char* /* tag */, const char* /* file */, unsigned int /* line */,
75 const char* message) {
76 static constexpr char log_characters[] = "VDIWEF";
77 if (severity >= android::base::ERROR && ui != nullptr) {
78 ui->Print("E:%s\n", message);
79 } else {
80 fprintf(stdout, "%c:%s\n", log_characters[severity], message);
81 }
82}
83
Jerry Zhangf5e319a2018-05-04 11:24:10 -070084// command line args come from, in decreasing precedence:
85// - the actual command line
86// - the bootloader control block (one per line, after "recovery")
87// - the contents of COMMAND_FILE (one per line)
88static std::vector<std::string> get_args(const int argc, char** const argv) {
89 CHECK_GT(argc, 0);
90
91 bootloader_message boot = {};
92 std::string err;
93 if (!read_bootloader_message(&boot, &err)) {
94 LOG(ERROR) << err;
95 // If fails, leave a zeroed bootloader_message.
96 boot = {};
97 }
98 stage = std::string(boot.stage);
99
David Andersoneee4e262018-08-21 13:10:45 -0700100 std::string boot_command;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700101 if (boot.command[0] != 0) {
David Andersoneee4e262018-08-21 13:10:45 -0700102 if (memchr(boot.command, '\0', sizeof(boot.command))) {
103 boot_command = std::string(boot.command);
104 } else {
105 boot_command = std::string(boot.command, sizeof(boot.command));
106 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700107 LOG(INFO) << "Boot command: " << boot_command;
108 }
109
110 if (boot.status[0] != 0) {
111 std::string boot_status = std::string(boot.status, sizeof(boot.status));
112 LOG(INFO) << "Boot status: " << boot_status;
113 }
114
115 std::vector<std::string> args(argv, argv + argc);
116
117 // --- if arguments weren't supplied, look in the bootloader control block
118 if (args.size() == 1) {
119 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
120 std::string boot_recovery(boot.recovery);
121 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
122 if (!tokens.empty() && tokens[0] == "recovery") {
123 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
124 // Skip empty and '\0'-filled tokens.
125 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
126 }
127 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
128 } else if (boot.recovery[0] != 0) {
129 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
130 }
131 }
132
133 // --- if that doesn't work, try the command file (if we have /cache).
134 if (args.size() == 1 && has_cache) {
135 std::string content;
136 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
137 android::base::ReadFileToString(COMMAND_FILE, &content)) {
138 std::vector<std::string> tokens = android::base::Split(content, "\n");
139 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
140 // COMMAND_FILE doesn't use filename as the first argument).
141 for (auto it = tokens.begin(); it != tokens.end(); it++) {
142 // Skip empty and '\0'-filled tokens.
143 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
144 }
145 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
146 }
147 }
148
149 // Write the arguments (excluding the filename in args[0]) back into the
150 // bootloader control block. So the device will always boot into recovery to
151 // finish the pending work, until finish_recovery() is called.
152 std::vector<std::string> options(args.cbegin() + 1, args.cend());
153 if (!update_bootloader_message(options, &err)) {
154 LOG(ERROR) << "Failed to set BCB message: " << err;
155 }
156
David Andersoneee4e262018-08-21 13:10:45 -0700157 // Finally, if no arguments were specified, check whether we should boot
158 // into fastboot.
159 if (args.size() == 1 && boot_command == "boot-fastboot") {
160 args.emplace_back("--fastboot");
161 }
162
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700163 return args;
164}
165
166static std::string load_locale_from_cache() {
167 if (ensure_path_mounted(LOCALE_FILE) != 0) {
168 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
169 return "";
170 }
171
172 std::string content;
173 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
174 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
175 return "";
176 }
177
178 return android::base::Trim(content);
179}
180
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700181static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
182 android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
183 if (sock_fd < 0) {
184 PLOG(ERROR) << "Failed to open recovery socket";
185 return;
186 }
187 listen(sock_fd, 4);
188
189 while (true) {
190 android::base::unique_fd connection_fd;
191 connection_fd.reset(accept(sock_fd, nullptr, nullptr));
192 if (connection_fd < 0) {
193 PLOG(ERROR) << "Failed to accept socket connection";
194 continue;
195 }
196 char msg;
197 constexpr char kSwitchToFastboot = 'f';
198 constexpr char kSwitchToRecovery = 'r';
199 ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
200 if (ret != sizeof(msg)) {
201 PLOG(ERROR) << "Couldn't read from socket";
202 continue;
203 }
204 switch (msg) {
205 case kSwitchToRecovery:
206 action = Device::BuiltinAction::ENTER_RECOVERY;
207 break;
208 case kSwitchToFastboot:
209 action = Device::BuiltinAction::ENTER_FASTBOOT;
210 break;
211 default:
212 LOG(ERROR) << "Unrecognized char from socket " << msg;
213 continue;
214 }
215 ui->InterruptKey();
216 }
217}
218
Tao Bao6d99d4b2018-04-25 16:47:04 -0700219static void redirect_stdio(const char* filename) {
220 int pipefd[2];
221 if (pipe(pipefd) == -1) {
222 PLOG(ERROR) << "pipe failed";
223
224 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
225 // anywhere to complain...
226 freopen(filename, "a", stdout);
227 setbuf(stdout, nullptr);
228 freopen(filename, "a", stderr);
229 setbuf(stderr, nullptr);
230
231 return;
232 }
233
234 pid_t pid = fork();
235 if (pid == -1) {
236 PLOG(ERROR) << "fork failed";
237
238 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
239 // anywhere to complain...
240 freopen(filename, "a", stdout);
241 setbuf(stdout, nullptr);
242 freopen(filename, "a", stderr);
243 setbuf(stderr, nullptr);
244
245 return;
246 }
247
248 if (pid == 0) {
249 /// Close the unused write end.
250 close(pipefd[1]);
251
252 auto start = std::chrono::steady_clock::now();
253
254 // Child logger to actually write to the log file.
255 FILE* log_fp = fopen(filename, "ae");
256 if (log_fp == nullptr) {
257 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
258 close(pipefd[0]);
259 _exit(EXIT_FAILURE);
260 }
261
262 FILE* pipe_fp = fdopen(pipefd[0], "r");
263 if (pipe_fp == nullptr) {
264 PLOG(ERROR) << "fdopen failed";
265 check_and_fclose(log_fp, filename);
266 close(pipefd[0]);
267 _exit(EXIT_FAILURE);
268 }
269
270 char* line = nullptr;
271 size_t len = 0;
272 while (getline(&line, &len, pipe_fp) != -1) {
273 auto now = std::chrono::steady_clock::now();
274 double duration =
275 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
276 if (line[0] == '\n') {
277 fprintf(log_fp, "[%12.6lf]\n", duration);
278 } else {
279 fprintf(log_fp, "[%12.6lf] %s", duration, line);
280 }
281 fflush(log_fp);
282 }
283
284 PLOG(ERROR) << "getline failed";
285
286 free(line);
287 check_and_fclose(log_fp, filename);
288 close(pipefd[0]);
289 _exit(EXIT_FAILURE);
290 } else {
291 // Redirect stdout/stderr to the logger process. Close the unused read end.
292 close(pipefd[0]);
293
294 setbuf(stdout, nullptr);
295 setbuf(stderr, nullptr);
296
297 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
298 PLOG(ERROR) << "dup2 stdout failed";
299 }
300 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
301 PLOG(ERROR) << "dup2 stderr failed";
302 }
303
304 close(pipefd[1]);
305 }
306}
307
308int main(int argc, char** argv) {
309 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
310 // (which is redirected to recovery.log) as we used to do.
311 android::base::InitLogging(argv, &UiLogger);
312
313 // Take last pmsg contents and rewrite it to the current pmsg session.
314 static constexpr const char filter[] = "recovery/";
315 // Do we need to rotate?
316 bool do_rotate = false;
317
318 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
319 // Take action to refresh pmsg contents
320 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
321
322 // If this binary is started with the single argument "--adbd", instead of being the normal
323 // recovery binary, it turns into kind of a stripped-down version of adbd that only supports the
324 // 'sideload' command. Note this must be a real argument, not anything in the command file or
325 // bootloader control block; the only way recovery should be run with this argument is when it
326 // starts a copy of itself from the apply_from_adb() function.
327 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
328 minadbd_main();
329 return 0;
330 }
331
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700332 time_t start = time(nullptr);
333
Tao Bao6d99d4b2018-04-25 16:47:04 -0700334 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
335 // instances with different timestamps.
336 redirect_stdio(Paths::Get().temporary_log_file().c_str());
337
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700338 load_volume_table();
339 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
340
341 std::vector<std::string> args = get_args(argc, argv);
Tao Bao1700cc42018-07-16 22:09:59 -0700342 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700343
344 static constexpr struct option OPTIONS[] = {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700345 { "fastboot", no_argument, nullptr, 0 },
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700346 { "locale", required_argument, nullptr, 0 },
347 { "show_text", no_argument, nullptr, 't' },
348 { nullptr, 0, nullptr, 0 },
349 };
350
351 bool show_text = false;
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700352 bool fastboot = false;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700353 std::string locale;
354
355 int arg;
356 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700357 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700358 &option_index)) != -1) {
359 switch (arg) {
360 case 't':
361 show_text = true;
362 break;
363 case 0: {
364 std::string option = OPTIONS[option_index].name;
365 if (option == "locale") {
366 locale = optarg;
Hridya Valsaraju7f41a2c2018-09-19 16:29:01 -0700367 } else if (option == "fastboot" &&
Yifan Hongd17174c2018-11-16 12:49:33 -0800368 android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700369 fastboot = true;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700370 }
371 break;
372 }
373 }
374 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700375 optind = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700376
377 if (locale.empty()) {
378 if (has_cache) {
379 locale = load_locale_from_cache();
380 }
381
382 if (locale.empty()) {
383 static constexpr const char* DEFAULT_LOCALE = "en-US";
384 locale = DEFAULT_LOCALE;
385 }
386 }
387
Tao Bao42c45e22018-07-31 09:37:12 -0700388 static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
389 // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
390 // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
391 // in on dlclose).
392 void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
393
394 using MakeDeviceType = decltype(&make_device);
395 MakeDeviceType make_device_func = nullptr;
396 if (librecovery_ui_ext == nullptr) {
397 printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
398 } else {
399 reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
400 if (make_device_func == nullptr) {
401 printf("Failed to dlsym make_device: %s\n", dlerror());
402 }
403 }
404
405 Device* device;
406 if (make_device_func == nullptr) {
407 printf("Falling back to the default make_device() instead\n");
408 device = make_device();
409 } else {
410 printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
411 device = (*make_device_func)();
412 }
413
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700414 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
415 printf("Quiescent recovery mode.\n");
416 device->ResetUI(new StubRecoveryUI());
417 } else {
418 if (!device->GetUI()->Init(locale)) {
419 printf("Failed to initialize UI; using stub UI instead.\n");
420 device->ResetUI(new StubRecoveryUI());
421 }
422 }
423 ui = device->GetUI();
424
425 if (!has_cache) {
426 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
427 }
428
Yifan Hongd17174c2018-11-16 12:49:33 -0800429 if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
Hridya Valsarajudaa301e2018-09-18 14:48:01 -0700430 device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
431 }
432
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700433 ui->SetBackground(RecoveryUI::NONE);
434 if (show_text) ui->ShowText(true);
435
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700436 LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
437 LOG(INFO) << "locale is [" << locale << "]";
438
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700439 sehandle = selinux_android_file_context_handle();
440 selinux_android_set_sehandle(sehandle);
441 if (!sehandle) {
442 ui->Print("Warning: No file_contexts\n");
443 }
444
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700445 std::atomic<Device::BuiltinAction> action;
446 std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
447 listener_thread.detach();
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700448
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700449 while (true) {
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700450 std::string usb_config = fastboot ? "fastboot" : is_ro_debuggable() ? "adb" : "none";
451 std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
452 if (usb_config != usb_state) {
453 if (!SetUsbConfig("none")) {
454 LOG(ERROR) << "Failed to clear USB config";
455 }
456 if (!SetUsbConfig(usb_config)) {
457 LOG(ERROR) << "Failed to set USB config to " << usb_config;
458 }
459 }
460
David Anderson983e2d52019-01-02 11:35:38 -0800461 ui->SetEnableFastbootdLogo(fastboot);
462
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700463 auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
464
465 if (ret == Device::KEY_INTERRUPTED) {
466 ret = action.exchange(ret);
467 if (ret == Device::NO_ACTION) {
468 continue;
469 }
470 }
471 switch (ret) {
472 case Device::SHUTDOWN:
473 ui->Print("Shutting down...\n");
474 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
475 break;
476
477 case Device::REBOOT_BOOTLOADER:
478 ui->Print("Rebooting to bootloader...\n");
479 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
480 break;
481
482 case Device::ENTER_FASTBOOT:
David Anderson2b2f4232018-10-29 18:48:56 -0700483 if (logical_partitions_mapped()) {
484 ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
485 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,fastboot");
486 } else {
487 LOG(INFO) << "Entering fastboot";
488 fastboot = true;
489 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700490 break;
491
492 case Device::ENTER_RECOVERY:
493 LOG(INFO) << "Entering recovery";
494 fastboot = false;
495 break;
496
497 default:
498 ui->Print("Rebooting...\n");
499 reboot("reboot,");
500 break;
501 }
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700502 }
Hridya Valsaraju20c81b32018-07-27 22:09:12 -0700503
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700504 // Should be unreachable.
505 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700506}