blob: 0fb14c42e0a97b4841c5945c7ad34f6264558738 [file] [log] [blame]
David Pursell4f344bb2015-08-28 15:08:49 -07001/*
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
David Pursell8da19a42015-08-31 10:42:13 -070017// 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
Yabin Cui19bec5b2015-09-22 15:52:57 -070078#define TRACE_TAG SHELL
David Pursell4f344bb2015-08-28 15:08:49 -070079
Yabin Cui5fc22312015-10-06 15:10:05 -070080#include "sysdeps.h"
David Pursell4f344bb2015-08-28 15:08:49 -070081
Yabin Cui5fc22312015-10-06 15:10:05 -070082#include "shell_service.h"
David Pursell4f344bb2015-08-28 15:08:49 -070083
David Pursell917dcfa2015-08-28 18:31:29 -070084#include <errno.h>
Mark Salyzyn81a870e2016-10-05 08:13:56 -070085#include <paths.h>
David Pursell4f344bb2015-08-28 15:08:49 -070086#include <pty.h>
Elliott Hughes90676d92015-11-02 13:29:19 -080087#include <pwd.h>
David Pursell8da19a42015-08-31 10:42:13 -070088#include <sys/select.h>
David Pursell4f344bb2015-08-28 15:08:49 -070089#include <termios.h>
90
David Pursell8da19a42015-08-31 10:42:13 -070091#include <memory>
Josh Gao8d76c452015-12-11 10:52:55 -080092#include <string>
Josh Gao0f3312a2017-04-12 17:00:49 -070093#include <thread>
Josh Gao8d76c452015-12-11 10:52:55 -080094#include <unordered_map>
95#include <vector>
David Pursell8da19a42015-08-31 10:42:13 -070096
Elliott Hughesf55ead92015-12-04 22:00:26 -080097#include <android-base/logging.h>
Elliott Hughes299da1c2017-10-03 08:44:27 -070098#include <android-base/properties.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080099#include <android-base/stringprintf.h>
Mark Salyzyn81a870e2016-10-05 08:13:56 -0700100#include <private/android_logger.h>
Josh Gao0560feb2019-01-22 19:36:15 -0800101
102#if defined(__ANDROID__)
Jiyong Park19c39fa2018-05-29 16:41:30 +0900103#include <selinux/android.h>
Josh Gao0560feb2019-01-22 19:36:15 -0800104#endif
David Pursell4f344bb2015-08-28 15:08:49 -0700105
106#include "adb.h"
107#include "adb_io.h"
108#include "adb_trace.h"
Josh Gaoea7457b2016-08-30 15:39:25 -0700109#include "adb_unique_fd.h"
Yabin Cui5fc22312015-10-06 15:10:05 -0700110#include "adb_utils.h"
Rubin Xu29a64f92016-01-11 10:23:47 +0000111#include "security_log_tags.h"
Josh Gao076b5ba2018-07-25 16:07:26 -0700112#include "shell_protocol.h"
David Pursell4f344bb2015-08-28 15:08:49 -0700113
114namespace {
115
David Pursell917dcfa2015-08-28 18:31:29 -0700116// Reads from |fd| until close or failure.
Josh Gao90228a62019-04-25 14:04:57 -0700117std::string ReadAll(borrowed_fd fd) {
David Pursell917dcfa2015-08-28 18:31:29 -0700118 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);
David Pursell4f344bb2015-08-28 15:08:49 -0700127 }
128
David Pursell917dcfa2015-08-28 18:31:29 -0700129 return received;
130}
131
David Pursell917dcfa2015-08-28 18:31:29 -0700132// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
Elliott Hughes857e6592016-05-27 17:51:24 -0700133bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
David Pursell917dcfa2015-08-28 18:31:29 -0700134 int sockets[2];
135 if (adb_socketpair(sockets) < 0) {
136 PLOG(ERROR) << "cannot create socket pair";
137 return false;
138 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700139 fd1->reset(sockets[0]);
140 fd2->reset(sockets[1]);
David Pursell917dcfa2015-08-28 18:31:29 -0700141 return true;
142}
143
144class Subprocess {
145 public:
Josh Gaof0fa1e42018-12-13 13:06:03 -0800146 Subprocess(std::string command, const char* terminal_type, SubprocessType type,
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800147 SubprocessProtocol protocol, bool make_pty_raw);
David Pursell917dcfa2015-08-28 18:31:29 -0700148 ~Subprocess();
149
150 const std::string& command() const { return command_; }
David Pursell917dcfa2015-08-28 18:31:29 -0700151
Josh Gaoa6545142016-06-22 15:57:12 -0700152 int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
David Pursell917dcfa2015-08-28 18:31:29 -0700153
154 pid_t pid() const { return pid_; }
155
156 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
Josh Gao6d3a75a2016-06-17 14:53:57 -0700157 // and exec's the child. Returns false and sets error on failure.
Josh Gao9dc2e932016-01-25 17:11:43 -0800158 bool ForkAndExec(std::string* _Nonnull error);
David Pursell917dcfa2015-08-28 18:31:29 -0700159
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800160 // Sets up FDs, starts a thread executing command and the manager thread,
161 // Returns false and sets error on failure.
162 bool ExecInProcess(Command command, std::string* _Nonnull error);
163
Josh Gao6d3a75a2016-06-17 14:53:57 -0700164 // Start the subprocess manager thread. Consumes the subprocess, regardless of success.
165 // Returns false and sets error on failure.
166 static bool StartThread(std::unique_ptr<Subprocess> subprocess,
167 std::string* _Nonnull error);
168
David Pursell917dcfa2015-08-28 18:31:29 -0700169 private:
170 // Opens the file at |pts_name|.
Elliott Hughes857e6592016-05-27 17:51:24 -0700171 int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700172
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800173 bool ConnectProtocolEndpoints(std::string* _Nonnull error);
174
Josh Gao7d405252016-02-12 14:31:15 -0800175 static void ThreadHandler(void* userdata);
David Pursell8da19a42015-08-31 10:42:13 -0700176 void PassDataStreams();
David Pursell917dcfa2015-08-28 18:31:29 -0700177 void WaitForExit();
178
Elliott Hughes857e6592016-05-27 17:51:24 -0700179 unique_fd* SelectLoop(fd_set* master_read_set_ptr,
180 fd_set* master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700181
182 // Input/output stream handlers. Success returns nullptr, failure returns
183 // a pointer to the failed FD.
Elliott Hughes857e6592016-05-27 17:51:24 -0700184 unique_fd* PassInput();
185 unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
David Pursell8da19a42015-08-31 10:42:13 -0700186
David Pursell917dcfa2015-08-28 18:31:29 -0700187 const std::string command_;
Elliott Hughesff444562015-11-16 10:55:34 -0800188 const std::string terminal_type_;
David Pursell917dcfa2015-08-28 18:31:29 -0700189 SubprocessType type_;
David Pursell8da19a42015-08-31 10:42:13 -0700190 SubprocessProtocol protocol_;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800191 bool make_pty_raw_;
David Pursell917dcfa2015-08-28 18:31:29 -0700192 pid_t pid_ = -1;
Elliott Hughes857e6592016-05-27 17:51:24 -0700193 unique_fd local_socket_sfd_;
David Pursell917dcfa2015-08-28 18:31:29 -0700194
David Pursell8da19a42015-08-31 10:42:13 -0700195 // Shell protocol variables.
Elliott Hughes857e6592016-05-27 17:51:24 -0700196 unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700197 std::unique_ptr<ShellProtocol> input_, output_;
198 size_t input_bytes_left_ = 0;
199
David Pursell917dcfa2015-08-28 18:31:29 -0700200 DISALLOW_COPY_AND_ASSIGN(Subprocess);
201};
202
Josh Gaof0fa1e42018-12-13 13:06:03 -0800203Subprocess::Subprocess(std::string command, const char* terminal_type, SubprocessType type,
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800204 SubprocessProtocol protocol, bool make_pty_raw)
Josh Gaof0fa1e42018-12-13 13:06:03 -0800205 : command_(std::move(command)),
Elliott Hughesff444562015-11-16 10:55:34 -0800206 terminal_type_(terminal_type ? terminal_type : ""),
207 type_(type),
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800208 protocol_(protocol),
209 make_pty_raw_(make_pty_raw) {}
David Pursell917dcfa2015-08-28 18:31:29 -0700210
211Subprocess::~Subprocess() {
Josh Gao6a98c6e2016-01-19 16:21:17 -0800212 WaitForExit();
David Pursell917dcfa2015-08-28 18:31:29 -0700213}
214
Elliott Hughes299da1c2017-10-03 08:44:27 -0700215static std::string GetHostName() {
216 char buf[HOST_NAME_MAX];
217 if (gethostname(buf, sizeof(buf)) != -1 && strcmp(buf, "localhost") != 0) return buf;
218
219 return android::base::GetProperty("ro.product.device", "android");
220}
221
Josh Gao9dc2e932016-01-25 17:11:43 -0800222bool Subprocess::ForkAndExec(std::string* error) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700223 unique_fd child_stdinout_sfd, child_stderr_sfd;
224 unique_fd parent_error_sfd, child_error_sfd;
Josh Gao95df24c2019-07-30 14:47:25 -0700225 const char* pts_name = nullptr;
David Pursell917dcfa2015-08-28 18:31:29 -0700226
Rubin Xu29a64f92016-01-11 10:23:47 +0000227 if (command_.empty()) {
228 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
229 } else {
230 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
231 }
232
Josh Gao8d76c452015-12-11 10:52:55 -0800233 // Create a socketpair for the fork() child to report any errors back to the parent. Since we
234 // use threads, logging directly from the child might deadlock due to locks held in another
235 // thread during the fork.
David Pursell917dcfa2015-08-28 18:31:29 -0700236 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800237 *error = android::base::StringPrintf(
238 "failed to create pipe for subprocess error reporting: %s", strerror(errno));
239 return false;
David Pursell917dcfa2015-08-28 18:31:29 -0700240 }
241
Josh Gao8d76c452015-12-11 10:52:55 -0800242 // Construct the environment for the child before we fork.
243 passwd* pw = getpwuid(getuid());
244 std::unordered_map<std::string, std::string> env;
Josh Gao81ea0022015-12-11 15:49:12 -0800245 if (environ) {
246 char** current = environ;
247 while (char* env_cstr = *current++) {
248 std::string env_string = env_cstr;
Dan Austin4bdf38b2016-03-28 14:37:01 -0700249 char* delimiter = strchr(&env_string[0], '=');
Josh Gao8d76c452015-12-11 10:52:55 -0800250
Josh Gao81ea0022015-12-11 15:49:12 -0800251 // Drop any values that don't contain '='.
252 if (delimiter) {
253 *delimiter++ = '\0';
254 env[env_string.c_str()] = delimiter;
255 }
256 }
Josh Gao8d76c452015-12-11 10:52:55 -0800257 }
258
259 if (pw != nullptr) {
Josh Gao8d76c452015-12-11 10:52:55 -0800260 env["HOME"] = pw->pw_dir;
Elliott Hughes299da1c2017-10-03 08:44:27 -0700261 env["HOSTNAME"] = GetHostName();
Josh Gao8d76c452015-12-11 10:52:55 -0800262 env["LOGNAME"] = pw->pw_name;
Josh Gao8d76c452015-12-11 10:52:55 -0800263 env["SHELL"] = pw->pw_shell;
Elliott Hughes8719f412017-12-11 10:40:57 -0800264 env["TMPDIR"] = "/data/local/tmp";
Elliott Hughes299da1c2017-10-03 08:44:27 -0700265 env["USER"] = pw->pw_name;
Josh Gao8d76c452015-12-11 10:52:55 -0800266 }
267
268 if (!terminal_type_.empty()) {
269 env["TERM"] = terminal_type_;
270 }
271
272 std::vector<std::string> joined_env;
Chih-Hung Hsieh93eb3892018-12-11 10:34:33 -0800273 for (const auto& it : env) {
Josh Gao8d76c452015-12-11 10:52:55 -0800274 const char* key = it.first.c_str();
275 const char* value = it.second.c_str();
276 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
277 }
278
279 std::vector<const char*> cenv;
280 for (const std::string& str : joined_env) {
281 cenv.push_back(str.c_str());
282 }
283 cenv.push_back(nullptr);
284
David Pursell917dcfa2015-08-28 18:31:29 -0700285 if (type_ == SubprocessType::kPty) {
Josh Gao95df24c2019-07-30 14:47:25 -0700286 unique_fd pty_master(posix_openpt(O_RDWR | O_NOCTTY | O_CLOEXEC));
287 if (pty_master == -1) {
288 *error =
289 android::base::StringPrintf("failed to create pty master: %s", strerror(errno));
290 return false;
291 }
292 if (unlockpt(pty_master.get()) != 0) {
293 *error = android::base::StringPrintf("failed to unlockpt pty master: %s",
294 strerror(errno));
295 return false;
296 }
297
298 pid_ = fork();
299 pts_name = ptsname(pty_master.get());
Josh Gao9a4b5e92016-03-04 17:50:10 -0800300 if (pid_ > 0) {
Josh Gao95df24c2019-07-30 14:47:25 -0700301 stdinout_sfd_ = std::move(pty_master);
Josh Gao9a4b5e92016-03-04 17:50:10 -0800302 }
David Pursell917dcfa2015-08-28 18:31:29 -0700303 } else {
David Pursell8da19a42015-08-31 10:42:13 -0700304 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800305 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
306 strerror(errno));
David Pursell8da19a42015-08-31 10:42:13 -0700307 return false;
308 }
309 // Raw subprocess + shell protocol allows for splitting stderr.
310 if (protocol_ == SubprocessProtocol::kShell &&
311 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800312 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
313 strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700314 return false;
315 }
316 pid_ = fork();
317 }
318
319 if (pid_ == -1) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800320 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700321 return false;
322 }
323
324 if (pid_ == 0) {
325 // Subprocess child.
Elliott Hughesfd20a0f2016-11-17 10:32:16 -0800326 setsid();
David Pursell4f344bb2015-08-28 15:08:49 -0700327
David Pursell917dcfa2015-08-28 18:31:29 -0700328 if (type_ == SubprocessType::kPty) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700329 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursell917dcfa2015-08-28 18:31:29 -0700330 }
331
Josh Gao90228a62019-04-25 14:04:57 -0700332 dup2(child_stdinout_sfd.get(), STDIN_FILENO);
333 dup2(child_stdinout_sfd.get(), STDOUT_FILENO);
334 dup2(child_stderr_sfd != -1 ? child_stderr_sfd.get() : child_stdinout_sfd.get(),
335 STDERR_FILENO);
David Pursell917dcfa2015-08-28 18:31:29 -0700336
337 // exec doesn't trigger destructors, close the FDs manually.
Elliott Hughes857e6592016-05-27 17:51:24 -0700338 stdinout_sfd_.reset(-1);
339 stderr_sfd_.reset(-1);
340 child_stdinout_sfd.reset(-1);
341 child_stderr_sfd.reset(-1);
342 parent_error_sfd.reset(-1);
343 close_on_exec(child_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700344
Elliott Hughes961083e2017-02-17 11:14:33 -0800345 // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
346 // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
347 signal(SIGPIPE, SIG_DFL);
348
Josh Gao212294f2018-03-28 13:16:01 -0700349 // Increase oom_score_adj from -1000, so that the child is visible to the OOM-killer.
350 // Don't treat failure as an error, because old Android kernels explicitly disabled this.
351 int oom_score_adj_fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
352 if (oom_score_adj_fd != -1) {
353 const char* oom_score_adj_value = "-950";
354 TEMP_FAILURE_RETRY(
355 adb_write(oom_score_adj_fd, oom_score_adj_value, strlen(oom_score_adj_value)));
356 }
357
Jiyong Park19c39fa2018-05-29 16:41:30 +0900358#ifdef __ANDROID_RECOVERY__
359 // Special routine for recovery. Switch to shell domain when adbd is
360 // is running with dropped privileged (i.e. not running as root) and
361 // is built for the recovery mode. This is required because recovery
362 // rootfs is not labeled and everything is labeled just as rootfs.
363 char* con = nullptr;
364 if (getcon(&con) == 0) {
365 if (!strcmp(con, "u:r:adbd:s0")) {
366 if (selinux_android_setcon("u:r:shell:s0") < 0) {
367 LOG(FATAL) << "Could not set SELinux context for subprocess";
368 }
369 }
370 freecon(con);
371 } else {
372 LOG(FATAL) << "Failed to get SELinux context";
373 }
374#endif
375
Josh Gao8a631162016-01-19 17:31:09 -0800376 if (command_.empty()) {
Josh Gao28db7292018-03-21 18:06:20 -0700377 // Spawn a login shell if we don't have a command.
378 execle(_PATH_BSHELL, "-" _PATH_BSHELL, nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700379 } else {
Josh Gao8d76c452015-12-11 10:52:55 -0800380 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700381 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700382 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
383 WriteFdExactly(child_error_sfd, strerror(errno));
384 child_error_sfd.reset(-1);
Josh Gao8d76c452015-12-11 10:52:55 -0800385 _Exit(1);
David Pursell917dcfa2015-08-28 18:31:29 -0700386 }
387
388 // Subprocess parent.
David Pursell8da19a42015-08-31 10:42:13 -0700389 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
Elliott Hughes857e6592016-05-27 17:51:24 -0700390 stdinout_sfd_.get(), stderr_sfd_.get());
David Pursell917dcfa2015-08-28 18:31:29 -0700391
392 // Wait to make sure the subprocess exec'd without error.
Elliott Hughes857e6592016-05-27 17:51:24 -0700393 child_error_sfd.reset(-1);
394 std::string error_message = ReadAll(parent_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700395 if (!error_message.empty()) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800396 *error = error_message;
David Pursell917dcfa2015-08-28 18:31:29 -0700397 return false;
398 }
399
Josh Gao8d76c452015-12-11 10:52:55 -0800400 D("subprocess parent: exec completed");
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800401 if (!ConnectProtocolEndpoints(error)) {
402 kill(pid_, SIGKILL);
403 return false;
David Pursell8da19a42015-08-31 10:42:13 -0700404 }
David Pursell917dcfa2015-08-28 18:31:29 -0700405
Josh Gao6d3a75a2016-06-17 14:53:57 -0700406 D("subprocess parent: completed");
407 return true;
408}
409
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800410bool Subprocess::ExecInProcess(Command command, std::string* _Nonnull error) {
411 unique_fd child_stdinout_sfd, child_stderr_sfd;
412
413 CHECK(type_ == SubprocessType::kRaw);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800414
415 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
416
417 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
418 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
419 strerror(errno));
420 return false;
421 }
Alex Buynytskyybeaa8842019-04-05 20:52:32 -0700422 if (protocol_ == SubprocessProtocol::kShell) {
423 // Shell protocol allows for splitting stderr.
424 if (!CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
425 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
426 strerror(errno));
427 return false;
428 }
429 } else {
430 // Raw protocol doesn't support multiple output streams, so combine stdout and stderr.
Josh Gao90228a62019-04-25 14:04:57 -0700431 child_stderr_sfd.reset(dup(child_stdinout_sfd.get()));
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800432 }
433
434 D("execinprocess: stdin/stdout FD = %d, stderr FD = %d", stdinout_sfd_.get(),
435 stderr_sfd_.get());
436
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800437 if (!ConnectProtocolEndpoints(error)) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800438 return false;
439 }
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800440
441 std::thread([inout_sfd = std::move(child_stdinout_sfd), err_sfd = std::move(child_stderr_sfd),
442 command = std::move(command),
443 args = command_]() { command(args, inout_sfd, inout_sfd, err_sfd); })
444 .detach();
445
446 D("execinprocess: completed");
447 return true;
448}
449
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800450bool Subprocess::ConnectProtocolEndpoints(std::string* _Nonnull error) {
451 if (protocol_ == SubprocessProtocol::kNone) {
452 // No protocol: all streams pass through the stdinout FD and hook
453 // directly into the local socket for raw data transfer.
454 local_socket_sfd_.reset(stdinout_sfd_.release());
455 } else {
456 // Required for shell protocol: create another socketpair to intercept data.
457 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
458 *error = android::base::StringPrintf(
459 "failed to create socketpair to intercept data: %s", strerror(errno));
460 return false;
461 }
462 D("protocol FD = %d", protocol_sfd_.get());
463
464 input_ = std::make_unique<ShellProtocol>(protocol_sfd_);
465 output_ = std::make_unique<ShellProtocol>(protocol_sfd_);
466 if (!input_ || !output_) {
467 *error = "failed to allocate shell protocol objects";
468 return false;
469 }
470
471 // Don't let reads/writes to the subprocess block our thread. This isn't
472 // likely but could happen under unusual circumstances, such as if we
473 // write a ton of data to stdin but the subprocess never reads it and
474 // the pipe fills up.
475 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
476 if (fd >= 0) {
477 if (!set_file_block_mode(fd, false)) {
478 *error = android::base::StringPrintf(
479 "failed to set non-blocking mode for fd %d", fd);
480 return false;
481 }
482 }
483 }
484 }
485
486 return true;
487}
488
Josh Gao6d3a75a2016-06-17 14:53:57 -0700489bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
490 Subprocess* raw = subprocess.release();
Josh Gao0f3312a2017-04-12 17:00:49 -0700491 std::thread(ThreadHandler, raw).detach();
David Pursell917dcfa2015-08-28 18:31:29 -0700492
493 return true;
494}
495
Elliott Hughes857e6592016-05-27 17:51:24 -0700496int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
David Pursell917dcfa2015-08-28 18:31:29 -0700497 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
498 if (child_fd == -1) {
499 // Don't use WriteFdFmt; since we're in the fork() child we don't want
500 // to allocate any heap memory to avoid race conditions.
501 const char* messages[] = {"child failed to open pseudo-term slave ",
502 pts_name, ": ", strerror(errno)};
503 for (const char* message : messages) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700504 WriteFdExactly(*error_sfd, message);
David Pursell917dcfa2015-08-28 18:31:29 -0700505 }
Josh Gao57cb2172016-05-13 18:16:43 -0700506 abort();
David Pursell917dcfa2015-08-28 18:31:29 -0700507 }
508
David Pursell182dc322016-01-27 16:07:52 -0800509 if (make_pty_raw_) {
510 termios tattr;
511 if (tcgetattr(child_fd, &tattr) == -1) {
512 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700513 WriteFdExactly(*error_sfd, "tcgetattr failed: ");
514 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700515 abort();
David Pursell182dc322016-01-27 16:07:52 -0800516 }
517
518 cfmakeraw(&tattr);
519 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
520 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700521 WriteFdExactly(*error_sfd, "tcsetattr failed: ");
522 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700523 abort();
David Pursell182dc322016-01-27 16:07:52 -0800524 }
525 }
526
David Pursell917dcfa2015-08-28 18:31:29 -0700527 return child_fd;
David Pursell4f344bb2015-08-28 15:08:49 -0700528}
529
Josh Gao7d405252016-02-12 14:31:15 -0800530void Subprocess::ThreadHandler(void* userdata) {
David Pursell917dcfa2015-08-28 18:31:29 -0700531 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell4f344bb2015-08-28 15:08:49 -0700532
Josh Gaod51515b2017-09-28 16:29:53 -0700533 adb_thread_setname(android::base::StringPrintf("shell svc %d", subprocess->pid()));
David Pursell4f344bb2015-08-28 15:08:49 -0700534
Josh Gao6d3a75a2016-06-17 14:53:57 -0700535 D("passing data streams for PID %d", subprocess->pid());
David Pursell8da19a42015-08-31 10:42:13 -0700536 subprocess->PassDataStreams();
David Pursell4f344bb2015-08-28 15:08:49 -0700537
David Pursell3fe11f62015-10-06 15:30:03 -0700538 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursell917dcfa2015-08-28 18:31:29 -0700539 delete subprocess;
David Pursell4f344bb2015-08-28 15:08:49 -0700540}
541
David Pursell8da19a42015-08-31 10:42:13 -0700542void Subprocess::PassDataStreams() {
Elliott Hughes857e6592016-05-27 17:51:24 -0700543 if (protocol_sfd_ == -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700544 return;
545 }
546
547 // Start by trying to read from the protocol FD, stdout, and stderr.
548 fd_set master_read_set, master_write_set;
549 FD_ZERO(&master_read_set);
550 FD_ZERO(&master_write_set);
Elliott Hughes857e6592016-05-27 17:51:24 -0700551 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
552 if (*sfd != -1) {
Josh Gao90228a62019-04-25 14:04:57 -0700553 FD_SET(sfd->get(), &master_read_set);
David Pursell8da19a42015-08-31 10:42:13 -0700554 }
555 }
556
557 // Pass data until the protocol FD or both the subprocess pipes die, at
558 // which point we can't pass any more data.
Elliott Hughes857e6592016-05-27 17:51:24 -0700559 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
560 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
David Pursell8da19a42015-08-31 10:42:13 -0700561 if (dead_sfd) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700562 D("closing FD %d", dead_sfd->get());
Josh Gao90228a62019-04-25 14:04:57 -0700563 FD_CLR(dead_sfd->get(), &master_read_set);
564 FD_CLR(dead_sfd->get(), &master_write_set);
David Pursell2b8d4a42015-09-14 15:36:26 -0700565 if (dead_sfd == &protocol_sfd_) {
566 // Using SIGHUP is a decent general way to indicate that the
567 // controlling process is going away. If specific signals are
568 // needed (e.g. SIGINT), pass those through the shell protocol
569 // and only fall back on this for unexpected closures.
570 D("protocol FD died, sending SIGHUP to pid %d", pid_);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800571 if (pid_ != -1) {
572 kill(pid_, SIGHUP);
573 }
David Pursellaeee0032016-06-06 09:37:16 -0700574
575 // We also need to close the pipes connected to the child process
576 // so that if it ignores SIGHUP and continues to write data it
577 // won't fill up the pipe and block.
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700578 stdinout_sfd_.reset();
579 stderr_sfd_.reset();
David Pursell2b8d4a42015-09-14 15:36:26 -0700580 }
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700581 dead_sfd->reset();
David Pursell8da19a42015-08-31 10:42:13 -0700582 }
583 }
584}
585
586namespace {
587
Elliott Hughes857e6592016-05-27 17:51:24 -0700588inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
Josh Gao90228a62019-04-25 14:04:57 -0700589 return sfd != -1 && FD_ISSET(sfd.get(), set);
David Pursell8da19a42015-08-31 10:42:13 -0700590}
591
592} // namespace
593
Elliott Hughes857e6592016-05-27 17:51:24 -0700594unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
595 fd_set* master_write_set_ptr) {
David Pursell8da19a42015-08-31 10:42:13 -0700596 fd_set read_set, write_set;
Josh Gao90228a62019-04-25 14:04:57 -0700597 int select_n =
598 std::max(std::max(protocol_sfd_.get(), stdinout_sfd_.get()), stderr_sfd_.get()) + 1;
Elliott Hughes857e6592016-05-27 17:51:24 -0700599 unique_fd* dead_sfd = nullptr;
David Pursell8da19a42015-08-31 10:42:13 -0700600
601 // Keep calling select() and passing data until an FD closes/errors.
602 while (!dead_sfd) {
603 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
604 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
605 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
606 if (errno == EINTR) {
607 continue;
608 } else {
609 PLOG(ERROR) << "select failed, closing subprocess pipes";
Elliott Hughes857e6592016-05-27 17:51:24 -0700610 stdinout_sfd_.reset(-1);
611 stderr_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700612 return nullptr;
613 }
614 }
615
616 // Read stdout, write to protocol FD.
617 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
618 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
619 }
620
621 // Read stderr, write to protocol FD.
622 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
623 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
624 }
625
626 // Read protocol FD, write to stdin.
627 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
628 dead_sfd = PassInput();
629 // If we didn't finish writing, block on stdin write.
630 if (input_bytes_left_) {
Josh Gao90228a62019-04-25 14:04:57 -0700631 FD_CLR(protocol_sfd_.get(), master_read_set_ptr);
632 FD_SET(stdinout_sfd_.get(), master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700633 }
634 }
635
636 // Continue writing to stdin; only happens if a previous write blocked.
637 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
638 dead_sfd = PassInput();
639 // If we finished writing, go back to blocking on protocol read.
640 if (!input_bytes_left_) {
Josh Gao90228a62019-04-25 14:04:57 -0700641 FD_SET(protocol_sfd_.get(), master_read_set_ptr);
642 FD_CLR(stdinout_sfd_.get(), master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700643 }
644 }
645 } // while (!dead_sfd)
646
647 return dead_sfd;
648}
649
Elliott Hughes857e6592016-05-27 17:51:24 -0700650unique_fd* Subprocess::PassInput() {
David Pursell8da19a42015-08-31 10:42:13 -0700651 // Only read a new packet if we've finished writing the last one.
652 if (!input_bytes_left_) {
653 if (!input_->Read()) {
654 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
655 if (errno != 0) {
Josh Gao90228a62019-04-25 14:04:57 -0700656 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.get();
David Pursell8da19a42015-08-31 10:42:13 -0700657 }
658 return &protocol_sfd_;
659 }
660
Elliott Hughes857e6592016-05-27 17:51:24 -0700661 if (stdinout_sfd_ != -1) {
David Pursell3fe11f62015-10-06 15:30:03 -0700662 switch (input_->id()) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800663 case ShellProtocol::kIdWindowSizeChange:
664 int rows, cols, x_pixels, y_pixels;
665 if (sscanf(input_->data(), "%dx%d,%dx%d",
666 &rows, &cols, &x_pixels, &y_pixels) == 4) {
667 winsize ws;
668 ws.ws_row = rows;
669 ws.ws_col = cols;
670 ws.ws_xpixel = x_pixels;
671 ws.ws_ypixel = y_pixels;
Josh Gao90228a62019-04-25 14:04:57 -0700672 ioctl(stdinout_sfd_.get(), TIOCSWINSZ, &ws);
Elliott Hughesa8265792015-11-03 11:18:40 -0800673 }
674 break;
David Pursell3fe11f62015-10-06 15:30:03 -0700675 case ShellProtocol::kIdStdin:
676 input_bytes_left_ = input_->data_length();
677 break;
678 case ShellProtocol::kIdCloseStdin:
679 if (type_ == SubprocessType::kRaw) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700680 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
David Pursell3fe11f62015-10-06 15:30:03 -0700681 return nullptr;
682 }
Josh Gao90228a62019-04-25 14:04:57 -0700683 PLOG(ERROR) << "failed to shutdown writes to FD " << stdinout_sfd_.get();
David Pursell3fe11f62015-10-06 15:30:03 -0700684 return &stdinout_sfd_;
685 } else {
686 // PTYs can't close just input, so rather than close the
687 // FD and risk losing subprocess output, leave it open.
688 // This only happens if the client starts a PTY shell
689 // non-interactively which is rare and unsupported.
690 // If necessary, the client can manually close the shell
691 // with `exit` or by killing the adb client process.
Elliott Hughes857e6592016-05-27 17:51:24 -0700692 D("can't close input for PTY FD %d", stdinout_sfd_.get());
David Pursell3fe11f62015-10-06 15:30:03 -0700693 }
694 break;
695 }
David Pursell8da19a42015-08-31 10:42:13 -0700696 }
697 }
698
699 if (input_bytes_left_ > 0) {
700 int index = input_->data_length() - input_bytes_left_;
Elliott Hughes857e6592016-05-27 17:51:24 -0700701 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
David Pursell8da19a42015-08-31 10:42:13 -0700702 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
703 if (bytes < 0) {
Josh Gao90228a62019-04-25 14:04:57 -0700704 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.get();
David Pursell8da19a42015-08-31 10:42:13 -0700705 }
706 // stdin is done, mark this packet as finished and we'll just start
707 // dumping any further data received from the protocol FD.
708 input_bytes_left_ = 0;
709 return &stdinout_sfd_;
710 } else if (bytes > 0) {
711 input_bytes_left_ -= bytes;
712 }
713 }
714
715 return nullptr;
716}
717
Elliott Hughes857e6592016-05-27 17:51:24 -0700718unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
719 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
David Pursell8da19a42015-08-31 10:42:13 -0700720 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell3fe11f62015-10-06 15:30:03 -0700721 // read() returns EIO if a PTY closes; don't report this as an error,
722 // it just means the subprocess completed.
723 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
Josh Gao90228a62019-04-25 14:04:57 -0700724 PLOG(ERROR) << "error reading output FD " << sfd->get();
David Pursell8da19a42015-08-31 10:42:13 -0700725 }
726 return sfd;
727 }
728
729 if (bytes > 0 && !output_->Write(id, bytes)) {
730 if (errno != 0) {
Josh Gao90228a62019-04-25 14:04:57 -0700731 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.get();
David Pursell8da19a42015-08-31 10:42:13 -0700732 }
733 return &protocol_sfd_;
734 }
735
736 return nullptr;
737}
738
David Pursell917dcfa2015-08-28 18:31:29 -0700739void Subprocess::WaitForExit() {
David Pursell8da19a42015-08-31 10:42:13 -0700740 int exit_code = 1;
741
David Pursell917dcfa2015-08-28 18:31:29 -0700742 D("waiting for pid %d", pid_);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800743 while (pid_ != -1) {
David Pursell4f344bb2015-08-28 15:08:49 -0700744 int status;
David Pursell917dcfa2015-08-28 18:31:29 -0700745 if (pid_ == waitpid(pid_, &status, 0)) {
746 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell4f344bb2015-08-28 15:08:49 -0700747 if (WIFSIGNALED(status)) {
David Pursell8da19a42015-08-31 10:42:13 -0700748 exit_code = 0x80 | WTERMSIG(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700749 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700750 break;
751 } else if (!WIFEXITED(status)) {
David Pursell917dcfa2015-08-28 18:31:29 -0700752 D("subprocess didn't exit");
David Pursell4f344bb2015-08-28 15:08:49 -0700753 break;
754 } else if (WEXITSTATUS(status) >= 0) {
David Pursell8da19a42015-08-31 10:42:13 -0700755 exit_code = WEXITSTATUS(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700756 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700757 break;
758 }
David Pursell917dcfa2015-08-28 18:31:29 -0700759 }
David Pursell4f344bb2015-08-28 15:08:49 -0700760 }
David Pursell917dcfa2015-08-28 18:31:29 -0700761
David Pursell8da19a42015-08-31 10:42:13 -0700762 // If we have an open protocol FD send an exit packet.
Elliott Hughes857e6592016-05-27 17:51:24 -0700763 if (protocol_sfd_ != -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700764 output_->data()[0] = exit_code;
765 if (output_->Write(ShellProtocol::kIdExit, 1)) {
766 D("wrote the exit code packet: %d", exit_code);
767 } else {
768 PLOG(ERROR) << "failed to write the exit code packet";
769 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700770 protocol_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700771 }
David Pursell4f344bb2015-08-28 15:08:49 -0700772}
773
774} // namespace
775
Josh Gao9dc2e932016-01-25 17:11:43 -0800776// Create a pipe containing the error.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800777unique_fd ReportError(SubprocessProtocol protocol, const std::string& message) {
Josh Gao5607e922018-07-25 18:15:52 -0700778 unique_fd read, write;
779 if (!Pipe(&read, &write)) {
780 PLOG(ERROR) << "failed to create pipe to report error";
781 return unique_fd{};
Josh Gao9dc2e932016-01-25 17:11:43 -0800782 }
783
784 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
785 if (protocol == SubprocessProtocol::kShell) {
786 ShellProtocol::Id id = ShellProtocol::kIdStderr;
787 uint32_t length = buf.length();
Josh Gao5607e922018-07-25 18:15:52 -0700788 WriteFdExactly(write.get(), &id, sizeof(id));
789 WriteFdExactly(write.get(), &length, sizeof(length));
Josh Gao9dc2e932016-01-25 17:11:43 -0800790 }
791
Josh Gao5607e922018-07-25 18:15:52 -0700792 WriteFdExactly(write.get(), buf.data(), buf.length());
Josh Gao9dc2e932016-01-25 17:11:43 -0800793
794 if (protocol == SubprocessProtocol::kShell) {
795 ShellProtocol::Id id = ShellProtocol::kIdExit;
796 uint32_t length = 1;
797 char exit_code = 126;
Josh Gao5607e922018-07-25 18:15:52 -0700798 WriteFdExactly(write.get(), &id, sizeof(id));
799 WriteFdExactly(write.get(), &length, sizeof(length));
800 WriteFdExactly(write.get(), &exit_code, sizeof(exit_code));
Josh Gao9dc2e932016-01-25 17:11:43 -0800801 }
802
Josh Gao5607e922018-07-25 18:15:52 -0700803 return read;
Josh Gao9dc2e932016-01-25 17:11:43 -0800804}
805
Josh Gaof0fa1e42018-12-13 13:06:03 -0800806unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
Josh Gao5607e922018-07-25 18:15:52 -0700807 SubprocessProtocol protocol) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800808 // If we aren't using the shell protocol we must allocate a PTY to properly close the
809 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
810 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
811 // e.g. screenrecord, will never notice the broken pipe and terminate.
812 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
813 // with select() and will send SIGHUP manually to the child process.
814 bool make_pty_raw = false;
815 if (protocol == SubprocessProtocol::kNone && type == SubprocessType::kRaw) {
816 // Disable PTY input/output processing since the client is expecting raw data.
817 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
818 type = SubprocessType::kPty;
819 make_pty_raw = true;
820 }
821
822 unique_fd error_fd;
823 unique_fd fd = StartSubprocess(std::move(name), terminal_type, type, protocol, make_pty_raw,
824 protocol, &error_fd);
825 if (fd == -1) {
826 return error_fd;
827 }
828 return fd;
829}
830
831unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
832 SubprocessProtocol protocol, bool make_pty_raw,
833 SubprocessProtocol error_protocol, unique_fd* error_fd) {
Elliott Hughesff444562015-11-16 10:55:34 -0800834 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell8da19a42015-08-31 10:42:13 -0700835 type == SubprocessType::kRaw ? "raw" : "PTY",
Josh Gaof0fa1e42018-12-13 13:06:03 -0800836 protocol == SubprocessProtocol::kNone ? "none" : "shell", terminal_type, name.c_str());
David Pursell4f344bb2015-08-28 15:08:49 -0700837
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800838 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
839 make_pty_raw);
David Pursell917dcfa2015-08-28 18:31:29 -0700840 if (!subprocess) {
841 LOG(ERROR) << "failed to allocate new subprocess";
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800842 *error_fd = ReportError(error_protocol, "failed to allocate new subprocess");
843 return {};
David Pursell4f344bb2015-08-28 15:08:49 -0700844 }
845
Josh Gao9dc2e932016-01-25 17:11:43 -0800846 std::string error;
847 if (!subprocess->ForkAndExec(&error)) {
848 LOG(ERROR) << "failed to start subprocess: " << error;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800849 *error_fd = ReportError(error_protocol, error);
850 return {};
David Pursell917dcfa2015-08-28 18:31:29 -0700851 }
852
Josh Gao8d84a312016-06-23 11:21:11 -0700853 unique_fd local_socket(subprocess->ReleaseLocalSocket());
854 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
855 subprocess->pid());
Josh Gao6d3a75a2016-06-17 14:53:57 -0700856
857 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
858 LOG(ERROR) << "failed to start subprocess management thread: " << error;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800859 *error_fd = ReportError(error_protocol, error);
860 return {};
861 }
862
863 return local_socket;
864}
865
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800866unique_fd StartCommandInProcess(std::string name, Command command, SubprocessProtocol protocol) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800867 LOG(INFO) << "StartCommandInProcess(" << dump_hex(name.data(), name.size()) << ")";
868
869 constexpr auto terminal_type = "";
870 constexpr auto type = SubprocessType::kRaw;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800871 constexpr auto make_pty_raw = false;
872
873 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
874 make_pty_raw);
875 if (!subprocess) {
876 LOG(ERROR) << "failed to allocate new subprocess";
877 return ReportError(protocol, "failed to allocate new subprocess");
878 }
879
880 std::string error;
881 if (!subprocess->ExecInProcess(std::move(command), &error)) {
882 LOG(ERROR) << "failed to start subprocess: " << error;
883 return ReportError(protocol, error);
884 }
885
886 unique_fd local_socket(subprocess->ReleaseLocalSocket());
887 D("inprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
888 subprocess->pid());
889
890 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
891 LOG(ERROR) << "failed to start inprocess management thread: " << error;
Josh Gao6d3a75a2016-06-17 14:53:57 -0700892 return ReportError(protocol, error);
893 }
894
Josh Gao5607e922018-07-25 18:15:52 -0700895 return local_socket;
David Pursell4f344bb2015-08-28 15:08:49 -0700896}