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,android::base::LogSeverity severity,const char *,const char *,unsigned int,const char * message)76 static void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
77                      const char* /* tag */, const char* /* file */, unsigned int /* line */,
78                      const char* message) {
79   static constexpr char log_characters[] = "VDIWEF";
80   if (severity >= android::base::ERROR && ui != nullptr) {
81     ui->Print("E:%s\n", 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";
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   std::vector<std::string> options(args.cbegin() + 1, args.cend());
159   if (!update_bootloader_message(options, &err)) {
160     LOG(ERROR) << "Failed to set BCB message: " << err;
161   }
162 
163   // Finally, if no arguments were specified, check whether we should boot
164   // into fastboot or rescue mode.
165   if (args.size() == 1 && boot_command == "boot-fastboot") {
166     args.emplace_back("--fastboot");
167   } else if (args.size() == 1 && boot_command == "boot-rescue") {
168     args.emplace_back("--rescue");
169   }
170 
171   return args;
172 }
173 
load_locale_from_cache()174 static std::string load_locale_from_cache() {
175   if (ensure_path_mounted(LOCALE_FILE) != 0) {
176     LOG(ERROR) << "Can't mount " << LOCALE_FILE;
177     return "";
178   }
179 
180   std::string content;
181   if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
182     PLOG(ERROR) << "Can't read " << LOCALE_FILE;
183     return "";
184   }
185 
186   return android::base::Trim(content);
187 }
188 
189 // Sets the usb config to 'state'.
SetUsbConfig(const std::string & state)190 static bool SetUsbConfig(const std::string& state) {
191   android::base::SetProperty("sys.usb.config", state);
192   return android::base::WaitForProperty("sys.usb.state", state);
193 }
194 
ListenRecoverySocket(RecoveryUI * ui,std::atomic<Device::BuiltinAction> & action)195 static void ListenRecoverySocket(RecoveryUI* ui, std::atomic<Device::BuiltinAction>& action) {
196   android::base::unique_fd sock_fd(android_get_control_socket("recovery"));
197   if (sock_fd < 0) {
198     PLOG(ERROR) << "Failed to open recovery socket";
199     return;
200   }
201   listen(sock_fd, 4);
202 
203   while (true) {
204     android::base::unique_fd connection_fd;
205     connection_fd.reset(accept(sock_fd, nullptr, nullptr));
206     if (connection_fd < 0) {
207       PLOG(ERROR) << "Failed to accept socket connection";
208       continue;
209     }
210     char msg;
211     constexpr char kSwitchToFastboot = 'f';
212     constexpr char kSwitchToRecovery = 'r';
213     ssize_t ret = TEMP_FAILURE_RETRY(read(connection_fd, &msg, sizeof(msg)));
214     if (ret != sizeof(msg)) {
215       PLOG(ERROR) << "Couldn't read from socket";
216       continue;
217     }
218     switch (msg) {
219       case kSwitchToRecovery:
220         action = Device::BuiltinAction::ENTER_RECOVERY;
221         break;
222       case kSwitchToFastboot:
223         action = Device::BuiltinAction::ENTER_FASTBOOT;
224         break;
225       default:
226         LOG(ERROR) << "Unrecognized char from socket " << msg;
227         continue;
228     }
229     ui->InterruptKey();
230   }
231 }
232 
redirect_stdio(const char * filename)233 static void redirect_stdio(const char* filename) {
234   android::base::unique_fd pipe_read, pipe_write;
235   // Create a pipe that allows parent process sending logs over.
236   if (!android::base::Pipe(&pipe_read, &pipe_write)) {
237     PLOG(ERROR) << "Failed to create pipe for redirecting stdio";
238 
239     // Fall back to traditional logging mode without timestamps. If these fail, there's not really
240     // anywhere to complain...
241     freopen(filename, "a", stdout);
242     setbuf(stdout, nullptr);
243     freopen(filename, "a", stderr);
244     setbuf(stderr, nullptr);
245 
246     return;
247   }
248 
249   pid_t pid = fork();
250   if (pid == -1) {
251     PLOG(ERROR) << "Failed to fork for redirecting stdio";
252 
253     // Fall back to traditional logging mode without timestamps. If these fail, there's not really
254     // anywhere to complain...
255     freopen(filename, "a", stdout);
256     setbuf(stdout, nullptr);
257     freopen(filename, "a", stderr);
258     setbuf(stderr, nullptr);
259 
260     return;
261   }
262 
263   if (pid == 0) {
264     // Child process reads the incoming logs and doesn't write to the pipe.
265     pipe_write.reset();
266 
267     auto start = std::chrono::steady_clock::now();
268 
269     // Child logger to actually write to the log file.
270     FILE* log_fp = fopen(filename, "ae");
271     if (log_fp == nullptr) {
272       PLOG(ERROR) << "fopen \"" << filename << "\" failed";
273       _exit(EXIT_FAILURE);
274     }
275 
276     FILE* pipe_fp = android::base::Fdopen(std::move(pipe_read), "r");
277     if (pipe_fp == nullptr) {
278       PLOG(ERROR) << "fdopen failed";
279       check_and_fclose(log_fp, filename);
280       _exit(EXIT_FAILURE);
281     }
282 
283     char* line = nullptr;
284     size_t len = 0;
285     while (getline(&line, &len, pipe_fp) != -1) {
286       auto now = std::chrono::steady_clock::now();
287       double duration =
288           std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
289       if (line[0] == '\n') {
290         fprintf(log_fp, "[%12.6lf]\n", duration);
291       } else {
292         fprintf(log_fp, "[%12.6lf] %s", duration, line);
293       }
294       fflush(log_fp);
295     }
296 
297     PLOG(ERROR) << "getline failed";
298 
299     fclose(pipe_fp);
300     free(line);
301     check_and_fclose(log_fp, filename);
302     _exit(EXIT_FAILURE);
303   } else {
304     // Redirect stdout/stderr to the logger process. Close the unused read end.
305     pipe_read.reset();
306 
307     setbuf(stdout, nullptr);
308     setbuf(stderr, nullptr);
309 
310     if (dup2(pipe_write.get(), STDOUT_FILENO) == -1) {
311       PLOG(ERROR) << "dup2 stdout failed";
312     }
313     if (dup2(pipe_write.get(), STDERR_FILENO) == -1) {
314       PLOG(ERROR) << "dup2 stderr failed";
315     }
316   }
317 }
318 
main(int argc,char ** argv)319 int main(int argc, char** argv) {
320   // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
321   // (which is redirected to recovery.log) as we used to do.
322   android::base::InitLogging(argv, &UiLogger);
323 
324   // Take last pmsg contents and rewrite it to the current pmsg session.
325   static constexpr const char filter[] = "recovery/";
326   // Do we need to rotate?
327   bool do_rotate = false;
328 
329   __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
330   // Take action to refresh pmsg contents
331   __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
332 
333   time_t start = time(nullptr);
334 
335   // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
336   // instances with different timestamps.
337   redirect_stdio(Paths::Get().temporary_log_file().c_str());
338 
339   load_volume_table();
340 
341   std::string stage;
342   std::vector<std::string> args = get_args(argc, argv, &stage);
343   auto args_to_parse = StringVectorToNullTerminatedArray(args);
344 
345   static constexpr struct option OPTIONS[] = {
346     { "fastboot", no_argument, nullptr, 0 },
347     { "locale", required_argument, nullptr, 0 },
348     { "reason", required_argument, nullptr, 0 },
349     { "show_text", no_argument, nullptr, 't' },
350     { nullptr, 0, nullptr, 0 },
351   };
352 
353   bool show_text = false;
354   bool fastboot = false;
355   std::string locale;
356   std::string reason;
357 
358   // The code here is only interested in the options that signal the intent to start fastbootd or
359   // recovery. Unrecognized options are likely meant for recovery, which will be processed later in
360   // start_recovery(). Suppress the warnings for such -- even if some flags were indeed invalid, the
361   // code in start_recovery() will capture and report them.
362   opterr = 0;
363 
364   int arg;
365   int option_index;
366   while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
367                             &option_index)) != -1) {
368     switch (arg) {
369       case 't':
370         show_text = true;
371         break;
372       case 0: {
373         std::string option = OPTIONS[option_index].name;
374         if (option == "locale") {
375           locale = optarg;
376         } else if (option == "reason") {
377           reason = optarg;
378         } else if (option == "fastboot" &&
379                    android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
380           fastboot = true;
381         }
382         break;
383       }
384     }
385   }
386   optind = 1;
387   opterr = 1;
388 
389   if (locale.empty()) {
390     if (HasCache()) {
391       locale = load_locale_from_cache();
392     }
393 
394     if (locale.empty()) {
395       locale = DEFAULT_LOCALE;
396     }
397   }
398 
399   static constexpr const char* kDefaultLibRecoveryUIExt = "librecovery_ui_ext.so";
400   // Intentionally not calling dlclose(3) to avoid potential gotchas (e.g. `make_device` may have
401   // handed out pointers to code or static [or thread-local] data and doesn't collect them all back
402   // in on dlclose).
403   void* librecovery_ui_ext = dlopen(kDefaultLibRecoveryUIExt, RTLD_NOW);
404 
405   using MakeDeviceType = decltype(&make_device);
406   MakeDeviceType make_device_func = nullptr;
407   if (librecovery_ui_ext == nullptr) {
408     printf("Failed to dlopen %s: %s\n", kDefaultLibRecoveryUIExt, dlerror());
409   } else {
410     reinterpret_cast<void*&>(make_device_func) = dlsym(librecovery_ui_ext, "make_device");
411     if (make_device_func == nullptr) {
412       printf("Failed to dlsym make_device: %s\n", dlerror());
413     }
414   }
415 
416   Device* device;
417   if (make_device_func == nullptr) {
418     printf("Falling back to the default make_device() instead\n");
419     device = make_device();
420   } else {
421     printf("Loading make_device from %s\n", kDefaultLibRecoveryUIExt);
422     device = (*make_device_func)();
423   }
424 
425   if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
426     printf("Quiescent recovery mode.\n");
427     device->ResetUI(new StubRecoveryUI());
428   } else {
429     if (!device->GetUI()->Init(locale)) {
430       printf("Failed to initialize UI; using stub UI instead.\n");
431       device->ResetUI(new StubRecoveryUI());
432     }
433   }
434 
435   BootState boot_state(reason, stage);  // recovery_main owns the state of boot.
436   device->SetBootState(&boot_state);
437   ui = device->GetUI();
438 
439   if (!HasCache()) {
440     device->RemoveMenuItemForAction(Device::WIPE_CACHE);
441   }
442 
443   if (!android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
444     device->RemoveMenuItemForAction(Device::ENTER_FASTBOOT);
445   }
446 
447   if (!IsRoDebuggable()) {
448     device->RemoveMenuItemForAction(Device::ENTER_RESCUE);
449   }
450 
451   ui->SetBackground(RecoveryUI::NONE);
452   if (show_text) ui->ShowText(true);
453 
454   LOG(INFO) << "Starting recovery (pid " << getpid() << ") on " << ctime(&start);
455   LOG(INFO) << "locale is [" << locale << "]";
456 
457   auto sehandle = selinux_android_file_context_handle();
458   selinux_android_set_sehandle(sehandle);
459   if (!sehandle) {
460     ui->Print("Warning: No file_contexts\n");
461   }
462 
463   SetLoggingSehandle(sehandle);
464 
465   std::atomic<Device::BuiltinAction> action;
466   std::thread listener_thread(ListenRecoverySocket, ui, std::ref(action));
467   listener_thread.detach();
468 
469   while (true) {
470     // We start adbd in recovery for the device with userdebug build or a unlocked bootloader.
471     std::string usb_config =
472         fastboot ? "fastboot" : IsRoDebuggable() || IsDeviceUnlocked() ? "adb" : "none";
473     std::string usb_state = android::base::GetProperty("sys.usb.state", "none");
474     if (fastboot) {
475       device->PreFastboot();
476     } else {
477       device->PreRecovery();
478     }
479     if (usb_config != usb_state) {
480       if (!SetUsbConfig("none")) {
481         LOG(ERROR) << "Failed to clear USB config";
482       }
483       if (!SetUsbConfig(usb_config)) {
484         LOG(ERROR) << "Failed to set USB config to " << usb_config;
485       }
486     }
487 
488     ui->SetEnableFastbootdLogo(fastboot);
489 
490     auto ret = fastboot ? StartFastboot(device, args) : start_recovery(device, args);
491 
492     if (ret == Device::KEY_INTERRUPTED) {
493       ret = action.exchange(ret);
494       if (ret == Device::NO_ACTION) {
495         continue;
496       }
497     }
498     switch (ret) {
499       case Device::SHUTDOWN:
500         ui->Print("Shutting down...\n");
501         Shutdown("userrequested,recovery");
502         break;
503 
504       case Device::SHUTDOWN_FROM_FASTBOOT:
505         ui->Print("Shutting down...\n");
506         Shutdown("userrequested,fastboot");
507         break;
508 
509       case Device::REBOOT_BOOTLOADER:
510         ui->Print("Rebooting to bootloader...\n");
511         Reboot("bootloader");
512         break;
513 
514       case Device::REBOOT_FASTBOOT:
515         ui->Print("Rebooting to recovery/fastboot...\n");
516         Reboot("fastboot");
517         break;
518 
519       case Device::REBOOT_RECOVERY:
520         ui->Print("Rebooting to recovery...\n");
521         Reboot("recovery");
522         break;
523 
524       case Device::REBOOT_RESCUE: {
525         // Not using `Reboot("rescue")`, as it requires matching support in kernel and/or
526         // bootloader.
527         bootloader_message boot = {};
528         strlcpy(boot.command, "boot-rescue", sizeof(boot.command));
529         std::string err;
530         if (!write_bootloader_message(boot, &err)) {
531           LOG(ERROR) << "Failed to write bootloader message: " << err;
532           // Stay under recovery on failure.
533           continue;
534         }
535         ui->Print("Rebooting to recovery/rescue...\n");
536         Reboot("recovery");
537         break;
538       }
539 
540       case Device::ENTER_FASTBOOT:
541         if (android::fs_mgr::LogicalPartitionsMapped()) {
542           ui->Print("Partitions may be mounted - rebooting to enter fastboot.");
543           Reboot("fastboot");
544         } else {
545           LOG(INFO) << "Entering fastboot";
546           fastboot = true;
547         }
548         break;
549 
550       case Device::ENTER_RECOVERY:
551         LOG(INFO) << "Entering recovery";
552         fastboot = false;
553         break;
554 
555       case Device::REBOOT:
556         ui->Print("Rebooting...\n");
557         Reboot("userrequested,recovery");
558         break;
559 
560       case Device::REBOOT_FROM_FASTBOOT:
561         ui->Print("Rebooting...\n");
562         Reboot("userrequested,fastboot");
563         break;
564 
565       default:
566         ui->Print("Rebooting...\n");
567         Reboot("unknown" + std::to_string(ret));
568         break;
569     }
570   }
571 
572   // Should be unreachable.
573   return EXIT_SUCCESS;
574 }
575