blob: 298a65c2c2ec25adb5494067010e681fd5626369 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 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//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/subprocess.h"
Darin Petkova0b9e772011-10-06 05:05:56 -070018
Alex Deymo29b81532015-07-09 11:51:49 -070019#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000020#include <stdlib.h>
21#include <string.h>
Kenneth Watersa7fcafa2010-09-21 10:27:03 -070022#include <unistd.h>
Darin Petkova0b9e772011-10-06 05:05:56 -070023
Ben Chan02f7c1d2014-10-18 15:18:02 -070024#include <memory>
Darin Petkova0b9e772011-10-06 05:05:56 -070025#include <string>
Amin Hassania8859542018-03-07 16:24:43 -080026#include <utility>
adlr@google.com3defe6a2009-12-04 20:57:17 +000027#include <vector>
Darin Petkova0b9e772011-10-06 05:05:56 -070028
Alex Deymo29b81532015-07-09 11:51:49 -070029#include <base/bind.h>
Darin Petkova0b9e772011-10-06 05:05:56 -070030#include <base/logging.h>
Alex Deymo29b81532015-07-09 11:51:49 -070031#include <base/posix/eintr_wrapper.h>
hscham00b6aa22020-02-20 12:32:06 +090032#include <base/stl_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070035#include <brillo/process.h>
36#include <brillo/secure_blob.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000037
Alex Deymo0d298542016-03-30 18:31:49 -070038#include "update_engine/common/utils.h"
39
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070040using brillo::MessageLoop;
adlr@google.com3defe6a2009-12-04 20:57:17 +000041using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070042using std::unique_ptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +000043using std::vector;
44
45namespace chromeos_update_engine {
46
Alex Deymo461b2592015-07-24 20:10:52 -070047namespace {
Darin Petkov6f03a3b2010-11-10 14:27:14 -080048
Alex Deymo109c28d2016-04-05 23:00:52 +000049bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
Alex Deymo461b2592015-07-24 20:10:52 -070050 // Setup the environment variables.
51 clearenv();
52 for (const auto& key_value : env) {
53 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
54 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -080055
Alex Deymo461b2592015-07-24 20:10:52 -070056 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
57 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
58 return false;
Alex Deymo29b81532015-07-09 11:51:49 -070059 }
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -070060
Alex Deymo461b2592015-07-24 20:10:52 -070061 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
62 if (fd < 0)
63 return false;
64 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
65 return false;
66 IGNORE_EINTR(close(fd));
67
68 return true;
adlr@google.com3defe6a2009-12-04 20:57:17 +000069}
70
Alex Deymo461b2592015-07-24 20:10:52 -070071// Helper function to launch a process with the given Subprocess::Flags.
72// This function only sets up and starts the process according to the |flags|.
73// The caller is responsible for watching the termination of the subprocess.
74// Return whether the process was successfully launched and fills in the |proc|
75// Process.
76bool LaunchProcess(const vector<string>& cmd,
77 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -070078 const vector<int>& output_pipes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070079 brillo::Process* proc) {
Alex Deymo461b2592015-07-24 20:10:52 -070080 for (const string& arg : cmd)
81 proc->AddArg(arg);
82 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
83
84 // Create an environment for the child process with just the required PATHs.
85 std::map<string, string> env;
86 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
87 const char* value = getenv(key);
88 if (value)
89 env.emplace(key, value);
90 }
91
Alex Deymoe384bb22016-03-29 17:23:33 -070092 for (const int fd : output_pipes) {
93 proc->RedirectUsingPipe(fd, false);
94 }
95 proc->SetCloseUnusedFileDescriptors(true);
Alex Deymo461b2592015-07-24 20:10:52 -070096 proc->RedirectUsingPipe(STDOUT_FILENO, false);
Alex Deymo109c28d2016-04-05 23:00:52 +000097 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
Alex Deymo461b2592015-07-24 20:10:52 -070098
Amin Hassani3a4caa12019-11-06 11:12:28 -080099 LOG(INFO) << "Running \"" << base::JoinString(cmd, " ") << "\"";
Alex Deymo461b2592015-07-24 20:10:52 -0700100 return proc->Start();
101}
102
103} // namespace
104
Alex Deymob7ca0962014-10-01 17:58:07 -0700105void Subprocess::Init(
Amin Hassanib2689592019-01-13 17:04:28 -0800106 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
Alex Deymo461b2592015-07-24 20:10:52 -0700107 if (subprocess_singleton_ == this)
108 return;
109 CHECK(subprocess_singleton_ == nullptr);
110 subprocess_singleton_ = this;
111
Alex Deymob7ca0962014-10-01 17:58:07 -0700112 process_reaper_.Register(async_signal_handler);
Alex Deymo461b2592015-07-24 20:10:52 -0700113}
114
115Subprocess::~Subprocess() {
116 if (subprocess_singleton_ == this)
117 subprocess_singleton_ = nullptr;
Kenneth Watersa7fcafa2010-09-21 10:27:03 -0700118}
119
Alex Deymo29b81532015-07-09 11:51:49 -0700120void Subprocess::OnStdoutReady(SubprocessRecord* record) {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800121 char buf[1024];
Alex Deymo0d298542016-03-30 18:31:49 -0700122 size_t bytes_read;
Alex Deymo29b81532015-07-09 11:51:49 -0700123 do {
Alex Deymo0d298542016-03-30 18:31:49 -0700124 bytes_read = 0;
125 bool eof;
126 bool ok = utils::ReadAll(
hscham00b6aa22020-02-20 12:32:06 +0900127 record->stdout_fd, buf, base::size(buf), &bytes_read, &eof);
Alex Deymo0d298542016-03-30 18:31:49 -0700128 record->stdout.append(buf, bytes_read);
129 if (!ok || eof) {
130 // There was either an error or an EOF condition, so we are done watching
131 // the file descriptor.
Tianjie55abd3c2020-06-19 00:22:59 -0700132#ifdef __ANDROID__
Alex Deymo461b2592015-07-24 20:10:52 -0700133 MessageLoop::current()->CancelTask(record->stdout_task_id);
134 record->stdout_task_id = MessageLoop::kTaskIdNull;
Tianjie55abd3c2020-06-19 00:22:59 -0700135#else
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900136 record->stdout_controller.reset();
Tianjie55abd3c2020-06-19 00:22:59 -0700137#endif // __ANDROID__
Alex Deymo0d298542016-03-30 18:31:49 -0700138 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700139 }
Alex Deymo0d298542016-03-30 18:31:49 -0700140 } while (bytes_read);
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800141}
142
Alex Deymo461b2592015-07-24 20:10:52 -0700143void Subprocess::ChildExitedCallback(const siginfo_t& info) {
144 auto pid_record = subprocess_records_.find(info.si_pid);
145 if (pid_record == subprocess_records_.end())
146 return;
147 SubprocessRecord* record = pid_record->second.get();
148
149 // Make sure we read any remaining process output and then close the pipe.
150 OnStdoutReady(record);
151
Tianjie55abd3c2020-06-19 00:22:59 -0700152#ifdef __ANDROID__
Alex Deymo461b2592015-07-24 20:10:52 -0700153 MessageLoop::current()->CancelTask(record->stdout_task_id);
154 record->stdout_task_id = MessageLoop::kTaskIdNull;
Tianjie55abd3c2020-06-19 00:22:59 -0700155#else
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900156 record->stdout_controller.reset();
Tianjie55abd3c2020-06-19 00:22:59 -0700157#endif // __ANDROID__
Alex Deymo461b2592015-07-24 20:10:52 -0700158
Alex Deymo461b2592015-07-24 20:10:52 -0700159 // Don't print any log if the subprocess exited with exit code 0.
160 if (info.si_code != CLD_EXITED) {
161 LOG(INFO) << "Subprocess terminated with si_code " << info.si_code;
162 } else if (info.si_status != 0) {
163 LOG(INFO) << "Subprocess exited with si_status: " << info.si_status;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000164 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700165
Alex Deymo461b2592015-07-24 20:10:52 -0700166 if (!record->stdout.empty()) {
167 LOG(INFO) << "Subprocess output:\n" << record->stdout;
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700168 }
Alex Deymo461b2592015-07-24 20:10:52 -0700169 if (!record->callback.is_null()) {
170 record->callback.Run(info.si_status, record->stdout);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700171 }
Alex Deymoe384bb22016-03-29 17:23:33 -0700172 // Release and close all the pipes after calling the callback so our
173 // redirected pipes are still alive. Releasing the process first makes
174 // Reset(0) not attempt to kill the process, which is already a zombie at this
175 // point.
176 record->proc.Release();
177 record->proc.Reset(0);
178
Alex Deymo461b2592015-07-24 20:10:52 -0700179 subprocess_records_.erase(pid_record);
Alex Deymo29b81532015-07-09 11:51:49 -0700180}
181
Alex Deymo461b2592015-07-24 20:10:52 -0700182pid_t Subprocess::Exec(const vector<string>& cmd,
183 const ExecCallback& callback) {
Alex Deymo109c28d2016-04-05 23:00:52 +0000184 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
Alex Deymo461b2592015-07-24 20:10:52 -0700185}
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700186
Alex Deymo461b2592015-07-24 20:10:52 -0700187pid_t Subprocess::ExecFlags(const vector<string>& cmd,
188 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -0700189 const vector<int>& output_pipes,
Alex Deymo461b2592015-07-24 20:10:52 -0700190 const ExecCallback& callback) {
191 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
192
Alex Deymo109c28d2016-04-05 23:00:52 +0000193 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700194 LOG(ERROR) << "Failed to launch subprocess";
Chris Masonec6c57a52010-09-23 13:06:14 -0700195 return 0;
196 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000197
Alex Deymo461b2592015-07-24 20:10:52 -0700198 pid_t pid = record->proc.pid();
Amin Hassanib2689592019-01-13 17:04:28 -0800199 CHECK(process_reaper_.WatchForChild(
200 FROM_HERE,
201 pid,
202 base::Bind(&Subprocess::ChildExitedCallback, base::Unretained(this))));
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800203
Alex Deymo461b2592015-07-24 20:10:52 -0700204 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
Alex Deymo29b81532015-07-09 11:51:49 -0700205 // Capture the subprocess output. Make our end of the pipe non-blocking.
Alex Deymo461b2592015-07-24 20:10:52 -0700206 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
Alex Deymo29b81532015-07-09 11:51:49 -0700207 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
208 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
209 << record->stdout_fd << ".";
210 }
211
Tianjie55abd3c2020-06-19 00:22:59 -0700212#ifdef __ANDROID__
Alex Deymo461b2592015-07-24 20:10:52 -0700213 record->stdout_task_id = MessageLoop::current()->WatchFileDescriptor(
Alex Deymo29b81532015-07-09 11:51:49 -0700214 FROM_HERE,
215 record->stdout_fd,
216 MessageLoop::WatchMode::kWatchRead,
217 true,
218 base::Bind(&Subprocess::OnStdoutReady, record.get()));
Tianjie55abd3c2020-06-19 00:22:59 -0700219#else
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900220 record->stdout_controller = base::FileDescriptorWatcher::WatchReadable(
Alex Deymo29b81532015-07-09 11:51:49 -0700221 record->stdout_fd,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900222 base::BindRepeating(&Subprocess::OnStdoutReady, record.get()));
Tianjie55abd3c2020-06-19 00:22:59 -0700223#endif // __ANDROID__
Alex Deymo29b81532015-07-09 11:51:49 -0700224
Alex Vakulenkoce8c8ee2016-04-08 08:59:26 -0700225 subprocess_records_[pid] = std::move(record);
Alex Deymo461b2592015-07-24 20:10:52 -0700226 return pid;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000227}
228
Alex Deymo461b2592015-07-24 20:10:52 -0700229void Subprocess::KillExec(pid_t pid) {
230 auto pid_record = subprocess_records_.find(pid);
231 if (pid_record == subprocess_records_.end())
Alex Deymo29b81532015-07-09 11:51:49 -0700232 return;
Alex Deymo461b2592015-07-24 20:10:52 -0700233 pid_record->second->callback.Reset();
Sen Jiang1d3b8632016-05-13 12:32:10 -0700234 // We don't care about output/return code, so we use SIGKILL here to ensure it
235 // will be killed, SIGTERM might lead to leaked subprocess.
236 if (kill(pid, SIGKILL) != 0) {
237 PLOG(WARNING) << "Error sending SIGKILL to " << pid;
Alex Deymod15c5462016-03-09 18:11:12 -0800238 }
239 // Release the pid now so we don't try to kill it if Subprocess is destroyed
240 // before the corresponding ChildExitedCallback() is called.
241 pid_record->second->proc.Release();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000242}
243
Alex Deymoe384bb22016-03-29 17:23:33 -0700244int Subprocess::GetPipeFd(pid_t pid, int fd) const {
245 auto pid_record = subprocess_records_.find(pid);
246 if (pid_record == subprocess_records_.end())
247 return -1;
248 return pid_record->second->proc.GetPipe(fd);
249}
250
Alex Deymof329b932014-10-30 01:37:48 -0700251bool Subprocess::SynchronousExec(const vector<string>& cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700252 int* return_code,
Amin Hassani3a4caa12019-11-06 11:12:28 -0800253 string* stdout,
254 string* stderr) {
255 // The default for |SynchronousExec| is to use |kSearchPath| since the code
256 // relies on that.
257 return SynchronousExecFlags(cmd, kSearchPath, return_code, stdout, stderr);
Alex Deymo461b2592015-07-24 20:10:52 -0700258}
259
260bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
261 uint32_t flags,
262 int* return_code,
Amin Hassani3a4caa12019-11-06 11:12:28 -0800263 string* stdout,
264 string* stderr) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700265 brillo::ProcessImpl proc;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800266 if (!LaunchProcess(cmd, flags, {STDERR_FILENO}, &proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700267 LOG(ERROR) << "Failed to launch subprocess";
268 return false;
269 }
270
271 if (stdout) {
272 stdout->clear();
273 }
Amin Hassani3a4caa12019-11-06 11:12:28 -0800274 if (stderr) {
275 stderr->clear();
276 }
Alex Deymo461b2592015-07-24 20:10:52 -0700277
Amin Hassani3a4caa12019-11-06 11:12:28 -0800278 // Read from both stdout and stderr individually.
279 int stdout_fd = proc.GetPipe(STDOUT_FILENO);
280 int stderr_fd = proc.GetPipe(STDERR_FILENO);
Alex Deymo461b2592015-07-24 20:10:52 -0700281 vector<char> buffer(32 * 1024);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800282 bool stdout_closed = false, stderr_closed = false;
283 while (!stdout_closed || !stderr_closed) {
284 if (!stdout_closed) {
285 int rc = HANDLE_EINTR(read(stdout_fd, buffer.data(), buffer.size()));
286 if (rc <= 0) {
287 stdout_closed = true;
288 if (rc < 0)
289 PLOG(ERROR) << "Reading from child's stdout";
290 } else if (stdout != nullptr) {
Alex Deymo461b2592015-07-24 20:10:52 -0700291 stdout->append(buffer.data(), rc);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800292 }
293 }
294
295 if (!stderr_closed) {
296 int rc = HANDLE_EINTR(read(stderr_fd, buffer.data(), buffer.size()));
297 if (rc <= 0) {
298 stderr_closed = true;
299 if (rc < 0)
300 PLOG(ERROR) << "Reading from child's stderr";
301 } else if (stderr != nullptr) {
302 stderr->append(buffer.data(), rc);
303 }
Alex Deymo461b2592015-07-24 20:10:52 -0700304 }
305 }
Amin Hassani3a4caa12019-11-06 11:12:28 -0800306
Alex Deymo461b2592015-07-24 20:10:52 -0700307 // At this point, the subprocess already closed the output, so we only need to
308 // wait for it to finish.
309 int proc_return_code = proc.Wait();
310 if (return_code)
311 *return_code = proc_return_code;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700312 return proc_return_code != brillo::Process::kErrorExitStatus;
Darin Petkov85d02b72011-05-17 13:25:51 -0700313}
314
Amin Hassania8859542018-03-07 16:24:43 -0800315void Subprocess::FlushBufferedLogsAtExit() {
316 if (!subprocess_records_.empty()) {
317 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
318 for (auto& pid_record : subprocess_records_) {
319 SubprocessRecord* record = pid_record.second.get();
320 // Make sure we read any remaining process output.
321 OnStdoutReady(record);
322 if (!record->stdout.empty()) {
323 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
324 << record->stdout;
325 }
326 }
327 }
328}
329
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700330Subprocess* Subprocess::subprocess_singleton_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000331
332} // namespace chromeos_update_engine