• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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__anon837ee51d0111::SubprocessPollfds147     adb_pollfd* data() { return pfds; }
size__anon837ee51d0111::SubprocessPollfds148     size_t size() { return 3; }
149 
begin__anon837ee51d0111::SubprocessPollfds150     adb_pollfd* begin() { return pfds; }
end__anon837ee51d0111::SubprocessPollfds151     adb_pollfd* end() { return pfds + size(); }
152 
stdinout_pfd__anon837ee51d0111::SubprocessPollfds153     adb_pollfd& stdinout_pfd() { return pfds[0]; }
stderr_pfd__anon837ee51d0111::SubprocessPollfds154     adb_pollfd& stderr_pfd() { return pfds[1]; }
protocol_pfd__anon837ee51d0111::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         int saved_errno = errno;
513         // Don't use WriteFdFmt; since we're in the fork() child we don't want
514         // to allocate any heap memory to avoid race conditions.
515         const char* messages[] = {"child failed to open pts ",
516                                   pts_name, ": ", strerror(saved_errno)};
517         for (const char* message : messages) {
518             WriteFdExactly(*error_sfd, message);
519         }
520         LOG(FATAL) << "child failed to open pts " << pts_name << ": " << strerror(saved_errno);
521     }
522 
523     if (make_pty_raw_) {
524         termios tattr;
525         if (tcgetattr(child_fd, &tattr) == -1) {
526             int saved_errno = errno;
527             WriteFdExactly(*error_sfd, "tcgetattr failed: ");
528             WriteFdExactly(*error_sfd, strerror(saved_errno));
529             LOG(FATAL) << "tcgetattr() failed: " << strerror(saved_errno);
530         }
531 
532         cfmakeraw(&tattr);
533         if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
534             int saved_errno = errno;
535             WriteFdExactly(*error_sfd, "tcsetattr failed: ");
536             WriteFdExactly(*error_sfd, strerror(saved_errno));
537             LOG(FATAL) << "tcsetattr() failed: " << strerror(saved_errno);
538         }
539     }
540 
541     return child_fd;
542 }
543 
ThreadHandler(void * userdata)544 void Subprocess::ThreadHandler(void* userdata) {
545     Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
546 
547     adb_thread_setname(android::base::StringPrintf("shell svc %d", subprocess->pid()));
548 
549     D("passing data streams for PID %d", subprocess->pid());
550     subprocess->PassDataStreams();
551 
552     D("deleting Subprocess for PID %d", subprocess->pid());
553     delete subprocess;
554 }
555 
PassDataStreams()556 void Subprocess::PassDataStreams() {
557     if (protocol_sfd_ == -1) {
558         return;
559     }
560 
561     // Start by trying to read from the protocol FD, stdout, and stderr.
562     SubprocessPollfds pfds;
563     pfds.stdinout_pfd() = {.fd = stdinout_sfd_.get(), .events = POLLIN};
564     pfds.stderr_pfd() = {.fd = stderr_sfd_.get(), .events = POLLIN};
565     pfds.protocol_pfd() = {.fd = protocol_sfd_.get(), .events = POLLIN};
566 
567     // Pass data until the protocol FD or both the subprocess pipes die, at
568     // which point we can't pass any more data.
569     while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
570         unique_fd* dead_sfd = PollLoop(&pfds);
571         if (dead_sfd) {
572             D("closing FD %d", dead_sfd->get());
573             auto it = std::find_if(pfds.begin(), pfds.end(), [=](const adb_pollfd& pfd) {
574                 return pfd.fd == dead_sfd->get();
575             });
576             CHECK(it != pfds.end());
577             it->fd = -1;
578             it->events = 0;
579             if (dead_sfd == &protocol_sfd_) {
580                 // Using SIGHUP is a decent general way to indicate that the
581                 // controlling process is going away. If specific signals are
582                 // needed (e.g. SIGINT), pass those through the shell protocol
583                 // and only fall back on this for unexpected closures.
584                 D("protocol FD died, sending SIGHUP to pid %d", pid_);
585                 if (pid_ != -1) {
586                     kill(pid_, SIGHUP);
587                 }
588 
589                 // We also need to close the pipes connected to the child process
590                 // so that if it ignores SIGHUP and continues to write data it
591                 // won't fill up the pipe and block.
592                 stdinout_sfd_.reset();
593                 stderr_sfd_.reset();
594             }
595             dead_sfd->reset();
596         }
597     }
598 }
599 
PollLoop(SubprocessPollfds * pfds)600 unique_fd* Subprocess::PollLoop(SubprocessPollfds* pfds) {
601     unique_fd* dead_sfd = nullptr;
602     adb_pollfd& stdinout_pfd = pfds->stdinout_pfd();
603     adb_pollfd& stderr_pfd = pfds->stderr_pfd();
604     adb_pollfd& protocol_pfd = pfds->protocol_pfd();
605 
606     // Keep calling poll() and passing data until an FD closes/errors.
607     while (!dead_sfd) {
608         if (adb_poll(pfds->data(), pfds->size(), -1) < 0) {
609             if (errno == EINTR) {
610                 continue;
611             } else {
612                 PLOG(ERROR) << "poll failed, closing subprocess pipes";
613                 stdinout_sfd_.reset(-1);
614                 stderr_sfd_.reset(-1);
615                 return nullptr;
616             }
617         }
618 
619         // Read stdout, write to protocol FD.
620         if (stdinout_pfd.fd != -1 && (stdinout_pfd.revents & POLLIN)) {
621             dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
622         }
623 
624         // Read stderr, write to protocol FD.
625         if (!dead_sfd && stderr_pfd.fd != 1 && (stderr_pfd.revents & POLLIN)) {
626             dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
627         }
628 
629         // Read protocol FD, write to stdin.
630         if (!dead_sfd && protocol_pfd.fd != -1 && (protocol_pfd.revents & POLLIN)) {
631             dead_sfd = PassInput();
632             // If we didn't finish writing, block on stdin write.
633             if (input_bytes_left_) {
634                 protocol_pfd.events &= ~POLLIN;
635                 stdinout_pfd.events |= POLLOUT;
636             }
637         }
638 
639         // Continue writing to stdin; only happens if a previous write blocked.
640         if (!dead_sfd && stdinout_pfd.fd != -1 && (stdinout_pfd.revents & POLLOUT)) {
641             dead_sfd = PassInput();
642             // If we finished writing, go back to blocking on protocol read.
643             if (!input_bytes_left_) {
644                 protocol_pfd.events |= POLLIN;
645                 stdinout_pfd.events &= ~POLLOUT;
646             }
647         }
648 
649         // After handling all of the events we've received, check to see if any fds have died.
650         auto poll_finished = [](int events) {
651             // Don't return failure until we've read out all of the fd's incoming data.
652             return (events & POLLIN) == 0 &&
653                    (events & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL)) != 0;
654         };
655 
656         if (poll_finished(stdinout_pfd.revents)) {
657             return &stdinout_sfd_;
658         }
659 
660         if (poll_finished(stderr_pfd.revents)) {
661             return &stderr_sfd_;
662         }
663 
664         if (poll_finished(protocol_pfd.revents)) {
665             return &protocol_sfd_;
666         }
667     }  // while (!dead_sfd)
668 
669     return dead_sfd;
670 }
671 
PassInput()672 unique_fd* Subprocess::PassInput() {
673     // Only read a new packet if we've finished writing the last one.
674     if (!input_bytes_left_) {
675         if (!input_->Read()) {
676             // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
677             if (errno != 0) {
678                 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.get();
679             }
680             return &protocol_sfd_;
681         }
682 
683         if (stdinout_sfd_ != -1) {
684             switch (input_->id()) {
685                 case ShellProtocol::kIdWindowSizeChange:
686                     int rows, cols, x_pixels, y_pixels;
687                     if (sscanf(input_->data(), "%dx%d,%dx%d",
688                                &rows, &cols, &x_pixels, &y_pixels) == 4) {
689                         winsize ws;
690                         ws.ws_row = rows;
691                         ws.ws_col = cols;
692                         ws.ws_xpixel = x_pixels;
693                         ws.ws_ypixel = y_pixels;
694                         ioctl(stdinout_sfd_.get(), TIOCSWINSZ, &ws);
695                     }
696                     break;
697                 case ShellProtocol::kIdStdin:
698                     input_bytes_left_ = input_->data_length();
699                     break;
700                 case ShellProtocol::kIdCloseStdin:
701                     if (type_ == SubprocessType::kRaw) {
702                         if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
703                             return nullptr;
704                         }
705                         PLOG(ERROR) << "failed to shutdown writes to FD " << stdinout_sfd_.get();
706                         return &stdinout_sfd_;
707                     } else {
708                         // PTYs can't close just input, so rather than close the
709                         // FD and risk losing subprocess output, leave it open.
710                         // This only happens if the client starts a PTY shell
711                         // non-interactively which is rare and unsupported.
712                         // If necessary, the client can manually close the shell
713                         // with `exit` or by killing the adb client process.
714                         D("can't close input for PTY FD %d", stdinout_sfd_.get());
715                     }
716                     break;
717             }
718         }
719     }
720 
721     if (input_bytes_left_ > 0) {
722         int index = input_->data_length() - input_bytes_left_;
723         int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
724         if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
725             if (bytes < 0) {
726                 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.get();
727             }
728             // stdin is done, mark this packet as finished and we'll just start
729             // dumping any further data received from the protocol FD.
730             input_bytes_left_ = 0;
731             return &stdinout_sfd_;
732         } else if (bytes > 0) {
733             input_bytes_left_ -= bytes;
734         }
735     }
736 
737     return nullptr;
738 }
739 
PassOutput(unique_fd * sfd,ShellProtocol::Id id)740 unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
741     int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
742     if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
743         // read() returns EIO if a PTY closes; don't report this as an error,
744         // it just means the subprocess completed.
745         if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
746             PLOG(ERROR) << "error reading output FD " << sfd->get();
747         }
748         return sfd;
749     }
750 
751     if (bytes > 0 && !output_->Write(id, bytes)) {
752         if (errno != 0) {
753             PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.get();
754         }
755         return &protocol_sfd_;
756     }
757 
758     return nullptr;
759 }
760 
WaitForExit()761 void Subprocess::WaitForExit() {
762     int exit_code = 1;
763 
764     D("waiting for pid %d", pid_);
765     while (pid_ != -1) {
766         int status;
767         if (pid_ == waitpid(pid_, &status, 0)) {
768             D("post waitpid (pid=%d) status=%04x", pid_, status);
769             if (WIFSIGNALED(status)) {
770                 exit_code = 0x80 | WTERMSIG(status);
771                 ADB_LOG(Shell) << "subprocess " << pid_ << " killed by signal " << WTERMSIG(status);
772                 break;
773             } else if (!WIFEXITED(status)) {
774                 D("subprocess didn't exit");
775                 break;
776             } else if (WEXITSTATUS(status) >= 0) {
777                 exit_code = WEXITSTATUS(status);
778                 ADB_LOG(Shell) << "subprocess " << pid_ << " exited with status " << exit_code;
779                 break;
780             }
781         }
782     }
783 
784     // If we have an open protocol FD send an exit packet.
785     if (protocol_sfd_ != -1) {
786         output_->data()[0] = exit_code;
787         if (output_->Write(ShellProtocol::kIdExit, 1)) {
788             D("wrote the exit code packet: %d", exit_code);
789         } else {
790             PLOG(ERROR) << "failed to write the exit code packet";
791         }
792         protocol_sfd_.reset(-1);
793     }
794 }
795 
796 }  // namespace
797 
798 // Create a pipe containing the error.
ReportError(SubprocessProtocol protocol,const std::string & message)799 unique_fd ReportError(SubprocessProtocol protocol, const std::string& message) {
800     unique_fd read, write;
801     if (!Pipe(&read, &write)) {
802         PLOG(ERROR) << "failed to create pipe to report error";
803         return unique_fd{};
804     }
805 
806     std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
807     if (protocol == SubprocessProtocol::kShell) {
808         ShellProtocol::Id id = ShellProtocol::kIdStderr;
809         uint32_t length = buf.length();
810         WriteFdExactly(write.get(), &id, sizeof(id));
811         WriteFdExactly(write.get(), &length, sizeof(length));
812     }
813 
814     WriteFdExactly(write.get(), buf.data(), buf.length());
815 
816     if (protocol == SubprocessProtocol::kShell) {
817         ShellProtocol::Id id = ShellProtocol::kIdExit;
818         uint32_t length = 1;
819         char exit_code = 126;
820         WriteFdExactly(write.get(), &id, sizeof(id));
821         WriteFdExactly(write.get(), &length, sizeof(length));
822         WriteFdExactly(write.get(), &exit_code, sizeof(exit_code));
823     }
824 
825     return read;
826 }
827 
StartSubprocess(std::string name,const char * terminal_type,SubprocessType type,SubprocessProtocol protocol)828 unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
829                           SubprocessProtocol protocol) {
830     // If we aren't using the shell protocol we must allocate a PTY to properly close the
831     // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
832     // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
833     // e.g. screenrecord, will never notice the broken pipe and terminate.
834     // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
835     // with select() and will send SIGHUP manually to the child process.
836     bool make_pty_raw = false;
837     if (protocol == SubprocessProtocol::kNone && type == SubprocessType::kRaw) {
838         // Disable PTY input/output processing since the client is expecting raw data.
839         D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
840         type = SubprocessType::kPty;
841         make_pty_raw = true;
842     }
843 
844     unique_fd error_fd;
845     unique_fd fd = StartSubprocess(std::move(name), terminal_type, type, protocol, make_pty_raw,
846                                    protocol, &error_fd);
847     if (fd == -1) {
848         return error_fd;
849     }
850     return fd;
851 }
852 
StartSubprocess(std::string name,const char * terminal_type,SubprocessType type,SubprocessProtocol protocol,bool make_pty_raw,SubprocessProtocol error_protocol,unique_fd * error_fd)853 unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
854                           SubprocessProtocol protocol, bool make_pty_raw,
855                           SubprocessProtocol error_protocol, unique_fd* error_fd) {
856     D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
857       type == SubprocessType::kRaw ? "raw" : "PTY",
858       protocol == SubprocessProtocol::kNone ? "none" : "shell", terminal_type, name.c_str());
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         *error_fd = ReportError(error_protocol, "failed to allocate new subprocess");
865         return {};
866     }
867 
868     std::string error;
869     if (!subprocess->ForkAndExec(&error)) {
870         LOG(ERROR) << "failed to start subprocess: " << error;
871         *error_fd = ReportError(error_protocol, error);
872         return {};
873     }
874 
875     unique_fd local_socket(subprocess->ReleaseLocalSocket());
876     D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
877       subprocess->pid());
878 
879     if (!Subprocess::StartThread(std::move(subprocess), &error)) {
880         LOG(ERROR) << "failed to start subprocess management thread: " << error;
881         *error_fd = ReportError(error_protocol, error);
882         return {};
883     }
884 
885     return local_socket;
886 }
887 
StartCommandInProcess(std::string name,Command command,SubprocessProtocol protocol)888 unique_fd StartCommandInProcess(std::string name, Command command, SubprocessProtocol protocol) {
889     LOG(INFO) << "StartCommandInProcess(" << dump_hex(name.data(), name.size()) << ")";
890 
891     constexpr auto terminal_type = "";
892     constexpr auto type = SubprocessType::kRaw;
893     constexpr auto make_pty_raw = false;
894 
895     auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
896                                                    make_pty_raw);
897     if (!subprocess) {
898         LOG(ERROR) << "failed to allocate new subprocess";
899         return ReportError(protocol, "failed to allocate new subprocess");
900     }
901 
902     std::string error;
903     if (!subprocess->ExecInProcess(std::move(command), &error)) {
904         LOG(ERROR) << "failed to start subprocess: " << error;
905         return ReportError(protocol, error);
906     }
907 
908     unique_fd local_socket(subprocess->ReleaseLocalSocket());
909     D("inprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
910       subprocess->pid());
911 
912     if (!Subprocess::StartThread(std::move(subprocess), &error)) {
913         LOG(ERROR) << "failed to start inprocess management thread: " << error;
914         return ReportError(protocol, error);
915     }
916 
917     return local_socket;
918 }
919