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 <chrono>
25 #include <memory>
26 #include <string>
27 #include <utility>
28 #include <vector>
29
30 #include <base/bind.h>
31 #include <base/logging.h>
32 #include <base/posix/eintr_wrapper.h>
33 #include <android-base/stringprintf.h>
34 #include <brillo/secure_blob.h>
35
36 #include "update_engine/common/utils.h"
37
38 using brillo::MessageLoop;
39 using std::string;
40 using std::unique_ptr;
41 using std::vector;
42
43 namespace chromeos_update_engine {
44
45 namespace {
46
SetupChild(const std::map<string,string> & env,uint32_t flags)47 bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
48 // Setup the environment variables.
49 clearenv();
50 if (setpgid(0, 0) != 0) {
51 PLOG(ERROR) << "Failed to setpgid on subprocess " << getpid();
52 return false;
53 }
54 for (const auto& key_value : env) {
55 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
56 }
57
58 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
59 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
60 return false;
61 }
62
63 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
64 if (fd < 0)
65 return false;
66 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
67 return false;
68 IGNORE_EINTR(close(fd));
69
70 return true;
71 }
72
73 // Helper function to launch a process with the given Subprocess::Flags.
74 // This function only sets up and starts the process according to the |flags|.
75 // The caller is responsible for watching the termination of the subprocess.
76 // Return whether the process was successfully launched and fills in the |proc|
77 // Process.
LaunchProcess(const vector<string> & cmd,uint32_t flags,const vector<int> & output_pipes,brillo::Process * proc)78 bool LaunchProcess(const vector<string>& cmd,
79 uint32_t flags,
80 const vector<int>& output_pipes,
81 brillo::Process* proc) {
82 for (const string& arg : cmd)
83 proc->AddArg(arg);
84 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
85
86 // Create an environment for the child process with just the required PATHs.
87 std::map<string, string> env;
88 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
89 const char* value = getenv(key);
90 if (value)
91 env.emplace(key, value);
92 }
93
94 for (const int fd : output_pipes) {
95 proc->RedirectUsingPipe(fd, false);
96 }
97 proc->SetCloseUnusedFileDescriptors(true);
98 proc->RedirectUsingPipe(STDOUT_FILENO, false);
99 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
100
101 LOG(INFO) << "Running \"" << android::base::Join(cmd, " ") << "\"";
102 return proc->Start();
103 }
104
105 } // namespace
106
Init(brillo::AsynchronousSignalHandlerInterface * async_signal_handler)107 void Subprocess::Init(
108 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
109 if (subprocess_singleton_ == this)
110 return;
111 CHECK(subprocess_singleton_ == nullptr);
112 subprocess_singleton_ = this;
113
114 process_reaper_.Register(async_signal_handler);
115 }
116
~Subprocess()117 Subprocess::~Subprocess() {
118 if (subprocess_singleton_ == this)
119 subprocess_singleton_ = nullptr;
120 }
121
OnStdoutReady(SubprocessRecord * record)122 void Subprocess::OnStdoutReady(SubprocessRecord* record) {
123 char buf[1024];
124 size_t bytes_read;
125 do {
126 bytes_read = 0;
127 bool eof;
128 bool ok = utils::ReadAll(
129 record->stdout_fd, buf, std::size(buf), &bytes_read, &eof);
130 record->stdout_str.append(buf, bytes_read);
131 if (!ok || eof) {
132 // There was either an error or an EOF condition, so we are done watching
133 // the file descriptor.
134 record->stdout_controller.reset();
135 return;
136 }
137 } while (bytes_read);
138 }
139
ChildExitedCallback(const siginfo_t & info)140 void Subprocess::ChildExitedCallback(const siginfo_t& info) {
141 auto pid_record = subprocess_records_.find(info.si_pid);
142 if (pid_record == subprocess_records_.end())
143 return;
144 SubprocessRecord* record = pid_record->second.get();
145
146 // Make sure we read any remaining process output and then close the pipe.
147 OnStdoutReady(record);
148
149 record->stdout_controller.reset();
150
151 // Don't print any log if the subprocess exited with exit code 0.
152 if (info.si_code != CLD_EXITED) {
153 LOG(INFO) << "Subprocess " << info.si_pid << " terminated with si_code "
154 << info.si_code;
155 } else if (info.si_status != 0) {
156 LOG(INFO) << "Subprocess " << info.si_pid
157 << " exited with si_status: " << info.si_status;
158 }
159
160 if (!record->stdout_str.empty()) {
161 LOG(INFO) << "Subprocess output:\n" << record->stdout_str;
162 }
163 if (!record->callback.is_null()) {
164 record->callback.Run(info.si_status, record->stdout_str);
165 }
166 // Release and close all the pipes after calling the callback so our
167 // redirected pipes are still alive. Releasing the process first makes
168 // Reset(0) not attempt to kill the process, which is already a zombie at this
169 // point.
170 record->proc.Release();
171 record->proc.Reset(0);
172
173 subprocess_records_.erase(pid_record);
174 }
175
Exec(const vector<string> & cmd,const ExecCallback & callback)176 pid_t Subprocess::Exec(const vector<string>& cmd,
177 const ExecCallback& callback) {
178 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
179 }
180
ExecFlags(const vector<string> & cmd,uint32_t flags,const vector<int> & output_pipes,const ExecCallback & callback)181 pid_t Subprocess::ExecFlags(const vector<string>& cmd,
182 uint32_t flags,
183 const vector<int>& output_pipes,
184 const ExecCallback& callback) {
185 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
186
187 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
188 LOG(ERROR) << "Failed to launch subprocess";
189 return 0;
190 }
191
192 pid_t pid = record->proc.pid();
193 CHECK(process_reaper_.WatchForChild(
194 FROM_HERE,
195 pid,
196 base::Bind(&Subprocess::ChildExitedCallback, base::Unretained(this))));
197
198 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
199 // Capture the subprocess output. Make our end of the pipe non-blocking.
200 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
201 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
202 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
203 << record->stdout_fd << ".";
204 }
205
206 record->stdout_controller = base::FileDescriptorWatcher::WatchReadable(
207 record->stdout_fd,
208 base::BindRepeating(&Subprocess::OnStdoutReady, record.get()));
209
210 subprocess_records_[pid] = std::move(record);
211 return pid;
212 }
213
WaitForProcessGroup(pid_t pid,std::chrono::milliseconds timeout)214 bool WaitForProcessGroup(pid_t pid, std::chrono::milliseconds timeout) {
215 using std::chrono::system_clock;
216 auto start = system_clock::now();
217 do {
218 pid_t w = waitpid(-pid, nullptr, WNOHANG);
219 if (w < 0) {
220 // When all of the child process with this process group ID exits, waitpid
221 // will return ECHILD. Until that point, keep callilng waitpid() as there
222 // might be multiple child processes with the same process group id.
223 if (errno == ECHILD) {
224 LOG(INFO) << "All processes with process group id " << pid << " exited";
225 return true;
226 }
227 PLOG(ERROR) << "Waitpid returned " << w;
228 return false;
229 }
230 usleep(100);
231 } while ((system_clock::now() - start) <= timeout);
232 LOG(INFO) << "process group " << pid << " did not exit in " << timeout.count()
233 << " milliseconds";
234 return false;
235 }
236
KillExec(pid_t pid)237 void Subprocess::KillExec(pid_t pid) {
238 using namespace std::chrono_literals;
239 auto pid_record = subprocess_records_.find(pid);
240 if (pid_record == subprocess_records_.end())
241 return;
242 pid_record->second->callback.Reset();
243 // We don't care about output/return code, so we use SIGKILL here to ensure it
244 // will be killed, SIGTERM might lead to leaked subprocess.
245 CHECK_EQ(pid_record->second->proc.pid(), pid);
246 if (kill(-pid, SIGKILL) != 0) {
247 PLOG(WARNING) << "Failed to kill subprocess group " << pid;
248 }
249 WaitForProcessGroup(pid, 5000ms);
250 // Release the pid now so we don't try to kill it if Subprocess is destroyed
251 // before the corresponding ChildExitedCallback() is called.
252 pid_record->second->proc.Release();
253 if (subprocess_records_.count(pid)) {
254 siginfo_t info;
255 info.si_code = CLD_KILLED;
256 info.si_status = SIGKILL;
257 info.si_pid = pid;
258 ChildExitedCallback(info);
259 }
260 }
261
GetPipeFd(pid_t pid,int fd) const262 int Subprocess::GetPipeFd(pid_t pid, int fd) const {
263 auto pid_record = subprocess_records_.find(pid);
264 if (pid_record == subprocess_records_.end())
265 return -1;
266 return pid_record->second->proc.GetPipe(fd);
267 }
268
SynchronousExec(const vector<string> & cmd,int * return_code,string * stdout_str,string * stderr_str)269 bool Subprocess::SynchronousExec(const vector<string>& cmd,
270 int* return_code,
271 string* stdout_str,
272 string* stderr_str) {
273 // The default for |SynchronousExec| is to use |kSearchPath| since the code
274 // relies on that.
275 return SynchronousExecFlags(
276 cmd, kSearchPath, return_code, stdout_str, stderr_str);
277 }
278
SynchronousExecFlags(const vector<string> & cmd,uint32_t flags,int * return_code,string * stdout_str,string * stderr_str)279 bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
280 uint32_t flags,
281 int* return_code,
282 string* stdout_str,
283 string* stderr_str) {
284 brillo::ProcessImpl proc;
285 if (!LaunchProcess(cmd, flags, {STDERR_FILENO}, &proc)) {
286 LOG(ERROR) << "Failed to launch subprocess";
287 return false;
288 }
289
290 if (stdout_str) {
291 stdout_str->clear();
292 }
293 if (stderr_str) {
294 stderr_str->clear();
295 }
296
297 // Read from both stdout and stderr individually.
298 int stdout_fd = proc.GetPipe(STDOUT_FILENO);
299 int stderr_fd = proc.GetPipe(STDERR_FILENO);
300 vector<char> buffer(32 * 1024);
301 bool stdout_closed = false, stderr_closed = false;
302 while (!stdout_closed || !stderr_closed) {
303 if (!stdout_closed) {
304 int rc = HANDLE_EINTR(read(stdout_fd, buffer.data(), buffer.size()));
305 if (rc <= 0) {
306 stdout_closed = true;
307 if (rc < 0)
308 PLOG(ERROR) << "Reading from child's stdout";
309 } else if (stdout_str != nullptr) {
310 stdout_str->append(buffer.data(), rc);
311 }
312 }
313
314 if (!stderr_closed) {
315 int rc = HANDLE_EINTR(read(stderr_fd, buffer.data(), buffer.size()));
316 if (rc <= 0) {
317 stderr_closed = true;
318 if (rc < 0)
319 PLOG(ERROR) << "Reading from child's stderr";
320 } else if (stderr_str != nullptr) {
321 stderr_str->append(buffer.data(), rc);
322 }
323 }
324 }
325
326 // At this point, the subprocess already closed the output, so we only need to
327 // wait for it to finish.
328 int proc_return_code = proc.Wait();
329 if (return_code)
330 *return_code = proc_return_code;
331 return proc_return_code != brillo::Process::kErrorExitStatus;
332 }
333
FlushBufferedLogsAtExit()334 void Subprocess::FlushBufferedLogsAtExit() {
335 if (!subprocess_records_.empty()) {
336 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
337 for (auto& pid_record : subprocess_records_) {
338 SubprocessRecord* record = pid_record.second.get();
339 // Make sure we read any remaining process output.
340 OnStdoutReady(record);
341 if (!record->stdout_str.empty()) {
342 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
343 << record->stdout_str;
344 }
345 }
346 }
347 }
348
349 Subprocess* Subprocess::subprocess_singleton_ = nullptr;
350
351 } // namespace chromeos_update_engine
352