blob: 491bb68da0e7b42bd00a98a801d26c329943d416 [file] [log] [blame]
David Pursell80f67022015-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 Pursell0955c662015-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 Cuiaed3c612015-09-22 15:52:57 -070078#define TRACE_TAG SHELL
David Pursell80f67022015-08-28 15:08:49 -070079
Yabin Cui6dfef252015-10-06 15:10:05 -070080#include "sysdeps.h"
David Pursell80f67022015-08-28 15:08:49 -070081
Yabin Cui6dfef252015-10-06 15:10:05 -070082#include "shell_service.h"
David Pursell80f67022015-08-28 15:08:49 -070083
David Pursella9320582015-08-28 18:31:29 -070084#include <errno.h>
David Pursell80f67022015-08-28 15:08:49 -070085#include <pty.h>
Elliott Hughesfbe43322015-11-02 13:29:19 -080086#include <pwd.h>
David Pursell0955c662015-08-31 10:42:13 -070087#include <sys/select.h>
David Pursell80f67022015-08-28 15:08:49 -070088#include <termios.h>
89
David Pursell0955c662015-08-31 10:42:13 -070090#include <memory>
Josh Gao9b3fd672015-12-11 10:52:55 -080091#include <string>
92#include <unordered_map>
93#include <vector>
David Pursell0955c662015-08-31 10:42:13 -070094
Elliott Hughes4f713192015-12-04 22:00:26 -080095#include <android-base/logging.h>
96#include <android-base/stringprintf.h>
David Pursell80f67022015-08-28 15:08:49 -070097#include <paths.h>
Rubin Xud61a25c2016-01-11 10:23:47 +000098#include <log/log.h>
David Pursell80f67022015-08-28 15:08:49 -070099
100#include "adb.h"
101#include "adb_io.h"
102#include "adb_trace.h"
Yabin Cui6dfef252015-10-06 15:10:05 -0700103#include "adb_utils.h"
Rubin Xud61a25c2016-01-11 10:23:47 +0000104#include "security_log_tags.h"
David Pursell80f67022015-08-28 15:08:49 -0700105
106namespace {
107
108void init_subproc_child()
109{
110 setsid();
111
112 // Set OOM score adjustment to prevent killing
113 int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
114 if (fd >= 0) {
115 adb_write(fd, "0", 1);
116 adb_close(fd);
117 } else {
118 D("adb: unable to update oom_score_adj");
119 }
120}
121
David Pursella9320582015-08-28 18:31:29 -0700122// Reads from |fd| until close or failure.
123std::string ReadAll(int fd) {
124 char buffer[512];
125 std::string received;
126
127 while (1) {
128 int bytes = adb_read(fd, buffer, sizeof(buffer));
129 if (bytes <= 0) {
130 break;
131 }
132 received.append(buffer, bytes);
David Pursell80f67022015-08-28 15:08:49 -0700133 }
134
David Pursella9320582015-08-28 18:31:29 -0700135 return received;
136}
137
138// Helper to automatically close an FD when it goes out of scope.
139class ScopedFd {
140 public:
141 ScopedFd() {}
142 ~ScopedFd() { Reset(); }
143
144 void Reset(int fd=-1) {
145 if (fd != fd_) {
146 if (valid()) {
147 adb_close(fd_);
148 }
149 fd_ = fd;
150 }
151 }
152
153 int Release() {
154 int temp = fd_;
155 fd_ = -1;
156 return temp;
157 }
158
159 bool valid() const { return fd_ >= 0; }
160
161 int fd() const { return fd_; }
162
163 private:
164 int fd_ = -1;
165
166 DISALLOW_COPY_AND_ASSIGN(ScopedFd);
167};
168
169// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
170bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
171 int sockets[2];
172 if (adb_socketpair(sockets) < 0) {
173 PLOG(ERROR) << "cannot create socket pair";
174 return false;
175 }
176 fd1->Reset(sockets[0]);
177 fd2->Reset(sockets[1]);
178 return true;
179}
180
181class Subprocess {
182 public:
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800183 Subprocess(const std::string& command, const char* terminal_type,
184 SubprocessType type, SubprocessProtocol protocol);
David Pursella9320582015-08-28 18:31:29 -0700185 ~Subprocess();
186
187 const std::string& command() const { return command_; }
David Pursella9320582015-08-28 18:31:29 -0700188
189 int local_socket_fd() const { return local_socket_sfd_.fd(); }
190
191 pid_t pid() const { return pid_; }
192
193 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
194 // and exec's the child. Returns false on failure.
195 bool ForkAndExec();
196
197 private:
198 // Opens the file at |pts_name|.
199 int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
200
201 static void* ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700202 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700203 void WaitForExit();
204
David Pursell0955c662015-08-31 10:42:13 -0700205 ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
206 fd_set* master_write_set_ptr);
207
208 // Input/output stream handlers. Success returns nullptr, failure returns
209 // a pointer to the failed FD.
210 ScopedFd* PassInput();
211 ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
212
David Pursella9320582015-08-28 18:31:29 -0700213 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800214 const std::string terminal_type_;
David Pursell57dd5ae2016-01-27 16:07:52 -0800215 bool make_pty_raw_ = false;
David Pursella9320582015-08-28 18:31:29 -0700216 SubprocessType type_;
David Pursell0955c662015-08-31 10:42:13 -0700217 SubprocessProtocol protocol_;
David Pursella9320582015-08-28 18:31:29 -0700218 pid_t pid_ = -1;
219 ScopedFd local_socket_sfd_;
220
David Pursell0955c662015-08-31 10:42:13 -0700221 // Shell protocol variables.
222 ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
223 std::unique_ptr<ShellProtocol> input_, output_;
224 size_t input_bytes_left_ = 0;
225
David Pursella9320582015-08-28 18:31:29 -0700226 DISALLOW_COPY_AND_ASSIGN(Subprocess);
227};
228
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800229Subprocess::Subprocess(const std::string& command, const char* terminal_type,
230 SubprocessType type, SubprocessProtocol protocol)
231 : command_(command),
232 terminal_type_(terminal_type ? terminal_type : ""),
233 type_(type),
234 protocol_(protocol) {
David Pursell57dd5ae2016-01-27 16:07:52 -0800235 // If we aren't using the shell protocol we must allocate a PTY to properly close the
236 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
237 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
238 // e.g. screenrecord, will never notice the broken pipe and terminate.
239 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
240 // with select() and will send SIGHUP manually to the child process.
241 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
242 // Disable PTY input/output processing since the client is expecting raw data.
243 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
244 type_ = SubprocessType::kPty;
245 make_pty_raw_ = true;
246 }
David Pursella9320582015-08-28 18:31:29 -0700247}
248
249Subprocess::~Subprocess() {
Josh Gaoc65fae92016-01-19 16:21:17 -0800250 WaitForExit();
David Pursella9320582015-08-28 18:31:29 -0700251}
252
253bool Subprocess::ForkAndExec() {
David Pursell0955c662015-08-31 10:42:13 -0700254 ScopedFd child_stdinout_sfd, child_stderr_sfd;
255 ScopedFd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700256 char pts_name[PATH_MAX];
257
Rubin Xud61a25c2016-01-11 10:23:47 +0000258 if (command_.empty()) {
259 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
260 } else {
261 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
262 }
263
Josh Gao9b3fd672015-12-11 10:52:55 -0800264 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
265 // use threads, logging directly from the child might deadlock due to locks held in another
266 // thread during the fork.
David Pursella9320582015-08-28 18:31:29 -0700267 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
268 LOG(ERROR) << "failed to create pipe for subprocess error reporting";
269 }
270
Josh Gao9b3fd672015-12-11 10:52:55 -0800271 // Construct the environment for the child before we fork.
272 passwd* pw = getpwuid(getuid());
273 std::unordered_map<std::string, std::string> env;
Josh Gaoe03c9882015-12-11 15:49:12 -0800274 if (environ) {
275 char** current = environ;
276 while (char* env_cstr = *current++) {
277 std::string env_string = env_cstr;
278 char* delimiter = strchr(env_string.c_str(), '=');
Josh Gao9b3fd672015-12-11 10:52:55 -0800279
Josh Gaoe03c9882015-12-11 15:49:12 -0800280 // Drop any values that don't contain '='.
281 if (delimiter) {
282 *delimiter++ = '\0';
283 env[env_string.c_str()] = delimiter;
284 }
285 }
Josh Gao9b3fd672015-12-11 10:52:55 -0800286 }
287
288 if (pw != nullptr) {
289 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
290 env["HOME"] = pw->pw_dir;
291 env["LOGNAME"] = pw->pw_name;
292 env["USER"] = pw->pw_name;
293 env["SHELL"] = pw->pw_shell;
294 }
295
296 if (!terminal_type_.empty()) {
297 env["TERM"] = terminal_type_;
298 }
299
300 std::vector<std::string> joined_env;
301 for (auto it : env) {
302 const char* key = it.first.c_str();
303 const char* value = it.second.c_str();
304 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
305 }
306
307 std::vector<const char*> cenv;
308 for (const std::string& str : joined_env) {
309 cenv.push_back(str.c_str());
310 }
311 cenv.push_back(nullptr);
312
David Pursella9320582015-08-28 18:31:29 -0700313 if (type_ == SubprocessType::kPty) {
314 int fd;
315 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700316 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700317 } else {
David Pursell0955c662015-08-31 10:42:13 -0700318 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
319 return false;
320 }
321 // Raw subprocess + shell protocol allows for splitting stderr.
322 if (protocol_ == SubprocessProtocol::kShell &&
323 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
David Pursella9320582015-08-28 18:31:29 -0700324 return false;
325 }
326 pid_ = fork();
327 }
328
329 if (pid_ == -1) {
330 PLOG(ERROR) << "fork failed";
331 return false;
332 }
333
334 if (pid_ == 0) {
335 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700336 init_subproc_child();
337
David Pursella9320582015-08-28 18:31:29 -0700338 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700339 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700340 }
341
David Pursell0955c662015-08-31 10:42:13 -0700342 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
343 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
344 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
345 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700346
347 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700348 stdinout_sfd_.Reset();
349 stderr_sfd_.Reset();
350 child_stdinout_sfd.Reset();
351 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700352 parent_error_sfd.Reset();
353 close_on_exec(child_error_sfd.fd());
354
Josh Gaob5028e42016-01-19 17:31:09 -0800355 if (command_.empty()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800356 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700357 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800358 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700359 }
360 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed");
361 child_error_sfd.Reset();
Josh Gao9b3fd672015-12-11 10:52:55 -0800362 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700363 }
364
365 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700366 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
367 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700368
369 // Wait to make sure the subprocess exec'd without error.
370 child_error_sfd.Reset();
371 std::string error_message = ReadAll(parent_error_sfd.fd());
372 if (!error_message.empty()) {
373 LOG(ERROR) << error_message;
374 return false;
375 }
376
Josh Gao9b3fd672015-12-11 10:52:55 -0800377 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700378 if (protocol_ == SubprocessProtocol::kNone) {
379 // No protocol: all streams pass through the stdinout FD and hook
380 // directly into the local socket for raw data transfer.
381 local_socket_sfd_.Reset(stdinout_sfd_.Release());
382 } else {
383 // Shell protocol: create another socketpair to intercept data.
384 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
385 return false;
386 }
387 D("protocol FD = %d", protocol_sfd_.fd());
388
389 input_.reset(new ShellProtocol(protocol_sfd_.fd()));
390 output_.reset(new ShellProtocol(protocol_sfd_.fd()));
391 if (!input_ || !output_) {
392 LOG(ERROR) << "failed to allocate shell protocol objects";
393 return false;
394 }
395
396 // Don't let reads/writes to the subprocess block our thread. This isn't
397 // likely but could happen under unusual circumstances, such as if we
398 // write a ton of data to stdin but the subprocess never reads it and
399 // the pipe fills up.
400 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
401 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700402 if (!set_file_block_mode(fd, false)) {
403 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
David Pursell0955c662015-08-31 10:42:13 -0700404 return false;
405 }
406 }
407 }
408 }
David Pursella9320582015-08-28 18:31:29 -0700409
410 if (!adb_thread_create(ThreadHandler, this)) {
411 PLOG(ERROR) << "failed to create subprocess thread";
412 return false;
413 }
414
Josh Gao9b3fd672015-12-11 10:52:55 -0800415 D("subprocess parent: completed");
David Pursella9320582015-08-28 18:31:29 -0700416 return true;
417}
418
419int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
420 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
421 if (child_fd == -1) {
422 // Don't use WriteFdFmt; since we're in the fork() child we don't want
423 // to allocate any heap memory to avoid race conditions.
424 const char* messages[] = {"child failed to open pseudo-term slave ",
425 pts_name, ": ", strerror(errno)};
426 for (const char* message : messages) {
427 WriteFdExactly(error_sfd->fd(), message);
428 }
429 exit(-1);
430 }
431
David Pursell57dd5ae2016-01-27 16:07:52 -0800432 if (make_pty_raw_) {
433 termios tattr;
434 if (tcgetattr(child_fd, &tattr) == -1) {
435 int saved_errno = errno;
436 WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
437 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
438 exit(-1);
439 }
440
441 cfmakeraw(&tattr);
442 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
443 int saved_errno = errno;
444 WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
445 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
446 exit(-1);
447 }
448 }
449
David Pursella9320582015-08-28 18:31:29 -0700450 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700451}
452
David Pursella9320582015-08-28 18:31:29 -0700453void* Subprocess::ThreadHandler(void* userdata) {
454 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700455
David Pursella9320582015-08-28 18:31:29 -0700456 adb_thread_setname(android::base::StringPrintf(
457 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700458
David Pursell0955c662015-08-31 10:42:13 -0700459 subprocess->PassDataStreams();
David Pursell80f67022015-08-28 15:08:49 -0700460
David Pursell1ed57f02015-10-06 15:30:03 -0700461 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700462 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700463
David Pursella9320582015-08-28 18:31:29 -0700464 return nullptr;
David Pursell80f67022015-08-28 15:08:49 -0700465}
466
David Pursell0955c662015-08-31 10:42:13 -0700467void Subprocess::PassDataStreams() {
468 if (!protocol_sfd_.valid()) {
469 return;
470 }
471
472 // Start by trying to read from the protocol FD, stdout, and stderr.
473 fd_set master_read_set, master_write_set;
474 FD_ZERO(&master_read_set);
475 FD_ZERO(&master_write_set);
476 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
477 if (sfd->valid()) {
478 FD_SET(sfd->fd(), &master_read_set);
479 }
480 }
481
482 // Pass data until the protocol FD or both the subprocess pipes die, at
483 // which point we can't pass any more data.
484 while (protocol_sfd_.valid() &&
485 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
486 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
487 if (dead_sfd) {
488 D("closing FD %d", dead_sfd->fd());
489 FD_CLR(dead_sfd->fd(), &master_read_set);
490 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700491 if (dead_sfd == &protocol_sfd_) {
492 // Using SIGHUP is a decent general way to indicate that the
493 // controlling process is going away. If specific signals are
494 // needed (e.g. SIGINT), pass those through the shell protocol
495 // and only fall back on this for unexpected closures.
496 D("protocol FD died, sending SIGHUP to pid %d", pid_);
497 kill(pid_, SIGHUP);
498 }
David Pursell0955c662015-08-31 10:42:13 -0700499 dead_sfd->Reset();
500 }
501 }
502}
503
504namespace {
505
506inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
507 return sfd.valid() && FD_ISSET(sfd.fd(), set);
508}
509
510} // namespace
511
512ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
513 fd_set* master_write_set_ptr) {
514 fd_set read_set, write_set;
515 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
516 stderr_sfd_.fd()) + 1;
517 ScopedFd* dead_sfd = nullptr;
518
519 // Keep calling select() and passing data until an FD closes/errors.
520 while (!dead_sfd) {
521 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
522 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
523 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
524 if (errno == EINTR) {
525 continue;
526 } else {
527 PLOG(ERROR) << "select failed, closing subprocess pipes";
528 stdinout_sfd_.Reset();
529 stderr_sfd_.Reset();
530 return nullptr;
531 }
532 }
533
534 // Read stdout, write to protocol FD.
535 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
536 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
537 }
538
539 // Read stderr, write to protocol FD.
540 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
541 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
542 }
543
544 // Read protocol FD, write to stdin.
545 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
546 dead_sfd = PassInput();
547 // If we didn't finish writing, block on stdin write.
548 if (input_bytes_left_) {
549 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
550 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
551 }
552 }
553
554 // Continue writing to stdin; only happens if a previous write blocked.
555 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
556 dead_sfd = PassInput();
557 // If we finished writing, go back to blocking on protocol read.
558 if (!input_bytes_left_) {
559 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
560 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
561 }
562 }
563 } // while (!dead_sfd)
564
565 return dead_sfd;
566}
567
568ScopedFd* Subprocess::PassInput() {
569 // Only read a new packet if we've finished writing the last one.
570 if (!input_bytes_left_) {
571 if (!input_->Read()) {
572 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
573 if (errno != 0) {
574 PLOG(ERROR) << "error reading protocol FD "
575 << protocol_sfd_.fd();
576 }
577 return &protocol_sfd_;
578 }
579
David Pursell1ed57f02015-10-06 15:30:03 -0700580 if (stdinout_sfd_.valid()) {
581 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800582 case ShellProtocol::kIdWindowSizeChange:
583 int rows, cols, x_pixels, y_pixels;
584 if (sscanf(input_->data(), "%dx%d,%dx%d",
585 &rows, &cols, &x_pixels, &y_pixels) == 4) {
586 winsize ws;
587 ws.ws_row = rows;
588 ws.ws_col = cols;
589 ws.ws_xpixel = x_pixels;
590 ws.ws_ypixel = y_pixels;
591 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
592 }
593 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700594 case ShellProtocol::kIdStdin:
595 input_bytes_left_ = input_->data_length();
596 break;
597 case ShellProtocol::kIdCloseStdin:
598 if (type_ == SubprocessType::kRaw) {
599 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
600 return nullptr;
601 }
602 PLOG(ERROR) << "failed to shutdown writes to FD "
603 << stdinout_sfd_.fd();
604 return &stdinout_sfd_;
605 } else {
606 // PTYs can't close just input, so rather than close the
607 // FD and risk losing subprocess output, leave it open.
608 // This only happens if the client starts a PTY shell
609 // non-interactively which is rare and unsupported.
610 // If necessary, the client can manually close the shell
611 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800612 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700613 }
614 break;
615 }
David Pursell0955c662015-08-31 10:42:13 -0700616 }
617 }
618
619 if (input_bytes_left_ > 0) {
620 int index = input_->data_length() - input_bytes_left_;
621 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
622 input_bytes_left_);
623 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
624 if (bytes < 0) {
625 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
626 }
627 // stdin is done, mark this packet as finished and we'll just start
628 // dumping any further data received from the protocol FD.
629 input_bytes_left_ = 0;
630 return &stdinout_sfd_;
631 } else if (bytes > 0) {
632 input_bytes_left_ -= bytes;
633 }
634 }
635
636 return nullptr;
637}
638
639ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
640 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
641 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700642 // read() returns EIO if a PTY closes; don't report this as an error,
643 // it just means the subprocess completed.
644 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700645 PLOG(ERROR) << "error reading output FD " << sfd->fd();
646 }
647 return sfd;
648 }
649
650 if (bytes > 0 && !output_->Write(id, bytes)) {
651 if (errno != 0) {
652 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
653 }
654 return &protocol_sfd_;
655 }
656
657 return nullptr;
658}
659
David Pursella9320582015-08-28 18:31:29 -0700660void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700661 int exit_code = 1;
662
David Pursella9320582015-08-28 18:31:29 -0700663 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700664 while (true) {
665 int status;
David Pursella9320582015-08-28 18:31:29 -0700666 if (pid_ == waitpid(pid_, &status, 0)) {
667 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700668 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700669 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700670 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700671 break;
672 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700673 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700674 break;
675 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700676 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700677 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700678 break;
679 }
David Pursella9320582015-08-28 18:31:29 -0700680 }
David Pursell80f67022015-08-28 15:08:49 -0700681 }
David Pursella9320582015-08-28 18:31:29 -0700682
David Pursell0955c662015-08-31 10:42:13 -0700683 // If we have an open protocol FD send an exit packet.
684 if (protocol_sfd_.valid()) {
685 output_->data()[0] = exit_code;
686 if (output_->Write(ShellProtocol::kIdExit, 1)) {
687 D("wrote the exit code packet: %d", exit_code);
688 } else {
689 PLOG(ERROR) << "failed to write the exit code packet";
690 }
691 protocol_sfd_.Reset();
692 }
693
David Pursella9320582015-08-28 18:31:29 -0700694 // Pass the local socket FD to the shell cleanup fdevent.
695 if (SHELL_EXIT_NOTIFY_FD >= 0) {
696 int fd = local_socket_sfd_.fd();
697 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
698 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
699 fd, SHELL_EXIT_NOTIFY_FD, pid_);
700 // The shell exit fdevent now owns the FD and will close it once
701 // the last bit of data flushes through.
702 local_socket_sfd_.Release();
703 } else {
704 PLOG(ERROR) << "failed to write fd " << fd
705 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
706 << ") for pid " << pid_;
707 }
David Pursell80f67022015-08-28 15:08:49 -0700708 }
709}
710
711} // namespace
712
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800713int StartSubprocess(const char* name, const char* terminal_type,
714 SubprocessType type, SubprocessProtocol protocol) {
715 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700716 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800717 protocol == SubprocessProtocol::kNone ? "none" : "shell",
718 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700719
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800720 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700721 if (!subprocess) {
722 LOG(ERROR) << "failed to allocate new subprocess";
David Pursell80f67022015-08-28 15:08:49 -0700723 return -1;
724 }
725
David Pursella9320582015-08-28 18:31:29 -0700726 if (!subprocess->ForkAndExec()) {
727 LOG(ERROR) << "failed to start subprocess";
728 delete subprocess;
729 return -1;
730 }
731
732 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
733 subprocess->local_socket_fd(), subprocess->pid());
734 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700735}