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/strings/string_util.h>
33 #include <base/strings/stringprintf.h>
34 #include <brillo/process.h>
35 #include <brillo/secure_blob.h>
36
37 #include "update_engine/common/utils.h"
38
39 using brillo::MessageLoop;
40 using std::string;
41 using std::unique_ptr;
42 using std::vector;
43
44 namespace chromeos_update_engine {
45
46 namespace {
47
SetupChild(const std::map<string,string> & env,uint32_t flags)48 bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
49 // Setup the environment variables.
50 clearenv();
51 for (const auto& key_value : env) {
52 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
53 }
54
55 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
56 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
57 return false;
58 }
59
60 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
61 if (fd < 0)
62 return false;
63 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
64 return false;
65 IGNORE_EINTR(close(fd));
66
67 return true;
68 }
69
70 // Helper function to launch a process with the given Subprocess::Flags.
71 // This function only sets up and starts the process according to the |flags|.
72 // The caller is responsible for watching the termination of the subprocess.
73 // Return whether the process was successfully launched and fills in the |proc|
74 // Process.
LaunchProcess(const vector<string> & cmd,uint32_t flags,const vector<int> & output_pipes,brillo::Process * proc)75 bool LaunchProcess(const vector<string>& cmd,
76 uint32_t flags,
77 const vector<int>& output_pipes,
78 brillo::Process* proc) {
79 for (const string& arg : cmd)
80 proc->AddArg(arg);
81 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
82
83 // Create an environment for the child process with just the required PATHs.
84 std::map<string, string> env;
85 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
86 const char* value = getenv(key);
87 if (value)
88 env.emplace(key, value);
89 }
90
91 for (const int fd : output_pipes) {
92 proc->RedirectUsingPipe(fd, false);
93 }
94 proc->SetCloseUnusedFileDescriptors(true);
95 proc->RedirectUsingPipe(STDOUT_FILENO, false);
96 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
97
98 return proc->Start();
99 }
100
101 } // namespace
102
Init(brillo::AsynchronousSignalHandlerInterface * async_signal_handler)103 void Subprocess::Init(
104 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
105 if (subprocess_singleton_ == this)
106 return;
107 CHECK(subprocess_singleton_ == nullptr);
108 subprocess_singleton_ = this;
109
110 process_reaper_.Register(async_signal_handler);
111 }
112
~Subprocess()113 Subprocess::~Subprocess() {
114 if (subprocess_singleton_ == this)
115 subprocess_singleton_ = nullptr;
116 }
117
OnStdoutReady(SubprocessRecord * record)118 void Subprocess::OnStdoutReady(SubprocessRecord* record) {
119 char buf[1024];
120 size_t bytes_read;
121 do {
122 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.
130 MessageLoop::current()->CancelTask(record->stdout_task_id);
131 record->stdout_task_id = MessageLoop::kTaskIdNull;
132 return;
133 }
134 } while (bytes_read);
135 }
136
ChildExitedCallback(const siginfo_t & info)137 void Subprocess::ChildExitedCallback(const siginfo_t& info) {
138 auto pid_record = subprocess_records_.find(info.si_pid);
139 if (pid_record == subprocess_records_.end())
140 return;
141 SubprocessRecord* record = pid_record->second.get();
142
143 // Make sure we read any remaining process output and then close the pipe.
144 OnStdoutReady(record);
145
146 MessageLoop::current()->CancelTask(record->stdout_task_id);
147 record->stdout_task_id = MessageLoop::kTaskIdNull;
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_task_id = MessageLoop::current()->WatchFileDescriptor(
203 FROM_HERE,
204 record->stdout_fd,
205 MessageLoop::WatchMode::kWatchRead,
206 true,
207 base::Bind(&Subprocess::OnStdoutReady, record.get()));
208
209 subprocess_records_[pid] = std::move(record);
210 return pid;
211 }
212
KillExec(pid_t pid)213 void Subprocess::KillExec(pid_t pid) {
214 auto pid_record = subprocess_records_.find(pid);
215 if (pid_record == subprocess_records_.end())
216 return;
217 pid_record->second->callback.Reset();
218 // We don't care about output/return code, so we use SIGKILL here to ensure it
219 // will be killed, SIGTERM might lead to leaked subprocess.
220 if (kill(pid, SIGKILL) != 0) {
221 PLOG(WARNING) << "Error sending SIGKILL to " << pid;
222 }
223 // Release the pid now so we don't try to kill it if Subprocess is destroyed
224 // before the corresponding ChildExitedCallback() is called.
225 pid_record->second->proc.Release();
226 }
227
GetPipeFd(pid_t pid,int fd) const228 int Subprocess::GetPipeFd(pid_t pid, int fd) const {
229 auto pid_record = subprocess_records_.find(pid);
230 if (pid_record == subprocess_records_.end())
231 return -1;
232 return pid_record->second->proc.GetPipe(fd);
233 }
234
SynchronousExec(const vector<string> & cmd,int * return_code,string * stdout)235 bool Subprocess::SynchronousExec(const vector<string>& cmd,
236 int* return_code,
237 string* stdout) {
238 // The default for SynchronousExec is to use kSearchPath since the code relies
239 // on that.
240 return SynchronousExecFlags(
241 cmd, kRedirectStderrToStdout | kSearchPath, return_code, stdout);
242 }
243
SynchronousExecFlags(const vector<string> & cmd,uint32_t flags,int * return_code,string * stdout)244 bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
245 uint32_t flags,
246 int* return_code,
247 string* stdout) {
248 brillo::ProcessImpl proc;
249 // It doesn't make sense to redirect some pipes in the synchronous case
250 // because we won't be reading on our end, so we don't expose the output_pipes
251 // in this case.
252 if (!LaunchProcess(cmd, flags, {}, &proc)) {
253 LOG(ERROR) << "Failed to launch subprocess";
254 return false;
255 }
256
257 if (stdout) {
258 stdout->clear();
259 }
260
261 int fd = proc.GetPipe(STDOUT_FILENO);
262 vector<char> buffer(32 * 1024);
263 while (true) {
264 int rc = HANDLE_EINTR(read(fd, buffer.data(), buffer.size()));
265 if (rc < 0) {
266 PLOG(ERROR) << "Reading from child's output";
267 break;
268 } else if (rc == 0) {
269 break;
270 } else {
271 if (stdout)
272 stdout->append(buffer.data(), rc);
273 }
274 }
275 // At this point, the subprocess already closed the output, so we only need to
276 // wait for it to finish.
277 int proc_return_code = proc.Wait();
278 if (return_code)
279 *return_code = proc_return_code;
280 return proc_return_code != brillo::Process::kErrorExitStatus;
281 }
282
FlushBufferedLogsAtExit()283 void Subprocess::FlushBufferedLogsAtExit() {
284 if (!subprocess_records_.empty()) {
285 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
286 for (auto& pid_record : subprocess_records_) {
287 SubprocessRecord* record = pid_record.second.get();
288 // Make sure we read any remaining process output.
289 OnStdoutReady(record);
290 if (!record->stdout.empty()) {
291 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
292 << record->stdout;
293 }
294 }
295 }
296 }
297
298 Subprocess* Subprocess::subprocess_singleton_ = nullptr;
299
300 } // namespace chromeos_update_engine
301