1 /*
2 * Copyright (C) 2016 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 #define LOG_TAG "dumpstate"
18
19 #include "DumpstateUtil.h"
20
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <sys/prctl.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26
27 #include <vector>
28
29 #include <android-base/file.h>
30 #include <android-base/properties.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/strings.h>
33 #include <android-base/unique_fd.h>
34 #include <log/log.h>
35
36 #include "DumpstateInternal.h"
37
38 namespace android {
39 namespace os {
40 namespace dumpstate {
41
42 namespace {
43
44 static constexpr const char* kSuPath = "/system/xbin/su";
45
waitpid_with_timeout(pid_t pid,int timeout_ms,int * status)46 static bool waitpid_with_timeout(pid_t pid, int timeout_ms, int* status) {
47 sigset_t child_mask, old_mask;
48 sigemptyset(&child_mask);
49 sigaddset(&child_mask, SIGCHLD);
50
51 // block SIGCHLD before we check if a process has exited
52 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
53 printf("*** sigprocmask failed: %s\n", strerror(errno));
54 return false;
55 }
56
57 // if the child has exited already, handle and reset signals before leaving
58 pid_t child_pid = waitpid(pid, status, WNOHANG);
59 if (child_pid != pid) {
60 if (child_pid > 0) {
61 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
62 sigprocmask(SIG_SETMASK, &old_mask, nullptr);
63 return false;
64 }
65 } else {
66 sigprocmask(SIG_SETMASK, &old_mask, nullptr);
67 return true;
68 }
69
70 // wait for a SIGCHLD
71 timespec ts;
72 ts.tv_sec = MSEC_TO_SEC(timeout_ms);
73 ts.tv_nsec = (timeout_ms % 1000) * 1000000;
74 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
75 int saved_errno = errno;
76
77 // Set the signals back the way they were.
78 if (sigprocmask(SIG_SETMASK, &old_mask, nullptr) == -1) {
79 printf("*** sigprocmask failed: %s\n", strerror(errno));
80 if (ret == 0) {
81 return false;
82 }
83 }
84 if (ret == -1) {
85 errno = saved_errno;
86 if (errno == EAGAIN) {
87 errno = ETIMEDOUT;
88 } else {
89 printf("*** sigtimedwait failed: %s\n", strerror(errno));
90 }
91 return false;
92 }
93
94 child_pid = waitpid(pid, status, WNOHANG);
95 if (child_pid != pid) {
96 if (child_pid != -1) {
97 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
98 } else {
99 printf("*** waitpid failed: %s\n", strerror(errno));
100 }
101 return false;
102 }
103 return true;
104 }
105 } // unnamed namespace
106
107 CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
108 CommandOptions CommandOptions::AS_ROOT = CommandOptions::WithTimeout(10).AsRoot().Build();
109
CommandOptionsBuilder(int64_t timeout_ms)110 CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(int64_t timeout_ms) : values(timeout_ms) {
111 }
112
Always()113 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
114 values.always_ = true;
115 return *this;
116 }
117
AsRoot()118 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
119 if (!PropertiesHelper::IsUnroot()) {
120 values.account_mode_ = SU_ROOT;
121 }
122 return *this;
123 }
124
AsRootIfAvailable()125 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRootIfAvailable() {
126 if (!PropertiesHelper::IsUserBuild()) {
127 return AsRoot();
128 }
129 return *this;
130 }
131
DropRoot()132 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
133 values.account_mode_ = DROP_ROOT;
134 return *this;
135 }
136
RedirectStderr()137 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
138 values.output_mode_ = REDIRECT_TO_STDERR;
139 return *this;
140 }
141
142 CommandOptions::CommandOptionsBuilder&
CloseAllFileDescriptorsOnExec()143 CommandOptions::CommandOptionsBuilder::CloseAllFileDescriptorsOnExec() {
144 values.close_all_fds_on_exec_ = true;
145 return *this;
146 }
147
Log(const std::string & message)148 CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
149 const std::string& message) {
150 values.logging_message_ = message;
151 return *this;
152 }
153
Build()154 CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
155 return CommandOptions(values);
156 }
157
CommandOptionsValues(int64_t timeout_ms)158 CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout_ms)
159 : timeout_ms_(timeout_ms),
160 always_(false),
161 close_all_fds_on_exec_(false),
162 account_mode_(DONT_DROP_ROOT),
163 output_mode_(NORMAL_OUTPUT),
164 logging_message_("") {
165 }
166
CommandOptions(const CommandOptionsValues & values)167 CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
168 }
169
Timeout() const170 int64_t CommandOptions::Timeout() const {
171 return MSEC_TO_SEC(values.timeout_ms_);
172 }
173
TimeoutInMs() const174 int64_t CommandOptions::TimeoutInMs() const {
175 return values.timeout_ms_;
176 }
177
Always() const178 bool CommandOptions::Always() const {
179 return values.always_;
180 }
181
ShouldCloseAllFileDescriptorsOnExec() const182 bool CommandOptions::ShouldCloseAllFileDescriptorsOnExec() const {
183 return values.close_all_fds_on_exec_;
184 }
185
PrivilegeMode() const186 PrivilegeMode CommandOptions::PrivilegeMode() const {
187 return values.account_mode_;
188 }
189
OutputMode() const190 OutputMode CommandOptions::OutputMode() const {
191 return values.output_mode_;
192 }
193
LoggingMessage() const194 std::string CommandOptions::LoggingMessage() const {
195 return values.logging_message_;
196 }
197
WithTimeout(int64_t timeout_sec)198 CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout_sec) {
199 return CommandOptions::CommandOptionsBuilder(SEC_TO_MSEC(timeout_sec));
200 }
201
WithTimeoutInMs(int64_t timeout_ms)202 CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeoutInMs(int64_t timeout_ms) {
203 return CommandOptions::CommandOptionsBuilder(timeout_ms);
204 }
205
206 std::string PropertiesHelper::build_type_ = "";
207 int PropertiesHelper::dry_run_ = -1;
208 int PropertiesHelper::unroot_ = -1;
209 int PropertiesHelper::parallel_run_ = -1;
210 #if !defined(__ANDROID_VNDK__)
211 int PropertiesHelper::strict_run_ = -1;
212 #endif
213
IsUserBuild()214 bool PropertiesHelper::IsUserBuild() {
215 if (build_type_.empty()) {
216 build_type_ = android::base::GetProperty("ro.build.type", "user");
217 }
218 return "user" == build_type_;
219 }
220
IsDryRun()221 bool PropertiesHelper::IsDryRun() {
222 if (dry_run_ == -1) {
223 dry_run_ = android::base::GetBoolProperty("dumpstate.dry_run", false) ? 1 : 0;
224 }
225 return dry_run_ == 1;
226 }
227
IsUnroot()228 bool PropertiesHelper::IsUnroot() {
229 if (unroot_ == -1) {
230 unroot_ = android::base::GetBoolProperty("dumpstate.unroot", false) ? 1 : 0;
231 }
232 return unroot_ == 1;
233 }
234
IsParallelRun()235 bool PropertiesHelper::IsParallelRun() {
236 if (parallel_run_ == -1) {
237 parallel_run_ = android::base::GetBoolProperty("dumpstate.parallel_run",
238 /* default_value = */true) ? 1 : 0;
239 }
240 return parallel_run_ == 1;
241 }
242
243 #if !defined(__ANDROID_VNDK__)
IsStrictRun()244 bool PropertiesHelper::IsStrictRun() {
245 if (strict_run_ == -1) {
246 // Defaults to using stricter timeouts.
247 strict_run_ = android::base::GetBoolProperty("dumpstate.strict_run", true) ? 1 : 0;
248 }
249 return strict_run_ == 1;
250 }
251 #endif
252
DumpFileToFd(int out_fd,const std::string & title,const std::string & path)253 int DumpFileToFd(int out_fd, const std::string& title, const std::string& path) {
254 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
255 if (fd.get() < 0) {
256 int err = errno;
257 if (title.empty()) {
258 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
259 } else {
260 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
261 strerror(err));
262 }
263 return -1;
264 }
265 return DumpFileFromFdToFd(title, path, fd.get(), out_fd, PropertiesHelper::IsDryRun());
266 }
267
RunCommandToFd(int fd,const std::string & title,const std::vector<std::string> & full_command,const CommandOptions & options)268 int RunCommandToFd(int fd, const std::string& title, const std::vector<std::string>& full_command,
269 const CommandOptions& options) {
270 if (full_command.empty()) {
271 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
272 return -1;
273 }
274
275 int size = full_command.size() + 1; // null terminated
276 int starting_index = 0;
277 if (options.PrivilegeMode() == SU_ROOT) {
278 starting_index = 2; // "su" "root"
279 size += starting_index;
280 }
281
282 std::vector<const char*> args;
283 args.resize(size);
284
285 std::string command_string;
286 if (options.PrivilegeMode() == SU_ROOT) {
287 args[0] = kSuPath;
288 command_string += kSuPath;
289 args[1] = "root";
290 command_string += " root ";
291 }
292 for (size_t i = 0; i < full_command.size(); i++) {
293 args[i + starting_index] = full_command[i].data();
294 command_string += args[i + starting_index];
295 if (i != full_command.size() - 1) {
296 command_string += " ";
297 }
298 }
299 args[size - 1] = nullptr;
300
301 const char* command = command_string.c_str();
302
303 if (options.PrivilegeMode() == SU_ROOT && PropertiesHelper::IsUserBuild()) {
304 dprintf(fd, "Skipping '%s' on user build.\n", command);
305 return 0;
306 }
307
308 if (!title.empty()) {
309 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
310 }
311
312 const std::string& logging_message = options.LoggingMessage();
313 if (!logging_message.empty()) {
314 MYLOGI(logging_message.c_str(), command_string.c_str());
315 }
316
317 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR ||
318 options.ShouldCloseAllFileDescriptorsOnExec());
319 bool redirecting_to_fd = STDOUT_FILENO != fd;
320
321 if (PropertiesHelper::IsDryRun() && !options.Always()) {
322 if (!title.empty()) {
323 dprintf(fd, "\t(skipped on dry run)\n");
324 } else if (redirecting_to_fd) {
325 // There is no title, but we should still print a dry-run message
326 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
327 }
328 return 0;
329 }
330
331 const char* path = args[0];
332
333 uint64_t start = Nanotime();
334 pid_t pid = vfork();
335
336 /* handle error case */
337 if (pid < 0) {
338 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
339 MYLOGE("*** fork: %s\n", strerror(errno));
340 return pid;
341 }
342
343 /* handle child case */
344 if (pid == 0) {
345 if (options.PrivilegeMode() == DROP_ROOT && !DropRootUser()) {
346 if (!silent) {
347 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
348 strerror(errno));
349 }
350 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
351 _exit(EXIT_FAILURE);
352 }
353
354 if (options.ShouldCloseAllFileDescriptorsOnExec()) {
355 int devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
356 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDIN_FILENO));
357 close(devnull_fd);
358 devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY));
359 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDOUT_FILENO));
360 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDERR_FILENO));
361 close(devnull_fd);
362 // This is to avoid leaking FDs that, accidentally, have not been
363 // marked as O_CLOEXEC. Leaking FDs across exec can cause failures
364 // when execing a process that has a SELinux auto_trans rule.
365 // Here we assume that the dumpstate process didn't open more than
366 // 1000 FDs. In theory we could iterate through /proc/self/fd/, but
367 // doing that in a fork-safe way is too complex and not worth it
368 // (opendir()/readdir() do heap allocations and take locks).
369 for (int i = 0; i < 1000; i++) {
370 if (i != STDIN_FILENO && i!= STDOUT_FILENO && i != STDERR_FILENO) {
371 close(i);
372 }
373 }
374 } else if (silent) {
375 // Redirects stdout to stderr
376 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
377 } else if (redirecting_to_fd) {
378 // Redirect stdout to fd
379 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
380 close(fd);
381 }
382
383 /* make sure the child dies when dumpstate dies */
384 prctl(PR_SET_PDEATHSIG, SIGKILL);
385
386 /* just ignore SIGPIPE, will go down with parent's */
387 struct sigaction sigact;
388 memset(&sigact, 0, sizeof(sigact));
389 sigact.sa_handler = SIG_IGN;
390 sigaction(SIGPIPE, &sigact, nullptr);
391
392 execvp(path, (char**)args.data());
393 // execvp's result will be handled after waitpid_with_timeout() below, but
394 // if it failed, it's safer to exit dumpstate.
395 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
396 // Must call _exit (instead of exit), otherwise it will corrupt the zip
397 // file.
398 _exit(EXIT_FAILURE);
399 }
400
401 /* handle parent case */
402 int status;
403 bool ret = waitpid_with_timeout(pid, options.TimeoutInMs(), &status);
404
405 uint64_t elapsed = Nanotime() - start;
406 if (!ret) {
407 if (errno == ETIMEDOUT) {
408 if (!silent)
409 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
410 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
411 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
412 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
413 } else {
414 if (!silent)
415 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
416 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
417 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
418 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
419 }
420 kill(pid, SIGTERM);
421 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
422 kill(pid, SIGKILL);
423 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
424 if (!silent)
425 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
426 command, pid);
427 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
428 }
429 }
430 return -1;
431 }
432
433 if (WIFSIGNALED(status)) {
434 if (!silent)
435 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
436 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
437 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
438 status = WEXITSTATUS(status);
439 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
440 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
441 }
442
443 return status;
444 }
445
446 } // namespace dumpstate
447 } // namespace os
448 } // namespace android
449