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