blob: 7b00d9d765e640f1c6d4fe044ead4b9d716a5ac9 [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
Mark Salyzynff2dcd92016-09-28 15:54:45 -070095#include <android/log.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080096#include <android-base/logging.h>
97#include <android-base/stringprintf.h>
David Pursell80f67022015-08-28 15:08:49 -070098#include <paths.h>
99
100#include "adb.h"
101#include "adb_io.h"
102#include "adb_trace.h"
Josh Gao924d35a2016-08-30 15:39:25 -0700103#include "adb_unique_fd.h"
Yabin Cui6dfef252015-10-06 15:10:05 -0700104#include "adb_utils.h"
Rubin Xud61a25c2016-01-11 10:23:47 +0000105#include "security_log_tags.h"
David Pursell80f67022015-08-28 15:08:49 -0700106
107namespace {
108
109void init_subproc_child()
110{
111 setsid();
112
113 // Set OOM score adjustment to prevent killing
114 int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
115 if (fd >= 0) {
116 adb_write(fd, "0", 1);
117 adb_close(fd);
118 } else {
119 D("adb: unable to update oom_score_adj");
120 }
121}
122
David Pursella9320582015-08-28 18:31:29 -0700123// Reads from |fd| until close or failure.
124std::string ReadAll(int fd) {
125 char buffer[512];
126 std::string received;
127
128 while (1) {
129 int bytes = adb_read(fd, buffer, sizeof(buffer));
130 if (bytes <= 0) {
131 break;
132 }
133 received.append(buffer, bytes);
David Pursell80f67022015-08-28 15:08:49 -0700134 }
135
David Pursella9320582015-08-28 18:31:29 -0700136 return received;
137}
138
David Pursella9320582015-08-28 18:31:29 -0700139// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700140bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
David Pursella9320582015-08-28 18:31:29 -0700141 int sockets[2];
142 if (adb_socketpair(sockets) < 0) {
143 PLOG(ERROR) << "cannot create socket pair";
144 return false;
145 }
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700146 fd1->reset(sockets[0]);
147 fd2->reset(sockets[1]);
David Pursella9320582015-08-28 18:31:29 -0700148 return true;
149}
150
151class Subprocess {
152 public:
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800153 Subprocess(const std::string& command, const char* terminal_type,
154 SubprocessType type, SubprocessProtocol protocol);
David Pursella9320582015-08-28 18:31:29 -0700155 ~Subprocess();
156
157 const std::string& command() const { return command_; }
David Pursella9320582015-08-28 18:31:29 -0700158
Josh Gaocd5d7372016-06-22 15:57:12 -0700159 int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
David Pursella9320582015-08-28 18:31:29 -0700160
161 pid_t pid() const { return pid_; }
162
163 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
Josh Gao344778d2016-06-17 14:53:57 -0700164 // and exec's the child. Returns false and sets error on failure.
Josh Gao43235072016-01-25 17:11:43 -0800165 bool ForkAndExec(std::string* _Nonnull error);
David Pursella9320582015-08-28 18:31:29 -0700166
Josh Gao344778d2016-06-17 14:53:57 -0700167 // Start the subprocess manager thread. Consumes the subprocess, regardless of success.
168 // Returns false and sets error on failure.
169 static bool StartThread(std::unique_ptr<Subprocess> subprocess,
170 std::string* _Nonnull error);
171
David Pursella9320582015-08-28 18:31:29 -0700172 private:
173 // Opens the file at |pts_name|.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700174 int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
David Pursella9320582015-08-28 18:31:29 -0700175
Josh Gaob5fea142016-02-12 14:31:15 -0800176 static void ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700177 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700178 void WaitForExit();
179
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700180 unique_fd* SelectLoop(fd_set* master_read_set_ptr,
181 fd_set* master_write_set_ptr);
David Pursell0955c662015-08-31 10:42:13 -0700182
183 // Input/output stream handlers. Success returns nullptr, failure returns
184 // a pointer to the failed FD.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700185 unique_fd* PassInput();
186 unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
David Pursell0955c662015-08-31 10:42:13 -0700187
David Pursella9320582015-08-28 18:31:29 -0700188 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800189 const std::string terminal_type_;
David Pursell57dd5ae2016-01-27 16:07:52 -0800190 bool make_pty_raw_ = false;
David Pursella9320582015-08-28 18:31:29 -0700191 SubprocessType type_;
David Pursell0955c662015-08-31 10:42:13 -0700192 SubprocessProtocol protocol_;
David Pursella9320582015-08-28 18:31:29 -0700193 pid_t pid_ = -1;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700194 unique_fd local_socket_sfd_;
David Pursella9320582015-08-28 18:31:29 -0700195
David Pursell0955c662015-08-31 10:42:13 -0700196 // Shell protocol variables.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700197 unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
David Pursell0955c662015-08-31 10:42:13 -0700198 std::unique_ptr<ShellProtocol> input_, output_;
199 size_t input_bytes_left_ = 0;
200
David Pursella9320582015-08-28 18:31:29 -0700201 DISALLOW_COPY_AND_ASSIGN(Subprocess);
202};
203
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800204Subprocess::Subprocess(const std::string& command, const char* terminal_type,
205 SubprocessType type, SubprocessProtocol protocol)
206 : command_(command),
207 terminal_type_(terminal_type ? terminal_type : ""),
208 type_(type),
209 protocol_(protocol) {
David Pursell57dd5ae2016-01-27 16:07:52 -0800210 // If we aren't using the shell protocol we must allocate a PTY to properly close the
211 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
212 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
213 // e.g. screenrecord, will never notice the broken pipe and terminate.
214 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
215 // with select() and will send SIGHUP manually to the child process.
216 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
217 // Disable PTY input/output processing since the client is expecting raw data.
218 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
219 type_ = SubprocessType::kPty;
220 make_pty_raw_ = true;
221 }
David Pursella9320582015-08-28 18:31:29 -0700222}
223
224Subprocess::~Subprocess() {
Josh Gaoc65fae92016-01-19 16:21:17 -0800225 WaitForExit();
David Pursella9320582015-08-28 18:31:29 -0700226}
227
Josh Gao43235072016-01-25 17:11:43 -0800228bool Subprocess::ForkAndExec(std::string* error) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700229 unique_fd child_stdinout_sfd, child_stderr_sfd;
230 unique_fd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700231 char pts_name[PATH_MAX];
232
Rubin Xud61a25c2016-01-11 10:23:47 +0000233 if (command_.empty()) {
234 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
235 } else {
236 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
237 }
238
Josh Gao9b3fd672015-12-11 10:52:55 -0800239 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
240 // use threads, logging directly from the child might deadlock due to locks held in another
241 // thread during the fork.
David Pursella9320582015-08-28 18:31:29 -0700242 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800243 *error = android::base::StringPrintf(
244 "failed to create pipe for subprocess error reporting: %s", strerror(errno));
245 return false;
David Pursella9320582015-08-28 18:31:29 -0700246 }
247
Josh Gao9b3fd672015-12-11 10:52:55 -0800248 // Construct the environment for the child before we fork.
249 passwd* pw = getpwuid(getuid());
250 std::unordered_map<std::string, std::string> env;
Josh Gaoe03c9882015-12-11 15:49:12 -0800251 if (environ) {
252 char** current = environ;
253 while (char* env_cstr = *current++) {
254 std::string env_string = env_cstr;
Dan Austin80fd4542016-03-28 14:37:01 -0700255 char* delimiter = strchr(&env_string[0], '=');
Josh Gao9b3fd672015-12-11 10:52:55 -0800256
Josh Gaoe03c9882015-12-11 15:49:12 -0800257 // Drop any values that don't contain '='.
258 if (delimiter) {
259 *delimiter++ = '\0';
260 env[env_string.c_str()] = delimiter;
261 }
262 }
Josh Gao9b3fd672015-12-11 10:52:55 -0800263 }
264
265 if (pw != nullptr) {
266 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
267 env["HOME"] = pw->pw_dir;
268 env["LOGNAME"] = pw->pw_name;
269 env["USER"] = pw->pw_name;
270 env["SHELL"] = pw->pw_shell;
271 }
272
273 if (!terminal_type_.empty()) {
274 env["TERM"] = terminal_type_;
275 }
276
277 std::vector<std::string> joined_env;
278 for (auto it : env) {
279 const char* key = it.first.c_str();
280 const char* value = it.second.c_str();
281 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
282 }
283
284 std::vector<const char*> cenv;
285 for (const std::string& str : joined_env) {
286 cenv.push_back(str.c_str());
287 }
288 cenv.push_back(nullptr);
289
David Pursella9320582015-08-28 18:31:29 -0700290 if (type_ == SubprocessType::kPty) {
291 int fd;
292 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
Josh Gaofcb063c2016-03-04 17:50:10 -0800293 if (pid_ > 0) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700294 stdinout_sfd_.reset(fd);
Josh Gaofcb063c2016-03-04 17:50:10 -0800295 }
David Pursella9320582015-08-28 18:31:29 -0700296 } else {
David Pursell0955c662015-08-31 10:42:13 -0700297 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800298 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
299 strerror(errno));
David Pursell0955c662015-08-31 10:42:13 -0700300 return false;
301 }
302 // Raw subprocess + shell protocol allows for splitting stderr.
303 if (protocol_ == SubprocessProtocol::kShell &&
304 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
Josh Gao43235072016-01-25 17:11:43 -0800305 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
306 strerror(errno));
David Pursella9320582015-08-28 18:31:29 -0700307 return false;
308 }
309 pid_ = fork();
310 }
311
312 if (pid_ == -1) {
Josh Gao43235072016-01-25 17:11:43 -0800313 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
David Pursella9320582015-08-28 18:31:29 -0700314 return false;
315 }
316
317 if (pid_ == 0) {
318 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700319 init_subproc_child();
320
David Pursella9320582015-08-28 18:31:29 -0700321 if (type_ == SubprocessType::kPty) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700322 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700323 }
324
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700325 dup2(child_stdinout_sfd, STDIN_FILENO);
326 dup2(child_stdinout_sfd, STDOUT_FILENO);
327 dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700328
329 // exec doesn't trigger destructors, close the FDs manually.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700330 stdinout_sfd_.reset(-1);
331 stderr_sfd_.reset(-1);
332 child_stdinout_sfd.reset(-1);
333 child_stderr_sfd.reset(-1);
334 parent_error_sfd.reset(-1);
335 close_on_exec(child_error_sfd);
David Pursella9320582015-08-28 18:31:29 -0700336
Josh Gaob5028e42016-01-19 17:31:09 -0800337 if (command_.empty()) {
Josh Gao9b3fd672015-12-11 10:52:55 -0800338 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700339 } else {
Josh Gao9b3fd672015-12-11 10:52:55 -0800340 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursella9320582015-08-28 18:31:29 -0700341 }
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700342 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
343 WriteFdExactly(child_error_sfd, strerror(errno));
344 child_error_sfd.reset(-1);
Josh Gao9b3fd672015-12-11 10:52:55 -0800345 _Exit(1);
David Pursella9320582015-08-28 18:31:29 -0700346 }
347
348 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700349 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700350 stdinout_sfd_.get(), stderr_sfd_.get());
David Pursella9320582015-08-28 18:31:29 -0700351
352 // Wait to make sure the subprocess exec'd without error.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700353 child_error_sfd.reset(-1);
354 std::string error_message = ReadAll(parent_error_sfd);
David Pursella9320582015-08-28 18:31:29 -0700355 if (!error_message.empty()) {
Josh Gao43235072016-01-25 17:11:43 -0800356 *error = error_message;
David Pursella9320582015-08-28 18:31:29 -0700357 return false;
358 }
359
Josh Gao9b3fd672015-12-11 10:52:55 -0800360 D("subprocess parent: exec completed");
David Pursell0955c662015-08-31 10:42:13 -0700361 if (protocol_ == SubprocessProtocol::kNone) {
362 // No protocol: all streams pass through the stdinout FD and hook
363 // directly into the local socket for raw data transfer.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700364 local_socket_sfd_.reset(stdinout_sfd_.release());
David Pursell0955c662015-08-31 10:42:13 -0700365 } else {
366 // Shell protocol: create another socketpair to intercept data.
367 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
Josh Gao43235072016-01-25 17:11:43 -0800368 *error = android::base::StringPrintf(
369 "failed to create socketpair to intercept data: %s", strerror(errno));
370 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700371 return false;
372 }
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700373 D("protocol FD = %d", protocol_sfd_.get());
David Pursell0955c662015-08-31 10:42:13 -0700374
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700375 input_.reset(new ShellProtocol(protocol_sfd_));
376 output_.reset(new ShellProtocol(protocol_sfd_));
David Pursell0955c662015-08-31 10:42:13 -0700377 if (!input_ || !output_) {
Josh Gao43235072016-01-25 17:11:43 -0800378 *error = "failed to allocate shell protocol objects";
379 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700380 return false;
381 }
382
383 // Don't let reads/writes to the subprocess block our thread. This isn't
384 // likely but could happen under unusual circumstances, such as if we
385 // write a ton of data to stdin but the subprocess never reads it and
386 // the pipe fills up.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700387 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
David Pursell0955c662015-08-31 10:42:13 -0700388 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700389 if (!set_file_block_mode(fd, false)) {
Josh Gao43235072016-01-25 17:11:43 -0800390 *error = android::base::StringPrintf(
391 "failed to set non-blocking mode for fd %d", fd);
392 kill(pid_, SIGKILL);
David Pursell0955c662015-08-31 10:42:13 -0700393 return false;
394 }
395 }
396 }
397 }
David Pursella9320582015-08-28 18:31:29 -0700398
Josh Gao344778d2016-06-17 14:53:57 -0700399 D("subprocess parent: completed");
400 return true;
401}
402
403bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
404 Subprocess* raw = subprocess.release();
405 if (!adb_thread_create(ThreadHandler, raw)) {
Josh Gao43235072016-01-25 17:11:43 -0800406 *error =
407 android::base::StringPrintf("failed to create subprocess thread: %s", strerror(errno));
Josh Gao344778d2016-06-17 14:53:57 -0700408 kill(raw->pid_, SIGKILL);
David Pursella9320582015-08-28 18:31:29 -0700409 return false;
410 }
411
412 return true;
413}
414
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700415int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
David Pursella9320582015-08-28 18:31:29 -0700416 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
417 if (child_fd == -1) {
418 // Don't use WriteFdFmt; since we're in the fork() child we don't want
419 // to allocate any heap memory to avoid race conditions.
420 const char* messages[] = {"child failed to open pseudo-term slave ",
421 pts_name, ": ", strerror(errno)};
422 for (const char* message : messages) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700423 WriteFdExactly(*error_sfd, message);
David Pursella9320582015-08-28 18:31:29 -0700424 }
Josh Gao4abdeee2016-05-13 18:16:43 -0700425 abort();
David Pursella9320582015-08-28 18:31:29 -0700426 }
427
David Pursell57dd5ae2016-01-27 16:07:52 -0800428 if (make_pty_raw_) {
429 termios tattr;
430 if (tcgetattr(child_fd, &tattr) == -1) {
431 int saved_errno = errno;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700432 WriteFdExactly(*error_sfd, "tcgetattr failed: ");
433 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao4abdeee2016-05-13 18:16:43 -0700434 abort();
David Pursell57dd5ae2016-01-27 16:07:52 -0800435 }
436
437 cfmakeraw(&tattr);
438 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
439 int saved_errno = errno;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700440 WriteFdExactly(*error_sfd, "tcsetattr failed: ");
441 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao4abdeee2016-05-13 18:16:43 -0700442 abort();
David Pursell57dd5ae2016-01-27 16:07:52 -0800443 }
444 }
445
David Pursella9320582015-08-28 18:31:29 -0700446 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700447}
448
Josh Gaob5fea142016-02-12 14:31:15 -0800449void Subprocess::ThreadHandler(void* userdata) {
David Pursella9320582015-08-28 18:31:29 -0700450 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700451
David Pursella9320582015-08-28 18:31:29 -0700452 adb_thread_setname(android::base::StringPrintf(
Josh Gaocd5d7372016-06-22 15:57:12 -0700453 "shell srvc %d", subprocess->pid()));
David Pursell80f67022015-08-28 15:08:49 -0700454
Josh Gao344778d2016-06-17 14:53:57 -0700455 D("passing data streams for PID %d", subprocess->pid());
David Pursell0955c662015-08-31 10:42:13 -0700456 subprocess->PassDataStreams();
David Pursell80f67022015-08-28 15:08:49 -0700457
David Pursell1ed57f02015-10-06 15:30:03 -0700458 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700459 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700460}
461
David Pursell0955c662015-08-31 10:42:13 -0700462void Subprocess::PassDataStreams() {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700463 if (protocol_sfd_ == -1) {
David Pursell0955c662015-08-31 10:42:13 -0700464 return;
465 }
466
467 // Start by trying to read from the protocol FD, stdout, and stderr.
468 fd_set master_read_set, master_write_set;
469 FD_ZERO(&master_read_set);
470 FD_ZERO(&master_write_set);
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700471 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
472 if (*sfd != -1) {
473 FD_SET(*sfd, &master_read_set);
David Pursell0955c662015-08-31 10:42:13 -0700474 }
475 }
476
477 // Pass data until the protocol FD or both the subprocess pipes die, at
478 // which point we can't pass any more data.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700479 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
480 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
David Pursell0955c662015-08-31 10:42:13 -0700481 if (dead_sfd) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700482 D("closing FD %d", dead_sfd->get());
483 FD_CLR(*dead_sfd, &master_read_set);
484 FD_CLR(*dead_sfd, &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700485 if (dead_sfd == &protocol_sfd_) {
486 // Using SIGHUP is a decent general way to indicate that the
487 // controlling process is going away. If specific signals are
488 // needed (e.g. SIGINT), pass those through the shell protocol
489 // and only fall back on this for unexpected closures.
490 D("protocol FD died, sending SIGHUP to pid %d", pid_);
491 kill(pid_, SIGHUP);
David Pursellf2aa1862016-06-06 09:37:16 -0700492
493 // We also need to close the pipes connected to the child process
494 // so that if it ignores SIGHUP and continues to write data it
495 // won't fill up the pipe and block.
Josh Gao5d1b1a82016-09-14 12:47:02 -0700496 stdinout_sfd_.reset();
497 stderr_sfd_.reset();
David Pursell544e7952015-09-14 15:36:26 -0700498 }
Josh Gao5d1b1a82016-09-14 12:47:02 -0700499 dead_sfd->reset();
David Pursell0955c662015-08-31 10:42:13 -0700500 }
501 }
502}
503
504namespace {
505
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700506inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
507 return sfd != -1 && FD_ISSET(sfd, set);
David Pursell0955c662015-08-31 10:42:13 -0700508}
509
510} // namespace
511
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700512unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
513 fd_set* master_write_set_ptr) {
David Pursell0955c662015-08-31 10:42:13 -0700514 fd_set read_set, write_set;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700515 int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
516 unique_fd* dead_sfd = nullptr;
David Pursell0955c662015-08-31 10:42:13 -0700517
518 // Keep calling select() and passing data until an FD closes/errors.
519 while (!dead_sfd) {
520 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
521 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
522 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
523 if (errno == EINTR) {
524 continue;
525 } else {
526 PLOG(ERROR) << "select failed, closing subprocess pipes";
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700527 stdinout_sfd_.reset(-1);
528 stderr_sfd_.reset(-1);
David Pursell0955c662015-08-31 10:42:13 -0700529 return nullptr;
530 }
531 }
532
533 // Read stdout, write to protocol FD.
534 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
535 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
536 }
537
538 // Read stderr, write to protocol FD.
539 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
540 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
541 }
542
543 // Read protocol FD, write to stdin.
544 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
545 dead_sfd = PassInput();
546 // If we didn't finish writing, block on stdin write.
547 if (input_bytes_left_) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700548 FD_CLR(protocol_sfd_, master_read_set_ptr);
549 FD_SET(stdinout_sfd_, master_write_set_ptr);
David Pursell0955c662015-08-31 10:42:13 -0700550 }
551 }
552
553 // Continue writing to stdin; only happens if a previous write blocked.
554 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
555 dead_sfd = PassInput();
556 // If we finished writing, go back to blocking on protocol read.
557 if (!input_bytes_left_) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700558 FD_SET(protocol_sfd_, master_read_set_ptr);
559 FD_CLR(stdinout_sfd_, master_write_set_ptr);
David Pursell0955c662015-08-31 10:42:13 -0700560 }
561 }
562 } // while (!dead_sfd)
563
564 return dead_sfd;
565}
566
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700567unique_fd* Subprocess::PassInput() {
David Pursell0955c662015-08-31 10:42:13 -0700568 // Only read a new packet if we've finished writing the last one.
569 if (!input_bytes_left_) {
570 if (!input_->Read()) {
571 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
572 if (errno != 0) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700573 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell0955c662015-08-31 10:42:13 -0700574 }
575 return &protocol_sfd_;
576 }
577
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700578 if (stdinout_sfd_ != -1) {
David Pursell1ed57f02015-10-06 15:30:03 -0700579 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800580 case ShellProtocol::kIdWindowSizeChange:
581 int rows, cols, x_pixels, y_pixels;
582 if (sscanf(input_->data(), "%dx%d,%dx%d",
583 &rows, &cols, &x_pixels, &y_pixels) == 4) {
584 winsize ws;
585 ws.ws_row = rows;
586 ws.ws_col = cols;
587 ws.ws_xpixel = x_pixels;
588 ws.ws_ypixel = y_pixels;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700589 ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800590 }
591 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700592 case ShellProtocol::kIdStdin:
593 input_bytes_left_ = input_->data_length();
594 break;
595 case ShellProtocol::kIdCloseStdin:
596 if (type_ == SubprocessType::kRaw) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700597 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
David Pursell1ed57f02015-10-06 15:30:03 -0700598 return nullptr;
599 }
600 PLOG(ERROR) << "failed to shutdown writes to FD "
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700601 << stdinout_sfd_;
David Pursell1ed57f02015-10-06 15:30:03 -0700602 return &stdinout_sfd_;
603 } else {
604 // PTYs can't close just input, so rather than close the
605 // FD and risk losing subprocess output, leave it open.
606 // This only happens if the client starts a PTY shell
607 // non-interactively which is rare and unsupported.
608 // If necessary, the client can manually close the shell
609 // with `exit` or by killing the adb client process.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700610 D("can't close input for PTY FD %d", stdinout_sfd_.get());
David Pursell1ed57f02015-10-06 15:30:03 -0700611 }
612 break;
613 }
David Pursell0955c662015-08-31 10:42:13 -0700614 }
615 }
616
617 if (input_bytes_left_ > 0) {
618 int index = input_->data_length() - input_bytes_left_;
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700619 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
David Pursell0955c662015-08-31 10:42:13 -0700620 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
621 if (bytes < 0) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700622 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
David Pursell0955c662015-08-31 10:42:13 -0700623 }
624 // stdin is done, mark this packet as finished and we'll just start
625 // dumping any further data received from the protocol FD.
626 input_bytes_left_ = 0;
627 return &stdinout_sfd_;
628 } else if (bytes > 0) {
629 input_bytes_left_ -= bytes;
630 }
631 }
632
633 return nullptr;
634}
635
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700636unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
637 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
David Pursell0955c662015-08-31 10:42:13 -0700638 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700639 // read() returns EIO if a PTY closes; don't report this as an error,
640 // it just means the subprocess completed.
641 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700642 PLOG(ERROR) << "error reading output FD " << *sfd;
David Pursell0955c662015-08-31 10:42:13 -0700643 }
644 return sfd;
645 }
646
647 if (bytes > 0 && !output_->Write(id, bytes)) {
648 if (errno != 0) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700649 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell0955c662015-08-31 10:42:13 -0700650 }
651 return &protocol_sfd_;
652 }
653
654 return nullptr;
655}
656
David Pursella9320582015-08-28 18:31:29 -0700657void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700658 int exit_code = 1;
659
David Pursella9320582015-08-28 18:31:29 -0700660 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700661 while (true) {
662 int status;
David Pursella9320582015-08-28 18:31:29 -0700663 if (pid_ == waitpid(pid_, &status, 0)) {
664 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700665 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700666 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700667 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700668 break;
669 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700670 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700671 break;
672 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700673 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700674 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700675 break;
676 }
David Pursella9320582015-08-28 18:31:29 -0700677 }
David Pursell80f67022015-08-28 15:08:49 -0700678 }
David Pursella9320582015-08-28 18:31:29 -0700679
David Pursell0955c662015-08-31 10:42:13 -0700680 // If we have an open protocol FD send an exit packet.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700681 if (protocol_sfd_ != -1) {
David Pursell0955c662015-08-31 10:42:13 -0700682 output_->data()[0] = exit_code;
683 if (output_->Write(ShellProtocol::kIdExit, 1)) {
684 D("wrote the exit code packet: %d", exit_code);
685 } else {
686 PLOG(ERROR) << "failed to write the exit code packet";
687 }
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700688 protocol_sfd_.reset(-1);
David Pursell0955c662015-08-31 10:42:13 -0700689 }
690
David Pursella9320582015-08-28 18:31:29 -0700691 // Pass the local socket FD to the shell cleanup fdevent.
692 if (SHELL_EXIT_NOTIFY_FD >= 0) {
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700693 int fd = local_socket_sfd_;
David Pursella9320582015-08-28 18:31:29 -0700694 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
695 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
696 fd, SHELL_EXIT_NOTIFY_FD, pid_);
697 // The shell exit fdevent now owns the FD and will close it once
698 // the last bit of data flushes through.
Elliott Hughes2ce86e52016-05-27 17:51:24 -0700699 static_cast<void>(local_socket_sfd_.release());
David Pursella9320582015-08-28 18:31:29 -0700700 } else {
701 PLOG(ERROR) << "failed to write fd " << fd
702 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
703 << ") for pid " << pid_;
704 }
David Pursell80f67022015-08-28 15:08:49 -0700705 }
706}
707
708} // namespace
709
Josh Gao43235072016-01-25 17:11:43 -0800710// Create a pipe containing the error.
711static int ReportError(SubprocessProtocol protocol, const std::string& message) {
712 int pipefd[2];
713 if (pipe(pipefd) != 0) {
714 LOG(ERROR) << "failed to create pipe to report error";
715 return -1;
716 }
717
718 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
719 if (protocol == SubprocessProtocol::kShell) {
720 ShellProtocol::Id id = ShellProtocol::kIdStderr;
721 uint32_t length = buf.length();
722 WriteFdExactly(pipefd[1], &id, sizeof(id));
723 WriteFdExactly(pipefd[1], &length, sizeof(length));
724 }
725
726 WriteFdExactly(pipefd[1], buf.data(), buf.length());
727
728 if (protocol == SubprocessProtocol::kShell) {
729 ShellProtocol::Id id = ShellProtocol::kIdExit;
730 uint32_t length = 1;
731 char exit_code = 126;
732 WriteFdExactly(pipefd[1], &id, sizeof(id));
733 WriteFdExactly(pipefd[1], &length, sizeof(length));
734 WriteFdExactly(pipefd[1], &exit_code, sizeof(exit_code));
735 }
736
737 adb_close(pipefd[1]);
738 return pipefd[0];
739}
740
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800741int StartSubprocess(const char* name, const char* terminal_type,
742 SubprocessType type, SubprocessProtocol protocol) {
743 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700744 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800745 protocol == SubprocessProtocol::kNone ? "none" : "shell",
746 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700747
Josh Gao344778d2016-06-17 14:53:57 -0700748 auto subprocess = std::make_unique<Subprocess>(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700749 if (!subprocess) {
750 LOG(ERROR) << "failed to allocate new subprocess";
Josh Gao43235072016-01-25 17:11:43 -0800751 return ReportError(protocol, "failed to allocate new subprocess");
David Pursell80f67022015-08-28 15:08:49 -0700752 }
753
Josh Gao43235072016-01-25 17:11:43 -0800754 std::string error;
755 if (!subprocess->ForkAndExec(&error)) {
756 LOG(ERROR) << "failed to start subprocess: " << error;
Josh Gao43235072016-01-25 17:11:43 -0800757 return ReportError(protocol, error);
David Pursella9320582015-08-28 18:31:29 -0700758 }
759
Josh Gaoe31a7a42016-06-23 11:21:11 -0700760 unique_fd local_socket(subprocess->ReleaseLocalSocket());
761 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
762 subprocess->pid());
Josh Gao344778d2016-06-17 14:53:57 -0700763
764 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
765 LOG(ERROR) << "failed to start subprocess management thread: " << error;
766 return ReportError(protocol, error);
767 }
768
Josh Gaoe31a7a42016-06-23 11:21:11 -0700769 return local_socket.release();
David Pursell80f67022015-08-28 15:08:49 -0700770}