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