blob: 24ad2d9b38eddb129477ffc94c165f17d28b7b42 [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>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_util.h>
33#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070034#include <brillo/process.h>
35#include <brillo/secure_blob.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000036
Alex Deymo0d298542016-03-30 18:31:49 -070037#include "update_engine/common/utils.h"
38
adlr@google.com3defe6a2009-12-04 20:57:17 +000039using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070040using std::unique_ptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +000041using std::vector;
42
43namespace chromeos_update_engine {
44
Alex Deymo461b2592015-07-24 20:10:52 -070045namespace {
Darin Petkov6f03a3b2010-11-10 14:27:14 -080046
Alex Deymo109c28d2016-04-05 23:00:52 +000047bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
Alex Deymo461b2592015-07-24 20:10:52 -070048 // Setup the environment variables.
49 clearenv();
50 for (const auto& key_value : env) {
51 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
52 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -080053
Alex Deymo461b2592015-07-24 20:10:52 -070054 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
55 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
56 return false;
Alex Deymo29b81532015-07-09 11:51:49 -070057 }
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -070058
Alex Deymo461b2592015-07-24 20:10:52 -070059 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
60 if (fd < 0)
61 return false;
62 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
63 return false;
64 IGNORE_EINTR(close(fd));
65
66 return true;
adlr@google.com3defe6a2009-12-04 20:57:17 +000067}
68
Alex Deymo461b2592015-07-24 20:10:52 -070069// Helper function to launch a process with the given Subprocess::Flags.
70// This function only sets up and starts the process according to the |flags|.
71// The caller is responsible for watching the termination of the subprocess.
72// Return whether the process was successfully launched and fills in the |proc|
73// Process.
74bool LaunchProcess(const vector<string>& cmd,
75 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -070076 const vector<int>& output_pipes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070077 brillo::Process* proc) {
Alex Deymo461b2592015-07-24 20:10:52 -070078 for (const string& arg : cmd)
79 proc->AddArg(arg);
80 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
81
82 // Create an environment for the child process with just the required PATHs.
83 std::map<string, string> env;
84 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
85 const char* value = getenv(key);
86 if (value)
87 env.emplace(key, value);
88 }
89
Alex Deymoe384bb22016-03-29 17:23:33 -070090 for (const int fd : output_pipes) {
91 proc->RedirectUsingPipe(fd, false);
92 }
93 proc->SetCloseUnusedFileDescriptors(true);
Alex Deymo461b2592015-07-24 20:10:52 -070094 proc->RedirectUsingPipe(STDOUT_FILENO, false);
Alex Deymo109c28d2016-04-05 23:00:52 +000095 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
Alex Deymo461b2592015-07-24 20:10:52 -070096
Amin Hassani3a4caa12019-11-06 11:12:28 -080097 LOG(INFO) << "Running \"" << base::JoinString(cmd, " ") << "\"";
Alex Deymo461b2592015-07-24 20:10:52 -070098 return proc->Start();
99}
100
101} // namespace
102
Alex Deymob7ca0962014-10-01 17:58:07 -0700103void Subprocess::Init(
Amin Hassanib2689592019-01-13 17:04:28 -0800104 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
Alex Deymo461b2592015-07-24 20:10:52 -0700105 if (subprocess_singleton_ == this)
106 return;
107 CHECK(subprocess_singleton_ == nullptr);
108 subprocess_singleton_ = this;
109
Alex Deymob7ca0962014-10-01 17:58:07 -0700110 process_reaper_.Register(async_signal_handler);
Alex Deymo461b2592015-07-24 20:10:52 -0700111}
112
113Subprocess::~Subprocess() {
114 if (subprocess_singleton_ == this)
115 subprocess_singleton_ = nullptr;
Kenneth Watersa7fcafa2010-09-21 10:27:03 -0700116}
117
Alex Deymo29b81532015-07-09 11:51:49 -0700118void Subprocess::OnStdoutReady(SubprocessRecord* record) {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800119 char buf[1024];
Alex Deymo0d298542016-03-30 18:31:49 -0700120 size_t bytes_read;
Alex Deymo29b81532015-07-09 11:51:49 -0700121 do {
Alex Deymo0d298542016-03-30 18:31:49 -0700122 bytes_read = 0;
123 bool eof;
124 bool ok = utils::ReadAll(
125 record->stdout_fd, buf, arraysize(buf), &bytes_read, &eof);
126 record->stdout.append(buf, bytes_read);
127 if (!ok || eof) {
128 // There was either an error or an EOF condition, so we are done watching
129 // the file descriptor.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900130 record->stdout_controller.reset();
Alex Deymo0d298542016-03-30 18:31:49 -0700131 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700132 }
Alex Deymo0d298542016-03-30 18:31:49 -0700133 } while (bytes_read);
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800134}
135
Alex Deymo461b2592015-07-24 20:10:52 -0700136void Subprocess::ChildExitedCallback(const siginfo_t& info) {
137 auto pid_record = subprocess_records_.find(info.si_pid);
138 if (pid_record == subprocess_records_.end())
139 return;
140 SubprocessRecord* record = pid_record->second.get();
141
142 // Make sure we read any remaining process output and then close the pipe.
143 OnStdoutReady(record);
144
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900145 record->stdout_controller.reset();
Alex Deymo461b2592015-07-24 20:10:52 -0700146
Alex Deymo461b2592015-07-24 20:10:52 -0700147 // Don't print any log if the subprocess exited with exit code 0.
148 if (info.si_code != CLD_EXITED) {
149 LOG(INFO) << "Subprocess terminated with si_code " << info.si_code;
150 } else if (info.si_status != 0) {
151 LOG(INFO) << "Subprocess exited with si_status: " << info.si_status;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000152 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700153
Alex Deymo461b2592015-07-24 20:10:52 -0700154 if (!record->stdout.empty()) {
155 LOG(INFO) << "Subprocess output:\n" << record->stdout;
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700156 }
Alex Deymo461b2592015-07-24 20:10:52 -0700157 if (!record->callback.is_null()) {
158 record->callback.Run(info.si_status, record->stdout);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700159 }
Alex Deymoe384bb22016-03-29 17:23:33 -0700160 // Release and close all the pipes after calling the callback so our
161 // redirected pipes are still alive. Releasing the process first makes
162 // Reset(0) not attempt to kill the process, which is already a zombie at this
163 // point.
164 record->proc.Release();
165 record->proc.Reset(0);
166
Alex Deymo461b2592015-07-24 20:10:52 -0700167 subprocess_records_.erase(pid_record);
Alex Deymo29b81532015-07-09 11:51:49 -0700168}
169
Alex Deymo461b2592015-07-24 20:10:52 -0700170pid_t Subprocess::Exec(const vector<string>& cmd,
171 const ExecCallback& callback) {
Alex Deymo109c28d2016-04-05 23:00:52 +0000172 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
Alex Deymo461b2592015-07-24 20:10:52 -0700173}
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700174
Alex Deymo461b2592015-07-24 20:10:52 -0700175pid_t Subprocess::ExecFlags(const vector<string>& cmd,
176 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -0700177 const vector<int>& output_pipes,
Alex Deymo461b2592015-07-24 20:10:52 -0700178 const ExecCallback& callback) {
179 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
180
Alex Deymo109c28d2016-04-05 23:00:52 +0000181 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700182 LOG(ERROR) << "Failed to launch subprocess";
Chris Masonec6c57a52010-09-23 13:06:14 -0700183 return 0;
184 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000185
Alex Deymo461b2592015-07-24 20:10:52 -0700186 pid_t pid = record->proc.pid();
Amin Hassanib2689592019-01-13 17:04:28 -0800187 CHECK(process_reaper_.WatchForChild(
188 FROM_HERE,
189 pid,
190 base::Bind(&Subprocess::ChildExitedCallback, base::Unretained(this))));
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800191
Alex Deymo461b2592015-07-24 20:10:52 -0700192 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
Alex Deymo29b81532015-07-09 11:51:49 -0700193 // Capture the subprocess output. Make our end of the pipe non-blocking.
Alex Deymo461b2592015-07-24 20:10:52 -0700194 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
Alex Deymo29b81532015-07-09 11:51:49 -0700195 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
196 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
197 << record->stdout_fd << ".";
198 }
199
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900200 record->stdout_controller = base::FileDescriptorWatcher::WatchReadable(
Alex Deymo29b81532015-07-09 11:51:49 -0700201 record->stdout_fd,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900202 base::BindRepeating(&Subprocess::OnStdoutReady, record.get()));
Alex Deymo29b81532015-07-09 11:51:49 -0700203
Alex Vakulenkoce8c8ee2016-04-08 08:59:26 -0700204 subprocess_records_[pid] = std::move(record);
Alex Deymo461b2592015-07-24 20:10:52 -0700205 return pid;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000206}
207
Alex Deymo461b2592015-07-24 20:10:52 -0700208void Subprocess::KillExec(pid_t pid) {
209 auto pid_record = subprocess_records_.find(pid);
210 if (pid_record == subprocess_records_.end())
Alex Deymo29b81532015-07-09 11:51:49 -0700211 return;
Alex Deymo461b2592015-07-24 20:10:52 -0700212 pid_record->second->callback.Reset();
Sen Jiang1d3b8632016-05-13 12:32:10 -0700213 // We don't care about output/return code, so we use SIGKILL here to ensure it
214 // will be killed, SIGTERM might lead to leaked subprocess.
215 if (kill(pid, SIGKILL) != 0) {
216 PLOG(WARNING) << "Error sending SIGKILL to " << pid;
Alex Deymod15c5462016-03-09 18:11:12 -0800217 }
218 // Release the pid now so we don't try to kill it if Subprocess is destroyed
219 // before the corresponding ChildExitedCallback() is called.
220 pid_record->second->proc.Release();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000221}
222
Alex Deymoe384bb22016-03-29 17:23:33 -0700223int Subprocess::GetPipeFd(pid_t pid, int fd) const {
224 auto pid_record = subprocess_records_.find(pid);
225 if (pid_record == subprocess_records_.end())
226 return -1;
227 return pid_record->second->proc.GetPipe(fd);
228}
229
Alex Deymof329b932014-10-30 01:37:48 -0700230bool Subprocess::SynchronousExec(const vector<string>& cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700231 int* return_code,
Amin Hassani3a4caa12019-11-06 11:12:28 -0800232 string* stdout,
233 string* stderr) {
234 // The default for |SynchronousExec| is to use |kSearchPath| since the code
235 // relies on that.
236 return SynchronousExecFlags(cmd, kSearchPath, return_code, stdout, stderr);
Alex Deymo461b2592015-07-24 20:10:52 -0700237}
238
239bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
240 uint32_t flags,
241 int* return_code,
Amin Hassani3a4caa12019-11-06 11:12:28 -0800242 string* stdout,
243 string* stderr) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700244 brillo::ProcessImpl proc;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800245 if (!LaunchProcess(cmd, flags, {STDERR_FILENO}, &proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700246 LOG(ERROR) << "Failed to launch subprocess";
247 return false;
248 }
249
250 if (stdout) {
251 stdout->clear();
252 }
Amin Hassani3a4caa12019-11-06 11:12:28 -0800253 if (stderr) {
254 stderr->clear();
255 }
Alex Deymo461b2592015-07-24 20:10:52 -0700256
Amin Hassani3a4caa12019-11-06 11:12:28 -0800257 // Read from both stdout and stderr individually.
258 int stdout_fd = proc.GetPipe(STDOUT_FILENO);
259 int stderr_fd = proc.GetPipe(STDERR_FILENO);
Alex Deymo461b2592015-07-24 20:10:52 -0700260 vector<char> buffer(32 * 1024);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800261 bool stdout_closed = false, stderr_closed = false;
262 while (!stdout_closed || !stderr_closed) {
263 if (!stdout_closed) {
264 int rc = HANDLE_EINTR(read(stdout_fd, buffer.data(), buffer.size()));
265 if (rc <= 0) {
266 stdout_closed = true;
267 if (rc < 0)
268 PLOG(ERROR) << "Reading from child's stdout";
269 } else if (stdout != nullptr) {
Alex Deymo461b2592015-07-24 20:10:52 -0700270 stdout->append(buffer.data(), rc);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800271 }
272 }
273
274 if (!stderr_closed) {
275 int rc = HANDLE_EINTR(read(stderr_fd, buffer.data(), buffer.size()));
276 if (rc <= 0) {
277 stderr_closed = true;
278 if (rc < 0)
279 PLOG(ERROR) << "Reading from child's stderr";
280 } else if (stderr != nullptr) {
281 stderr->append(buffer.data(), rc);
282 }
Alex Deymo461b2592015-07-24 20:10:52 -0700283 }
284 }
Amin Hassani3a4caa12019-11-06 11:12:28 -0800285
Alex Deymo461b2592015-07-24 20:10:52 -0700286 // At this point, the subprocess already closed the output, so we only need to
287 // wait for it to finish.
288 int proc_return_code = proc.Wait();
289 if (return_code)
290 *return_code = proc_return_code;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700291 return proc_return_code != brillo::Process::kErrorExitStatus;
Darin Petkov85d02b72011-05-17 13:25:51 -0700292}
293
Amin Hassania8859542018-03-07 16:24:43 -0800294void Subprocess::FlushBufferedLogsAtExit() {
295 if (!subprocess_records_.empty()) {
296 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
297 for (auto& pid_record : subprocess_records_) {
298 SubprocessRecord* record = pid_record.second.get();
299 // Make sure we read any remaining process output.
300 OnStdoutReady(record);
301 if (!record->stdout.empty()) {
302 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
303 << record->stdout;
304 }
305 }
306 }
307}
308
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700309Subprocess* Subprocess::subprocess_singleton_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000310
311} // namespace chromeos_update_engine