blob: 9faa63e3e9fe4d9f130b34e2002d3777791872be [file] [log] [blame]
Felipe Lemef0292972016-11-22 13:57:05 -08001/*
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 <fcntl.h>
22#include <sys/prctl.h>
23#include <sys/wait.h>
24#include <unistd.h>
25
26#include <vector>
27
28#include <android-base/properties.h>
29#include <cutils/log.h>
30
31#include "DumpstateInternal.h"
32
33// TODO: move to unnamed namespace
34static constexpr const char* kSuPath = "/system/xbin/su";
35
36// TODO: move to unnamed namespace
37static bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
38 sigset_t child_mask, old_mask;
39 sigemptyset(&child_mask);
40 sigaddset(&child_mask, SIGCHLD);
41
42 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
43 printf("*** sigprocmask failed: %s\n", strerror(errno));
44 return false;
45 }
46
47 timespec ts;
48 ts.tv_sec = timeout_seconds;
49 ts.tv_nsec = 0;
50 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
51 int saved_errno = errno;
52 // Set the signals back the way they were.
53 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
54 printf("*** sigprocmask failed: %s\n", strerror(errno));
55 if (ret == 0) {
56 return false;
57 }
58 }
59 if (ret == -1) {
60 errno = saved_errno;
61 if (errno == EAGAIN) {
62 errno = ETIMEDOUT;
63 } else {
64 printf("*** sigtimedwait failed: %s\n", strerror(errno));
65 }
66 return false;
67 }
68
69 pid_t child_pid = waitpid(pid, status, WNOHANG);
70 if (child_pid != pid) {
71 if (child_pid != -1) {
72 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
73 } else {
74 printf("*** waitpid failed: %s\n", strerror(errno));
75 }
76 return false;
77 }
78 return true;
79}
80
81CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
82CommandOptions CommandOptions::AS_ROOT = CommandOptions::WithTimeout(10).AsRoot().Build();
83CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
84
85CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(int64_t timeout) : values(timeout) {
86}
87
88CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
89 values.always_ = true;
90 return *this;
91}
92
93CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
94 values.account_mode_ = SU_ROOT;
95 return *this;
96}
97
98CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
99 values.account_mode_ = DROP_ROOT;
100 return *this;
101}
102
103CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
104 values.output_mode_ = REDIRECT_TO_STDERR;
105 return *this;
106}
107
108CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
109 const std::string& message) {
110 values.logging_message_ = message;
111 return *this;
112}
113
114CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
115 return CommandOptions(values);
116}
117
118CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout)
119 : timeout_(timeout),
120 always_(false),
121 account_mode_(DONT_DROP_ROOT),
122 output_mode_(NORMAL_OUTPUT),
123 logging_message_("") {
124}
125
126CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
127}
128
129int64_t CommandOptions::Timeout() const {
130 return values.timeout_;
131}
132
133bool CommandOptions::Always() const {
134 return values.always_;
135}
136
137PrivilegeMode CommandOptions::PrivilegeMode() const {
138 return values.account_mode_;
139}
140
141OutputMode CommandOptions::OutputMode() const {
142 return values.output_mode_;
143}
144
145std::string CommandOptions::LoggingMessage() const {
146 return values.logging_message_;
147}
148
149CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout) {
150 return CommandOptions::CommandOptionsBuilder(timeout);
151}
152
153std::string PropertiesHelper::build_type_ = "";
154int PropertiesHelper::dry_run_ = -1;
155
156bool PropertiesHelper::IsUserBuild() {
157 if (build_type_.empty()) {
158 build_type_ = android::base::GetProperty("ro.build.type", "user");
159 }
160 return "user" == build_type_;
161}
162
163bool PropertiesHelper::IsDryRun() {
164 if (dry_run_ == -1) {
165 dry_run_ = android::base::GetBoolProperty("dumpstate.dry_run", false) ? 1 : 0;
166 }
167 return dry_run_ == 1;
168}
169
170int DumpFileToFd(int out_fd, const std::string& title, const std::string& path) {
171 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
172 if (fd < 0) {
173 int err = errno;
174 if (title.empty()) {
175 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
176 } else {
177 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
178 strerror(err));
179 }
180 fsync(out_fd);
181 return -1;
182 }
183 return DumpFileFromFdToFd(title, path, fd, out_fd, PropertiesHelper::IsDryRun());
184}
185
186int RunCommandToFd(int fd, const std::string& title, const std::vector<std::string>& full_command,
187 const CommandOptions& options) {
188 if (full_command.empty()) {
189 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
190 return -1;
191 }
192
193 int size = full_command.size() + 1; // null terminated
194 int starting_index = 0;
195 if (options.PrivilegeMode() == SU_ROOT) {
196 starting_index = 2; // "su" "root"
197 size += starting_index;
198 }
199
200 std::vector<const char*> args;
201 args.resize(size);
202
203 std::string command_string;
204 if (options.PrivilegeMode() == SU_ROOT) {
205 args[0] = kSuPath;
206 command_string += kSuPath;
207 args[1] = "root";
208 command_string += " root ";
209 }
210 for (size_t i = 0; i < full_command.size(); i++) {
211 args[i + starting_index] = full_command[i].data();
212 command_string += args[i + starting_index];
213 if (i != full_command.size() - 1) {
214 command_string += " ";
215 }
216 }
217 args[size - 1] = nullptr;
218
219 const char* command = command_string.c_str();
220
221 if (options.PrivilegeMode() == SU_ROOT && PropertiesHelper::IsUserBuild()) {
222 dprintf(fd, "Skipping '%s' on user build.\n", command);
223 return 0;
224 }
225
226 if (!title.empty()) {
227 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
228 fsync(fd);
229 }
230
231 const std::string& logging_message = options.LoggingMessage();
232 if (!logging_message.empty()) {
233 MYLOGI(logging_message.c_str(), command_string.c_str());
234 }
235
236 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR);
237 bool redirecting_to_fd = STDOUT_FILENO != fd;
238
239 if (PropertiesHelper::IsDryRun() && !options.Always()) {
240 if (!title.empty()) {
241 dprintf(fd, "\t(skipped on dry run)\n");
242 } else if (redirecting_to_fd) {
243 // There is no title, but we should still print a dry-run message
244 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
245 }
246 fsync(fd);
247 return 0;
248 }
249
250 const char* path = args[0];
251
252 uint64_t start = Nanotime();
253 pid_t pid = fork();
254
255 /* handle error case */
256 if (pid < 0) {
257 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
258 MYLOGE("*** fork: %s\n", strerror(errno));
259 return pid;
260 }
261
262 /* handle child case */
263 if (pid == 0) {
264 if (options.PrivilegeMode() == DROP_ROOT && !DropRootUser()) {
265 if (!silent) {
266 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
267 strerror(errno));
268 }
269 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
270 return -1;
271 }
272
273 if (silent) {
274 // Redirects stdout to stderr
275 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
276 } else if (redirecting_to_fd) {
277 // Redirect stdout to fd
278 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
279 close(fd);
280 }
281
282 /* make sure the child dies when dumpstate dies */
283 prctl(PR_SET_PDEATHSIG, SIGKILL);
284
285 /* just ignore SIGPIPE, will go down with parent's */
286 struct sigaction sigact;
287 memset(&sigact, 0, sizeof(sigact));
288 sigact.sa_handler = SIG_IGN;
289 sigaction(SIGPIPE, &sigact, NULL);
290
291 execvp(path, (char**)args.data());
292 // execvp's result will be handled after waitpid_with_timeout() below, but
293 // if it failed, it's safer to exit dumpstate.
294 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
295 // Must call _exit (instead of exit), otherwise it will corrupt the zip
296 // file.
297 _exit(EXIT_FAILURE);
298 }
299
300 /* handle parent case */
301 int status;
302 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
303 fsync(fd);
304
305 uint64_t elapsed = Nanotime() - start;
306 if (!ret) {
307 if (errno == ETIMEDOUT) {
308 if (!silent)
309 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
310 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
311 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
312 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
313 } else {
314 if (!silent)
315 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
316 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
317 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
318 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
319 }
320 kill(pid, SIGTERM);
321 if (!waitpid_with_timeout(pid, 5, nullptr)) {
322 kill(pid, SIGKILL);
323 if (!waitpid_with_timeout(pid, 5, nullptr)) {
324 if (!silent)
325 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
326 command, pid);
327 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
328 }
329 }
330 return -1;
331 }
332
333 if (WIFSIGNALED(status)) {
334 if (!silent)
335 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
336 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
337 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
338 status = WEXITSTATUS(status);
339 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
340 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
341 }
342
343 return status;
344}