blob: 1bfb911f6f9f74caf4a3dd80f82aa1f8785d345e [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>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <vector>
Darin Petkova0b9e772011-10-06 05:05:56 -070027
Alex Deymo29b81532015-07-09 11:51:49 -070028#include <base/bind.h>
Darin Petkova0b9e772011-10-06 05:05:56 -070029#include <base/logging.h>
Alex Deymo29b81532015-07-09 11:51:49 -070030#include <base/posix/eintr_wrapper.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_util.h>
32#include <base/strings/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070033#include <brillo/process.h>
34#include <brillo/secure_blob.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000035
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070036using brillo::MessageLoop;
adlr@google.com3defe6a2009-12-04 20:57:17 +000037using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070038using std::unique_ptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +000039using std::vector;
40
41namespace chromeos_update_engine {
42
Alex Deymo461b2592015-07-24 20:10:52 -070043namespace {
Darin Petkov6f03a3b2010-11-10 14:27:14 -080044
Alex Deymo461b2592015-07-24 20:10:52 -070045bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
46 // Setup the environment variables.
47 clearenv();
48 for (const auto& key_value : env) {
49 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
50 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -080051
Alex Deymo461b2592015-07-24 20:10:52 -070052 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
53 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
54 return false;
Alex Deymo29b81532015-07-09 11:51:49 -070055 }
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -070056
Alex Deymo461b2592015-07-24 20:10:52 -070057 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
58 if (fd < 0)
59 return false;
60 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
61 return false;
62 IGNORE_EINTR(close(fd));
63
64 return true;
adlr@google.com3defe6a2009-12-04 20:57:17 +000065}
66
Alex Deymo461b2592015-07-24 20:10:52 -070067// Helper function to launch a process with the given Subprocess::Flags.
68// This function only sets up and starts the process according to the |flags|.
69// The caller is responsible for watching the termination of the subprocess.
70// Return whether the process was successfully launched and fills in the |proc|
71// Process.
72bool LaunchProcess(const vector<string>& cmd,
73 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -070074 const vector<int>& output_pipes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070075 brillo::Process* proc) {
Alex Deymo461b2592015-07-24 20:10:52 -070076 for (const string& arg : cmd)
77 proc->AddArg(arg);
78 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
79
80 // Create an environment for the child process with just the required PATHs.
81 std::map<string, string> env;
82 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
83 const char* value = getenv(key);
84 if (value)
85 env.emplace(key, value);
86 }
87
Alex Deymoe384bb22016-03-29 17:23:33 -070088 for (const int fd : output_pipes) {
89 proc->RedirectUsingPipe(fd, false);
90 }
91 proc->SetCloseUnusedFileDescriptors(true);
Alex Deymo461b2592015-07-24 20:10:52 -070092 proc->RedirectUsingPipe(STDOUT_FILENO, false);
93 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
94
95 return proc->Start();
96}
97
98} // namespace
99
Alex Deymob7ca0962014-10-01 17:58:07 -0700100void Subprocess::Init(
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700101 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
Alex Deymo461b2592015-07-24 20:10:52 -0700102 if (subprocess_singleton_ == this)
103 return;
104 CHECK(subprocess_singleton_ == nullptr);
105 subprocess_singleton_ = this;
106
Alex Deymob7ca0962014-10-01 17:58:07 -0700107 process_reaper_.Register(async_signal_handler);
Alex Deymo461b2592015-07-24 20:10:52 -0700108}
109
110Subprocess::~Subprocess() {
111 if (subprocess_singleton_ == this)
112 subprocess_singleton_ = nullptr;
Kenneth Watersa7fcafa2010-09-21 10:27:03 -0700113}
114
Alex Deymo29b81532015-07-09 11:51:49 -0700115void Subprocess::OnStdoutReady(SubprocessRecord* record) {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800116 char buf[1024];
Alex Deymo29b81532015-07-09 11:51:49 -0700117 ssize_t rc = 0;
118 do {
119 rc = HANDLE_EINTR(read(record->stdout_fd, buf, arraysize(buf)));
120 if (rc < 0) {
121 // EAGAIN and EWOULDBLOCK are normal return values when there's no more
122 // input as we are in non-blocking mode.
123 if (errno != EWOULDBLOCK && errno != EAGAIN) {
124 PLOG(ERROR) << "Error reading fd " << record->stdout_fd;
Alex Deymo461b2592015-07-24 20:10:52 -0700125 MessageLoop::current()->CancelTask(record->stdout_task_id);
126 record->stdout_task_id = MessageLoop::kTaskIdNull;
Alex Deymo29b81532015-07-09 11:51:49 -0700127 }
Alex Deymo957cf4d2015-07-14 23:18:33 -0700128 } else if (rc == 0) {
129 // A value of 0 means that the child closed its end of the pipe and there
130 // is nothing else to read from stdout.
Alex Deymo461b2592015-07-24 20:10:52 -0700131 MessageLoop::current()->CancelTask(record->stdout_task_id);
132 record->stdout_task_id = MessageLoop::kTaskIdNull;
Alex Deymo29b81532015-07-09 11:51:49 -0700133 } else {
134 record->stdout.append(buf, rc);
135 }
136 } while (rc > 0);
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800137}
138
Alex Deymo461b2592015-07-24 20:10:52 -0700139void Subprocess::ChildExitedCallback(const siginfo_t& info) {
140 auto pid_record = subprocess_records_.find(info.si_pid);
141 if (pid_record == subprocess_records_.end())
142 return;
143 SubprocessRecord* record = pid_record->second.get();
144
145 // Make sure we read any remaining process output and then close the pipe.
146 OnStdoutReady(record);
147
148 MessageLoop::current()->CancelTask(record->stdout_task_id);
149 record->stdout_task_id = MessageLoop::kTaskIdNull;
150
Alex Deymo461b2592015-07-24 20:10:52 -0700151 // Don't print any log if the subprocess exited with exit code 0.
152 if (info.si_code != CLD_EXITED) {
153 LOG(INFO) << "Subprocess terminated with si_code " << info.si_code;
154 } else if (info.si_status != 0) {
155 LOG(INFO) << "Subprocess exited with si_status: " << info.si_status;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000156 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700157
Alex Deymo461b2592015-07-24 20:10:52 -0700158 if (!record->stdout.empty()) {
159 LOG(INFO) << "Subprocess output:\n" << record->stdout;
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700160 }
Alex Deymo461b2592015-07-24 20:10:52 -0700161 if (!record->callback.is_null()) {
162 record->callback.Run(info.si_status, record->stdout);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700163 }
Alex Deymoe384bb22016-03-29 17:23:33 -0700164 // Release and close all the pipes after calling the callback so our
165 // redirected pipes are still alive. Releasing the process first makes
166 // Reset(0) not attempt to kill the process, which is already a zombie at this
167 // point.
168 record->proc.Release();
169 record->proc.Reset(0);
170
Alex Deymo461b2592015-07-24 20:10:52 -0700171 subprocess_records_.erase(pid_record);
Alex Deymo29b81532015-07-09 11:51:49 -0700172}
173
Alex Deymo461b2592015-07-24 20:10:52 -0700174pid_t Subprocess::Exec(const vector<string>& cmd,
175 const ExecCallback& callback) {
Alex Deymoe384bb22016-03-29 17:23:33 -0700176 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
Alex Deymo461b2592015-07-24 20:10:52 -0700177}
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700178
Alex Deymo461b2592015-07-24 20:10:52 -0700179pid_t Subprocess::ExecFlags(const vector<string>& cmd,
180 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -0700181 const vector<int>& output_pipes,
Alex Deymo461b2592015-07-24 20:10:52 -0700182 const ExecCallback& callback) {
183 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
184
Alex Deymoe384bb22016-03-29 17:23:33 -0700185 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700186 LOG(ERROR) << "Failed to launch subprocess";
Chris Masonec6c57a52010-09-23 13:06:14 -0700187 return 0;
188 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000189
Alex Deymo461b2592015-07-24 20:10:52 -0700190 pid_t pid = record->proc.pid();
191 CHECK(process_reaper_.WatchForChild(FROM_HERE, pid, base::Bind(
192 &Subprocess::ChildExitedCallback,
193 base::Unretained(this))));
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800194
Alex Deymo461b2592015-07-24 20:10:52 -0700195 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
Alex Deymo29b81532015-07-09 11:51:49 -0700196 // Capture the subprocess output. Make our end of the pipe non-blocking.
Alex Deymo461b2592015-07-24 20:10:52 -0700197 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
Alex Deymo29b81532015-07-09 11:51:49 -0700198 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
199 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
200 << record->stdout_fd << ".";
201 }
202
Alex Deymo461b2592015-07-24 20:10:52 -0700203 record->stdout_task_id = MessageLoop::current()->WatchFileDescriptor(
Alex Deymo29b81532015-07-09 11:51:49 -0700204 FROM_HERE,
205 record->stdout_fd,
206 MessageLoop::WatchMode::kWatchRead,
207 true,
208 base::Bind(&Subprocess::OnStdoutReady, record.get()));
209
Alex Deymo461b2592015-07-24 20:10:52 -0700210 subprocess_records_[pid].reset(record.release());
211 return pid;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000212}
213
Alex Deymo461b2592015-07-24 20:10:52 -0700214void Subprocess::KillExec(pid_t pid) {
215 auto pid_record = subprocess_records_.find(pid);
216 if (pid_record == subprocess_records_.end())
Alex Deymo29b81532015-07-09 11:51:49 -0700217 return;
Alex Deymo461b2592015-07-24 20:10:52 -0700218 pid_record->second->callback.Reset();
Alex Deymod15c5462016-03-09 18:11:12 -0800219 if (kill(pid, SIGTERM) != 0) {
220 PLOG(WARNING) << "Error sending SIGTERM to " << pid;
221 }
222 // Release the pid now so we don't try to kill it if Subprocess is destroyed
223 // before the corresponding ChildExitedCallback() is called.
224 pid_record->second->proc.Release();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000225}
226
Alex Deymoe384bb22016-03-29 17:23:33 -0700227int Subprocess::GetPipeFd(pid_t pid, int fd) const {
228 auto pid_record = subprocess_records_.find(pid);
229 if (pid_record == subprocess_records_.end())
230 return -1;
231 return pid_record->second->proc.GetPipe(fd);
232}
233
Alex Deymof329b932014-10-30 01:37:48 -0700234bool Subprocess::SynchronousExec(const vector<string>& cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700235 int* return_code,
Alex Deymof329b932014-10-30 01:37:48 -0700236 string* stdout) {
Alex Deymo461b2592015-07-24 20:10:52 -0700237 // The default for SynchronousExec is to use kSearchPath since the code relies
238 // on that.
239 return SynchronousExecFlags(
240 cmd,
241 kRedirectStderrToStdout | kSearchPath,
242 return_code,
243 stdout);
244}
245
246bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
247 uint32_t flags,
248 int* return_code,
249 string* stdout) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700250 brillo::ProcessImpl proc;
Alex Deymoe384bb22016-03-29 17:23:33 -0700251 // It doesn't make sense to redirect some pipes in the synchronous case
252 // because we won't be reading on our end, so we don't expose the output_pipes
253 // in this case.
254 if (!LaunchProcess(cmd, flags, {}, &proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700255 LOG(ERROR) << "Failed to launch subprocess";
256 return false;
257 }
258
259 if (stdout) {
260 stdout->clear();
261 }
262
263 int fd = proc.GetPipe(STDOUT_FILENO);
264 vector<char> buffer(32 * 1024);
265 while (true) {
266 int rc = HANDLE_EINTR(read(fd, buffer.data(), buffer.size()));
267 if (rc < 0) {
268 PLOG(ERROR) << "Reading from child's output";
269 break;
270 } else if (rc == 0) {
271 break;
272 } else {
273 if (stdout)
274 stdout->append(buffer.data(), rc);
275 }
276 }
277 // At this point, the subprocess already closed the output, so we only need to
278 // wait for it to finish.
279 int proc_return_code = proc.Wait();
280 if (return_code)
281 *return_code = proc_return_code;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700282 return proc_return_code != brillo::Process::kErrorExitStatus;
Darin Petkov85d02b72011-05-17 13:25:51 -0700283}
284
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800285bool Subprocess::SubprocessInFlight() {
Alex Deymo461b2592015-07-24 20:10:52 -0700286 for (const auto& pid_record : subprocess_records_) {
287 if (!pid_record.second->callback.is_null())
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800288 return true;
289 }
290 return false;
291}
292
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700293Subprocess* Subprocess::subprocess_singleton_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000294
295} // namespace chromeos_update_engine