blob: 366ed074a7c479919567237e3f62248e8c975aa8 [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_; }
186 bool is_interactive() const { return command_.empty(); }
187
188 int local_socket_fd() const { return local_socket_sfd_.fd(); }
189
190 pid_t pid() const { return pid_; }
191
192 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
193 // and exec's the child. Returns false on failure.
194 bool ForkAndExec();
195
196 private:
197 // Opens the file at |pts_name|.
198 int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
199
200 static void* ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700201 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700202 void WaitForExit();
203
David Pursell0955c662015-08-31 10:42:13 -0700204 ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
205 fd_set* master_write_set_ptr);
206
207 // Input/output stream handlers. Success returns nullptr, failure returns
208 // a pointer to the failed FD.
209 ScopedFd* PassInput();
210 ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
211
David Pursella9320582015-08-28 18:31:29 -0700212 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800213 const std::string terminal_type_;
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 Pursella9320582015-08-28 18:31:29 -0700233}
234
235Subprocess::~Subprocess() {
236}
237
238bool Subprocess::ForkAndExec() {
David Pursell0955c662015-08-31 10:42:13 -0700239 ScopedFd child_stdinout_sfd, child_stderr_sfd;
240 ScopedFd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700241 char pts_name[PATH_MAX];
242
Josh Gao9b3fd672015-12-11 10:52:55 -0800243 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
244 // use threads, logging directly from the child might deadlock due to locks held in another
245 // thread during the fork.
David Pursella9320582015-08-28 18:31:29 -0700246 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
247 LOG(ERROR) << "failed to create pipe for subprocess error reporting";
248 }
249
Josh Gao9b3fd672015-12-11 10:52:55 -0800250 // Construct the environment for the child before we fork.
251 passwd* pw = getpwuid(getuid());
252 std::unordered_map<std::string, std::string> env;
Josh Gaoe03c9882015-12-11 15:49:12 -0800253 if (environ) {
254 char** current = environ;
255 while (char* env_cstr = *current++) {
256 std::string env_string = env_cstr;
257 char* delimiter = strchr(env_string.c_str(), '=');
Josh Gao9b3fd672015-12-11 10:52:55 -0800258
Josh Gaoe03c9882015-12-11 15:49:12 -0800259 // Drop any values that don't contain '='.
260 if (delimiter) {
261 *delimiter++ = '\0';
262 env[env_string.c_str()] = delimiter;
263 }
264 }
Josh Gao9b3fd672015-12-11 10:52:55 -0800265 }
266
267 if (pw != nullptr) {
268 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
269 env["HOME"] = pw->pw_dir;
270 env["LOGNAME"] = pw->pw_name;
271 env["USER"] = pw->pw_name;
272 env["SHELL"] = pw->pw_shell;
273 }
274
275 if (!terminal_type_.empty()) {
276 env["TERM"] = terminal_type_;
277 }
278
279 std::vector<std::string> joined_env;
280 for (auto it : env) {
281 const char* key = it.first.c_str();
282 const char* value = it.second.c_str();
283 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
284 }
285
286 std::vector<const char*> cenv;
287 for (const std::string& str : joined_env) {
288 cenv.push_back(str.c_str());
289 }
290 cenv.push_back(nullptr);
291
David Pursella9320582015-08-28 18:31:29 -0700292 if (type_ == SubprocessType::kPty) {
293 int fd;
294 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700295 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700296 } else {
David Pursell0955c662015-08-31 10:42:13 -0700297 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
298 return false;
299 }
300 // Raw subprocess + shell protocol allows for splitting stderr.
301 if (protocol_ == SubprocessProtocol::kShell &&
302 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
David Pursella9320582015-08-28 18:31:29 -0700303 return false;
304 }
305 pid_ = fork();
306 }
307
308 if (pid_ == -1) {
309 PLOG(ERROR) << "fork failed";
310 return false;
311 }
312
313 if (pid_ == 0) {
314 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700315 init_subproc_child();
316
David Pursella9320582015-08-28 18:31:29 -0700317 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700318 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700319 }
320
David Pursell0955c662015-08-31 10:42:13 -0700321 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
322 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
323 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
324 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700325
326 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700327 stdinout_sfd_.Reset();
328 stderr_sfd_.Reset();
329 child_stdinout_sfd.Reset();
330 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700331 parent_error_sfd.Reset();
332 close_on_exec(child_error_sfd.fd());
333
334 if (is_interactive()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800335 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700336 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800337 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700338 }
339 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed");
340 child_error_sfd.Reset();
Josh Gao9b3fd672015-12-11 10:52:55 -0800341 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700342 }
343
344 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700345 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
346 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700347
348 // Wait to make sure the subprocess exec'd without error.
349 child_error_sfd.Reset();
350 std::string error_message = ReadAll(parent_error_sfd.fd());
351 if (!error_message.empty()) {
352 LOG(ERROR) << error_message;
353 return false;
354 }
355
Josh Gao9b3fd672015-12-11 10:52:55 -0800356 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700357 if (protocol_ == SubprocessProtocol::kNone) {
358 // No protocol: all streams pass through the stdinout FD and hook
359 // directly into the local socket for raw data transfer.
360 local_socket_sfd_.Reset(stdinout_sfd_.Release());
361 } else {
362 // Shell protocol: create another socketpair to intercept data.
363 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
364 return false;
365 }
366 D("protocol FD = %d", protocol_sfd_.fd());
367
368 input_.reset(new ShellProtocol(protocol_sfd_.fd()));
369 output_.reset(new ShellProtocol(protocol_sfd_.fd()));
370 if (!input_ || !output_) {
371 LOG(ERROR) << "failed to allocate shell protocol objects";
372 return false;
373 }
374
375 // Don't let reads/writes to the subprocess block our thread. This isn't
376 // likely but could happen under unusual circumstances, such as if we
377 // write a ton of data to stdin but the subprocess never reads it and
378 // the pipe fills up.
379 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
380 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700381 if (!set_file_block_mode(fd, false)) {
382 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
David Pursell0955c662015-08-31 10:42:13 -0700383 return false;
384 }
385 }
386 }
387 }
David Pursella9320582015-08-28 18:31:29 -0700388
389 if (!adb_thread_create(ThreadHandler, this)) {
390 PLOG(ERROR) << "failed to create subprocess thread";
391 return false;
392 }
393
Josh Gao9b3fd672015-12-11 10:52:55 -0800394 D("subprocess parent: completed");
David Pursella9320582015-08-28 18:31:29 -0700395 return true;
396}
397
398int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
399 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
400 if (child_fd == -1) {
401 // Don't use WriteFdFmt; since we're in the fork() child we don't want
402 // to allocate any heap memory to avoid race conditions.
403 const char* messages[] = {"child failed to open pseudo-term slave ",
404 pts_name, ": ", strerror(errno)};
405 for (const char* message : messages) {
406 WriteFdExactly(error_sfd->fd(), message);
407 }
408 exit(-1);
409 }
410
411 if (!is_interactive()) {
412 termios tattr;
413 if (tcgetattr(child_fd, &tattr) == -1) {
414 WriteFdExactly(error_sfd->fd(), "tcgetattr failed");
David Pursell80f67022015-08-28 15:08:49 -0700415 exit(-1);
416 }
417
David Pursella9320582015-08-28 18:31:29 -0700418 cfmakeraw(&tattr);
419 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
420 WriteFdExactly(error_sfd->fd(), "tcsetattr failed");
421 exit(-1);
David Pursell80f67022015-08-28 15:08:49 -0700422 }
David Pursell80f67022015-08-28 15:08:49 -0700423 }
David Pursella9320582015-08-28 18:31:29 -0700424
425 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700426}
427
David Pursella9320582015-08-28 18:31:29 -0700428void* Subprocess::ThreadHandler(void* userdata) {
429 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700430
David Pursella9320582015-08-28 18:31:29 -0700431 adb_thread_setname(android::base::StringPrintf(
432 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700433
David Pursell0955c662015-08-31 10:42:13 -0700434 subprocess->PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700435 subprocess->WaitForExit();
David Pursell80f67022015-08-28 15:08:49 -0700436
David Pursell1ed57f02015-10-06 15:30:03 -0700437 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700438 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700439
David Pursella9320582015-08-28 18:31:29 -0700440 return nullptr;
David Pursell80f67022015-08-28 15:08:49 -0700441}
442
David Pursell0955c662015-08-31 10:42:13 -0700443void Subprocess::PassDataStreams() {
444 if (!protocol_sfd_.valid()) {
445 return;
446 }
447
448 // Start by trying to read from the protocol FD, stdout, and stderr.
449 fd_set master_read_set, master_write_set;
450 FD_ZERO(&master_read_set);
451 FD_ZERO(&master_write_set);
452 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
453 if (sfd->valid()) {
454 FD_SET(sfd->fd(), &master_read_set);
455 }
456 }
457
458 // Pass data until the protocol FD or both the subprocess pipes die, at
459 // which point we can't pass any more data.
460 while (protocol_sfd_.valid() &&
461 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
462 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
463 if (dead_sfd) {
464 D("closing FD %d", dead_sfd->fd());
465 FD_CLR(dead_sfd->fd(), &master_read_set);
466 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700467 if (dead_sfd == &protocol_sfd_) {
468 // Using SIGHUP is a decent general way to indicate that the
469 // controlling process is going away. If specific signals are
470 // needed (e.g. SIGINT), pass those through the shell protocol
471 // and only fall back on this for unexpected closures.
472 D("protocol FD died, sending SIGHUP to pid %d", pid_);
473 kill(pid_, SIGHUP);
474 }
David Pursell0955c662015-08-31 10:42:13 -0700475 dead_sfd->Reset();
476 }
477 }
478}
479
480namespace {
481
482inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
483 return sfd.valid() && FD_ISSET(sfd.fd(), set);
484}
485
486} // namespace
487
488ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
489 fd_set* master_write_set_ptr) {
490 fd_set read_set, write_set;
491 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
492 stderr_sfd_.fd()) + 1;
493 ScopedFd* dead_sfd = nullptr;
494
495 // Keep calling select() and passing data until an FD closes/errors.
496 while (!dead_sfd) {
497 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
498 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
499 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
500 if (errno == EINTR) {
501 continue;
502 } else {
503 PLOG(ERROR) << "select failed, closing subprocess pipes";
504 stdinout_sfd_.Reset();
505 stderr_sfd_.Reset();
506 return nullptr;
507 }
508 }
509
510 // Read stdout, write to protocol FD.
511 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
512 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
513 }
514
515 // Read stderr, write to protocol FD.
516 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
517 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
518 }
519
520 // Read protocol FD, write to stdin.
521 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
522 dead_sfd = PassInput();
523 // If we didn't finish writing, block on stdin write.
524 if (input_bytes_left_) {
525 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
526 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
527 }
528 }
529
530 // Continue writing to stdin; only happens if a previous write blocked.
531 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
532 dead_sfd = PassInput();
533 // If we finished writing, go back to blocking on protocol read.
534 if (!input_bytes_left_) {
535 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
536 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
537 }
538 }
539 } // while (!dead_sfd)
540
541 return dead_sfd;
542}
543
544ScopedFd* Subprocess::PassInput() {
545 // Only read a new packet if we've finished writing the last one.
546 if (!input_bytes_left_) {
547 if (!input_->Read()) {
548 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
549 if (errno != 0) {
550 PLOG(ERROR) << "error reading protocol FD "
551 << protocol_sfd_.fd();
552 }
553 return &protocol_sfd_;
554 }
555
David Pursell1ed57f02015-10-06 15:30:03 -0700556 if (stdinout_sfd_.valid()) {
557 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800558 case ShellProtocol::kIdWindowSizeChange:
559 int rows, cols, x_pixels, y_pixels;
560 if (sscanf(input_->data(), "%dx%d,%dx%d",
561 &rows, &cols, &x_pixels, &y_pixels) == 4) {
562 winsize ws;
563 ws.ws_row = rows;
564 ws.ws_col = cols;
565 ws.ws_xpixel = x_pixels;
566 ws.ws_ypixel = y_pixels;
567 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
568 }
569 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700570 case ShellProtocol::kIdStdin:
571 input_bytes_left_ = input_->data_length();
572 break;
573 case ShellProtocol::kIdCloseStdin:
574 if (type_ == SubprocessType::kRaw) {
575 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
576 return nullptr;
577 }
578 PLOG(ERROR) << "failed to shutdown writes to FD "
579 << stdinout_sfd_.fd();
580 return &stdinout_sfd_;
581 } else {
582 // PTYs can't close just input, so rather than close the
583 // FD and risk losing subprocess output, leave it open.
584 // This only happens if the client starts a PTY shell
585 // non-interactively which is rare and unsupported.
586 // If necessary, the client can manually close the shell
587 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800588 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700589 }
590 break;
591 }
David Pursell0955c662015-08-31 10:42:13 -0700592 }
593 }
594
595 if (input_bytes_left_ > 0) {
596 int index = input_->data_length() - input_bytes_left_;
597 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
598 input_bytes_left_);
599 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
600 if (bytes < 0) {
601 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
602 }
603 // stdin is done, mark this packet as finished and we'll just start
604 // dumping any further data received from the protocol FD.
605 input_bytes_left_ = 0;
606 return &stdinout_sfd_;
607 } else if (bytes > 0) {
608 input_bytes_left_ -= bytes;
609 }
610 }
611
612 return nullptr;
613}
614
615ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
616 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
617 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700618 // read() returns EIO if a PTY closes; don't report this as an error,
619 // it just means the subprocess completed.
620 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700621 PLOG(ERROR) << "error reading output FD " << sfd->fd();
622 }
623 return sfd;
624 }
625
626 if (bytes > 0 && !output_->Write(id, bytes)) {
627 if (errno != 0) {
628 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
629 }
630 return &protocol_sfd_;
631 }
632
633 return nullptr;
634}
635
David Pursella9320582015-08-28 18:31:29 -0700636void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700637 int exit_code = 1;
638
David Pursella9320582015-08-28 18:31:29 -0700639 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700640 while (true) {
641 int status;
David Pursella9320582015-08-28 18:31:29 -0700642 if (pid_ == waitpid(pid_, &status, 0)) {
643 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700644 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700645 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700646 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700647 break;
648 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700649 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700650 break;
651 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700652 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700653 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700654 break;
655 }
David Pursella9320582015-08-28 18:31:29 -0700656 }
David Pursell80f67022015-08-28 15:08:49 -0700657 }
David Pursella9320582015-08-28 18:31:29 -0700658
David Pursell0955c662015-08-31 10:42:13 -0700659 // If we have an open protocol FD send an exit packet.
660 if (protocol_sfd_.valid()) {
661 output_->data()[0] = exit_code;
662 if (output_->Write(ShellProtocol::kIdExit, 1)) {
663 D("wrote the exit code packet: %d", exit_code);
664 } else {
665 PLOG(ERROR) << "failed to write the exit code packet";
666 }
667 protocol_sfd_.Reset();
668 }
669
David Pursella9320582015-08-28 18:31:29 -0700670 // Pass the local socket FD to the shell cleanup fdevent.
671 if (SHELL_EXIT_NOTIFY_FD >= 0) {
672 int fd = local_socket_sfd_.fd();
673 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
674 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
675 fd, SHELL_EXIT_NOTIFY_FD, pid_);
676 // The shell exit fdevent now owns the FD and will close it once
677 // the last bit of data flushes through.
678 local_socket_sfd_.Release();
679 } else {
680 PLOG(ERROR) << "failed to write fd " << fd
681 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
682 << ") for pid " << pid_;
683 }
David Pursell80f67022015-08-28 15:08:49 -0700684 }
685}
686
687} // namespace
688
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800689int StartSubprocess(const char* name, const char* terminal_type,
690 SubprocessType type, SubprocessProtocol protocol) {
691 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700692 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800693 protocol == SubprocessProtocol::kNone ? "none" : "shell",
694 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700695
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800696 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700697 if (!subprocess) {
698 LOG(ERROR) << "failed to allocate new subprocess";
David Pursell80f67022015-08-28 15:08:49 -0700699 return -1;
700 }
701
David Pursella9320582015-08-28 18:31:29 -0700702 if (!subprocess->ForkAndExec()) {
703 LOG(ERROR) << "failed to start subprocess";
704 delete subprocess;
705 return -1;
706 }
707
708 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
709 subprocess->local_socket_fd(), subprocess->pid());
710 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700711}