blob: 0f893788b22344393d0e425f8dbeb43156ffb572 [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;
253
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(), '=');
258 *delimiter++ = '\0';
259 env[env_string.c_str()] = delimiter;
260 }
261
262 if (pw != nullptr) {
263 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
264 env["HOME"] = pw->pw_dir;
265 env["LOGNAME"] = pw->pw_name;
266 env["USER"] = pw->pw_name;
267 env["SHELL"] = pw->pw_shell;
268 }
269
270 if (!terminal_type_.empty()) {
271 env["TERM"] = terminal_type_;
272 }
273
274 std::vector<std::string> joined_env;
275 for (auto it : env) {
276 const char* key = it.first.c_str();
277 const char* value = it.second.c_str();
278 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
279 }
280
281 std::vector<const char*> cenv;
282 for (const std::string& str : joined_env) {
283 cenv.push_back(str.c_str());
284 }
285 cenv.push_back(nullptr);
286
David Pursella9320582015-08-28 18:31:29 -0700287 if (type_ == SubprocessType::kPty) {
288 int fd;
289 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700290 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700291 } else {
David Pursell0955c662015-08-31 10:42:13 -0700292 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
293 return false;
294 }
295 // Raw subprocess + shell protocol allows for splitting stderr.
296 if (protocol_ == SubprocessProtocol::kShell &&
297 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
David Pursella9320582015-08-28 18:31:29 -0700298 return false;
299 }
300 pid_ = fork();
301 }
302
303 if (pid_ == -1) {
304 PLOG(ERROR) << "fork failed";
305 return false;
306 }
307
308 if (pid_ == 0) {
309 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700310 init_subproc_child();
311
David Pursella9320582015-08-28 18:31:29 -0700312 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700313 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700314 }
315
David Pursell0955c662015-08-31 10:42:13 -0700316 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
317 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
318 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
319 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700320
321 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700322 stdinout_sfd_.Reset();
323 stderr_sfd_.Reset();
324 child_stdinout_sfd.Reset();
325 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700326 parent_error_sfd.Reset();
327 close_on_exec(child_error_sfd.fd());
328
329 if (is_interactive()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800330 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700331 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800332 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700333 }
334 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed");
335 child_error_sfd.Reset();
Josh Gao9b3fd672015-12-11 10:52:55 -0800336 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700337 }
338
339 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700340 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
341 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700342
343 // Wait to make sure the subprocess exec'd without error.
344 child_error_sfd.Reset();
345 std::string error_message = ReadAll(parent_error_sfd.fd());
346 if (!error_message.empty()) {
347 LOG(ERROR) << error_message;
348 return false;
349 }
350
Josh Gao9b3fd672015-12-11 10:52:55 -0800351 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700352 if (protocol_ == SubprocessProtocol::kNone) {
353 // No protocol: all streams pass through the stdinout FD and hook
354 // directly into the local socket for raw data transfer.
355 local_socket_sfd_.Reset(stdinout_sfd_.Release());
356 } else {
357 // Shell protocol: create another socketpair to intercept data.
358 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
359 return false;
360 }
361 D("protocol FD = %d", protocol_sfd_.fd());
362
363 input_.reset(new ShellProtocol(protocol_sfd_.fd()));
364 output_.reset(new ShellProtocol(protocol_sfd_.fd()));
365 if (!input_ || !output_) {
366 LOG(ERROR) << "failed to allocate shell protocol objects";
367 return false;
368 }
369
370 // Don't let reads/writes to the subprocess block our thread. This isn't
371 // likely but could happen under unusual circumstances, such as if we
372 // write a ton of data to stdin but the subprocess never reads it and
373 // the pipe fills up.
374 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
375 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700376 if (!set_file_block_mode(fd, false)) {
377 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
David Pursell0955c662015-08-31 10:42:13 -0700378 return false;
379 }
380 }
381 }
382 }
David Pursella9320582015-08-28 18:31:29 -0700383
384 if (!adb_thread_create(ThreadHandler, this)) {
385 PLOG(ERROR) << "failed to create subprocess thread";
386 return false;
387 }
388
Josh Gao9b3fd672015-12-11 10:52:55 -0800389 D("subprocess parent: completed");
David Pursella9320582015-08-28 18:31:29 -0700390 return true;
391}
392
393int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
394 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
395 if (child_fd == -1) {
396 // Don't use WriteFdFmt; since we're in the fork() child we don't want
397 // to allocate any heap memory to avoid race conditions.
398 const char* messages[] = {"child failed to open pseudo-term slave ",
399 pts_name, ": ", strerror(errno)};
400 for (const char* message : messages) {
401 WriteFdExactly(error_sfd->fd(), message);
402 }
403 exit(-1);
404 }
405
406 if (!is_interactive()) {
407 termios tattr;
408 if (tcgetattr(child_fd, &tattr) == -1) {
409 WriteFdExactly(error_sfd->fd(), "tcgetattr failed");
David Pursell80f67022015-08-28 15:08:49 -0700410 exit(-1);
411 }
412
David Pursella9320582015-08-28 18:31:29 -0700413 cfmakeraw(&tattr);
414 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
415 WriteFdExactly(error_sfd->fd(), "tcsetattr failed");
416 exit(-1);
David Pursell80f67022015-08-28 15:08:49 -0700417 }
David Pursell80f67022015-08-28 15:08:49 -0700418 }
David Pursella9320582015-08-28 18:31:29 -0700419
420 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700421}
422
David Pursella9320582015-08-28 18:31:29 -0700423void* Subprocess::ThreadHandler(void* userdata) {
424 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700425
David Pursella9320582015-08-28 18:31:29 -0700426 adb_thread_setname(android::base::StringPrintf(
427 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700428
David Pursell0955c662015-08-31 10:42:13 -0700429 subprocess->PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700430 subprocess->WaitForExit();
David Pursell80f67022015-08-28 15:08:49 -0700431
David Pursell1ed57f02015-10-06 15:30:03 -0700432 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700433 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700434
David Pursella9320582015-08-28 18:31:29 -0700435 return nullptr;
David Pursell80f67022015-08-28 15:08:49 -0700436}
437
David Pursell0955c662015-08-31 10:42:13 -0700438void Subprocess::PassDataStreams() {
439 if (!protocol_sfd_.valid()) {
440 return;
441 }
442
443 // Start by trying to read from the protocol FD, stdout, and stderr.
444 fd_set master_read_set, master_write_set;
445 FD_ZERO(&master_read_set);
446 FD_ZERO(&master_write_set);
447 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
448 if (sfd->valid()) {
449 FD_SET(sfd->fd(), &master_read_set);
450 }
451 }
452
453 // Pass data until the protocol FD or both the subprocess pipes die, at
454 // which point we can't pass any more data.
455 while (protocol_sfd_.valid() &&
456 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
457 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
458 if (dead_sfd) {
459 D("closing FD %d", dead_sfd->fd());
460 FD_CLR(dead_sfd->fd(), &master_read_set);
461 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700462 if (dead_sfd == &protocol_sfd_) {
463 // Using SIGHUP is a decent general way to indicate that the
464 // controlling process is going away. If specific signals are
465 // needed (e.g. SIGINT), pass those through the shell protocol
466 // and only fall back on this for unexpected closures.
467 D("protocol FD died, sending SIGHUP to pid %d", pid_);
468 kill(pid_, SIGHUP);
469 }
David Pursell0955c662015-08-31 10:42:13 -0700470 dead_sfd->Reset();
471 }
472 }
473}
474
475namespace {
476
477inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
478 return sfd.valid() && FD_ISSET(sfd.fd(), set);
479}
480
481} // namespace
482
483ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
484 fd_set* master_write_set_ptr) {
485 fd_set read_set, write_set;
486 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
487 stderr_sfd_.fd()) + 1;
488 ScopedFd* dead_sfd = nullptr;
489
490 // Keep calling select() and passing data until an FD closes/errors.
491 while (!dead_sfd) {
492 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
493 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
494 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
495 if (errno == EINTR) {
496 continue;
497 } else {
498 PLOG(ERROR) << "select failed, closing subprocess pipes";
499 stdinout_sfd_.Reset();
500 stderr_sfd_.Reset();
501 return nullptr;
502 }
503 }
504
505 // Read stdout, write to protocol FD.
506 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
507 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
508 }
509
510 // Read stderr, write to protocol FD.
511 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
512 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
513 }
514
515 // Read protocol FD, write to stdin.
516 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
517 dead_sfd = PassInput();
518 // If we didn't finish writing, block on stdin write.
519 if (input_bytes_left_) {
520 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
521 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
522 }
523 }
524
525 // Continue writing to stdin; only happens if a previous write blocked.
526 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
527 dead_sfd = PassInput();
528 // If we finished writing, go back to blocking on protocol read.
529 if (!input_bytes_left_) {
530 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
531 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
532 }
533 }
534 } // while (!dead_sfd)
535
536 return dead_sfd;
537}
538
539ScopedFd* Subprocess::PassInput() {
540 // Only read a new packet if we've finished writing the last one.
541 if (!input_bytes_left_) {
542 if (!input_->Read()) {
543 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
544 if (errno != 0) {
545 PLOG(ERROR) << "error reading protocol FD "
546 << protocol_sfd_.fd();
547 }
548 return &protocol_sfd_;
549 }
550
David Pursell1ed57f02015-10-06 15:30:03 -0700551 if (stdinout_sfd_.valid()) {
552 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800553 case ShellProtocol::kIdWindowSizeChange:
554 int rows, cols, x_pixels, y_pixels;
555 if (sscanf(input_->data(), "%dx%d,%dx%d",
556 &rows, &cols, &x_pixels, &y_pixels) == 4) {
557 winsize ws;
558 ws.ws_row = rows;
559 ws.ws_col = cols;
560 ws.ws_xpixel = x_pixels;
561 ws.ws_ypixel = y_pixels;
562 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
563 }
564 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700565 case ShellProtocol::kIdStdin:
566 input_bytes_left_ = input_->data_length();
567 break;
568 case ShellProtocol::kIdCloseStdin:
569 if (type_ == SubprocessType::kRaw) {
570 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
571 return nullptr;
572 }
573 PLOG(ERROR) << "failed to shutdown writes to FD "
574 << stdinout_sfd_.fd();
575 return &stdinout_sfd_;
576 } else {
577 // PTYs can't close just input, so rather than close the
578 // FD and risk losing subprocess output, leave it open.
579 // This only happens if the client starts a PTY shell
580 // non-interactively which is rare and unsupported.
581 // If necessary, the client can manually close the shell
582 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800583 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700584 }
585 break;
586 }
David Pursell0955c662015-08-31 10:42:13 -0700587 }
588 }
589
590 if (input_bytes_left_ > 0) {
591 int index = input_->data_length() - input_bytes_left_;
592 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
593 input_bytes_left_);
594 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
595 if (bytes < 0) {
596 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
597 }
598 // stdin is done, mark this packet as finished and we'll just start
599 // dumping any further data received from the protocol FD.
600 input_bytes_left_ = 0;
601 return &stdinout_sfd_;
602 } else if (bytes > 0) {
603 input_bytes_left_ -= bytes;
604 }
605 }
606
607 return nullptr;
608}
609
610ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
611 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
612 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700613 // read() returns EIO if a PTY closes; don't report this as an error,
614 // it just means the subprocess completed.
615 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700616 PLOG(ERROR) << "error reading output FD " << sfd->fd();
617 }
618 return sfd;
619 }
620
621 if (bytes > 0 && !output_->Write(id, bytes)) {
622 if (errno != 0) {
623 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
624 }
625 return &protocol_sfd_;
626 }
627
628 return nullptr;
629}
630
David Pursella9320582015-08-28 18:31:29 -0700631void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700632 int exit_code = 1;
633
David Pursella9320582015-08-28 18:31:29 -0700634 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700635 while (true) {
636 int status;
David Pursella9320582015-08-28 18:31:29 -0700637 if (pid_ == waitpid(pid_, &status, 0)) {
638 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700639 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700640 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700641 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700642 break;
643 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700644 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700645 break;
646 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700647 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700648 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700649 break;
650 }
David Pursella9320582015-08-28 18:31:29 -0700651 }
David Pursell80f67022015-08-28 15:08:49 -0700652 }
David Pursella9320582015-08-28 18:31:29 -0700653
David Pursell0955c662015-08-31 10:42:13 -0700654 // If we have an open protocol FD send an exit packet.
655 if (protocol_sfd_.valid()) {
656 output_->data()[0] = exit_code;
657 if (output_->Write(ShellProtocol::kIdExit, 1)) {
658 D("wrote the exit code packet: %d", exit_code);
659 } else {
660 PLOG(ERROR) << "failed to write the exit code packet";
661 }
662 protocol_sfd_.Reset();
663 }
664
David Pursella9320582015-08-28 18:31:29 -0700665 // Pass the local socket FD to the shell cleanup fdevent.
666 if (SHELL_EXIT_NOTIFY_FD >= 0) {
667 int fd = local_socket_sfd_.fd();
668 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
669 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
670 fd, SHELL_EXIT_NOTIFY_FD, pid_);
671 // The shell exit fdevent now owns the FD and will close it once
672 // the last bit of data flushes through.
673 local_socket_sfd_.Release();
674 } else {
675 PLOG(ERROR) << "failed to write fd " << fd
676 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
677 << ") for pid " << pid_;
678 }
David Pursell80f67022015-08-28 15:08:49 -0700679 }
680}
681
682} // namespace
683
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800684int StartSubprocess(const char* name, const char* terminal_type,
685 SubprocessType type, SubprocessProtocol protocol) {
686 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700687 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800688 protocol == SubprocessProtocol::kNone ? "none" : "shell",
689 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700690
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800691 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700692 if (!subprocess) {
693 LOG(ERROR) << "failed to allocate new subprocess";
David Pursell80f67022015-08-28 15:08:49 -0700694 return -1;
695 }
696
David Pursella9320582015-08-28 18:31:29 -0700697 if (!subprocess->ForkAndExec()) {
698 LOG(ERROR) << "failed to start subprocess";
699 delete subprocess;
700 return -1;
701 }
702
703 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
704 subprocess->local_socket_fd(), subprocess->pid());
705 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700706}