1 /*
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 
17 #include <dlfcn.h>
18 #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>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include <atomic>
34 #include <string>
35 #include <thread>
36 #include <vector>
37 
38 #include <android-base/file.h>
39 #include <android-base/logging.h>
40 #include <android-base/properties.h>
41 #include <android-base/strings.h>
42 #include <android-base/unique_fd.h>
43 #include <bootloader_message/bootloader_message.h>
44 #include <cutils/sockets.h>
45 #include <fs_mgr/roots.h>
46 #include <private/android_logger.h> /* private pmsg functions */
47 #include <selinux/android.h>
48 #include <selinux/label.h>
49 #include <selinux/selinux.h>
50 
51 #include "fastboot/fastboot.h"
52 #include "install/wipe_data.h"
53 #include "otautil/boot_state.h"
54 #include "otautil/paths.h"
55 #include "otautil/sysutil.h"
56 #include "recovery.h"
57 #include "recovery_ui/device.h"
58 #include "recovery_ui/stub_ui.h"
59 #include "recovery_ui/ui.h"
60 #include "recovery_utils/logging.h"
61 #include "recovery_utils/roots.h"
62 
63 static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
64 static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
65 
66 static RecoveryUI* ui = nullptr;
67 
IsRoDebuggable()68 static bool IsRoDebuggable() {
69   return android::base::GetBoolProperty("ro.debuggable", false);
70 }
71 
IsDeviceUnlocked()72 static bool IsDeviceUnlocked() {
73   return "orange" == android::base::GetProperty("ro.boot.verifiedbootstate", "");
74 }
75 
UiLogger(android::base::LogId log_buffer_id,android::base::LogSeverity severity,const char * tag,const char * file,unsigned int line,const char * message)76 static void UiLogger(android::base::LogId log_buffer_id, android::base::LogSeverity severity,
77                      const char* tag, const char* file, unsigned int line, const char* message) {
78   android::base::KernelLogger(log_buffer_id, severity, tag, file, line, message);
79   static constexpr auto&& log_characters = "VDIWEF";
80   if (severity >= android::base::ERROR && ui != nullptr) {
81     ui->Print("ERROR: %10s: %s\n", tag, message);
82   } else {
83     fprintf(stdout, "%c:%s\n", log_characters[severity], message);
84   }
85 }
86 
87 // Parses the command line argument from various sources; and reads the stage field from BCB.
88 // command line args come from, in decreasing precedence:
89 //   - the actual command line
90 //   - the bootloader control block (one per line, after "recovery")
91 //   - the contents of COMMAND_FILE (one per line)
get_args(const int argc,char ** const argv,std::string * stage)92 static std::vector<std::string> get_args(const int argc, char** const argv, std::string* stage) {
93   CHECK_GT(argc, 0);
94 
95   bootloader_message boot = {};
96   std::string err;
97   if (!read_bootloader_message(&boot, &err)) {
98     LOG(ERROR) << err;
99     // If fails, leave a zeroed bootloader_message.
100     boot = {};
101   }
102   if (stage) {
103     *stage = std::string(boot.stage);
104   }
105 
106   std::string boot_command;
107   if (boot.command[0] != 0) {
108     if (memchr(boot.command, '\0', sizeof(boot.command))) {
109       boot_command = std::string(boot.command);
110     } else {
111       boot_command = std::string(boot.command, sizeof(boot.command));
112     }
113     LOG(INFO) << "Boot command: " << boot_command;
114   }
115 
116   if (boot.status[0] != 0) {
117     std::string boot_status = std::string(boot.status, sizeof(boot.status));
118     LOG(INFO) << "Boot status: " << boot_status;
119   }
120 
121   std::vector<std::string> args(argv, argv + argc);
122 
123   // --- if arguments weren't supplied, look in the bootloader control block
124   if (args.size() == 1) {
125     boot.recovery[sizeof(boot.recovery) - 1] = '\0';  // Ensure termination
126     std::string boot_recovery(boot.recovery);
127     std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
128     if (!tokens.empty() && tokens[0] == "recovery") {
129       for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
130         // Skip empty and '\0'-filled tokens.
131         if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
132       }
133       LOG(INFO) << "Got " << args.size() << " arguments from boot message " << android::base::Join(args, ", ");
134     } else if (boot.recovery[0] != 0) {
135       LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
136     }
137   }
138 
139   // --- if that doesn't work, try the command file (if we have /cache).
140   if (args.size() == 1 && HasCache()) {
141     std::string content;
142     if (ensure_path_mounted(COMMAND_FILE) == 0 &&
143         android::base::ReadFileToString(COMMAND_FILE, &content)) {
144       std::vector<std::string> tokens = android::base::Split(content, "\n");
145       // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
146       // COMMAND_FILE doesn't use filename as the first argument).
147       for (auto it = tokens.begin(); it != tokens.end(); it++) {
148         // Skip empty and '\0'-filled tokens.
149         if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
150       }
151       LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
152     }
153   }
154 
155   // Write the arguments (excluding the filename in args[0]) back into the
156   // bootloader control block. So the device will always boot into recovery to
157   // finish the pending work, until FinishRecovery() is called.
158   // This should only be done for boot-recovery command so that other commands
159   // won't be overwritten.
160   if (boot_command == "boot-recovery") {
161     std::vector<std::string> options(args.cbegin() + 1, args.cend());
162     if (!update_bootloader_message(options, &err)) {
163       LOG(ERROR) << "Failed to set BCB message: " << err;
164     }
165   }
166 
167   // Finally, if no arguments were specified, check whether we should boot
168   // into fastboot or rescue mode.
169   if (args.size() == 1 && boot_command == "boot-fastboot") {
170     args.emplace_back("--fastboot");
171   } else if (args.size() == 1 && boot_command == "boot-rescue") {
172     args.emplace_back("--rescue");
173   }
174 
175   return args;
176 }
177 
load_locale_from_cache()178 static std::string load_locale_from_cache() {
179   if (ensure_path_mounted(LOCALE_FILE) != 0) {
180     LOG(ERROR) << "Can't mount " << LOCALE_FILE;
181     return "";
182   }
183 
184   std::string content;
185   if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
186     PLOG(ERROR) << "Can't read " << LOCALE_FILE;
187     return "";
188   }
189 
190   return android::base::Trim(content);
191 }
192 
193 // Sets the usb config to 'state'.
SetUsbConfig(const std::string & state)194 static bool SetUsbConfig(const std::string& state) {
195   android::base::SetProperty("sys.usb.config", state);
196   return android::base::WaitForProperty("sys.usb.state", state);
197 }
198 
ListenRecoverySocket(RecoveryUI * ui,std::atomic<Device::BuiltinAction> & action)199 static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
200   android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
201   if (sock_fd < 0) {
202     PLOG(ERROR) << "Failed to open recovery socket";
203     return;
204   }
205   listen(sock_fd, 4);
206 
207   while (true) {
208     android::base::unique_fd connection_fd;
209     connection_fd.reset(accept(sock_fd, nullptr, nullptr));
210     if (connection_fd < 0) {
211       PLOG(ERROR) << "Failed to accept socket connection";
212       continue;
213     }
214     char msg;
215     constexpr char kSwitchToFastboot = 'f';
216     constexpr char kSwitchToRecovery = 'r';
217     ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
218     if (ret != sizeof(msg)) {
219       PLOG(ERROR) << "Couldn't read from socket";
220       continue;
221     }
222     switch (msg) {
223       case kSwitchToRecovery:
224         action = Device::BuiltinAction::ENTER_RECOVERY;
225         break;
226       case kSwitchToFastboot:
227         action = Device::BuiltinAction::ENTER_FASTBOOT;
228         break;
229       default:
230         LOG(ERROR) << "Unrecognized char from socket " << msg;
231         continue;
232     }
233     ui->InterruptKey();
234   }
235 }
236 
redirect_stdio(const char * filename)237 static void redirect_stdio(const char* filename) {
238   android::base::unique_fd pipe_read, pipe_write;
239   // Create a pipe that allows parent process sending logs over.
240   if (!android::base::Pipe(&pipe_read, &pipe_write)) {
241     PLOG(ERROR) << "Failed to create pipe for redirecting stdio";
242 
243     // Fall back to traditional logging mode without timestamps. If these fail, there's not really
244     // anywhere to complain...
245     freopen(filename, "a", stdout);
246     setbuf(stdout, nullptr);
247     freopen(filename, "a", stderr);
248     setbuf(stderr, nullptr);
249 
250     return;
251   }
252 
253   pid_t pid = fork();
254   if (pid == -1) {
255     PLOG(ERROR) << "Failed to fork for redirecting stdio";
256 
257     // Fall back to traditional logging mode without timestamps. If these fail, there's not really
258     // anywhere to complain...
259     freopen(filename, "a", stdout);
260     setbuf(stdout, nullptr);
261     freopen(filename, "a", stderr);
262     setbuf(stderr, nullptr);
263 
264     return;
265   }
266 
267   if (pid == 0) {
268     // Child process reads the incoming logs and doesn't write to the pipe.
269     pipe_write.reset();
270 
271     auto start = std::chrono::steady_clock::now();
272 
273     // Child logger to actually write to the log file.
274     FILE* log_fp = fopen(filename, "ae");
275     if (log_fp == nullptr) {
276       PLOG(ERROR) << "fopen \"" << filename << "\" failed";
277       _exit(EXIT_FAILURE);
278     }
279 
280     FILE* pipe_fp = android::base::Fdopen(std::move(pipe_read), "r");
281     if (pipe_fp == nullptr) {
282       PLOG(ERROR) << "fdopen failed";
283       check_and_fclose(log_fp, filename);
284       _exit(EXIT_FAILURE);
285     }
286 
287     char* line = nullptr;
288     size_t len = 0;
289     while (getline(&line, &len, pipe_fp) != -1) {
290       auto now = std::chrono::steady_clock::now();
291       double duration =
292           std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
293       if (line[0] == '\n') {
294         fprintf(log_fp, "[%12.6lf]\n", duration);
295       } else {
296         fprintf(log_fp, "[%12.6lf] %s", duration, line);
297       }
298       fflush(log_fp);
299     }
300 
301     PLOG(ERROR) << "getline failed";
302 
303     fclose(pipe_fp);
304     free(line);
305     check_and_fclose(log_fp, filename);
306     _exit(EXIT_FAILURE);
307   } else {
308     // Redirect stdout/stderr to the logger process. Close the unused read end.
309     pipe_read.reset();
310 
311     setbuf(stdout, nullptr);
312     setbuf(stderr, nullptr);
313 
314     if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
315       PLOG(ERROR) << "dup2 stdout failed";
316     }
317     if (dup2(pipe_write.get(), STDERR_FILENO) == -1) {
318       PLOG(ERROR) << "dup2 stderr failed";
319     }
320   }
321 }
322 
main(int argc,char ** argv)323 int main(int argc, char** argv) {
324   // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
325   // (which is redirected to recovery.log) as we used to do.
326   android::base::InitLogging(argv, &UiLogger);
327 
328   // Take last pmsg contents and rewrite it to the current pmsg session.
329   static constexpr const char filter[] = "recovery/";
330   // Do we need to rotate?
331   bool do_rotate = false;
332 
333   __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
334   // Take action to refresh pmsg contents
335   __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
336 
337   time_t start = time(nullptr);
338 
339   // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
340   // instances with different timestamps.
341   redirect_stdio(Paths::Get().temporary_log_file().c_str());
342 
343   load_volume_table();
344 
345   std::string stage;
346   std::vector<std::string> args = get_args(argc, argv, &stage);
347   auto args_to_parse = StringVectorToNullTerminatedArray(args);
348 
349   static constexpr struct option OPTIONS[] = {
350     { "fastboot", no_argument, nullptr, 0 },
351     { "locale", required_argument, nullptr, 0 },
352     { "reason", required_argument, nullptr, 0 },
353     { "show_text", no_argument, nullptr, 't' },
354     { nullptr, 0, nullptr, 0 },
355   };
356 
357   bool show_text = false;
358   bool fastboot = false;
359   std::string locale;
360   std::string reason;
361 
362   // The code here is only interested in the options that signal the intent to start fastbootd or
363   // recovery. Unrecognized options are likely meant for recovery, which will be processed later in
364   // start_recovery(). Suppress the warnings for such -- even if some flags were indeed invalid, the
365   // code in start_recovery() will capture and report them.
366   opterr = 0;
367 
368   int arg;
369   int option_index;
370   while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
371                             &option_index)) != -1) {
372     switch (arg) {
373       case 't':
374         show_text = true;
375         break;
376       case 0: {
377         std::string option = OPTIONS[option_index].name;
378         if (option == "locale") {
379           locale = optarg;
380         } else if (option == "reason") {
381           reason = optarg;
382         } else if (option == "fastboot" &&
383                    android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
384           fastboot = true;
385         }
386         break;
387       }
388     }
389   }
390   optind = 1;
391   opterr = 1;
392 
393   if (locale.empty()) {
394     if (HasCache()) {
395       locale = load_locale_from_cache();
396     }
397 
398     if (locale.empty()) {
399       locale = DEFAULT_LOCALE;
400     }
401   }
402 
403   static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
404   // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
405   // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
406   // in on dlclose).
407   void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
408 
409   using MakeDeviceType = decltype(&make_device);
410   MakeDeviceType make_device_func = nullptr;
411   if (librecovery_ui_ext == nullptr) {
412     printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
413   } else {
414     reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
415     if (make_device_func == nullptr) {
416       printf("Failed to dlsym make_device: %s\n", dlerror());
417     }
418   }
419 
420   Device* device;
421   if (make_device_func == nullptr) {
422     printf("Falling back to the default make_device() instead\n");
423     device = make_device();
424   } else {
425     printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
426     device = (*make_device_func)();
427   }
428 
429   if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
430     printf("Quiescent recovery mode.\n");
431     device->ResetUI(new StubRecoveryUI());
432   } else {
433     if (!device->GetUI()->Init(locale)) {
434       printf("Failed to initialize UI; using stub UI instead.\n");
435       device->ResetUI(new StubRecoveryUI());
436     }
437   }
438 
439   BootState boot_state(reason, stage);  // recovery_main owns the state of boot.
440   device->SetBootState(&boot_state);
441   ui = device->GetUI();
442 
443   if (!HasCache()) {
444     device->RemoveMenuItemForAction(Device::WIPE_CACHE);
445   }
446 
447   if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
448     device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
449   }
450 
451   if (!IsRoDebuggable()) {
452     device->RemoveMenuItemForAction(Device::ENTER_RESCUE);
453   }
454 
455   ui->SetBackground(RecoveryUI::NONE);
456   if (show_text) ui->ShowText(true);
457 
458   LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
459   LOG(INFO) << "locale is [" << locale << "]";
460 
461   auto sehandle = selinux_android_file_context_handle();
462   selinux_android_set_sehandle(sehandle);
463   if (!sehandle) {
464     ui->Print("Warning: No file_contexts\n");
465   }
466 
467   SetLoggingSehandle(sehandle);
468 
469   std::atomic<Device::BuiltinAction> action;
470   std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
471   listener_thread.detach();
472 
473   while (true) {
474     // We start adbd in recovery for the device with userdebug build or a unlocked bootloader.
475     std::string usb_config =
476         fastboot ? "fastboot" : IsRoDebuggable() || IsDeviceUnlocked() ? "adb" : "none";
477     std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
478     if (fastboot) {
479       device->PreFastboot();
480     } else {
481       device->PreRecovery();
482     }
483     if (usb_config != usb_state) {
484       if (!SetUsbConfig("none")) {
485         LOG(ERROR) << "Failed to clear USB config";
486       }
487       if (!SetUsbConfig(usb_config)) {
488         LOG(ERROR) << "Failed to set USB config to " << usb_config;
489       }
490     }
491 
492     auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
493 
494     if (ret == Device::KEY_INTERRUPTED) {
495       ret = action.exchange(ret);
496       if (ret == Device::NO_ACTION) {
497         continue;
498       }
499     }
500     switch (ret) {
501       case Device::SHUTDOWN:
502         ui->Print("Shutting down...\n");
503         Shutdown("userrequested,recovery");
504         break;
505 
506       case Device::SHUTDOWN_FROM_FASTBOOT:
507         ui->Print("Shutting down...\n");
508         Shutdown("userrequested,fastboot");
509         break;
510 
511       case Device::REBOOT_BOOTLOADER:
512         ui->Print("Rebooting to bootloader...\n");
513         Reboot("bootloader");
514         break;
515 
516       case Device::REBOOT_FASTBOOT:
517         ui->Print("Rebooting to recovery/fastboot...\n");
518         Reboot("fastboot");
519         break;
520 
521       case Device::REBOOT_RECOVERY:
522         ui->Print("Rebooting to recovery...\n");
523         Reboot("recovery");
524         break;
525 
526       case Device::REBOOT_RESCUE: {
527         // Not using `Reboot("rescue")`, as it requires matching support in kernel and/or
528         // bootloader.
529         bootloader_message boot = {};
530         strlcpy(boot.command, "boot-rescue", sizeof(boot.command));
531         std::string err;
532         if (!write_bootloader_message(boot, &err)) {
533           LOG(ERROR) << "Failed to write bootloader message: " << err;
534           // Stay under recovery on failure.
535           continue;
536         }
537         ui->Print("Rebooting to recovery/rescue...\n");
538         Reboot("recovery");
539         break;
540       }
541 
542       case Device::ENTER_FASTBOOT:
543         if (android::fs_mgr::LogicalPartitionsMapped()) {
544           ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
545           Reboot("fastboot");
546         } else {
547           LOG(INFO) << "Entering fastboot";
548           fastboot = true;
549         }
550         break;
551 
552       case Device::ENTER_RECOVERY:
553         LOG(INFO) << "Entering recovery";
554         fastboot = false;
555         ui->SetEnableFastbootdLogo(fastboot);
556         break;
557 
558       case Device::REBOOT:
559         ui->Print("Rebooting...\n");
560         Reboot("userrequested,recovery");
561         break;
562 
563       case Device::REBOOT_FROM_FASTBOOT:
564         ui->Print("Rebooting...\n");
565         Reboot("userrequested,fastboot");
566         break;
567 
568       default:
569         ui->Print("Rebooting...\n");
570         Reboot("unknown" + std::to_string(ret));
571         break;
572     }
573   }
574 
575   // Should be unreachable.
576   return EXIT_SUCCESS;
577 }
578