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