blob: b9a22dc1952924ab663e63f48cb4692420eb2fd9 [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>
98
99#include "adb.h"
100#include "adb_io.h"
101#include "adb_trace.h"
Yabin Cui6dfef252015-10-06 15:10:05 -0700102#include "adb_utils.h"
David Pursell80f67022015-08-28 15:08:49 -0700103
104namespace {
105
106void init_subproc_child()
107{
108 setsid();
109
110 // Set OOM score adjustment to prevent killing
111 int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
112 if (fd >= 0) {
113 adb_write(fd, "0", 1);
114 adb_close(fd);
115 } else {
116 D("adb: unable to update oom_score_adj");
117 }
118}
119
David Pursella9320582015-08-28 18:31:29 -0700120// Reads from |fd| until close or failure.
121std::string ReadAll(int fd) {
122 char buffer[512];
123 std::string received;
124
125 while (1) {
126 int bytes = adb_read(fd, buffer, sizeof(buffer));
127 if (bytes <= 0) {
128 break;
129 }
130 received.append(buffer, bytes);
David Pursell80f67022015-08-28 15:08:49 -0700131 }
132
David Pursella9320582015-08-28 18:31:29 -0700133 return received;
134}
135
136// Helper to automatically close an FD when it goes out of scope.
137class ScopedFd {
138 public:
139 ScopedFd() {}
140 ~ScopedFd() { Reset(); }
141
142 void Reset(int fd=-1) {
143 if (fd != fd_) {
144 if (valid()) {
145 adb_close(fd_);
146 }
147 fd_ = fd;
148 }
149 }
150
151 int Release() {
152 int temp = fd_;
153 fd_ = -1;
154 return temp;
155 }
156
157 bool valid() const { return fd_ >= 0; }
158
159 int fd() const { return fd_; }
160
161 private:
162 int fd_ = -1;
163
164 DISALLOW_COPY_AND_ASSIGN(ScopedFd);
165};
166
167// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
168bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
169 int sockets[2];
170 if (adb_socketpair(sockets) < 0) {
171 PLOG(ERROR) << "cannot create socket pair";
172 return false;
173 }
174 fd1->Reset(sockets[0]);
175 fd2->Reset(sockets[1]);
176 return true;
177}
178
179class Subprocess {
180 public:
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800181 Subprocess(const std::string& command, const char* terminal_type,
182 SubprocessType type, SubprocessProtocol protocol);
David Pursella9320582015-08-28 18:31:29 -0700183 ~Subprocess();
184
185 const std::string& command() const { return command_; }
David Pursella9320582015-08-28 18:31:29 -0700186
187 int local_socket_fd() const { return local_socket_sfd_.fd(); }
188
189 pid_t pid() const { return pid_; }
190
191 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
192 // and exec's the child. Returns false on failure.
193 bool ForkAndExec();
194
195 private:
196 // Opens the file at |pts_name|.
197 int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
198
199 static void* ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700200 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700201 void WaitForExit();
202
David Pursell0955c662015-08-31 10:42:13 -0700203 ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
204 fd_set* master_write_set_ptr);
205
206 // Input/output stream handlers. Success returns nullptr, failure returns
207 // a pointer to the failed FD.
208 ScopedFd* PassInput();
209 ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
210
David Pursella9320582015-08-28 18:31:29 -0700211 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800212 const std::string terminal_type_;
David Pursell57dd5ae2016-01-27 16:07:52 -0800213 bool make_pty_raw_ = false;
David Pursella9320582015-08-28 18:31:29 -0700214 SubprocessType type_;
David Pursell0955c662015-08-31 10:42:13 -0700215 SubprocessProtocol protocol_;
David Pursella9320582015-08-28 18:31:29 -0700216 pid_t pid_ = -1;
217 ScopedFd local_socket_sfd_;
218
David Pursell0955c662015-08-31 10:42:13 -0700219 // Shell protocol variables.
220 ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
221 std::unique_ptr<ShellProtocol> input_, output_;
222 size_t input_bytes_left_ = 0;
223
David Pursella9320582015-08-28 18:31:29 -0700224 DISALLOW_COPY_AND_ASSIGN(Subprocess);
225};
226
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800227Subprocess::Subprocess(const std::string& command, const char* terminal_type,
228 SubprocessType type, SubprocessProtocol protocol)
229 : command_(command),
230 terminal_type_(terminal_type ? terminal_type : ""),
231 type_(type),
232 protocol_(protocol) {
David Pursell57dd5ae2016-01-27 16:07:52 -0800233 // If we aren't using the shell protocol we must allocate a PTY to properly close the
234 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
235 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
236 // e.g. screenrecord, will never notice the broken pipe and terminate.
237 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
238 // with select() and will send SIGHUP manually to the child process.
239 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
240 // Disable PTY input/output processing since the client is expecting raw data.
241 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
242 type_ = SubprocessType::kPty;
243 make_pty_raw_ = true;
244 }
David Pursella9320582015-08-28 18:31:29 -0700245}
246
247Subprocess::~Subprocess() {
Josh Gaoc65fae92016-01-19 16:21:17 -0800248 WaitForExit();
David Pursella9320582015-08-28 18:31:29 -0700249}
250
251bool Subprocess::ForkAndExec() {
David Pursell0955c662015-08-31 10:42:13 -0700252 ScopedFd child_stdinout_sfd, child_stderr_sfd;
253 ScopedFd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700254 char pts_name[PATH_MAX];
255
Josh Gao9b3fd672015-12-11 10:52:55 -0800256 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
257 // use threads, logging directly from the child might deadlock due to locks held in another
258 // thread during the fork.
David Pursella9320582015-08-28 18:31:29 -0700259 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
260 LOG(ERROR) << "failed to create pipe for subprocess error reporting";
261 }
262
Josh Gao9b3fd672015-12-11 10:52:55 -0800263 // Construct the environment for the child before we fork.
264 passwd* pw = getpwuid(getuid());
265 std::unordered_map<std::string, std::string> env;
Josh Gaoe03c9882015-12-11 15:49:12 -0800266 if (environ) {
267 char** current = environ;
268 while (char* env_cstr = *current++) {
269 std::string env_string = env_cstr;
270 char* delimiter = strchr(env_string.c_str(), '=');
Josh Gao9b3fd672015-12-11 10:52:55 -0800271
Josh Gaoe03c9882015-12-11 15:49:12 -0800272 // Drop any values that don't contain '='.
273 if (delimiter) {
274 *delimiter++ = '\0';
275 env[env_string.c_str()] = delimiter;
276 }
277 }
Josh Gao9b3fd672015-12-11 10:52:55 -0800278 }
279
280 if (pw != nullptr) {
281 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
282 env["HOME"] = pw->pw_dir;
283 env["LOGNAME"] = pw->pw_name;
284 env["USER"] = pw->pw_name;
285 env["SHELL"] = pw->pw_shell;
286 }
287
288 if (!terminal_type_.empty()) {
289 env["TERM"] = terminal_type_;
290 }
291
292 std::vector<std::string> joined_env;
293 for (auto it : env) {
294 const char* key = it.first.c_str();
295 const char* value = it.second.c_str();
296 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
297 }
298
299 std::vector<const char*> cenv;
300 for (const std::string& str : joined_env) {
301 cenv.push_back(str.c_str());
302 }
303 cenv.push_back(nullptr);
304
David Pursella9320582015-08-28 18:31:29 -0700305 if (type_ == SubprocessType::kPty) {
306 int fd;
307 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700308 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700309 } else {
David Pursell0955c662015-08-31 10:42:13 -0700310 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
311 return false;
312 }
313 // Raw subprocess + shell protocol allows for splitting stderr.
314 if (protocol_ == SubprocessProtocol::kShell &&
315 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
David Pursella9320582015-08-28 18:31:29 -0700316 return false;
317 }
318 pid_ = fork();
319 }
320
321 if (pid_ == -1) {
322 PLOG(ERROR) << "fork failed";
323 return false;
324 }
325
326 if (pid_ == 0) {
327 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700328 init_subproc_child();
329
David Pursella9320582015-08-28 18:31:29 -0700330 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700331 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700332 }
333
David Pursell0955c662015-08-31 10:42:13 -0700334 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
335 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
336 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
337 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700338
339 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700340 stdinout_sfd_.Reset();
341 stderr_sfd_.Reset();
342 child_stdinout_sfd.Reset();
343 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700344 parent_error_sfd.Reset();
345 close_on_exec(child_error_sfd.fd());
346
Josh Gaob5028e42016-01-19 17:31:09 -0800347 if (command_.empty()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800348 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700349 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800350 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700351 }
352 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed");
353 child_error_sfd.Reset();
Josh Gao9b3fd672015-12-11 10:52:55 -0800354 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700355 }
356
357 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700358 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
359 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700360
361 // Wait to make sure the subprocess exec'd without error.
362 child_error_sfd.Reset();
363 std::string error_message = ReadAll(parent_error_sfd.fd());
364 if (!error_message.empty()) {
365 LOG(ERROR) << error_message;
366 return false;
367 }
368
Josh Gao9b3fd672015-12-11 10:52:55 -0800369 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700370 if (protocol_ == SubprocessProtocol::kNone) {
371 // No protocol: all streams pass through the stdinout FD and hook
372 // directly into the local socket for raw data transfer.
373 local_socket_sfd_.Reset(stdinout_sfd_.Release());
374 } else {
375 // Shell protocol: create another socketpair to intercept data.
376 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
377 return false;
378 }
379 D("protocol FD = %d", protocol_sfd_.fd());
380
381 input_.reset(new ShellProtocol(protocol_sfd_.fd()));
382 output_.reset(new ShellProtocol(protocol_sfd_.fd()));
383 if (!input_ || !output_) {
384 LOG(ERROR) << "failed to allocate shell protocol objects";
385 return false;
386 }
387
388 // Don't let reads/writes to the subprocess block our thread. This isn't
389 // likely but could happen under unusual circumstances, such as if we
390 // write a ton of data to stdin but the subprocess never reads it and
391 // the pipe fills up.
392 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
393 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700394 if (!set_file_block_mode(fd, false)) {
395 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
David Pursell0955c662015-08-31 10:42:13 -0700396 return false;
397 }
398 }
399 }
400 }
David Pursella9320582015-08-28 18:31:29 -0700401
402 if (!adb_thread_create(ThreadHandler, this)) {
403 PLOG(ERROR) << "failed to create subprocess thread";
404 return false;
405 }
406
Josh Gao9b3fd672015-12-11 10:52:55 -0800407 D("subprocess parent: completed");
David Pursella9320582015-08-28 18:31:29 -0700408 return true;
409}
410
411int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
412 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
413 if (child_fd == -1) {
414 // Don't use WriteFdFmt; since we're in the fork() child we don't want
415 // to allocate any heap memory to avoid race conditions.
416 const char* messages[] = {"child failed to open pseudo-term slave ",
417 pts_name, ": ", strerror(errno)};
418 for (const char* message : messages) {
419 WriteFdExactly(error_sfd->fd(), message);
420 }
421 exit(-1);
422 }
423
David Pursell57dd5ae2016-01-27 16:07:52 -0800424 if (make_pty_raw_) {
425 termios tattr;
426 if (tcgetattr(child_fd, &tattr) == -1) {
427 int saved_errno = errno;
428 WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
429 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
430 exit(-1);
431 }
432
433 cfmakeraw(&tattr);
434 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
435 int saved_errno = errno;
436 WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
437 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
438 exit(-1);
439 }
440 }
441
David Pursella9320582015-08-28 18:31:29 -0700442 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700443}
444
David Pursella9320582015-08-28 18:31:29 -0700445void* Subprocess::ThreadHandler(void* userdata) {
446 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700447
David Pursella9320582015-08-28 18:31:29 -0700448 adb_thread_setname(android::base::StringPrintf(
449 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700450
David Pursell0955c662015-08-31 10:42:13 -0700451 subprocess->PassDataStreams();
David Pursell80f67022015-08-28 15:08:49 -0700452
David Pursell1ed57f02015-10-06 15:30:03 -0700453 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700454 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700455
David Pursella9320582015-08-28 18:31:29 -0700456 return nullptr;
David Pursell80f67022015-08-28 15:08:49 -0700457}
458
David Pursell0955c662015-08-31 10:42:13 -0700459void Subprocess::PassDataStreams() {
460 if (!protocol_sfd_.valid()) {
461 return;
462 }
463
464 // Start by trying to read from the protocol FD, stdout, and stderr.
465 fd_set master_read_set, master_write_set;
466 FD_ZERO(&master_read_set);
467 FD_ZERO(&master_write_set);
468 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
469 if (sfd->valid()) {
470 FD_SET(sfd->fd(), &master_read_set);
471 }
472 }
473
474 // Pass data until the protocol FD or both the subprocess pipes die, at
475 // which point we can't pass any more data.
476 while (protocol_sfd_.valid() &&
477 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
478 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
479 if (dead_sfd) {
480 D("closing FD %d", dead_sfd->fd());
481 FD_CLR(dead_sfd->fd(), &master_read_set);
482 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700483 if (dead_sfd == &protocol_sfd_) {
484 // Using SIGHUP is a decent general way to indicate that the
485 // controlling process is going away. If specific signals are
486 // needed (e.g. SIGINT), pass those through the shell protocol
487 // and only fall back on this for unexpected closures.
488 D("protocol FD died, sending SIGHUP to pid %d", pid_);
489 kill(pid_, SIGHUP);
490 }
David Pursell0955c662015-08-31 10:42:13 -0700491 dead_sfd->Reset();
492 }
493 }
494}
495
496namespace {
497
498inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
499 return sfd.valid() && FD_ISSET(sfd.fd(), set);
500}
501
502} // namespace
503
504ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
505 fd_set* master_write_set_ptr) {
506 fd_set read_set, write_set;
507 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
508 stderr_sfd_.fd()) + 1;
509 ScopedFd* dead_sfd = nullptr;
510
511 // Keep calling select() and passing data until an FD closes/errors.
512 while (!dead_sfd) {
513 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
514 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
515 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
516 if (errno == EINTR) {
517 continue;
518 } else {
519 PLOG(ERROR) << "select failed, closing subprocess pipes";
520 stdinout_sfd_.Reset();
521 stderr_sfd_.Reset();
522 return nullptr;
523 }
524 }
525
526 // Read stdout, write to protocol FD.
527 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
528 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
529 }
530
531 // Read stderr, write to protocol FD.
532 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
533 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
534 }
535
536 // Read protocol FD, write to stdin.
537 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
538 dead_sfd = PassInput();
539 // If we didn't finish writing, block on stdin write.
540 if (input_bytes_left_) {
541 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
542 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
543 }
544 }
545
546 // Continue writing to stdin; only happens if a previous write blocked.
547 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
548 dead_sfd = PassInput();
549 // If we finished writing, go back to blocking on protocol read.
550 if (!input_bytes_left_) {
551 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
552 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
553 }
554 }
555 } // while (!dead_sfd)
556
557 return dead_sfd;
558}
559
560ScopedFd* Subprocess::PassInput() {
561 // Only read a new packet if we've finished writing the last one.
562 if (!input_bytes_left_) {
563 if (!input_->Read()) {
564 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
565 if (errno != 0) {
566 PLOG(ERROR) << "error reading protocol FD "
567 << protocol_sfd_.fd();
568 }
569 return &protocol_sfd_;
570 }
571
David Pursell1ed57f02015-10-06 15:30:03 -0700572 if (stdinout_sfd_.valid()) {
573 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800574 case ShellProtocol::kIdWindowSizeChange:
575 int rows, cols, x_pixels, y_pixels;
576 if (sscanf(input_->data(), "%dx%d,%dx%d",
577 &rows, &cols, &x_pixels, &y_pixels) == 4) {
578 winsize ws;
579 ws.ws_row = rows;
580 ws.ws_col = cols;
581 ws.ws_xpixel = x_pixels;
582 ws.ws_ypixel = y_pixels;
583 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
584 }
585 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700586 case ShellProtocol::kIdStdin:
587 input_bytes_left_ = input_->data_length();
588 break;
589 case ShellProtocol::kIdCloseStdin:
590 if (type_ == SubprocessType::kRaw) {
591 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
592 return nullptr;
593 }
594 PLOG(ERROR) << "failed to shutdown writes to FD "
595 << stdinout_sfd_.fd();
596 return &stdinout_sfd_;
597 } else {
598 // PTYs can't close just input, so rather than close the
599 // FD and risk losing subprocess output, leave it open.
600 // This only happens if the client starts a PTY shell
601 // non-interactively which is rare and unsupported.
602 // If necessary, the client can manually close the shell
603 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800604 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700605 }
606 break;
607 }
David Pursell0955c662015-08-31 10:42:13 -0700608 }
609 }
610
611 if (input_bytes_left_ > 0) {
612 int index = input_->data_length() - input_bytes_left_;
613 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
614 input_bytes_left_);
615 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
616 if (bytes < 0) {
617 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
618 }
619 // stdin is done, mark this packet as finished and we'll just start
620 // dumping any further data received from the protocol FD.
621 input_bytes_left_ = 0;
622 return &stdinout_sfd_;
623 } else if (bytes > 0) {
624 input_bytes_left_ -= bytes;
625 }
626 }
627
628 return nullptr;
629}
630
631ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
632 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
633 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700634 // read() returns EIO if a PTY closes; don't report this as an error,
635 // it just means the subprocess completed.
636 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700637 PLOG(ERROR) << "error reading output FD " << sfd->fd();
638 }
639 return sfd;
640 }
641
642 if (bytes > 0 && !output_->Write(id, bytes)) {
643 if (errno != 0) {
644 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
645 }
646 return &protocol_sfd_;
647 }
648
649 return nullptr;
650}
651
David Pursella9320582015-08-28 18:31:29 -0700652void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700653 int exit_code = 1;
654
David Pursella9320582015-08-28 18:31:29 -0700655 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700656 while (true) {
657 int status;
David Pursella9320582015-08-28 18:31:29 -0700658 if (pid_ == waitpid(pid_, &status, 0)) {
659 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700660 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700661 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700662 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700663 break;
664 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700665 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700666 break;
667 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700668 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700669 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700670 break;
671 }
David Pursella9320582015-08-28 18:31:29 -0700672 }
David Pursell80f67022015-08-28 15:08:49 -0700673 }
David Pursella9320582015-08-28 18:31:29 -0700674
David Pursell0955c662015-08-31 10:42:13 -0700675 // If we have an open protocol FD send an exit packet.
676 if (protocol_sfd_.valid()) {
677 output_->data()[0] = exit_code;
678 if (output_->Write(ShellProtocol::kIdExit, 1)) {
679 D("wrote the exit code packet: %d", exit_code);
680 } else {
681 PLOG(ERROR) << "failed to write the exit code packet";
682 }
683 protocol_sfd_.Reset();
684 }
685
David Pursella9320582015-08-28 18:31:29 -0700686 // Pass the local socket FD to the shell cleanup fdevent.
687 if (SHELL_EXIT_NOTIFY_FD >= 0) {
688 int fd = local_socket_sfd_.fd();
689 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
690 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
691 fd, SHELL_EXIT_NOTIFY_FD, pid_);
692 // The shell exit fdevent now owns the FD and will close it once
693 // the last bit of data flushes through.
694 local_socket_sfd_.Release();
695 } else {
696 PLOG(ERROR) << "failed to write fd " << fd
697 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
698 << ") for pid " << pid_;
699 }
David Pursell80f67022015-08-28 15:08:49 -0700700 }
701}
702
703} // namespace
704
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800705int StartSubprocess(const char* name, const char* terminal_type,
706 SubprocessType type, SubprocessProtocol protocol) {
707 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700708 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800709 protocol == SubprocessProtocol::kNone ? "none" : "shell",
710 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700711
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800712 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700713 if (!subprocess) {
714 LOG(ERROR) << "failed to allocate new subprocess";
David Pursell80f67022015-08-28 15:08:49 -0700715 return -1;
716 }
717
David Pursella9320582015-08-28 18:31:29 -0700718 if (!subprocess->ForkAndExec()) {
719 LOG(ERROR) << "failed to start subprocess";
720 delete subprocess;
721 return -1;
722 }
723
724 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
725 subprocess->local_socket_fd(), subprocess->pid());
726 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700727}