blob: 4975fab9978fa854bf21f1249f850013b72a1f61 [file] [log] [blame]
David Pursell4f344bb2015-08-28 15:08:49 -07001/*
2 * Copyright (C) 2015 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
David Pursell8da19a42015-08-31 10:42:13 -070017// Functionality for launching and managing shell subprocesses.
18//
19// There are two types of subprocesses, PTY or raw. PTY is typically used for
20// an interactive session, raw for non-interactive. There are also two methods
21// of communication with the subprocess, passing raw data or using a simple
22// protocol to wrap packets. The protocol allows separating stdout/stderr and
23// passing the exit code back, but is not backwards compatible.
24// ----------------+--------------------------------------
25// Type Protocol | Exit code? Separate stdout/stderr?
26// ----------------+--------------------------------------
27// PTY No | No No
28// Raw No | No No
29// PTY Yes | Yes No
30// Raw Yes | Yes Yes
31// ----------------+--------------------------------------
32//
33// Non-protocol subprocesses work by passing subprocess stdin/out/err through
34// a single pipe which is registered with a local socket in adbd. The local
35// socket uses the fdevent loop to pass raw data between this pipe and the
36// transport, which then passes data back to the adb client. Cleanup is done by
37// waiting in a separate thread for the subprocesses to exit and then signaling
38// a separate fdevent to close out the local socket from the main loop.
39//
40// ------------------+-------------------------+------------------------------
41// Subprocess | adbd subprocess thread | adbd main fdevent loop
42// ------------------+-------------------------+------------------------------
43// | |
44// stdin/out/err <-----------------------------> LocalSocket
45// | | |
46// | | Block on exit |
47// | | * |
48// v | * |
49// Exit ---> Unblock |
50// | | |
51// | v |
52// | Notify shell exit FD ---> Close LocalSocket
53// ------------------+-------------------------+------------------------------
54//
55// The protocol requires the thread to intercept stdin/out/err in order to
56// wrap/unwrap data with shell protocol packets.
57//
58// ------------------+-------------------------+------------------------------
59// Subprocess | adbd subprocess thread | adbd main fdevent loop
60// ------------------+-------------------------+------------------------------
61// | |
62// stdin/out <---> Protocol <---> LocalSocket
63// stderr ---> Protocol ---> LocalSocket
64// | | |
65// v | |
66// Exit ---> Exit code protocol ---> LocalSocket
67// | | |
68// | v |
69// | Notify shell exit FD ---> Close LocalSocket
70// ------------------+-------------------------+------------------------------
71//
72// An alternate approach is to put the protocol wrapping/unwrapping in the main
73// fdevent loop, which has the advantage of being able to re-use the existing
74// select() code for handling data streams. However, implementation turned out
75// to be more complex due to partial reads and non-blocking I/O so this model
76// was chosen instead.
77
Yabin Cui19bec5b2015-09-22 15:52:57 -070078#define TRACE_TAG SHELL
David Pursell4f344bb2015-08-28 15:08:49 -070079
Yabin Cui5fc22312015-10-06 15:10:05 -070080#include "sysdeps.h"
David Pursell4f344bb2015-08-28 15:08:49 -070081
Yabin Cui5fc22312015-10-06 15:10:05 -070082#include "shell_service.h"
David Pursell4f344bb2015-08-28 15:08:49 -070083
David Pursell917dcfa2015-08-28 18:31:29 -070084#include <errno.h>
Mark Salyzyn81a870e2016-10-05 08:13:56 -070085#include <paths.h>
David Pursell4f344bb2015-08-28 15:08:49 -070086#include <pty.h>
Elliott Hughes90676d92015-11-02 13:29:19 -080087#include <pwd.h>
David Pursell8da19a42015-08-31 10:42:13 -070088#include <sys/select.h>
David Pursell4f344bb2015-08-28 15:08:49 -070089#include <termios.h>
90
David Pursell8da19a42015-08-31 10:42:13 -070091#include <memory>
Josh Gao8d76c452015-12-11 10:52:55 -080092#include <string>
93#include <unordered_map>
94#include <vector>
David Pursell8da19a42015-08-31 10:42:13 -070095
Elliott Hughesf55ead92015-12-04 22:00:26 -080096#include <android-base/logging.h>
97#include <android-base/stringprintf.h>
Mark Salyzyn81a870e2016-10-05 08:13:56 -070098#include <private/android_logger.h>
David Pursell4f344bb2015-08-28 15:08:49 -070099
100#include "adb.h"
101#include "adb_io.h"
102#include "adb_trace.h"
Josh Gaoea7457b2016-08-30 15:39:25 -0700103#include "adb_unique_fd.h"
Yabin Cui5fc22312015-10-06 15:10:05 -0700104#include "adb_utils.h"
Rubin Xu29a64f92016-01-11 10:23:47 +0000105#include "security_log_tags.h"
David Pursell4f344bb2015-08-28 15:08:49 -0700106
107namespace {
108
David Pursell917dcfa2015-08-28 18:31:29 -0700109// Reads from |fd| until close or failure.
110std::string ReadAll(int fd) {
111 char buffer[512];
112 std::string received;
113
114 while (1) {
115 int bytes = adb_read(fd, buffer, sizeof(buffer));
116 if (bytes <= 0) {
117 break;
118 }
119 received.append(buffer, bytes);
David Pursell4f344bb2015-08-28 15:08:49 -0700120 }
121
David Pursell917dcfa2015-08-28 18:31:29 -0700122 return received;
123}
124
David Pursell917dcfa2015-08-28 18:31:29 -0700125// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
Elliott Hughes857e6592016-05-27 17:51:24 -0700126bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
David Pursell917dcfa2015-08-28 18:31:29 -0700127 int sockets[2];
128 if (adb_socketpair(sockets) < 0) {
129 PLOG(ERROR) << "cannot create socket pair";
130 return false;
131 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700132 fd1->reset(sockets[0]);
133 fd2->reset(sockets[1]);
David Pursell917dcfa2015-08-28 18:31:29 -0700134 return true;
135}
136
137class Subprocess {
138 public:
Elliott Hughesff444562015-11-16 10:55:34 -0800139 Subprocess(const std::string& command, const char* terminal_type,
140 SubprocessType type, SubprocessProtocol protocol);
David Pursell917dcfa2015-08-28 18:31:29 -0700141 ~Subprocess();
142
143 const std::string& command() const { return command_; }
David Pursell917dcfa2015-08-28 18:31:29 -0700144
Josh Gaoa6545142016-06-22 15:57:12 -0700145 int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
David Pursell917dcfa2015-08-28 18:31:29 -0700146
147 pid_t pid() const { return pid_; }
148
149 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
Josh Gao6d3a75a2016-06-17 14:53:57 -0700150 // and exec's the child. Returns false and sets error on failure.
Josh Gao9dc2e932016-01-25 17:11:43 -0800151 bool ForkAndExec(std::string* _Nonnull error);
David Pursell917dcfa2015-08-28 18:31:29 -0700152
Josh Gao6d3a75a2016-06-17 14:53:57 -0700153 // Start the subprocess manager thread. Consumes the subprocess, regardless of success.
154 // Returns false and sets error on failure.
155 static bool StartThread(std::unique_ptr<Subprocess> subprocess,
156 std::string* _Nonnull error);
157
David Pursell917dcfa2015-08-28 18:31:29 -0700158 private:
159 // Opens the file at |pts_name|.
Elliott Hughes857e6592016-05-27 17:51:24 -0700160 int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700161
Josh Gao7d405252016-02-12 14:31:15 -0800162 static void ThreadHandler(void* userdata);
David Pursell8da19a42015-08-31 10:42:13 -0700163 void PassDataStreams();
David Pursell917dcfa2015-08-28 18:31:29 -0700164 void WaitForExit();
165
Elliott Hughes857e6592016-05-27 17:51:24 -0700166 unique_fd* SelectLoop(fd_set* master_read_set_ptr,
167 fd_set* master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700168
169 // Input/output stream handlers. Success returns nullptr, failure returns
170 // a pointer to the failed FD.
Elliott Hughes857e6592016-05-27 17:51:24 -0700171 unique_fd* PassInput();
172 unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
David Pursell8da19a42015-08-31 10:42:13 -0700173
David Pursell917dcfa2015-08-28 18:31:29 -0700174 const std::string command_;
Elliott Hughesff444562015-11-16 10:55:34 -0800175 const std::string terminal_type_;
David Pursell182dc322016-01-27 16:07:52 -0800176 bool make_pty_raw_ = false;
David Pursell917dcfa2015-08-28 18:31:29 -0700177 SubprocessType type_;
David Pursell8da19a42015-08-31 10:42:13 -0700178 SubprocessProtocol protocol_;
David Pursell917dcfa2015-08-28 18:31:29 -0700179 pid_t pid_ = -1;
Elliott Hughes857e6592016-05-27 17:51:24 -0700180 unique_fd local_socket_sfd_;
David Pursell917dcfa2015-08-28 18:31:29 -0700181
David Pursell8da19a42015-08-31 10:42:13 -0700182 // Shell protocol variables.
Elliott Hughes857e6592016-05-27 17:51:24 -0700183 unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700184 std::unique_ptr<ShellProtocol> input_, output_;
185 size_t input_bytes_left_ = 0;
186
David Pursell917dcfa2015-08-28 18:31:29 -0700187 DISALLOW_COPY_AND_ASSIGN(Subprocess);
188};
189
Elliott Hughesff444562015-11-16 10:55:34 -0800190Subprocess::Subprocess(const std::string& command, const char* terminal_type,
191 SubprocessType type, SubprocessProtocol protocol)
192 : command_(command),
193 terminal_type_(terminal_type ? terminal_type : ""),
194 type_(type),
195 protocol_(protocol) {
David Pursell182dc322016-01-27 16:07:52 -0800196 // If we aren't using the shell protocol we must allocate a PTY to properly close the
197 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
198 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
199 // e.g. screenrecord, will never notice the broken pipe and terminate.
200 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
201 // with select() and will send SIGHUP manually to the child process.
202 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
203 // Disable PTY input/output processing since the client is expecting raw data.
204 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
205 type_ = SubprocessType::kPty;
206 make_pty_raw_ = true;
207 }
David Pursell917dcfa2015-08-28 18:31:29 -0700208}
209
210Subprocess::~Subprocess() {
Josh Gao6a98c6e2016-01-19 16:21:17 -0800211 WaitForExit();
David Pursell917dcfa2015-08-28 18:31:29 -0700212}
213
Josh Gao9dc2e932016-01-25 17:11:43 -0800214bool Subprocess::ForkAndExec(std::string* error) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700215 unique_fd child_stdinout_sfd, child_stderr_sfd;
216 unique_fd parent_error_sfd, child_error_sfd;
David Pursell917dcfa2015-08-28 18:31:29 -0700217 char pts_name[PATH_MAX];
218
Rubin Xu29a64f92016-01-11 10:23:47 +0000219 if (command_.empty()) {
220 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
221 } else {
222 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
223 }
224
Josh Gao8d76c452015-12-11 10:52:55 -0800225 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
226 // use threads, logging directly from the child might deadlock due to locks held in another
227 // thread during the fork.
David Pursell917dcfa2015-08-28 18:31:29 -0700228 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800229 *error = android::base::StringPrintf(
230 "failed to create pipe for subprocess error reporting: %s", strerror(errno));
231 return false;
David Pursell917dcfa2015-08-28 18:31:29 -0700232 }
233
Josh Gao8d76c452015-12-11 10:52:55 -0800234 // Construct the environment for the child before we fork.
235 passwd* pw = getpwuid(getuid());
236 std::unordered_map<std::string, std::string> env;
Josh Gao81ea0022015-12-11 15:49:12 -0800237 if (environ) {
238 char** current = environ;
239 while (char* env_cstr = *current++) {
240 std::string env_string = env_cstr;
Dan Austin4bdf38b2016-03-28 14:37:01 -0700241 char* delimiter = strchr(&env_string[0], '=');
Josh Gao8d76c452015-12-11 10:52:55 -0800242
Josh Gao81ea0022015-12-11 15:49:12 -0800243 // Drop any values that don't contain '='.
244 if (delimiter) {
245 *delimiter++ = '\0';
246 env[env_string.c_str()] = delimiter;
247 }
248 }
Josh Gao8d76c452015-12-11 10:52:55 -0800249 }
250
251 if (pw != nullptr) {
252 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
253 env["HOME"] = pw->pw_dir;
254 env["LOGNAME"] = pw->pw_name;
255 env["USER"] = pw->pw_name;
256 env["SHELL"] = pw->pw_shell;
257 }
258
259 if (!terminal_type_.empty()) {
260 env["TERM"] = terminal_type_;
261 }
262
263 std::vector<std::string> joined_env;
264 for (auto it : env) {
265 const char* key = it.first.c_str();
266 const char* value = it.second.c_str();
267 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
268 }
269
270 std::vector<const char*> cenv;
271 for (const std::string& str : joined_env) {
272 cenv.push_back(str.c_str());
273 }
274 cenv.push_back(nullptr);
275
David Pursell917dcfa2015-08-28 18:31:29 -0700276 if (type_ == SubprocessType::kPty) {
277 int fd;
278 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
Josh Gao9a4b5e92016-03-04 17:50:10 -0800279 if (pid_ > 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700280 stdinout_sfd_.reset(fd);
Josh Gao9a4b5e92016-03-04 17:50:10 -0800281 }
David Pursell917dcfa2015-08-28 18:31:29 -0700282 } else {
David Pursell8da19a42015-08-31 10:42:13 -0700283 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800284 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
285 strerror(errno));
David Pursell8da19a42015-08-31 10:42:13 -0700286 return false;
287 }
288 // Raw subprocess + shell protocol allows for splitting stderr.
289 if (protocol_ == SubprocessProtocol::kShell &&
290 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800291 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
292 strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700293 return false;
294 }
295 pid_ = fork();
296 }
297
298 if (pid_ == -1) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800299 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700300 return false;
301 }
302
303 if (pid_ == 0) {
304 // Subprocess child.
Elliott Hughesfd20a0f2016-11-17 10:32:16 -0800305 setsid();
David Pursell4f344bb2015-08-28 15:08:49 -0700306
David Pursell917dcfa2015-08-28 18:31:29 -0700307 if (type_ == SubprocessType::kPty) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700308 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursell917dcfa2015-08-28 18:31:29 -0700309 }
310
Elliott Hughes857e6592016-05-27 17:51:24 -0700311 dup2(child_stdinout_sfd, STDIN_FILENO);
312 dup2(child_stdinout_sfd, STDOUT_FILENO);
313 dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
David Pursell917dcfa2015-08-28 18:31:29 -0700314
315 // exec doesn't trigger destructors, close the FDs manually.
Elliott Hughes857e6592016-05-27 17:51:24 -0700316 stdinout_sfd_.reset(-1);
317 stderr_sfd_.reset(-1);
318 child_stdinout_sfd.reset(-1);
319 child_stderr_sfd.reset(-1);
320 parent_error_sfd.reset(-1);
321 close_on_exec(child_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700322
Josh Gao8a631162016-01-19 17:31:09 -0800323 if (command_.empty()) {
Josh Gao8d76c452015-12-11 10:52:55 -0800324 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700325 } else {
Josh Gao8d76c452015-12-11 10:52:55 -0800326 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700327 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700328 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
329 WriteFdExactly(child_error_sfd, strerror(errno));
330 child_error_sfd.reset(-1);
Josh Gao8d76c452015-12-11 10:52:55 -0800331 _Exit(1);
David Pursell917dcfa2015-08-28 18:31:29 -0700332 }
333
334 // Subprocess parent.
David Pursell8da19a42015-08-31 10:42:13 -0700335 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
Elliott Hughes857e6592016-05-27 17:51:24 -0700336 stdinout_sfd_.get(), stderr_sfd_.get());
David Pursell917dcfa2015-08-28 18:31:29 -0700337
338 // Wait to make sure the subprocess exec'd without error.
Elliott Hughes857e6592016-05-27 17:51:24 -0700339 child_error_sfd.reset(-1);
340 std::string error_message = ReadAll(parent_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700341 if (!error_message.empty()) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800342 *error = error_message;
David Pursell917dcfa2015-08-28 18:31:29 -0700343 return false;
344 }
345
Josh Gao8d76c452015-12-11 10:52:55 -0800346 D("subprocess parent: exec completed");
David Pursell8da19a42015-08-31 10:42:13 -0700347 if (protocol_ == SubprocessProtocol::kNone) {
348 // No protocol: all streams pass through the stdinout FD and hook
349 // directly into the local socket for raw data transfer.
Elliott Hughes857e6592016-05-27 17:51:24 -0700350 local_socket_sfd_.reset(stdinout_sfd_.release());
David Pursell8da19a42015-08-31 10:42:13 -0700351 } else {
352 // Shell protocol: create another socketpair to intercept data.
353 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800354 *error = android::base::StringPrintf(
355 "failed to create socketpair to intercept data: %s", strerror(errno));
356 kill(pid_, SIGKILL);
David Pursell8da19a42015-08-31 10:42:13 -0700357 return false;
358 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700359 D("protocol FD = %d", protocol_sfd_.get());
David Pursell8da19a42015-08-31 10:42:13 -0700360
Elliott Hughes857e6592016-05-27 17:51:24 -0700361 input_.reset(new ShellProtocol(protocol_sfd_));
362 output_.reset(new ShellProtocol(protocol_sfd_));
David Pursell8da19a42015-08-31 10:42:13 -0700363 if (!input_ || !output_) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800364 *error = "failed to allocate shell protocol objects";
365 kill(pid_, SIGKILL);
David Pursell8da19a42015-08-31 10:42:13 -0700366 return false;
367 }
368
369 // Don't let reads/writes to the subprocess block our thread. This isn't
370 // likely but could happen under unusual circumstances, such as if we
371 // write a ton of data to stdin but the subprocess never reads it and
372 // the pipe fills up.
Elliott Hughes857e6592016-05-27 17:51:24 -0700373 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
David Pursell8da19a42015-08-31 10:42:13 -0700374 if (fd >= 0) {
Yabin Cui5fc22312015-10-06 15:10:05 -0700375 if (!set_file_block_mode(fd, false)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800376 *error = android::base::StringPrintf(
377 "failed to set non-blocking mode for fd %d", fd);
378 kill(pid_, SIGKILL);
David Pursell8da19a42015-08-31 10:42:13 -0700379 return false;
380 }
381 }
382 }
383 }
David Pursell917dcfa2015-08-28 18:31:29 -0700384
Josh Gao6d3a75a2016-06-17 14:53:57 -0700385 D("subprocess parent: completed");
386 return true;
387}
388
389bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
390 Subprocess* raw = subprocess.release();
391 if (!adb_thread_create(ThreadHandler, raw)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800392 *error =
393 android::base::StringPrintf("failed to create subprocess thread: %s", strerror(errno));
Josh Gao6d3a75a2016-06-17 14:53:57 -0700394 kill(raw->pid_, SIGKILL);
David Pursell917dcfa2015-08-28 18:31:29 -0700395 return false;
396 }
397
398 return true;
399}
400
Elliott Hughes857e6592016-05-27 17:51:24 -0700401int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
David Pursell917dcfa2015-08-28 18:31:29 -0700402 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
403 if (child_fd == -1) {
404 // Don't use WriteFdFmt; since we're in the fork() child we don't want
405 // to allocate any heap memory to avoid race conditions.
406 const char* messages[] = {"child failed to open pseudo-term slave ",
407 pts_name, ": ", strerror(errno)};
408 for (const char* message : messages) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700409 WriteFdExactly(*error_sfd, message);
David Pursell917dcfa2015-08-28 18:31:29 -0700410 }
Josh Gao57cb2172016-05-13 18:16:43 -0700411 abort();
David Pursell917dcfa2015-08-28 18:31:29 -0700412 }
413
David Pursell182dc322016-01-27 16:07:52 -0800414 if (make_pty_raw_) {
415 termios tattr;
416 if (tcgetattr(child_fd, &tattr) == -1) {
417 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700418 WriteFdExactly(*error_sfd, "tcgetattr failed: ");
419 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700420 abort();
David Pursell182dc322016-01-27 16:07:52 -0800421 }
422
423 cfmakeraw(&tattr);
424 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
425 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700426 WriteFdExactly(*error_sfd, "tcsetattr failed: ");
427 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700428 abort();
David Pursell182dc322016-01-27 16:07:52 -0800429 }
430 }
431
David Pursell917dcfa2015-08-28 18:31:29 -0700432 return child_fd;
David Pursell4f344bb2015-08-28 15:08:49 -0700433}
434
Josh Gao7d405252016-02-12 14:31:15 -0800435void Subprocess::ThreadHandler(void* userdata) {
David Pursell917dcfa2015-08-28 18:31:29 -0700436 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell4f344bb2015-08-28 15:08:49 -0700437
David Pursell917dcfa2015-08-28 18:31:29 -0700438 adb_thread_setname(android::base::StringPrintf(
Josh Gaoa6545142016-06-22 15:57:12 -0700439 "shell srvc %d", subprocess->pid()));
David Pursell4f344bb2015-08-28 15:08:49 -0700440
Josh Gao6d3a75a2016-06-17 14:53:57 -0700441 D("passing data streams for PID %d", subprocess->pid());
David Pursell8da19a42015-08-31 10:42:13 -0700442 subprocess->PassDataStreams();
David Pursell4f344bb2015-08-28 15:08:49 -0700443
David Pursell3fe11f62015-10-06 15:30:03 -0700444 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursell917dcfa2015-08-28 18:31:29 -0700445 delete subprocess;
David Pursell4f344bb2015-08-28 15:08:49 -0700446}
447
David Pursell8da19a42015-08-31 10:42:13 -0700448void Subprocess::PassDataStreams() {
Elliott Hughes857e6592016-05-27 17:51:24 -0700449 if (protocol_sfd_ == -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700450 return;
451 }
452
453 // Start by trying to read from the protocol FD, stdout, and stderr.
454 fd_set master_read_set, master_write_set;
455 FD_ZERO(&master_read_set);
456 FD_ZERO(&master_write_set);
Elliott Hughes857e6592016-05-27 17:51:24 -0700457 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
458 if (*sfd != -1) {
459 FD_SET(*sfd, &master_read_set);
David Pursell8da19a42015-08-31 10:42:13 -0700460 }
461 }
462
463 // Pass data until the protocol FD or both the subprocess pipes die, at
464 // which point we can't pass any more data.
Elliott Hughes857e6592016-05-27 17:51:24 -0700465 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
466 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
David Pursell8da19a42015-08-31 10:42:13 -0700467 if (dead_sfd) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700468 D("closing FD %d", dead_sfd->get());
469 FD_CLR(*dead_sfd, &master_read_set);
470 FD_CLR(*dead_sfd, &master_write_set);
David Pursell2b8d4a42015-09-14 15:36:26 -0700471 if (dead_sfd == &protocol_sfd_) {
472 // Using SIGHUP is a decent general way to indicate that the
473 // controlling process is going away. If specific signals are
474 // needed (e.g. SIGINT), pass those through the shell protocol
475 // and only fall back on this for unexpected closures.
476 D("protocol FD died, sending SIGHUP to pid %d", pid_);
477 kill(pid_, SIGHUP);
David Pursellaeee0032016-06-06 09:37:16 -0700478
479 // We also need to close the pipes connected to the child process
480 // so that if it ignores SIGHUP and continues to write data it
481 // won't fill up the pipe and block.
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700482 stdinout_sfd_.reset();
483 stderr_sfd_.reset();
David Pursell2b8d4a42015-09-14 15:36:26 -0700484 }
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700485 dead_sfd->reset();
David Pursell8da19a42015-08-31 10:42:13 -0700486 }
487 }
488}
489
490namespace {
491
Elliott Hughes857e6592016-05-27 17:51:24 -0700492inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
493 return sfd != -1 && FD_ISSET(sfd, set);
David Pursell8da19a42015-08-31 10:42:13 -0700494}
495
496} // namespace
497
Elliott Hughes857e6592016-05-27 17:51:24 -0700498unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
499 fd_set* master_write_set_ptr) {
David Pursell8da19a42015-08-31 10:42:13 -0700500 fd_set read_set, write_set;
Elliott Hughes857e6592016-05-27 17:51:24 -0700501 int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
502 unique_fd* dead_sfd = nullptr;
David Pursell8da19a42015-08-31 10:42:13 -0700503
504 // Keep calling select() and passing data until an FD closes/errors.
505 while (!dead_sfd) {
506 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
507 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
508 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
509 if (errno == EINTR) {
510 continue;
511 } else {
512 PLOG(ERROR) << "select failed, closing subprocess pipes";
Elliott Hughes857e6592016-05-27 17:51:24 -0700513 stdinout_sfd_.reset(-1);
514 stderr_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700515 return nullptr;
516 }
517 }
518
519 // Read stdout, write to protocol FD.
520 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
521 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
522 }
523
524 // Read stderr, write to protocol FD.
525 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
526 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
527 }
528
529 // Read protocol FD, write to stdin.
530 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
531 dead_sfd = PassInput();
532 // If we didn't finish writing, block on stdin write.
533 if (input_bytes_left_) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700534 FD_CLR(protocol_sfd_, master_read_set_ptr);
535 FD_SET(stdinout_sfd_, master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700536 }
537 }
538
539 // Continue writing to stdin; only happens if a previous write blocked.
540 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
541 dead_sfd = PassInput();
542 // If we finished writing, go back to blocking on protocol read.
543 if (!input_bytes_left_) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700544 FD_SET(protocol_sfd_, master_read_set_ptr);
545 FD_CLR(stdinout_sfd_, master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700546 }
547 }
548 } // while (!dead_sfd)
549
550 return dead_sfd;
551}
552
Elliott Hughes857e6592016-05-27 17:51:24 -0700553unique_fd* Subprocess::PassInput() {
David Pursell8da19a42015-08-31 10:42:13 -0700554 // Only read a new packet if we've finished writing the last one.
555 if (!input_bytes_left_) {
556 if (!input_->Read()) {
557 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
558 if (errno != 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700559 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700560 }
561 return &protocol_sfd_;
562 }
563
Elliott Hughes857e6592016-05-27 17:51:24 -0700564 if (stdinout_sfd_ != -1) {
David Pursell3fe11f62015-10-06 15:30:03 -0700565 switch (input_->id()) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800566 case ShellProtocol::kIdWindowSizeChange:
567 int rows, cols, x_pixels, y_pixels;
568 if (sscanf(input_->data(), "%dx%d,%dx%d",
569 &rows, &cols, &x_pixels, &y_pixels) == 4) {
570 winsize ws;
571 ws.ws_row = rows;
572 ws.ws_col = cols;
573 ws.ws_xpixel = x_pixels;
574 ws.ws_ypixel = y_pixels;
Elliott Hughes857e6592016-05-27 17:51:24 -0700575 ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
Elliott Hughesa8265792015-11-03 11:18:40 -0800576 }
577 break;
David Pursell3fe11f62015-10-06 15:30:03 -0700578 case ShellProtocol::kIdStdin:
579 input_bytes_left_ = input_->data_length();
580 break;
581 case ShellProtocol::kIdCloseStdin:
582 if (type_ == SubprocessType::kRaw) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700583 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
David Pursell3fe11f62015-10-06 15:30:03 -0700584 return nullptr;
585 }
586 PLOG(ERROR) << "failed to shutdown writes to FD "
Elliott Hughes857e6592016-05-27 17:51:24 -0700587 << stdinout_sfd_;
David Pursell3fe11f62015-10-06 15:30:03 -0700588 return &stdinout_sfd_;
589 } else {
590 // PTYs can't close just input, so rather than close the
591 // FD and risk losing subprocess output, leave it open.
592 // This only happens if the client starts a PTY shell
593 // non-interactively which is rare and unsupported.
594 // If necessary, the client can manually close the shell
595 // with `exit` or by killing the adb client process.
Elliott Hughes857e6592016-05-27 17:51:24 -0700596 D("can't close input for PTY FD %d", stdinout_sfd_.get());
David Pursell3fe11f62015-10-06 15:30:03 -0700597 }
598 break;
599 }
David Pursell8da19a42015-08-31 10:42:13 -0700600 }
601 }
602
603 if (input_bytes_left_ > 0) {
604 int index = input_->data_length() - input_bytes_left_;
Elliott Hughes857e6592016-05-27 17:51:24 -0700605 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
David Pursell8da19a42015-08-31 10:42:13 -0700606 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
607 if (bytes < 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700608 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700609 }
610 // stdin is done, mark this packet as finished and we'll just start
611 // dumping any further data received from the protocol FD.
612 input_bytes_left_ = 0;
613 return &stdinout_sfd_;
614 } else if (bytes > 0) {
615 input_bytes_left_ -= bytes;
616 }
617 }
618
619 return nullptr;
620}
621
Elliott Hughes857e6592016-05-27 17:51:24 -0700622unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
623 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
David Pursell8da19a42015-08-31 10:42:13 -0700624 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell3fe11f62015-10-06 15:30:03 -0700625 // read() returns EIO if a PTY closes; don't report this as an error,
626 // it just means the subprocess completed.
627 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700628 PLOG(ERROR) << "error reading output FD " << *sfd;
David Pursell8da19a42015-08-31 10:42:13 -0700629 }
630 return sfd;
631 }
632
633 if (bytes > 0 && !output_->Write(id, bytes)) {
634 if (errno != 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700635 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700636 }
637 return &protocol_sfd_;
638 }
639
640 return nullptr;
641}
642
David Pursell917dcfa2015-08-28 18:31:29 -0700643void Subprocess::WaitForExit() {
David Pursell8da19a42015-08-31 10:42:13 -0700644 int exit_code = 1;
645
David Pursell917dcfa2015-08-28 18:31:29 -0700646 D("waiting for pid %d", pid_);
David Pursell4f344bb2015-08-28 15:08:49 -0700647 while (true) {
648 int status;
David Pursell917dcfa2015-08-28 18:31:29 -0700649 if (pid_ == waitpid(pid_, &status, 0)) {
650 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell4f344bb2015-08-28 15:08:49 -0700651 if (WIFSIGNALED(status)) {
David Pursell8da19a42015-08-31 10:42:13 -0700652 exit_code = 0x80 | WTERMSIG(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700653 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700654 break;
655 } else if (!WIFEXITED(status)) {
David Pursell917dcfa2015-08-28 18:31:29 -0700656 D("subprocess didn't exit");
David Pursell4f344bb2015-08-28 15:08:49 -0700657 break;
658 } else if (WEXITSTATUS(status) >= 0) {
David Pursell8da19a42015-08-31 10:42:13 -0700659 exit_code = WEXITSTATUS(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700660 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700661 break;
662 }
David Pursell917dcfa2015-08-28 18:31:29 -0700663 }
David Pursell4f344bb2015-08-28 15:08:49 -0700664 }
David Pursell917dcfa2015-08-28 18:31:29 -0700665
David Pursell8da19a42015-08-31 10:42:13 -0700666 // If we have an open protocol FD send an exit packet.
Elliott Hughes857e6592016-05-27 17:51:24 -0700667 if (protocol_sfd_ != -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700668 output_->data()[0] = exit_code;
669 if (output_->Write(ShellProtocol::kIdExit, 1)) {
670 D("wrote the exit code packet: %d", exit_code);
671 } else {
672 PLOG(ERROR) << "failed to write the exit code packet";
673 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700674 protocol_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700675 }
676
David Pursell917dcfa2015-08-28 18:31:29 -0700677 // Pass the local socket FD to the shell cleanup fdevent.
678 if (SHELL_EXIT_NOTIFY_FD >= 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700679 int fd = local_socket_sfd_;
David Pursell917dcfa2015-08-28 18:31:29 -0700680 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
681 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
682 fd, SHELL_EXIT_NOTIFY_FD, pid_);
683 // The shell exit fdevent now owns the FD and will close it once
684 // the last bit of data flushes through.
Elliott Hughes857e6592016-05-27 17:51:24 -0700685 static_cast<void>(local_socket_sfd_.release());
David Pursell917dcfa2015-08-28 18:31:29 -0700686 } else {
687 PLOG(ERROR) << "failed to write fd " << fd
688 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
689 << ") for pid " << pid_;
690 }
David Pursell4f344bb2015-08-28 15:08:49 -0700691 }
692}
693
694} // namespace
695
Josh Gao9dc2e932016-01-25 17:11:43 -0800696// Create a pipe containing the error.
697static int ReportError(SubprocessProtocol protocol, const std::string& message) {
698 int pipefd[2];
699 if (pipe(pipefd) != 0) {
700 LOG(ERROR) << "failed to create pipe to report error";
701 return -1;
702 }
703
704 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
705 if (protocol == SubprocessProtocol::kShell) {
706 ShellProtocol::Id id = ShellProtocol::kIdStderr;
707 uint32_t length = buf.length();
708 WriteFdExactly(pipefd[1], &id, sizeof(id));
709 WriteFdExactly(pipefd[1], &length, sizeof(length));
710 }
711
712 WriteFdExactly(pipefd[1], buf.data(), buf.length());
713
714 if (protocol == SubprocessProtocol::kShell) {
715 ShellProtocol::Id id = ShellProtocol::kIdExit;
716 uint32_t length = 1;
717 char exit_code = 126;
718 WriteFdExactly(pipefd[1], &id, sizeof(id));
719 WriteFdExactly(pipefd[1], &length, sizeof(length));
720 WriteFdExactly(pipefd[1], &exit_code, sizeof(exit_code));
721 }
722
723 adb_close(pipefd[1]);
724 return pipefd[0];
725}
726
Elliott Hughesff444562015-11-16 10:55:34 -0800727int StartSubprocess(const char* name, const char* terminal_type,
728 SubprocessType type, SubprocessProtocol protocol) {
729 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell8da19a42015-08-31 10:42:13 -0700730 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughesff444562015-11-16 10:55:34 -0800731 protocol == SubprocessProtocol::kNone ? "none" : "shell",
732 terminal_type, name);
David Pursell4f344bb2015-08-28 15:08:49 -0700733
Josh Gao6d3a75a2016-06-17 14:53:57 -0700734 auto subprocess = std::make_unique<Subprocess>(name, terminal_type, type, protocol);
David Pursell917dcfa2015-08-28 18:31:29 -0700735 if (!subprocess) {
736 LOG(ERROR) << "failed to allocate new subprocess";
Josh Gao9dc2e932016-01-25 17:11:43 -0800737 return ReportError(protocol, "failed to allocate new subprocess");
David Pursell4f344bb2015-08-28 15:08:49 -0700738 }
739
Josh Gao9dc2e932016-01-25 17:11:43 -0800740 std::string error;
741 if (!subprocess->ForkAndExec(&error)) {
742 LOG(ERROR) << "failed to start subprocess: " << error;
Josh Gao9dc2e932016-01-25 17:11:43 -0800743 return ReportError(protocol, error);
David Pursell917dcfa2015-08-28 18:31:29 -0700744 }
745
Josh Gao8d84a312016-06-23 11:21:11 -0700746 unique_fd local_socket(subprocess->ReleaseLocalSocket());
747 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
748 subprocess->pid());
Josh Gao6d3a75a2016-06-17 14:53:57 -0700749
750 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
751 LOG(ERROR) << "failed to start subprocess management thread: " << error;
752 return ReportError(protocol, error);
753 }
754
Josh Gao8d84a312016-06-23 11:21:11 -0700755 return local_socket.release();
David Pursell4f344bb2015-08-28 15:08:49 -0700756}