1 //
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 //
16
17 #include "update_engine/common/subprocess.h"
18
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23
24 #include <memory>
25 #include <string>
26 #include <utility>
27 #include <vector>
28
29 #include <base/bind.h>
30 #include <base/logging.h>
31 #include <base/posix/eintr_wrapper.h>
32 #include <base/stl_util.h>
33 #include <base/strings/string_util.h>
34 #include <base/strings/stringprintf.h>
35 #include <brillo/process.h>
36 #include <brillo/secure_blob.h>
37
38 #include "update_engine/common/utils.h"
39
40 using brillo::MessageLoop;
41 using std::string;
42 using std::unique_ptr;
43 using std::vector;
44
45 namespace chromeos_update_engine {
46
47 namespace {
48
SetupChild(const std::map<string,string> & env,uint32_t flags)49 bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
50 // 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 }
55
56 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
57 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
58 return false;
59 }
60
61 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;
69 }
70
71 // 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.
LaunchProcess(const vector<string> & cmd,uint32_t flags,const vector<int> & output_pipes,brillo::Process * proc)76 bool LaunchProcess(const vector<string>& cmd,
77 uint32_t flags,
78 const vector<int>& output_pipes,
79 brillo::Process* proc) {
80 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
92 for (const int fd : output_pipes) {
93 proc->RedirectUsingPipe(fd, false);
94 }
95 proc->SetCloseUnusedFileDescriptors(true);
96 proc->RedirectUsingPipe(STDOUT_FILENO, false);
97 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
98
99 LOG(INFO) << "Running \"" << base::JoinString(cmd, " ") << "\"";
100 return proc->Start();
101 }
102
103 } // namespace
104
Init(brillo::AsynchronousSignalHandlerInterface * async_signal_handler)105 void Subprocess::Init(
106 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
107 if (subprocess_singleton_ == this)
108 return;
109 CHECK(subprocess_singleton_ == nullptr);
110 subprocess_singleton_ = this;
111
112 process_reaper_.Register(async_signal_handler);
113 }
114
~Subprocess()115 Subprocess::~Subprocess() {
116 if (subprocess_singleton_ == this)
117 subprocess_singleton_ = nullptr;
118 }
119
OnStdoutReady(SubprocessRecord * record)120 void Subprocess::OnStdoutReady(SubprocessRecord* record) {
121 char buf[1024];
122 size_t bytes_read;
123 do {
124 bytes_read = 0;
125 bool eof;
126 bool ok = utils::ReadAll(
127 record->stdout_fd, buf, base::size(buf), &bytes_read, &eof);
128 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.
132 record->stdout_controller.reset();
133 return;
134 }
135 } while (bytes_read);
136 }
137
ChildExitedCallback(const siginfo_t & info)138 void Subprocess::ChildExitedCallback(const siginfo_t& info) {
139 auto pid_record = subprocess_records_.find(info.si_pid);
140 if (pid_record == subprocess_records_.end())
141 return;
142 SubprocessRecord* record = pid_record->second.get();
143
144 // Make sure we read any remaining process output and then close the pipe.
145 OnStdoutReady(record);
146
147 record->stdout_controller.reset();
148
149 // Don't print any log if the subprocess exited with exit code 0.
150 if (info.si_code != CLD_EXITED) {
151 LOG(INFO) << "Subprocess terminated with si_code " << info.si_code;
152 } else if (info.si_status != 0) {
153 LOG(INFO) << "Subprocess exited with si_status: " << info.si_status;
154 }
155
156 if (!record->stdout.empty()) {
157 LOG(INFO) << "Subprocess output:\n" << record->stdout;
158 }
159 if (!record->callback.is_null()) {
160 record->callback.Run(info.si_status, record->stdout);
161 }
162 // Release and close all the pipes after calling the callback so our
163 // redirected pipes are still alive. Releasing the process first makes
164 // Reset(0) not attempt to kill the process, which is already a zombie at this
165 // point.
166 record->proc.Release();
167 record->proc.Reset(0);
168
169 subprocess_records_.erase(pid_record);
170 }
171
Exec(const vector<string> & cmd,const ExecCallback & callback)172 pid_t Subprocess::Exec(const vector<string>& cmd,
173 const ExecCallback& callback) {
174 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
175 }
176
ExecFlags(const vector<string> & cmd,uint32_t flags,const vector<int> & output_pipes,const ExecCallback & callback)177 pid_t Subprocess::ExecFlags(const vector<string>& cmd,
178 uint32_t flags,
179 const vector<int>& output_pipes,
180 const ExecCallback& callback) {
181 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
182
183 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
184 LOG(ERROR) << "Failed to launch subprocess";
185 return 0;
186 }
187
188 pid_t pid = record->proc.pid();
189 CHECK(process_reaper_.WatchForChild(
190 FROM_HERE,
191 pid,
192 base::Bind(&Subprocess::ChildExitedCallback, base::Unretained(this))));
193
194 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
195 // Capture the subprocess output. Make our end of the pipe non-blocking.
196 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
197 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
198 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
199 << record->stdout_fd << ".";
200 }
201
202 record->stdout_controller = base::FileDescriptorWatcher::WatchReadable(
203 record->stdout_fd,
204 base::BindRepeating(&Subprocess::OnStdoutReady, record.get()));
205
206 subprocess_records_[pid] = std::move(record);
207 return pid;
208 }
209
KillExec(pid_t pid)210 void Subprocess::KillExec(pid_t pid) {
211 auto pid_record = subprocess_records_.find(pid);
212 if (pid_record == subprocess_records_.end())
213 return;
214 pid_record->second->callback.Reset();
215 // We don't care about output/return code, so we use SIGKILL here to ensure it
216 // will be killed, SIGTERM might lead to leaked subprocess.
217 if (kill(pid, SIGKILL) != 0) {
218 PLOG(WARNING) << "Error sending SIGKILL to " << pid;
219 }
220 // Release the pid now so we don't try to kill it if Subprocess is destroyed
221 // before the corresponding ChildExitedCallback() is called.
222 pid_record->second->proc.Release();
223 }
224
GetPipeFd(pid_t pid,int fd) const225 int Subprocess::GetPipeFd(pid_t pid, int fd) const {
226 auto pid_record = subprocess_records_.find(pid);
227 if (pid_record == subprocess_records_.end())
228 return -1;
229 return pid_record->second->proc.GetPipe(fd);
230 }
231
SynchronousExec(const vector<string> & cmd,int * return_code,string * stdout,string * stderr)232 bool Subprocess::SynchronousExec(const vector<string>& cmd,
233 int* return_code,
234 string* stdout,
235 string* stderr) {
236 // The default for |SynchronousExec| is to use |kSearchPath| since the code
237 // relies on that.
238 return SynchronousExecFlags(cmd, kSearchPath, return_code, stdout, stderr);
239 }
240
SynchronousExecFlags(const vector<string> & cmd,uint32_t flags,int * return_code,string * stdout,string * stderr)241 bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
242 uint32_t flags,
243 int* return_code,
244 string* stdout,
245 string* stderr) {
246 brillo::ProcessImpl proc;
247 if (!LaunchProcess(cmd, flags, {STDERR_FILENO}, &proc)) {
248 LOG(ERROR) << "Failed to launch subprocess";
249 return false;
250 }
251
252 if (stdout) {
253 stdout->clear();
254 }
255 if (stderr) {
256 stderr->clear();
257 }
258
259 // Read from both stdout and stderr individually.
260 int stdout_fd = proc.GetPipe(STDOUT_FILENO);
261 int stderr_fd = proc.GetPipe(STDERR_FILENO);
262 vector<char> buffer(32 * 1024);
263 bool stdout_closed = false, stderr_closed = false;
264 while (!stdout_closed || !stderr_closed) {
265 if (!stdout_closed) {
266 int rc = HANDLE_EINTR(read(stdout_fd, buffer.data(), buffer.size()));
267 if (rc <= 0) {
268 stdout_closed = true;
269 if (rc < 0)
270 PLOG(ERROR) << "Reading from child's stdout";
271 } else if (stdout != nullptr) {
272 stdout->append(buffer.data(), rc);
273 }
274 }
275
276 if (!stderr_closed) {
277 int rc = HANDLE_EINTR(read(stderr_fd, buffer.data(), buffer.size()));
278 if (rc <= 0) {
279 stderr_closed = true;
280 if (rc < 0)
281 PLOG(ERROR) << "Reading from child's stderr";
282 } else if (stderr != nullptr) {
283 stderr->append(buffer.data(), rc);
284 }
285 }
286 }
287
288 // At this point, the subprocess already closed the output, so we only need to
289 // wait for it to finish.
290 int proc_return_code = proc.Wait();
291 if (return_code)
292 *return_code = proc_return_code;
293 return proc_return_code != brillo::Process::kErrorExitStatus;
294 }
295
FlushBufferedLogsAtExit()296 void Subprocess::FlushBufferedLogsAtExit() {
297 if (!subprocess_records_.empty()) {
298 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
299 for (auto& pid_record : subprocess_records_) {
300 SubprocessRecord* record = pid_record.second.get();
301 // Make sure we read any remaining process output.
302 OnStdoutReady(record);
303 if (!record->stdout.empty()) {
304 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
305 << record->stdout;
306 }
307 }
308 }
309 }
310
311 Subprocess* Subprocess::subprocess_singleton_ = nullptr;
312
313 } // namespace chromeos_update_engine
314