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