1 /*
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
17 // 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
78 #define TRACE_TAG SHELL
79
80 #include "sysdeps.h"
81
82 #include "shell_service.h"
83
84 #include <errno.h>
85 #include <paths.h>
86 #include <pty.h>
87 #include <pwd.h>
88 #include <sys/select.h>
89 #include <termios.h>
90
91 #include <memory>
92 #include <string>
93 #include <thread>
94 #include <unordered_map>
95 #include <vector>
96
97 #include <android-base/logging.h>
98 #include <android-base/properties.h>
99 #include <android-base/stringprintf.h>
100 #include <private/android_logger.h>
101
102 #if defined(__ANDROID__)
103 #include <selinux/android.h>
104 #endif
105
106 #include "adb.h"
107 #include "adb_io.h"
108 #include "adb_trace.h"
109 #include "adb_unique_fd.h"
110 #include "adb_utils.h"
111 #include "security_log_tags.h"
112 #include "shell_protocol.h"
113
114 namespace {
115
116 // Reads from |fd| until close or failure.
ReadAll(int fd)117 std::string ReadAll(int fd) {
118 char buffer[512];
119 std::string received;
120
121 while (1) {
122 int bytes = adb_read(fd, buffer, sizeof(buffer));
123 if (bytes <= 0) {
124 break;
125 }
126 received.append(buffer, bytes);
127 }
128
129 return received;
130 }
131
132 // Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
CreateSocketpair(unique_fd * fd1,unique_fd * fd2)133 bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
134 int sockets[2];
135 if (adb_socketpair(sockets) < 0) {
136 PLOG(ERROR) << "cannot create socket pair";
137 return false;
138 }
139 fd1->reset(sockets[0]);
140 fd2->reset(sockets[1]);
141 return true;
142 }
143
144 class Subprocess {
145 public:
146 Subprocess(std::string command, const char* terminal_type, SubprocessType type,
147 SubprocessProtocol protocol, bool make_pty_raw);
148 ~Subprocess();
149
command() const150 const std::string& command() const { return command_; }
151
ReleaseLocalSocket()152 int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
153
pid() const154 pid_t pid() const { return pid_; }
155
156 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
157 // and exec's the child. Returns false and sets error on failure.
158 bool ForkAndExec(std::string* _Nonnull error);
159
160 // Sets up FDs, starts a thread executing command and the manager thread,
161 // Returns false and sets error on failure.
162 bool ExecInProcess(Command command, std::string* _Nonnull error);
163
164 // Start the subprocess manager thread. Consumes the subprocess, regardless of success.
165 // Returns false and sets error on failure.
166 static bool StartThread(std::unique_ptr<Subprocess> subprocess,
167 std::string* _Nonnull error);
168
169 private:
170 // Opens the file at |pts_name|.
171 int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
172
173 bool ConnectProtocolEndpoints(std::string* _Nonnull error);
174
175 static void ThreadHandler(void* userdata);
176 void PassDataStreams();
177 void WaitForExit();
178
179 unique_fd* SelectLoop(fd_set* master_read_set_ptr,
180 fd_set* master_write_set_ptr);
181
182 // Input/output stream handlers. Success returns nullptr, failure returns
183 // a pointer to the failed FD.
184 unique_fd* PassInput();
185 unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
186
187 const std::string command_;
188 const std::string terminal_type_;
189 SubprocessType type_;
190 SubprocessProtocol protocol_;
191 bool make_pty_raw_;
192 pid_t pid_ = -1;
193 unique_fd local_socket_sfd_;
194
195 // Shell protocol variables.
196 unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
197 std::unique_ptr<ShellProtocol> input_, output_;
198 size_t input_bytes_left_ = 0;
199
200 DISALLOW_COPY_AND_ASSIGN(Subprocess);
201 };
202
Subprocess(std::string command,const char * terminal_type,SubprocessType type,SubprocessProtocol protocol,bool make_pty_raw)203 Subprocess::Subprocess(std::string command, const char* terminal_type, SubprocessType type,
204 SubprocessProtocol protocol, bool make_pty_raw)
205 : command_(std::move(command)),
206 terminal_type_(terminal_type ? terminal_type : ""),
207 type_(type),
208 protocol_(protocol),
209 make_pty_raw_(make_pty_raw) {}
210
~Subprocess()211 Subprocess::~Subprocess() {
212 WaitForExit();
213 }
214
GetHostName()215 static std::string GetHostName() {
216 char buf[HOST_NAME_MAX];
217 if (gethostname(buf, sizeof(buf)) != -1 && strcmp(buf, "localhost") != 0) return buf;
218
219 return android::base::GetProperty("ro.product.device", "android");
220 }
221
ForkAndExec(std::string * error)222 bool Subprocess::ForkAndExec(std::string* error) {
223 unique_fd child_stdinout_sfd, child_stderr_sfd;
224 unique_fd parent_error_sfd, child_error_sfd;
225 char pts_name[PATH_MAX];
226
227 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
233 // 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.
236 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
237 *error = android::base::StringPrintf(
238 "failed to create pipe for subprocess error reporting: %s", strerror(errno));
239 return false;
240 }
241
242 // Construct the environment for the child before we fork.
243 passwd* pw = getpwuid(getuid());
244 std::unordered_map<std::string, std::string> env;
245 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[0], '=');
250
251 // Drop any values that don't contain '='.
252 if (delimiter) {
253 *delimiter++ = '\0';
254 env[env_string.c_str()] = delimiter;
255 }
256 }
257 }
258
259 if (pw != nullptr) {
260 env["HOME"] = pw->pw_dir;
261 env["HOSTNAME"] = GetHostName();
262 env["LOGNAME"] = pw->pw_name;
263 env["SHELL"] = pw->pw_shell;
264 env["TMPDIR"] = "/data/local/tmp";
265 env["USER"] = pw->pw_name;
266 }
267
268 if (!terminal_type_.empty()) {
269 env["TERM"] = terminal_type_;
270 }
271
272 std::vector<std::string> joined_env;
273 for (const auto& it : env) {
274 const char* key = it.first.c_str();
275 const char* value = it.second.c_str();
276 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
277 }
278
279 std::vector<const char*> cenv;
280 for (const std::string& str : joined_env) {
281 cenv.push_back(str.c_str());
282 }
283 cenv.push_back(nullptr);
284
285 if (type_ == SubprocessType::kPty) {
286 int fd;
287 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
288 if (pid_ > 0) {
289 stdinout_sfd_.reset(fd);
290 }
291 } else {
292 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
293 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
294 strerror(errno));
295 return false;
296 }
297 // Raw subprocess + shell protocol allows for splitting stderr.
298 if (protocol_ == SubprocessProtocol::kShell &&
299 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
300 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
301 strerror(errno));
302 return false;
303 }
304 pid_ = fork();
305 }
306
307 if (pid_ == -1) {
308 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
309 return false;
310 }
311
312 if (pid_ == 0) {
313 // Subprocess child.
314 setsid();
315
316 if (type_ == SubprocessType::kPty) {
317 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
318 }
319
320 dup2(child_stdinout_sfd, STDIN_FILENO);
321 dup2(child_stdinout_sfd, STDOUT_FILENO);
322 dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
323
324 // exec doesn't trigger destructors, close the FDs manually.
325 stdinout_sfd_.reset(-1);
326 stderr_sfd_.reset(-1);
327 child_stdinout_sfd.reset(-1);
328 child_stderr_sfd.reset(-1);
329 parent_error_sfd.reset(-1);
330 close_on_exec(child_error_sfd);
331
332 // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
333 // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
334 signal(SIGPIPE, SIG_DFL);
335
336 // Increase oom_score_adj from -1000, so that the child is visible to the OOM-killer.
337 // Don't treat failure as an error, because old Android kernels explicitly disabled this.
338 int oom_score_adj_fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
339 if (oom_score_adj_fd != -1) {
340 const char* oom_score_adj_value = "-950";
341 TEMP_FAILURE_RETRY(
342 adb_write(oom_score_adj_fd, oom_score_adj_value, strlen(oom_score_adj_value)));
343 }
344
345 #ifdef __ANDROID_RECOVERY__
346 // Special routine for recovery. Switch to shell domain when adbd is
347 // is running with dropped privileged (i.e. not running as root) and
348 // is built for the recovery mode. This is required because recovery
349 // rootfs is not labeled and everything is labeled just as rootfs.
350 char* con = nullptr;
351 if (getcon(&con) == 0) {
352 if (!strcmp(con, "u:r:adbd:s0")) {
353 if (selinux_android_setcon("u:r:shell:s0") < 0) {
354 LOG(FATAL) << "Could not set SELinux context for subprocess";
355 }
356 }
357 freecon(con);
358 } else {
359 LOG(FATAL) << "Failed to get SELinux context";
360 }
361 #endif
362
363 if (command_.empty()) {
364 // Spawn a login shell if we don't have a command.
365 execle(_PATH_BSHELL, "-" _PATH_BSHELL, nullptr, cenv.data());
366 } else {
367 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
368 }
369 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
370 WriteFdExactly(child_error_sfd, strerror(errno));
371 child_error_sfd.reset(-1);
372 _Exit(1);
373 }
374
375 // Subprocess parent.
376 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
377 stdinout_sfd_.get(), stderr_sfd_.get());
378
379 // Wait to make sure the subprocess exec'd without error.
380 child_error_sfd.reset(-1);
381 std::string error_message = ReadAll(parent_error_sfd);
382 if (!error_message.empty()) {
383 *error = error_message;
384 return false;
385 }
386
387 D("subprocess parent: exec completed");
388 if (!ConnectProtocolEndpoints(error)) {
389 kill(pid_, SIGKILL);
390 return false;
391 }
392
393 D("subprocess parent: completed");
394 return true;
395 }
396
ExecInProcess(Command command,std::string * _Nonnull error)397 bool Subprocess::ExecInProcess(Command command, std::string* _Nonnull error) {
398 unique_fd child_stdinout_sfd, child_stderr_sfd;
399
400 CHECK(type_ == SubprocessType::kRaw);
401
402 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
403
404 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
405 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
406 strerror(errno));
407 return false;
408 }
409 if (protocol_ == SubprocessProtocol::kShell) {
410 // Shell protocol allows for splitting stderr.
411 if (!CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
412 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
413 strerror(errno));
414 return false;
415 }
416 } else {
417 // Raw protocol doesn't support multiple output streams, so combine stdout and stderr.
418 child_stderr_sfd.reset(dup(child_stdinout_sfd));
419 }
420
421 D("execinprocess: stdin/stdout FD = %d, stderr FD = %d", stdinout_sfd_.get(),
422 stderr_sfd_.get());
423
424 if (!ConnectProtocolEndpoints(error)) {
425 return false;
426 }
427
428 std::thread([inout_sfd = std::move(child_stdinout_sfd), err_sfd = std::move(child_stderr_sfd),
429 command = std::move(command),
430 args = command_]() { command(args, inout_sfd, inout_sfd, err_sfd); })
431 .detach();
432
433 D("execinprocess: completed");
434 return true;
435 }
436
ConnectProtocolEndpoints(std::string * _Nonnull error)437 bool Subprocess::ConnectProtocolEndpoints(std::string* _Nonnull error) {
438 if (protocol_ == SubprocessProtocol::kNone) {
439 // No protocol: all streams pass through the stdinout FD and hook
440 // directly into the local socket for raw data transfer.
441 local_socket_sfd_.reset(stdinout_sfd_.release());
442 } else {
443 // Required for shell protocol: create another socketpair to intercept data.
444 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
445 *error = android::base::StringPrintf(
446 "failed to create socketpair to intercept data: %s", strerror(errno));
447 return false;
448 }
449 D("protocol FD = %d", protocol_sfd_.get());
450
451 input_ = std::make_unique<ShellProtocol>(protocol_sfd_);
452 output_ = std::make_unique<ShellProtocol>(protocol_sfd_);
453 if (!input_ || !output_) {
454 *error = "failed to allocate shell protocol objects";
455 return false;
456 }
457
458 // Don't let reads/writes to the subprocess block our thread. This isn't
459 // likely but could happen under unusual circumstances, such as if we
460 // write a ton of data to stdin but the subprocess never reads it and
461 // the pipe fills up.
462 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
463 if (fd >= 0) {
464 if (!set_file_block_mode(fd, false)) {
465 *error = android::base::StringPrintf(
466 "failed to set non-blocking mode for fd %d", fd);
467 return false;
468 }
469 }
470 }
471 }
472
473 return true;
474 }
475
StartThread(std::unique_ptr<Subprocess> subprocess,std::string * error)476 bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
477 Subprocess* raw = subprocess.release();
478 std::thread(ThreadHandler, raw).detach();
479
480 return true;
481 }
482
OpenPtyChildFd(const char * pts_name,unique_fd * error_sfd)483 int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
484 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
485 if (child_fd == -1) {
486 // Don't use WriteFdFmt; since we're in the fork() child we don't want
487 // to allocate any heap memory to avoid race conditions.
488 const char* messages[] = {"child failed to open pseudo-term slave ",
489 pts_name, ": ", strerror(errno)};
490 for (const char* message : messages) {
491 WriteFdExactly(*error_sfd, message);
492 }
493 abort();
494 }
495
496 if (make_pty_raw_) {
497 termios tattr;
498 if (tcgetattr(child_fd, &tattr) == -1) {
499 int saved_errno = errno;
500 WriteFdExactly(*error_sfd, "tcgetattr failed: ");
501 WriteFdExactly(*error_sfd, strerror(saved_errno));
502 abort();
503 }
504
505 cfmakeraw(&tattr);
506 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
507 int saved_errno = errno;
508 WriteFdExactly(*error_sfd, "tcsetattr failed: ");
509 WriteFdExactly(*error_sfd, strerror(saved_errno));
510 abort();
511 }
512 }
513
514 return child_fd;
515 }
516
ThreadHandler(void * userdata)517 void Subprocess::ThreadHandler(void* userdata) {
518 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
519
520 adb_thread_setname(android::base::StringPrintf("shell svc %d", subprocess->pid()));
521
522 D("passing data streams for PID %d", subprocess->pid());
523 subprocess->PassDataStreams();
524
525 D("deleting Subprocess for PID %d", subprocess->pid());
526 delete subprocess;
527 }
528
PassDataStreams()529 void Subprocess::PassDataStreams() {
530 if (protocol_sfd_ == -1) {
531 return;
532 }
533
534 // Start by trying to read from the protocol FD, stdout, and stderr.
535 fd_set master_read_set, master_write_set;
536 FD_ZERO(&master_read_set);
537 FD_ZERO(&master_write_set);
538 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
539 if (*sfd != -1) {
540 FD_SET(*sfd, &master_read_set);
541 }
542 }
543
544 // Pass data until the protocol FD or both the subprocess pipes die, at
545 // which point we can't pass any more data.
546 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
547 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
548 if (dead_sfd) {
549 D("closing FD %d", dead_sfd->get());
550 FD_CLR(*dead_sfd, &master_read_set);
551 FD_CLR(*dead_sfd, &master_write_set);
552 if (dead_sfd == &protocol_sfd_) {
553 // Using SIGHUP is a decent general way to indicate that the
554 // controlling process is going away. If specific signals are
555 // needed (e.g. SIGINT), pass those through the shell protocol
556 // and only fall back on this for unexpected closures.
557 D("protocol FD died, sending SIGHUP to pid %d", pid_);
558 if (pid_ != -1) {
559 kill(pid_, SIGHUP);
560 }
561
562 // We also need to close the pipes connected to the child process
563 // so that if it ignores SIGHUP and continues to write data it
564 // won't fill up the pipe and block.
565 stdinout_sfd_.reset();
566 stderr_sfd_.reset();
567 }
568 dead_sfd->reset();
569 }
570 }
571 }
572
573 namespace {
574
ValidAndInSet(const unique_fd & sfd,fd_set * set)575 inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
576 return sfd != -1 && FD_ISSET(sfd, set);
577 }
578
579 } // namespace
580
SelectLoop(fd_set * master_read_set_ptr,fd_set * master_write_set_ptr)581 unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
582 fd_set* master_write_set_ptr) {
583 fd_set read_set, write_set;
584 int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
585 unique_fd* dead_sfd = nullptr;
586
587 // Keep calling select() and passing data until an FD closes/errors.
588 while (!dead_sfd) {
589 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
590 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
591 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
592 if (errno == EINTR) {
593 continue;
594 } else {
595 PLOG(ERROR) << "select failed, closing subprocess pipes";
596 stdinout_sfd_.reset(-1);
597 stderr_sfd_.reset(-1);
598 return nullptr;
599 }
600 }
601
602 // Read stdout, write to protocol FD.
603 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
604 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
605 }
606
607 // Read stderr, write to protocol FD.
608 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
609 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
610 }
611
612 // Read protocol FD, write to stdin.
613 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
614 dead_sfd = PassInput();
615 // If we didn't finish writing, block on stdin write.
616 if (input_bytes_left_) {
617 FD_CLR(protocol_sfd_, master_read_set_ptr);
618 FD_SET(stdinout_sfd_, master_write_set_ptr);
619 }
620 }
621
622 // Continue writing to stdin; only happens if a previous write blocked.
623 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
624 dead_sfd = PassInput();
625 // If we finished writing, go back to blocking on protocol read.
626 if (!input_bytes_left_) {
627 FD_SET(protocol_sfd_, master_read_set_ptr);
628 FD_CLR(stdinout_sfd_, master_write_set_ptr);
629 }
630 }
631 } // while (!dead_sfd)
632
633 return dead_sfd;
634 }
635
PassInput()636 unique_fd* Subprocess::PassInput() {
637 // Only read a new packet if we've finished writing the last one.
638 if (!input_bytes_left_) {
639 if (!input_->Read()) {
640 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
641 if (errno != 0) {
642 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
643 }
644 return &protocol_sfd_;
645 }
646
647 if (stdinout_sfd_ != -1) {
648 switch (input_->id()) {
649 case ShellProtocol::kIdWindowSizeChange:
650 int rows, cols, x_pixels, y_pixels;
651 if (sscanf(input_->data(), "%dx%d,%dx%d",
652 &rows, &cols, &x_pixels, &y_pixels) == 4) {
653 winsize ws;
654 ws.ws_row = rows;
655 ws.ws_col = cols;
656 ws.ws_xpixel = x_pixels;
657 ws.ws_ypixel = y_pixels;
658 ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
659 }
660 break;
661 case ShellProtocol::kIdStdin:
662 input_bytes_left_ = input_->data_length();
663 break;
664 case ShellProtocol::kIdCloseStdin:
665 if (type_ == SubprocessType::kRaw) {
666 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
667 return nullptr;
668 }
669 PLOG(ERROR) << "failed to shutdown writes to FD "
670 << stdinout_sfd_;
671 return &stdinout_sfd_;
672 } else {
673 // PTYs can't close just input, so rather than close the
674 // FD and risk losing subprocess output, leave it open.
675 // This only happens if the client starts a PTY shell
676 // non-interactively which is rare and unsupported.
677 // If necessary, the client can manually close the shell
678 // with `exit` or by killing the adb client process.
679 D("can't close input for PTY FD %d", stdinout_sfd_.get());
680 }
681 break;
682 }
683 }
684 }
685
686 if (input_bytes_left_ > 0) {
687 int index = input_->data_length() - input_bytes_left_;
688 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
689 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
690 if (bytes < 0) {
691 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
692 }
693 // stdin is done, mark this packet as finished and we'll just start
694 // dumping any further data received from the protocol FD.
695 input_bytes_left_ = 0;
696 return &stdinout_sfd_;
697 } else if (bytes > 0) {
698 input_bytes_left_ -= bytes;
699 }
700 }
701
702 return nullptr;
703 }
704
PassOutput(unique_fd * sfd,ShellProtocol::Id id)705 unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
706 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
707 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
708 // read() returns EIO if a PTY closes; don't report this as an error,
709 // it just means the subprocess completed.
710 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
711 PLOG(ERROR) << "error reading output FD " << *sfd;
712 }
713 return sfd;
714 }
715
716 if (bytes > 0 && !output_->Write(id, bytes)) {
717 if (errno != 0) {
718 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
719 }
720 return &protocol_sfd_;
721 }
722
723 return nullptr;
724 }
725
WaitForExit()726 void Subprocess::WaitForExit() {
727 int exit_code = 1;
728
729 D("waiting for pid %d", pid_);
730 while (pid_ != -1) {
731 int status;
732 if (pid_ == waitpid(pid_, &status, 0)) {
733 D("post waitpid (pid=%d) status=%04x", pid_, status);
734 if (WIFSIGNALED(status)) {
735 exit_code = 0x80 | WTERMSIG(status);
736 D("subprocess killed by signal %d", WTERMSIG(status));
737 break;
738 } else if (!WIFEXITED(status)) {
739 D("subprocess didn't exit");
740 break;
741 } else if (WEXITSTATUS(status) >= 0) {
742 exit_code = WEXITSTATUS(status);
743 D("subprocess exit code = %d", WEXITSTATUS(status));
744 break;
745 }
746 }
747 }
748
749 // If we have an open protocol FD send an exit packet.
750 if (protocol_sfd_ != -1) {
751 output_->data()[0] = exit_code;
752 if (output_->Write(ShellProtocol::kIdExit, 1)) {
753 D("wrote the exit code packet: %d", exit_code);
754 } else {
755 PLOG(ERROR) << "failed to write the exit code packet";
756 }
757 protocol_sfd_.reset(-1);
758 }
759 }
760
761 } // namespace
762
763 // Create a pipe containing the error.
ReportError(SubprocessProtocol protocol,const std::string & message)764 unique_fd ReportError(SubprocessProtocol protocol, const std::string& message) {
765 unique_fd read, write;
766 if (!Pipe(&read, &write)) {
767 PLOG(ERROR) << "failed to create pipe to report error";
768 return unique_fd{};
769 }
770
771 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
772 if (protocol == SubprocessProtocol::kShell) {
773 ShellProtocol::Id id = ShellProtocol::kIdStderr;
774 uint32_t length = buf.length();
775 WriteFdExactly(write.get(), &id, sizeof(id));
776 WriteFdExactly(write.get(), &length, sizeof(length));
777 }
778
779 WriteFdExactly(write.get(), buf.data(), buf.length());
780
781 if (protocol == SubprocessProtocol::kShell) {
782 ShellProtocol::Id id = ShellProtocol::kIdExit;
783 uint32_t length = 1;
784 char exit_code = 126;
785 WriteFdExactly(write.get(), &id, sizeof(id));
786 WriteFdExactly(write.get(), &length, sizeof(length));
787 WriteFdExactly(write.get(), &exit_code, sizeof(exit_code));
788 }
789
790 return read;
791 }
792
StartSubprocess(std::string name,const char * terminal_type,SubprocessType type,SubprocessProtocol protocol)793 unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
794 SubprocessProtocol protocol) {
795 // If we aren't using the shell protocol we must allocate a PTY to properly close the
796 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
797 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
798 // e.g. screenrecord, will never notice the broken pipe and terminate.
799 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
800 // with select() and will send SIGHUP manually to the child process.
801 bool make_pty_raw = false;
802 if (protocol == SubprocessProtocol::kNone && type == SubprocessType::kRaw) {
803 // Disable PTY input/output processing since the client is expecting raw data.
804 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
805 type = SubprocessType::kPty;
806 make_pty_raw = true;
807 }
808
809 unique_fd error_fd;
810 unique_fd fd = StartSubprocess(std::move(name), terminal_type, type, protocol, make_pty_raw,
811 protocol, &error_fd);
812 if (fd == -1) {
813 return error_fd;
814 }
815 return fd;
816 }
817
StartSubprocess(std::string name,const char * terminal_type,SubprocessType type,SubprocessProtocol protocol,bool make_pty_raw,SubprocessProtocol error_protocol,unique_fd * error_fd)818 unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
819 SubprocessProtocol protocol, bool make_pty_raw,
820 SubprocessProtocol error_protocol, unique_fd* error_fd) {
821 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
822 type == SubprocessType::kRaw ? "raw" : "PTY",
823 protocol == SubprocessProtocol::kNone ? "none" : "shell", terminal_type, name.c_str());
824
825 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
826 make_pty_raw);
827 if (!subprocess) {
828 LOG(ERROR) << "failed to allocate new subprocess";
829 *error_fd = ReportError(error_protocol, "failed to allocate new subprocess");
830 return {};
831 }
832
833 std::string error;
834 if (!subprocess->ForkAndExec(&error)) {
835 LOG(ERROR) << "failed to start subprocess: " << error;
836 *error_fd = ReportError(error_protocol, error);
837 return {};
838 }
839
840 unique_fd local_socket(subprocess->ReleaseLocalSocket());
841 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
842 subprocess->pid());
843
844 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
845 LOG(ERROR) << "failed to start subprocess management thread: " << error;
846 *error_fd = ReportError(error_protocol, error);
847 return {};
848 }
849
850 return local_socket;
851 }
852
StartCommandInProcess(std::string name,Command command,SubprocessProtocol protocol)853 unique_fd StartCommandInProcess(std::string name, Command command, SubprocessProtocol protocol) {
854 LOG(INFO) << "StartCommandInProcess(" << dump_hex(name.data(), name.size()) << ")";
855
856 constexpr auto terminal_type = "";
857 constexpr auto type = SubprocessType::kRaw;
858 constexpr auto make_pty_raw = false;
859
860 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
861 make_pty_raw);
862 if (!subprocess) {
863 LOG(ERROR) << "failed to allocate new subprocess";
864 return ReportError(protocol, "failed to allocate new subprocess");
865 }
866
867 std::string error;
868 if (!subprocess->ExecInProcess(std::move(command), &error)) {
869 LOG(ERROR) << "failed to start subprocess: " << error;
870 return ReportError(protocol, error);
871 }
872
873 unique_fd local_socket(subprocess->ReleaseLocalSocket());
874 D("inprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
875 subprocess->pid());
876
877 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
878 LOG(ERROR) << "failed to start inprocess management thread: " << error;
879 return ReportError(protocol, error);
880 }
881
882 return local_socket;
883 }
884