blob: 95fd49b741ae56915b76a78922cef2de8039c850 [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
David Pursella9320582015-08-28 18:31:29 -0700138// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
139bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
140 int sockets[2];
141 if (adb_socketpair(sockets) < 0) {
142 PLOG(ERROR) << "cannot create socket pair";
143 return false;
144 }
145 fd1->Reset(sockets[0]);
146 fd2->Reset(sockets[1]);
147 return true;
148}
149
150class Subprocess {
151 public:
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800152 Subprocess(const std::string& command, const char* terminal_type,
153 SubprocessType type, SubprocessProtocol protocol);
David Pursella9320582015-08-28 18:31:29 -0700154 ~Subprocess();
155
156 const std::string& command() const { return command_; }
David Pursella9320582015-08-28 18:31:29 -0700157
158 int local_socket_fd() const { return local_socket_sfd_.fd(); }
159
160 pid_t pid() const { return pid_; }
161
162 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
163 // and exec's the child. Returns false on failure.
Josh Gao43235072016-01-25 17:11:43 -0800164 bool ForkAndExec(std::string* _Nonnull error);
David Pursella9320582015-08-28 18:31:29 -0700165
166 private:
167 // Opens the file at |pts_name|.
168 int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
169
Josh Gaod9db09c2016-02-12 14:31:15 -0800170 static void ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700171 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700172 void WaitForExit();
173
David Pursell0955c662015-08-31 10:42:13 -0700174 ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
175 fd_set* master_write_set_ptr);
176
177 // Input/output stream handlers. Success returns nullptr, failure returns
178 // a pointer to the failed FD.
179 ScopedFd* PassInput();
180 ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
181
David Pursella9320582015-08-28 18:31:29 -0700182 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800183 const std::string terminal_type_;
David Pursell57dd5ae2016-01-27 16:07:52 -0800184 bool make_pty_raw_ = false;
David Pursella9320582015-08-28 18:31:29 -0700185 SubprocessType type_;
David Pursell0955c662015-08-31 10:42:13 -0700186 SubprocessProtocol protocol_;
David Pursella9320582015-08-28 18:31:29 -0700187 pid_t pid_ = -1;
188 ScopedFd local_socket_sfd_;
189
David Pursell0955c662015-08-31 10:42:13 -0700190 // Shell protocol variables.
191 ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
192 std::unique_ptr<ShellProtocol> input_, output_;
193 size_t input_bytes_left_ = 0;
194
David Pursella9320582015-08-28 18:31:29 -0700195 DISALLOW_COPY_AND_ASSIGN(Subprocess);
196};
197
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800198Subprocess::Subprocess(const std::string& command, const char* terminal_type,
199 SubprocessType type, SubprocessProtocol protocol)
200 : command_(command),
201 terminal_type_(terminal_type ? terminal_type : ""),
202 type_(type),
203 protocol_(protocol) {
David Pursell57dd5ae2016-01-27 16:07:52 -0800204 // If we aren't using the shell protocol we must allocate a PTY to properly close the
205 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
206 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
207 // e.g. screenrecord, will never notice the broken pipe and terminate.
208 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
209 // with select() and will send SIGHUP manually to the child process.
210 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
211 // Disable PTY input/output processing since the client is expecting raw data.
212 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
213 type_ = SubprocessType::kPty;
214 make_pty_raw_ = true;
215 }
David Pursella9320582015-08-28 18:31:29 -0700216}
217
218Subprocess::~Subprocess() {
Josh Gaoc65fae92016-01-19 16:21:17 -0800219 WaitForExit();
David Pursella9320582015-08-28 18:31:29 -0700220}
221
Josh Gao43235072016-01-25 17:11:43 -0800222bool Subprocess::ForkAndExec(std::string* error) {
David Pursell0955c662015-08-31 10:42:13 -0700223 ScopedFd child_stdinout_sfd, child_stderr_sfd;
224 ScopedFd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700225 char pts_name[PATH_MAX];
226
Rubin Xud61a25c2016-01-11 10:23:47 +0000227 if (command_.empty()) {
228 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
229 } else {
230 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
231 }
232
Josh Gao9b3fd672015-12-11 10:52:55 -0800233 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
234 // use threads, logging directly from the child might deadlock due to locks held in another
235 // thread during the fork.
David Pursella9320582015-08-28 18:31:29 -0700236 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800237 *error = android::base::StringPrintf(
238 "failed to create pipe for subprocess error reporting: %s", strerror(errno));
239 return false;
David Pursella9320582015-08-28 18:31:29 -0700240 }
241
Josh Gao9b3fd672015-12-11 10:52:55 -0800242 // Construct the environment for the child before we fork.
243 passwd* pw = getpwuid(getuid());
244 std::unordered_map<std::string, std::string> env;
Josh Gaoe03c9882015-12-11 15:49:12 -0800245 if (environ) {
246 char** current = environ;
247 while (char* env_cstr = *current++) {
248 std::string env_string = env_cstr;
249 char* delimiter = strchr(env_string.c_str(), '=');
Josh Gao9b3fd672015-12-11 10:52:55 -0800250
Josh Gaoe03c9882015-12-11 15:49:12 -0800251 // Drop any values that don't contain '='.
252 if (delimiter) {
253 *delimiter++ = '\0';
254 env[env_string.c_str()] = delimiter;
255 }
256 }
Josh Gao9b3fd672015-12-11 10:52:55 -0800257 }
258
259 if (pw != nullptr) {
260 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
261 env["HOME"] = pw->pw_dir;
262 env["LOGNAME"] = pw->pw_name;
263 env["USER"] = pw->pw_name;
264 env["SHELL"] = pw->pw_shell;
265 }
266
267 if (!terminal_type_.empty()) {
268 env["TERM"] = terminal_type_;
269 }
270
271 std::vector<std::string> joined_env;
272 for (auto it : env) {
273 const char* key = it.first.c_str();
274 const char* value = it.second.c_str();
275 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
276 }
277
278 std::vector<const char*> cenv;
279 for (const std::string& str : joined_env) {
280 cenv.push_back(str.c_str());
281 }
282 cenv.push_back(nullptr);
283
David Pursella9320582015-08-28 18:31:29 -0700284 if (type_ == SubprocessType::kPty) {
285 int fd;
286 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700287 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700288 } else {
David Pursell0955c662015-08-31 10:42:13 -0700289 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800290 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
291 strerror(errno));
David Pursell0955c662015-08-31 10:42:13 -0700292 return false;
293 }
294 // Raw subprocess + shell protocol allows for splitting stderr.
295 if (protocol_ == SubprocessProtocol::kShell &&
296 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800297 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
298 strerror(errno));
David Pursella9320582015-08-28 18:31:29 -0700299 return false;
300 }
301 pid_ = fork();
302 }
303
304 if (pid_ == -1) {
Josh Gao43235072016-01-25 17:11:43 -0800305 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
David Pursella9320582015-08-28 18:31:29 -0700306 return false;
307 }
308
309 if (pid_ == 0) {
310 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700311 init_subproc_child();
312
David Pursella9320582015-08-28 18:31:29 -0700313 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700314 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700315 }
316
David Pursell0955c662015-08-31 10:42:13 -0700317 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
318 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
319 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
320 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700321
322 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700323 stdinout_sfd_.Reset();
324 stderr_sfd_.Reset();
325 child_stdinout_sfd.Reset();
326 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700327 parent_error_sfd.Reset();
328 close_on_exec(child_error_sfd.fd());
329
Josh Gaob5028e42016-01-19 17:31:09 -0800330 if (command_.empty()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800331 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700332 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800333 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700334 }
Josh Gao43235072016-01-25 17:11:43 -0800335 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed: ");
336 WriteFdExactly(child_error_sfd.fd(), strerror(errno));
David Pursella9320582015-08-28 18:31:29 -0700337 child_error_sfd.Reset();
Josh Gao9b3fd672015-12-11 10:52:55 -0800338 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700339 }
340
341 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700342 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
343 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700344
345 // Wait to make sure the subprocess exec'd without error.
346 child_error_sfd.Reset();
347 std::string error_message = ReadAll(parent_error_sfd.fd());
348 if (!error_message.empty()) {
Josh Gao43235072016-01-25 17:11:43 -0800349 *error = error_message;
David Pursella9320582015-08-28 18:31:29 -0700350 return false;
351 }
352
Josh Gao9b3fd672015-12-11 10:52:55 -0800353 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700354 if (protocol_ == SubprocessProtocol::kNone) {
355 // No protocol: all streams pass through the stdinout FD and hook
356 // directly into the local socket for raw data transfer.
357 local_socket_sfd_.Reset(stdinout_sfd_.Release());
358 } else {
359 // Shell protocol: create another socketpair to intercept data.
360 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
Josh Gao43235072016-01-25 17:11:43 -0800361 *error = android::base::StringPrintf(
362 "failed to create socketpair to intercept data: %s", strerror(errno));
363 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700364 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_) {
Josh Gao43235072016-01-25 17:11:43 -0800371 *error = "failed to allocate shell protocol objects";
372 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700373 return false;
374 }
375
376 // Don't let reads/writes to the subprocess block our thread. This isn't
377 // likely but could happen under unusual circumstances, such as if we
378 // write a ton of data to stdin but the subprocess never reads it and
379 // the pipe fills up.
380 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
381 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700382 if (!set_file_block_mode(fd, false)) {
Josh Gao43235072016-01-25 17:11:43 -0800383 *error = android::base::StringPrintf(
384 "failed to set non-blocking mode for fd %d", fd);
385 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700386 return false;
387 }
388 }
389 }
390 }
David Pursella9320582015-08-28 18:31:29 -0700391
392 if (!adb_thread_create(ThreadHandler, this)) {
Josh Gao43235072016-01-25 17:11:43 -0800393 *error =
394 android::base::StringPrintf("failed to create subprocess thread: %s", strerror(errno));
395 kill(pid_, SIGKILL);
David Pursella9320582015-08-28 18:31:29 -0700396 return false;
397 }
398
Josh Gao9b3fd672015-12-11 10:52:55 -0800399 D("subprocess parent: completed");
David Pursella9320582015-08-28 18:31:29 -0700400 return true;
401}
402
403int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
404 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
405 if (child_fd == -1) {
406 // Don't use WriteFdFmt; since we're in the fork() child we don't want
407 // to allocate any heap memory to avoid race conditions.
408 const char* messages[] = {"child failed to open pseudo-term slave ",
409 pts_name, ": ", strerror(errno)};
410 for (const char* message : messages) {
411 WriteFdExactly(error_sfd->fd(), message);
412 }
413 exit(-1);
414 }
415
David Pursell57dd5ae2016-01-27 16:07:52 -0800416 if (make_pty_raw_) {
417 termios tattr;
418 if (tcgetattr(child_fd, &tattr) == -1) {
419 int saved_errno = errno;
420 WriteFdExactly(error_sfd->fd(), "tcgetattr failed: ");
421 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
422 exit(-1);
423 }
424
425 cfmakeraw(&tattr);
426 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
427 int saved_errno = errno;
428 WriteFdExactly(error_sfd->fd(), "tcsetattr failed: ");
429 WriteFdExactly(error_sfd->fd(), strerror(saved_errno));
430 exit(-1);
431 }
432 }
433
David Pursella9320582015-08-28 18:31:29 -0700434 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700435}
436
Josh Gaod9db09c2016-02-12 14:31:15 -0800437void Subprocess::ThreadHandler(void* userdata) {
David Pursella9320582015-08-28 18:31:29 -0700438 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700439
David Pursella9320582015-08-28 18:31:29 -0700440 adb_thread_setname(android::base::StringPrintf(
441 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700442
David Pursell0955c662015-08-31 10:42:13 -0700443 subprocess->PassDataStreams();
David Pursell80f67022015-08-28 15:08:49 -0700444
David Pursell1ed57f02015-10-06 15:30:03 -0700445 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700446 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700447}
448
David Pursell0955c662015-08-31 10:42:13 -0700449void Subprocess::PassDataStreams() {
450 if (!protocol_sfd_.valid()) {
451 return;
452 }
453
454 // Start by trying to read from the protocol FD, stdout, and stderr.
455 fd_set master_read_set, master_write_set;
456 FD_ZERO(&master_read_set);
457 FD_ZERO(&master_write_set);
458 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
459 if (sfd->valid()) {
460 FD_SET(sfd->fd(), &master_read_set);
461 }
462 }
463
464 // Pass data until the protocol FD or both the subprocess pipes die, at
465 // which point we can't pass any more data.
466 while (protocol_sfd_.valid() &&
467 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
468 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
469 if (dead_sfd) {
470 D("closing FD %d", dead_sfd->fd());
471 FD_CLR(dead_sfd->fd(), &master_read_set);
472 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700473 if (dead_sfd == &protocol_sfd_) {
474 // Using SIGHUP is a decent general way to indicate that the
475 // controlling process is going away. If specific signals are
476 // needed (e.g. SIGINT), pass those through the shell protocol
477 // and only fall back on this for unexpected closures.
478 D("protocol FD died, sending SIGHUP to pid %d", pid_);
479 kill(pid_, SIGHUP);
480 }
David Pursell0955c662015-08-31 10:42:13 -0700481 dead_sfd->Reset();
482 }
483 }
484}
485
486namespace {
487
488inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
489 return sfd.valid() && FD_ISSET(sfd.fd(), set);
490}
491
492} // namespace
493
494ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
495 fd_set* master_write_set_ptr) {
496 fd_set read_set, write_set;
497 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
498 stderr_sfd_.fd()) + 1;
499 ScopedFd* dead_sfd = nullptr;
500
501 // Keep calling select() and passing data until an FD closes/errors.
502 while (!dead_sfd) {
503 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
504 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
505 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
506 if (errno == EINTR) {
507 continue;
508 } else {
509 PLOG(ERROR) << "select failed, closing subprocess pipes";
510 stdinout_sfd_.Reset();
511 stderr_sfd_.Reset();
512 return nullptr;
513 }
514 }
515
516 // Read stdout, write to protocol FD.
517 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
518 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
519 }
520
521 // Read stderr, write to protocol FD.
522 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
523 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
524 }
525
526 // Read protocol FD, write to stdin.
527 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
528 dead_sfd = PassInput();
529 // If we didn't finish writing, block on stdin write.
530 if (input_bytes_left_) {
531 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
532 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
533 }
534 }
535
536 // Continue writing to stdin; only happens if a previous write blocked.
537 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
538 dead_sfd = PassInput();
539 // If we finished writing, go back to blocking on protocol read.
540 if (!input_bytes_left_) {
541 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
542 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
543 }
544 }
545 } // while (!dead_sfd)
546
547 return dead_sfd;
548}
549
550ScopedFd* Subprocess::PassInput() {
551 // Only read a new packet if we've finished writing the last one.
552 if (!input_bytes_left_) {
553 if (!input_->Read()) {
554 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
555 if (errno != 0) {
556 PLOG(ERROR) << "error reading protocol FD "
557 << protocol_sfd_.fd();
558 }
559 return &protocol_sfd_;
560 }
561
David Pursell1ed57f02015-10-06 15:30:03 -0700562 if (stdinout_sfd_.valid()) {
563 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800564 case ShellProtocol::kIdWindowSizeChange:
565 int rows, cols, x_pixels, y_pixels;
566 if (sscanf(input_->data(), "%dx%d,%dx%d",
567 &rows, &cols, &x_pixels, &y_pixels) == 4) {
568 winsize ws;
569 ws.ws_row = rows;
570 ws.ws_col = cols;
571 ws.ws_xpixel = x_pixels;
572 ws.ws_ypixel = y_pixels;
573 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
574 }
575 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700576 case ShellProtocol::kIdStdin:
577 input_bytes_left_ = input_->data_length();
578 break;
579 case ShellProtocol::kIdCloseStdin:
580 if (type_ == SubprocessType::kRaw) {
581 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
582 return nullptr;
583 }
584 PLOG(ERROR) << "failed to shutdown writes to FD "
585 << stdinout_sfd_.fd();
586 return &stdinout_sfd_;
587 } else {
588 // PTYs can't close just input, so rather than close the
589 // FD and risk losing subprocess output, leave it open.
590 // This only happens if the client starts a PTY shell
591 // non-interactively which is rare and unsupported.
592 // If necessary, the client can manually close the shell
593 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800594 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700595 }
596 break;
597 }
David Pursell0955c662015-08-31 10:42:13 -0700598 }
599 }
600
601 if (input_bytes_left_ > 0) {
602 int index = input_->data_length() - input_bytes_left_;
603 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
604 input_bytes_left_);
605 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
606 if (bytes < 0) {
607 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
608 }
609 // stdin is done, mark this packet as finished and we'll just start
610 // dumping any further data received from the protocol FD.
611 input_bytes_left_ = 0;
612 return &stdinout_sfd_;
613 } else if (bytes > 0) {
614 input_bytes_left_ -= bytes;
615 }
616 }
617
618 return nullptr;
619}
620
621ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
622 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
623 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700624 // read() returns EIO if a PTY closes; don't report this as an error,
625 // it just means the subprocess completed.
626 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700627 PLOG(ERROR) << "error reading output FD " << sfd->fd();
628 }
629 return sfd;
630 }
631
632 if (bytes > 0 && !output_->Write(id, bytes)) {
633 if (errno != 0) {
634 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
635 }
636 return &protocol_sfd_;
637 }
638
639 return nullptr;
640}
641
David Pursella9320582015-08-28 18:31:29 -0700642void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700643 int exit_code = 1;
644
David Pursella9320582015-08-28 18:31:29 -0700645 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700646 while (true) {
647 int status;
David Pursella9320582015-08-28 18:31:29 -0700648 if (pid_ == waitpid(pid_, &status, 0)) {
649 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700650 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700651 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700652 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700653 break;
654 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700655 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700656 break;
657 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700658 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700659 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700660 break;
661 }
David Pursella9320582015-08-28 18:31:29 -0700662 }
David Pursell80f67022015-08-28 15:08:49 -0700663 }
David Pursella9320582015-08-28 18:31:29 -0700664
David Pursell0955c662015-08-31 10:42:13 -0700665 // If we have an open protocol FD send an exit packet.
666 if (protocol_sfd_.valid()) {
667 output_->data()[0] = exit_code;
668 if (output_->Write(ShellProtocol::kIdExit, 1)) {
669 D("wrote the exit code packet: %d", exit_code);
670 } else {
671 PLOG(ERROR) << "failed to write the exit code packet";
672 }
673 protocol_sfd_.Reset();
674 }
675
David Pursella9320582015-08-28 18:31:29 -0700676 // Pass the local socket FD to the shell cleanup fdevent.
677 if (SHELL_EXIT_NOTIFY_FD >= 0) {
678 int fd = local_socket_sfd_.fd();
679 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
680 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
681 fd, SHELL_EXIT_NOTIFY_FD, pid_);
682 // The shell exit fdevent now owns the FD and will close it once
683 // the last bit of data flushes through.
684 local_socket_sfd_.Release();
685 } else {
686 PLOG(ERROR) << "failed to write fd " << fd
687 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
688 << ") for pid " << pid_;
689 }
David Pursell80f67022015-08-28 15:08:49 -0700690 }
691}
692
693} // namespace
694
Josh Gao43235072016-01-25 17:11:43 -0800695// Create a pipe containing the error.
696static int ReportError(SubprocessProtocol protocol, const std::string& message) {
697 int pipefd[2];
698 if (pipe(pipefd) != 0) {
699 LOG(ERROR) << "failed to create pipe to report error";
700 return -1;
701 }
702
703 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
704 if (protocol == SubprocessProtocol::kShell) {
705 ShellProtocol::Id id = ShellProtocol::kIdStderr;
706 uint32_t length = buf.length();
707 WriteFdExactly(pipefd[1], &id, sizeof(id));
708 WriteFdExactly(pipefd[1], &length, sizeof(length));
709 }
710
711 WriteFdExactly(pipefd[1], buf.data(), buf.length());
712
713 if (protocol == SubprocessProtocol::kShell) {
714 ShellProtocol::Id id = ShellProtocol::kIdExit;
715 uint32_t length = 1;
716 char exit_code = 126;
717 WriteFdExactly(pipefd[1], &id, sizeof(id));
718 WriteFdExactly(pipefd[1], &length, sizeof(length));
719 WriteFdExactly(pipefd[1], &exit_code, sizeof(exit_code));
720 }
721
722 adb_close(pipefd[1]);
723 return pipefd[0];
724}
725
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800726int StartSubprocess(const char* name, const char* terminal_type,
727 SubprocessType type, SubprocessProtocol protocol) {
728 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700729 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800730 protocol == SubprocessProtocol::kNone ? "none" : "shell",
731 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700732
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800733 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700734 if (!subprocess) {
735 LOG(ERROR) << "failed to allocate new subprocess";
Josh Gao43235072016-01-25 17:11:43 -0800736 return ReportError(protocol, "failed to allocate new subprocess");
David Pursell80f67022015-08-28 15:08:49 -0700737 }
738
Josh Gao43235072016-01-25 17:11:43 -0800739 std::string error;
740 if (!subprocess->ForkAndExec(&error)) {
741 LOG(ERROR) << "failed to start subprocess: " << error;
David Pursella9320582015-08-28 18:31:29 -0700742 delete subprocess;
Josh Gao43235072016-01-25 17:11:43 -0800743 return ReportError(protocol, error);
David Pursella9320582015-08-28 18:31:29 -0700744 }
745
746 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
747 subprocess->local_socket_fd(), subprocess->pid());
748 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700749}