• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 "common/libs/utils/subprocess.h"
18 
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23 #include <unistd.h>
24 
25 #include <map>
26 #include <set>
27 
28 #include <glog/logging.h>
29 namespace {
30 
31 // If a redirected-to file descriptor was already closed, it's possible that
32 // some inherited file descriptor duped to this file descriptor and the redirect
33 // would override that. This function makes sure that doesn't happen.
validate_redirects(const std::map<cvd::Subprocess::StdIOChannel,int> & redirects,const std::map<cvd::SharedFD,int> & inherited_fds)34 bool validate_redirects(
35     const std::map<cvd::Subprocess::StdIOChannel, int>& redirects,
36     const std::map<cvd::SharedFD, int>& inherited_fds) {
37   // Add the redirected IO channels to a set as integers. This allows converting
38   // the enum values into integers instead of the other way around.
39   std::set<int> int_redirects;
40   for (const auto& entry: redirects) {
41     int_redirects.insert(static_cast<int>(entry.first));
42   }
43   for (const auto& entry: inherited_fds) {
44     auto dupped_fd = entry.second;
45     if (int_redirects.count(dupped_fd)) {
46       LOG(ERROR) << "Requested redirect of fd(" << dupped_fd
47                  << ") conflicts with inherited FD.";
48       return false;
49     }
50   }
51   return true;
52 }
53 
do_redirects(const std::map<cvd::Subprocess::StdIOChannel,int> & redirects)54 void do_redirects(const std::map<cvd::Subprocess::StdIOChannel, int>& redirects) {
55   for (const auto& entry: redirects) {
56     auto std_channel = static_cast<int>(entry.first);
57     auto fd = entry.second;
58     TEMP_FAILURE_RETRY(dup2(fd, std_channel));
59   }
60 }
61 
subprocess_impl(const char * const * command,const char * const * envp,const std::map<cvd::Subprocess::StdIOChannel,int> & redirects,const std::map<cvd::SharedFD,int> & inherited_fds,bool with_control_socket)62 cvd::Subprocess subprocess_impl(
63     const char* const* command,
64     const char* const* envp,
65     const std::map<cvd::Subprocess::StdIOChannel, int>& redirects,
66     const std::map<cvd::SharedFD, int>& inherited_fds,
67     bool with_control_socket) {
68   // The parent socket will get closed on the child on the call to exec, the
69   // child socket will be closed on the parent when this function returns and no
70   // references to the fd are left
71   cvd::SharedFD parent_socket, child_socket;
72   if (with_control_socket) {
73     if (!cvd::SharedFD::SocketPair(AF_LOCAL, SOCK_STREAM, 0, &parent_socket,
74                                    &child_socket)) {
75       LOG(ERROR) << "Unable to create control socket pair: " << strerror(errno);
76       return cvd::Subprocess(-1, {});
77     }
78     // Remove FD_CLOEXEC from the child socket, ensure the parent has it
79     child_socket->Fcntl(F_SETFD, 0);
80     parent_socket->Fcntl(F_SETFD, FD_CLOEXEC);
81   }
82 
83   if (!validate_redirects(redirects, inherited_fds)) {
84     return cvd::Subprocess(-1, {});
85   }
86 
87   pid_t pid = fork();
88   if (!pid) {
89     do_redirects(redirects);
90     int rval;
91     // If envp is NULL, the current process's environment is used as the
92     // environment of the child process. To force an empty emvironment for
93     // the child process pass the address of a pointer to NULL
94     if (envp == NULL) {
95       rval = execv(command[0], const_cast<char* const*>(command));
96     } else {
97       rval = execve(command[0],
98                     const_cast<char* const*>(command),
99                     const_cast<char* const*>(envp));
100     }
101     // No need for an if: if exec worked it wouldn't have returned
102     LOG(ERROR) << "exec of " << command[0] << " failed (" << strerror(errno)
103                << ")";
104     exit(rval);
105   }
106   if (pid == -1) {
107     LOG(ERROR) << "fork failed (" << strerror(errno) << ")";
108   }
109   LOG(INFO) << "Started (pid: " << pid << "): " << command[0];
110   int i = 1;
111   while (command[i]) {
112     LOG(INFO) << command[i++];
113   }
114   return cvd::Subprocess(pid, parent_socket);
115 }
116 
ToCharPointers(const std::vector<std::string> & vect)117 std::vector<const char*> ToCharPointers(
118     const std::vector<std::string>& vect) {
119   std::vector<const char*> ret = {};
120   for (const auto& str : vect) {
121     ret.push_back(str.c_str());
122   }
123   ret.push_back(NULL);
124   return ret;
125 }
126 }  // namespace
127 namespace cvd {
128 
Subprocess(Subprocess && subprocess)129 Subprocess::Subprocess(Subprocess&& subprocess)
130     : pid_(subprocess.pid_),
131       started_(subprocess.started_),
132       control_socket_(subprocess.control_socket_) {
133   // Make sure the moved object no longer controls this subprocess
134   subprocess.pid_ = -1;
135   subprocess.started_ = false;
136   subprocess.control_socket_ = SharedFD();
137 }
138 
operator =(Subprocess && other)139 Subprocess& Subprocess::operator=(Subprocess&& other) {
140   pid_ = other.pid_;
141   started_ = other.started_;
142   control_socket_ = other.control_socket_;
143 
144   other.pid_ = -1;
145   other.started_ = false;
146   other.control_socket_ = SharedFD();
147   return *this;
148 }
149 
Wait()150 int Subprocess::Wait() {
151   if (pid_ < 0) {
152     LOG(ERROR)
153         << "Attempt to wait on invalid pid(has it been waited on already?): "
154         << pid_;
155     return -1;
156   }
157   int wstatus = 0;
158   auto pid = pid_; // Wait will set pid_ to -1 after waiting
159   auto wait_ret = Wait(&wstatus, 0);
160   if (wait_ret < 0) {
161     LOG(ERROR) << "Error on call to waitpid: " << strerror(errno);
162     return wait_ret;
163   }
164   int retval = 0;
165   if (WIFEXITED(wstatus)) {
166     retval = WEXITSTATUS(wstatus);
167     if (retval) {
168       LOG(ERROR) << "Subprocess " << pid
169                  << " exited with error code: " << retval;
170     }
171   } else if (WIFSIGNALED(wstatus)) {
172     LOG(ERROR) << "Subprocess " << pid
173                << " was interrupted by a signal: " << WTERMSIG(wstatus);
174     retval = -1;
175   }
176   return retval;
177 }
Wait(int * wstatus,int options)178 pid_t Subprocess::Wait(int* wstatus, int options) {
179   if (pid_ < 0) {
180     LOG(ERROR)
181         << "Attempt to wait on invalid pid(has it been waited on already?): "
182         << pid_;
183     return -1;
184   }
185   auto retval = waitpid(pid_, wstatus, options);
186   // We don't want to wait twice for the same process
187   pid_ = -1;
188   return retval;
189 }
190 
~Command()191 Command::~Command() {
192   // Close all inherited file descriptors
193   for(const auto& entry: inherited_fds_) {
194     close(entry.second);
195   }
196   // Close all redirected file descriptors
197   for (const auto& entry: redirects_) {
198     close(entry.second);
199   }
200 }
201 
BuildParameter(std::stringstream * stream,SharedFD shared_fd)202 bool Command::BuildParameter(std::stringstream* stream, SharedFD shared_fd) {
203   int fd;
204   if (inherited_fds_.count(shared_fd)) {
205     fd = inherited_fds_[shared_fd];
206   } else {
207     fd = shared_fd->UNMANAGED_Dup();
208     if (fd < 0) {
209       return false;
210     }
211     inherited_fds_[shared_fd] = fd;
212   }
213   *stream << fd;
214   return true;
215 }
216 
RedirectStdIO(cvd::Subprocess::StdIOChannel channel,cvd::SharedFD shared_fd)217 bool Command::RedirectStdIO(cvd::Subprocess::StdIOChannel channel,
218                             cvd::SharedFD shared_fd){
219   if (!shared_fd->IsOpen()) {
220     return false;
221   }
222   if (redirects_.count(channel)) {
223     LOG(ERROR) << "Attempted multiple redirections of fd: "
224                << static_cast<int>(channel);
225     return false;
226   }
227   auto dup_fd = shared_fd->UNMANAGED_Dup();
228   if (dup_fd < 0) {
229     return false;
230   }
231   redirects_[channel] = dup_fd;
232   return true;
233 }
234 
Start(bool with_control_socket) const235 Subprocess Command::Start(bool with_control_socket) const {
236   auto cmd = ToCharPointers(command_);
237   if (use_parent_env_) {
238     return subprocess_impl(cmd.data(), nullptr, redirects_, inherited_fds_,
239                            with_control_socket);
240   } else {
241     auto envp = ToCharPointers(env_);
242     return subprocess_impl(cmd.data(), envp.data(), redirects_, inherited_fds_,
243                            with_control_socket);
244   }
245 }
246 
execute(const std::vector<std::string> & command,const std::vector<std::string> & env)247 int execute(const std::vector<std::string>& command,
248             const std::vector<std::string>& env) {
249   Command cmd(command[0]);
250   for (size_t i = 1; i < command.size(); ++i) {
251     cmd.AddParameter(command[i]);
252   }
253   cmd.SetEnvironment(env);
254   auto subprocess = cmd.Start();
255   if (!subprocess.Started()) {
256     return -1;
257   }
258   return subprocess.Wait();
259 }
execute(const std::vector<std::string> & command)260 int execute(const std::vector<std::string>& command) {
261   Command cmd(command[0]);
262   for (size_t i = 1; i < command.size(); ++i) {
263     cmd.AddParameter(command[i]);
264   }
265   auto subprocess = cmd.Start();
266   if (!subprocess.Started()) {
267     return -1;
268   }
269   return subprocess.Wait();
270 }
271 }  // namespace cvd
272