blob: c79d7d8d835d7f148bbcc522f6b518d82d1e97d3 [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
Jerry Zhangf5e319a2018-05-04 11:24:10 -070017#include <errno.h>
18#include <fcntl.h>
19#include <getopt.h>
20#include <inttypes.h>
21#include <limits.h>
22#include <linux/fs.h>
23#include <stdarg.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070024#include <stdio.h>
25#include <stdlib.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070026#include <string.h>
27#include <sys/stat.h>
28#include <sys/types.h>
29#include <time.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070030#include <unistd.h>
31
Jerry Zhangf5e319a2018-05-04 11:24:10 -070032#include <string>
33#include <vector>
Tao Bao6d99d4b2018-04-25 16:47:04 -070034
Jerry Zhangf5e319a2018-05-04 11:24:10 -070035#include <android-base/file.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070036#include <android-base/logging.h>
Jerry Zhangf5e319a2018-05-04 11:24:10 -070037#include <android-base/properties.h>
38#include <android-base/strings.h>
39#include <bootloader_message/bootloader_message.h>
40#include <cutils/android_reboot.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070041#include <private/android_logger.h> /* private pmsg functions */
Jerry Zhangf5e319a2018-05-04 11:24:10 -070042#include <selinux/android.h>
43#include <selinux/label.h>
44#include <selinux/selinux.h>
Tao Bao6d99d4b2018-04-25 16:47:04 -070045
46#include "common.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070047#include "device.h"
Jerry Zhang152933a2018-05-02 16:56:00 -070048#include "logging.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070049#include "minadbd/minadbd.h"
50#include "otautil/paths.h"
Jerry Zhangf5e319a2018-05-04 11:24:10 -070051#include "otautil/sysutil.h"
52#include "recovery.h"
53#include "roots.h"
54#include "stub_ui.h"
Tao Bao6d99d4b2018-04-25 16:47:04 -070055#include "ui.h"
56
Jerry Zhangf5e319a2018-05-04 11:24:10 -070057static constexpr const char* COMMAND_FILE = "/cache/recovery/command";
58static constexpr const char* LOCALE_FILE = "/cache/recovery/last_locale";
59
60static constexpr const char* CACHE_ROOT = "/cache";
61
62bool has_cache = false;
63
64RecoveryUI* ui = nullptr;
65struct selabel_handle* sehandle;
66
Tao Bao6d99d4b2018-04-25 16:47:04 -070067static void UiLogger(android::base::LogId /* id */, android::base::LogSeverity severity,
68 const char* /* tag */, const char* /* file */, unsigned int /* line */,
69 const char* message) {
70 static constexpr char log_characters[] = "VDIWEF";
71 if (severity >= android::base::ERROR && ui != nullptr) {
72 ui->Print("E:%s\n", message);
73 } else {
74 fprintf(stdout, "%c:%s\n", log_characters[severity], message);
75 }
76}
77
Jerry Zhangf5e319a2018-05-04 11:24:10 -070078// command line args come from, in decreasing precedence:
79// - the actual command line
80// - the bootloader control block (one per line, after "recovery")
81// - the contents of COMMAND_FILE (one per line)
82static std::vector<std::string> get_args(const int argc, char** const argv) {
83 CHECK_GT(argc, 0);
84
85 bootloader_message boot = {};
86 std::string err;
87 if (!read_bootloader_message(&boot, &err)) {
88 LOG(ERROR) << err;
89 // If fails, leave a zeroed bootloader_message.
90 boot = {};
91 }
92 stage = std::string(boot.stage);
93
94 if (boot.command[0] != 0) {
95 std::string boot_command = std::string(boot.command, sizeof(boot.command));
96 LOG(INFO) << "Boot command: " << boot_command;
97 }
98
99 if (boot.status[0] != 0) {
100 std::string boot_status = std::string(boot.status, sizeof(boot.status));
101 LOG(INFO) << "Boot status: " << boot_status;
102 }
103
104 std::vector<std::string> args(argv, argv + argc);
105
106 // --- if arguments weren't supplied, look in the bootloader control block
107 if (args.size() == 1) {
108 boot.recovery[sizeof(boot.recovery) - 1] = '\0'; // Ensure termination
109 std::string boot_recovery(boot.recovery);
110 std::vector<std::string> tokens = android::base::Split(boot_recovery, "\n");
111 if (!tokens.empty() && tokens[0] == "recovery") {
112 for (auto it = tokens.begin() + 1; it != tokens.end(); it++) {
113 // Skip empty and '\0'-filled tokens.
114 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
115 }
116 LOG(INFO) << "Got " << args.size() << " arguments from boot message";
117 } else if (boot.recovery[0] != 0) {
118 LOG(ERROR) << "Bad boot message: \"" << boot_recovery << "\"";
119 }
120 }
121
122 // --- if that doesn't work, try the command file (if we have /cache).
123 if (args.size() == 1 && has_cache) {
124 std::string content;
125 if (ensure_path_mounted(COMMAND_FILE) == 0 &&
126 android::base::ReadFileToString(COMMAND_FILE, &content)) {
127 std::vector<std::string> tokens = android::base::Split(content, "\n");
128 // All the arguments in COMMAND_FILE are needed (unlike the BCB message,
129 // COMMAND_FILE doesn't use filename as the first argument).
130 for (auto it = tokens.begin(); it != tokens.end(); it++) {
131 // Skip empty and '\0'-filled tokens.
132 if (!it->empty() && (*it)[0] != '\0') args.push_back(std::move(*it));
133 }
134 LOG(INFO) << "Got " << args.size() << " arguments from " << COMMAND_FILE;
135 }
136 }
137
138 // Write the arguments (excluding the filename in args[0]) back into the
139 // bootloader control block. So the device will always boot into recovery to
140 // finish the pending work, until finish_recovery() is called.
141 std::vector<std::string> options(args.cbegin() + 1, args.cend());
142 if (!update_bootloader_message(options, &err)) {
143 LOG(ERROR) << "Failed to set BCB message: " << err;
144 }
145
146 return args;
147}
148
149static std::string load_locale_from_cache() {
150 if (ensure_path_mounted(LOCALE_FILE) != 0) {
151 LOG(ERROR) << "Can't mount " << LOCALE_FILE;
152 return "";
153 }
154
155 std::string content;
156 if (!android::base::ReadFileToString(LOCALE_FILE, &content)) {
157 PLOG(ERROR) << "Can't read " << LOCALE_FILE;
158 return "";
159 }
160
161 return android::base::Trim(content);
162}
163
Tao Bao6d99d4b2018-04-25 16:47:04 -0700164static void redirect_stdio(const char* filename) {
165 int pipefd[2];
166 if (pipe(pipefd) == -1) {
167 PLOG(ERROR) << "pipe failed";
168
169 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
170 // anywhere to complain...
171 freopen(filename, "a", stdout);
172 setbuf(stdout, nullptr);
173 freopen(filename, "a", stderr);
174 setbuf(stderr, nullptr);
175
176 return;
177 }
178
179 pid_t pid = fork();
180 if (pid == -1) {
181 PLOG(ERROR) << "fork failed";
182
183 // Fall back to traditional logging mode without timestamps. If these fail, there's not really
184 // anywhere to complain...
185 freopen(filename, "a", stdout);
186 setbuf(stdout, nullptr);
187 freopen(filename, "a", stderr);
188 setbuf(stderr, nullptr);
189
190 return;
191 }
192
193 if (pid == 0) {
194 /// Close the unused write end.
195 close(pipefd[1]);
196
197 auto start = std::chrono::steady_clock::now();
198
199 // Child logger to actually write to the log file.
200 FILE* log_fp = fopen(filename, "ae");
201 if (log_fp == nullptr) {
202 PLOG(ERROR) << "fopen \"" << filename << "\" failed";
203 close(pipefd[0]);
204 _exit(EXIT_FAILURE);
205 }
206
207 FILE* pipe_fp = fdopen(pipefd[0], "r");
208 if (pipe_fp == nullptr) {
209 PLOG(ERROR) << "fdopen failed";
210 check_and_fclose(log_fp, filename);
211 close(pipefd[0]);
212 _exit(EXIT_FAILURE);
213 }
214
215 char* line = nullptr;
216 size_t len = 0;
217 while (getline(&line, &len, pipe_fp) != -1) {
218 auto now = std::chrono::steady_clock::now();
219 double duration =
220 std::chrono::duration_cast<std::chrono::duration<double>>(now - start).count();
221 if (line[0] == '\n') {
222 fprintf(log_fp, "[%12.6lf]\n", duration);
223 } else {
224 fprintf(log_fp, "[%12.6lf] %s", duration, line);
225 }
226 fflush(log_fp);
227 }
228
229 PLOG(ERROR) << "getline failed";
230
231 free(line);
232 check_and_fclose(log_fp, filename);
233 close(pipefd[0]);
234 _exit(EXIT_FAILURE);
235 } else {
236 // Redirect stdout/stderr to the logger process. Close the unused read end.
237 close(pipefd[0]);
238
239 setbuf(stdout, nullptr);
240 setbuf(stderr, nullptr);
241
242 if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
243 PLOG(ERROR) << "dup2 stdout failed";
244 }
245 if (dup2(pipefd[1], STDERR_FILENO) == -1) {
246 PLOG(ERROR) << "dup2 stderr failed";
247 }
248
249 close(pipefd[1]);
250 }
251}
252
253int main(int argc, char** argv) {
254 // We don't have logcat yet under recovery; so we'll print error on screen and log to stdout
255 // (which is redirected to recovery.log) as we used to do.
256 android::base::InitLogging(argv, &UiLogger);
257
258 // Take last pmsg contents and rewrite it to the current pmsg session.
259 static constexpr const char filter[] = "recovery/";
260 // Do we need to rotate?
261 bool do_rotate = false;
262
263 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logbasename, &do_rotate);
264 // Take action to refresh pmsg contents
265 __android_log_pmsg_file_read(LOG_ID_SYSTEM, ANDROID_LOG_INFO, filter, logrotate, &do_rotate);
266
267 // If this binary is started with the single argument "--adbd", instead of being the normal
268 // recovery binary, it turns into kind of a stripped-down version of adbd that only supports the
269 // 'sideload' command. Note this must be a real argument, not anything in the command file or
270 // bootloader control block; the only way recovery should be run with this argument is when it
271 // starts a copy of itself from the apply_from_adb() function.
272 if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
273 minadbd_main();
274 return 0;
275 }
276
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700277 time_t start = time(nullptr);
278
Tao Bao6d99d4b2018-04-25 16:47:04 -0700279 // redirect_stdio should be called only in non-sideload mode. Otherwise we may have two logger
280 // instances with different timestamps.
281 redirect_stdio(Paths::Get().temporary_log_file().c_str());
282
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700283 printf("Starting recovery (pid %d) on %s", getpid(), ctime(&start));
284
285 load_volume_table();
286 has_cache = volume_for_mount_point(CACHE_ROOT) != nullptr;
287
288 std::vector<std::string> args = get_args(argc, argv);
Tao Bao1700cc42018-07-16 22:09:59 -0700289 auto args_to_parse = StringVectorToNullTerminatedArray(args);
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700290
291 static constexpr struct option OPTIONS[] = {
292 { "locale", required_argument, nullptr, 0 },
293 { "show_text", no_argument, nullptr, 't' },
294 { nullptr, 0, nullptr, 0 },
295 };
296
297 bool show_text = false;
298 std::string locale;
299
300 int arg;
301 int option_index;
Tao Bao1700cc42018-07-16 22:09:59 -0700302 while ((arg = getopt_long(args_to_parse.size() - 1, args_to_parse.data(), "", OPTIONS,
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700303 &option_index)) != -1) {
304 switch (arg) {
305 case 't':
306 show_text = true;
307 break;
308 case 0: {
309 std::string option = OPTIONS[option_index].name;
310 if (option == "locale") {
311 locale = optarg;
312 }
313 break;
314 }
315 }
316 }
Jerry Zhang49fd5d22018-05-17 12:54:41 -0700317 optind = 1;
Jerry Zhangf5e319a2018-05-04 11:24:10 -0700318
319 if (locale.empty()) {
320 if (has_cache) {
321 locale = load_locale_from_cache();
322 }
323
324 if (locale.empty()) {
325 static constexpr const char* DEFAULT_LOCALE = "en-US";
326 locale = DEFAULT_LOCALE;
327 }
328 }
329
330 printf("locale is [%s]\n", locale.c_str());
331
332 Device* device = make_device();
333 if (android::base::GetBoolProperty("ro.boot.quiescent", false)) {
334 printf("Quiescent recovery mode.\n");
335 device->ResetUI(new StubRecoveryUI());
336 } else {
337 if (!device->GetUI()->Init(locale)) {
338 printf("Failed to initialize UI; using stub UI instead.\n");
339 device->ResetUI(new StubRecoveryUI());
340 }
341 }
342 ui = device->GetUI();
343
344 if (!has_cache) {
345 device->RemoveMenuItemForAction(Device::WIPE_CACHE);
346 }
347
348 ui->SetBackground(RecoveryUI::NONE);
349 if (show_text) ui->ShowText(true);
350
351 sehandle = selinux_android_file_context_handle();
352 selinux_android_set_sehandle(sehandle);
353 if (!sehandle) {
354 ui->Print("Warning: No file_contexts\n");
355 }
356
357 Device::BuiltinAction after = start_recovery(device, args);
358
359 switch (after) {
360 case Device::SHUTDOWN:
361 ui->Print("Shutting down...\n");
362 android::base::SetProperty(ANDROID_RB_PROPERTY, "shutdown,");
363 break;
364
365 case Device::REBOOT_BOOTLOADER:
366 ui->Print("Rebooting to bootloader...\n");
367 android::base::SetProperty(ANDROID_RB_PROPERTY, "reboot,bootloader");
368 break;
369
370 default:
371 ui->Print("Rebooting...\n");
372 reboot("reboot,");
373 break;
374 }
375 while (true) {
376 pause();
377 }
378 // Should be unreachable.
379 return EXIT_SUCCESS;
Tao Bao6d99d4b2018-04-25 16:47:04 -0700380}