blob: e9d9c63fc7704086648ad7e96d45b661db479a87 [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.
117std::string ReadAll(int fd) {
118 char buffer[512];
119 std::string received;
120
121 while (1) {
122 int bytes = adb_read(fd, buffer, sizeof(buffer));
123 if (bytes <= 0) {
124 break;
125 }
126 received.append(buffer, bytes);
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;
David Pursell917dcfa2015-08-28 18:31:29 -0700225 char pts_name[PATH_MAX];
226
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) {
286 int fd;
287 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
Josh Gao9a4b5e92016-03-04 17:50:10 -0800288 if (pid_ > 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700289 stdinout_sfd_.reset(fd);
Josh Gao9a4b5e92016-03-04 17:50:10 -0800290 }
David Pursell917dcfa2015-08-28 18:31:29 -0700291 } else {
David Pursell8da19a42015-08-31 10:42:13 -0700292 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800293 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
294 strerror(errno));
David Pursell8da19a42015-08-31 10:42:13 -0700295 return false;
296 }
297 // Raw subprocess + shell protocol allows for splitting stderr.
298 if (protocol_ == SubprocessProtocol::kShell &&
299 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800300 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
301 strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700302 return false;
303 }
304 pid_ = fork();
305 }
306
307 if (pid_ == -1) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800308 *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
David Pursell917dcfa2015-08-28 18:31:29 -0700309 return false;
310 }
311
312 if (pid_ == 0) {
313 // Subprocess child.
Elliott Hughesfd20a0f2016-11-17 10:32:16 -0800314 setsid();
David Pursell4f344bb2015-08-28 15:08:49 -0700315
David Pursell917dcfa2015-08-28 18:31:29 -0700316 if (type_ == SubprocessType::kPty) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700317 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursell917dcfa2015-08-28 18:31:29 -0700318 }
319
Elliott Hughes857e6592016-05-27 17:51:24 -0700320 dup2(child_stdinout_sfd, STDIN_FILENO);
321 dup2(child_stdinout_sfd, STDOUT_FILENO);
322 dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
David Pursell917dcfa2015-08-28 18:31:29 -0700323
324 // exec doesn't trigger destructors, close the FDs manually.
Elliott Hughes857e6592016-05-27 17:51:24 -0700325 stdinout_sfd_.reset(-1);
326 stderr_sfd_.reset(-1);
327 child_stdinout_sfd.reset(-1);
328 child_stderr_sfd.reset(-1);
329 parent_error_sfd.reset(-1);
330 close_on_exec(child_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700331
Elliott Hughes961083e2017-02-17 11:14:33 -0800332 // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
333 // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
334 signal(SIGPIPE, SIG_DFL);
335
Josh Gao212294f2018-03-28 13:16:01 -0700336 // Increase oom_score_adj from -1000, so that the child is visible to the OOM-killer.
337 // Don't treat failure as an error, because old Android kernels explicitly disabled this.
338 int oom_score_adj_fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
339 if (oom_score_adj_fd != -1) {
340 const char* oom_score_adj_value = "-950";
341 TEMP_FAILURE_RETRY(
342 adb_write(oom_score_adj_fd, oom_score_adj_value, strlen(oom_score_adj_value)));
343 }
344
Jiyong Park19c39fa2018-05-29 16:41:30 +0900345#ifdef __ANDROID_RECOVERY__
346 // Special routine for recovery. Switch to shell domain when adbd is
347 // is running with dropped privileged (i.e. not running as root) and
348 // is built for the recovery mode. This is required because recovery
349 // rootfs is not labeled and everything is labeled just as rootfs.
350 char* con = nullptr;
351 if (getcon(&con) == 0) {
352 if (!strcmp(con, "u:r:adbd:s0")) {
353 if (selinux_android_setcon("u:r:shell:s0") < 0) {
354 LOG(FATAL) << "Could not set SELinux context for subprocess";
355 }
356 }
357 freecon(con);
358 } else {
359 LOG(FATAL) << "Failed to get SELinux context";
360 }
361#endif
362
Josh Gao8a631162016-01-19 17:31:09 -0800363 if (command_.empty()) {
Josh Gao28db7292018-03-21 18:06:20 -0700364 // Spawn a login shell if we don't have a command.
365 execle(_PATH_BSHELL, "-" _PATH_BSHELL, nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700366 } else {
Josh Gao8d76c452015-12-11 10:52:55 -0800367 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
David Pursell917dcfa2015-08-28 18:31:29 -0700368 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700369 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
370 WriteFdExactly(child_error_sfd, strerror(errno));
371 child_error_sfd.reset(-1);
Josh Gao8d76c452015-12-11 10:52:55 -0800372 _Exit(1);
David Pursell917dcfa2015-08-28 18:31:29 -0700373 }
374
375 // Subprocess parent.
David Pursell8da19a42015-08-31 10:42:13 -0700376 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
Elliott Hughes857e6592016-05-27 17:51:24 -0700377 stdinout_sfd_.get(), stderr_sfd_.get());
David Pursell917dcfa2015-08-28 18:31:29 -0700378
379 // Wait to make sure the subprocess exec'd without error.
Elliott Hughes857e6592016-05-27 17:51:24 -0700380 child_error_sfd.reset(-1);
381 std::string error_message = ReadAll(parent_error_sfd);
David Pursell917dcfa2015-08-28 18:31:29 -0700382 if (!error_message.empty()) {
Josh Gao9dc2e932016-01-25 17:11:43 -0800383 *error = error_message;
David Pursell917dcfa2015-08-28 18:31:29 -0700384 return false;
385 }
386
Josh Gao8d76c452015-12-11 10:52:55 -0800387 D("subprocess parent: exec completed");
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800388 if (!ConnectProtocolEndpoints(error)) {
389 kill(pid_, SIGKILL);
390 return false;
David Pursell8da19a42015-08-31 10:42:13 -0700391 }
David Pursell917dcfa2015-08-28 18:31:29 -0700392
Josh Gao6d3a75a2016-06-17 14:53:57 -0700393 D("subprocess parent: completed");
394 return true;
395}
396
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800397bool Subprocess::ExecInProcess(Command command, std::string* _Nonnull error) {
398 unique_fd child_stdinout_sfd, child_stderr_sfd;
399
400 CHECK(type_ == SubprocessType::kRaw);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800401
402 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
403
404 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
405 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
406 strerror(errno));
407 return false;
408 }
409 // Raw subprocess + shell protocol allows for splitting stderr.
410 if (!CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
411 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
412 strerror(errno));
413 return false;
414 }
415
416 D("execinprocess: stdin/stdout FD = %d, stderr FD = %d", stdinout_sfd_.get(),
417 stderr_sfd_.get());
418
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800419 if (!ConnectProtocolEndpoints(error)) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800420 return false;
421 }
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800422
423 std::thread([inout_sfd = std::move(child_stdinout_sfd), err_sfd = std::move(child_stderr_sfd),
424 command = std::move(command),
425 args = command_]() { command(args, inout_sfd, inout_sfd, err_sfd); })
426 .detach();
427
428 D("execinprocess: completed");
429 return true;
430}
431
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800432bool Subprocess::ConnectProtocolEndpoints(std::string* _Nonnull error) {
433 if (protocol_ == SubprocessProtocol::kNone) {
434 // No protocol: all streams pass through the stdinout FD and hook
435 // directly into the local socket for raw data transfer.
436 local_socket_sfd_.reset(stdinout_sfd_.release());
437 } else {
438 // Required for shell protocol: create another socketpair to intercept data.
439 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
440 *error = android::base::StringPrintf(
441 "failed to create socketpair to intercept data: %s", strerror(errno));
442 return false;
443 }
444 D("protocol FD = %d", protocol_sfd_.get());
445
446 input_ = std::make_unique<ShellProtocol>(protocol_sfd_);
447 output_ = std::make_unique<ShellProtocol>(protocol_sfd_);
448 if (!input_ || !output_) {
449 *error = "failed to allocate shell protocol objects";
450 return false;
451 }
452
453 // Don't let reads/writes to the subprocess block our thread. This isn't
454 // likely but could happen under unusual circumstances, such as if we
455 // write a ton of data to stdin but the subprocess never reads it and
456 // the pipe fills up.
457 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
458 if (fd >= 0) {
459 if (!set_file_block_mode(fd, false)) {
460 *error = android::base::StringPrintf(
461 "failed to set non-blocking mode for fd %d", fd);
462 return false;
463 }
464 }
465 }
466 }
467
468 return true;
469}
470
Josh Gao6d3a75a2016-06-17 14:53:57 -0700471bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
472 Subprocess* raw = subprocess.release();
Josh Gao0f3312a2017-04-12 17:00:49 -0700473 std::thread(ThreadHandler, raw).detach();
David Pursell917dcfa2015-08-28 18:31:29 -0700474
475 return true;
476}
477
Elliott Hughes857e6592016-05-27 17:51:24 -0700478int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
David Pursell917dcfa2015-08-28 18:31:29 -0700479 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
480 if (child_fd == -1) {
481 // Don't use WriteFdFmt; since we're in the fork() child we don't want
482 // to allocate any heap memory to avoid race conditions.
483 const char* messages[] = {"child failed to open pseudo-term slave ",
484 pts_name, ": ", strerror(errno)};
485 for (const char* message : messages) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700486 WriteFdExactly(*error_sfd, message);
David Pursell917dcfa2015-08-28 18:31:29 -0700487 }
Josh Gao57cb2172016-05-13 18:16:43 -0700488 abort();
David Pursell917dcfa2015-08-28 18:31:29 -0700489 }
490
David Pursell182dc322016-01-27 16:07:52 -0800491 if (make_pty_raw_) {
492 termios tattr;
493 if (tcgetattr(child_fd, &tattr) == -1) {
494 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700495 WriteFdExactly(*error_sfd, "tcgetattr failed: ");
496 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700497 abort();
David Pursell182dc322016-01-27 16:07:52 -0800498 }
499
500 cfmakeraw(&tattr);
501 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
502 int saved_errno = errno;
Elliott Hughes857e6592016-05-27 17:51:24 -0700503 WriteFdExactly(*error_sfd, "tcsetattr failed: ");
504 WriteFdExactly(*error_sfd, strerror(saved_errno));
Josh Gao57cb2172016-05-13 18:16:43 -0700505 abort();
David Pursell182dc322016-01-27 16:07:52 -0800506 }
507 }
508
David Pursell917dcfa2015-08-28 18:31:29 -0700509 return child_fd;
David Pursell4f344bb2015-08-28 15:08:49 -0700510}
511
Josh Gao7d405252016-02-12 14:31:15 -0800512void Subprocess::ThreadHandler(void* userdata) {
David Pursell917dcfa2015-08-28 18:31:29 -0700513 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell4f344bb2015-08-28 15:08:49 -0700514
Josh Gaod51515b2017-09-28 16:29:53 -0700515 adb_thread_setname(android::base::StringPrintf("shell svc %d", subprocess->pid()));
David Pursell4f344bb2015-08-28 15:08:49 -0700516
Josh Gao6d3a75a2016-06-17 14:53:57 -0700517 D("passing data streams for PID %d", subprocess->pid());
David Pursell8da19a42015-08-31 10:42:13 -0700518 subprocess->PassDataStreams();
David Pursell4f344bb2015-08-28 15:08:49 -0700519
David Pursell3fe11f62015-10-06 15:30:03 -0700520 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursell917dcfa2015-08-28 18:31:29 -0700521 delete subprocess;
David Pursell4f344bb2015-08-28 15:08:49 -0700522}
523
David Pursell8da19a42015-08-31 10:42:13 -0700524void Subprocess::PassDataStreams() {
Elliott Hughes857e6592016-05-27 17:51:24 -0700525 if (protocol_sfd_ == -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700526 return;
527 }
528
529 // Start by trying to read from the protocol FD, stdout, and stderr.
530 fd_set master_read_set, master_write_set;
531 FD_ZERO(&master_read_set);
532 FD_ZERO(&master_write_set);
Elliott Hughes857e6592016-05-27 17:51:24 -0700533 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
534 if (*sfd != -1) {
535 FD_SET(*sfd, &master_read_set);
David Pursell8da19a42015-08-31 10:42:13 -0700536 }
537 }
538
539 // Pass data until the protocol FD or both the subprocess pipes die, at
540 // which point we can't pass any more data.
Elliott Hughes857e6592016-05-27 17:51:24 -0700541 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
542 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
David Pursell8da19a42015-08-31 10:42:13 -0700543 if (dead_sfd) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700544 D("closing FD %d", dead_sfd->get());
545 FD_CLR(*dead_sfd, &master_read_set);
546 FD_CLR(*dead_sfd, &master_write_set);
David Pursell2b8d4a42015-09-14 15:36:26 -0700547 if (dead_sfd == &protocol_sfd_) {
548 // Using SIGHUP is a decent general way to indicate that the
549 // controlling process is going away. If specific signals are
550 // needed (e.g. SIGINT), pass those through the shell protocol
551 // and only fall back on this for unexpected closures.
552 D("protocol FD died, sending SIGHUP to pid %d", pid_);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800553 if (pid_ != -1) {
554 kill(pid_, SIGHUP);
555 }
David Pursellaeee0032016-06-06 09:37:16 -0700556
557 // We also need to close the pipes connected to the child process
558 // so that if it ignores SIGHUP and continues to write data it
559 // won't fill up the pipe and block.
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700560 stdinout_sfd_.reset();
561 stderr_sfd_.reset();
David Pursell2b8d4a42015-09-14 15:36:26 -0700562 }
Josh Gaoc2d2cb62016-09-14 12:47:02 -0700563 dead_sfd->reset();
David Pursell8da19a42015-08-31 10:42:13 -0700564 }
565 }
566}
567
568namespace {
569
Elliott Hughes857e6592016-05-27 17:51:24 -0700570inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
571 return sfd != -1 && FD_ISSET(sfd, set);
David Pursell8da19a42015-08-31 10:42:13 -0700572}
573
574} // namespace
575
Elliott Hughes857e6592016-05-27 17:51:24 -0700576unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
577 fd_set* master_write_set_ptr) {
David Pursell8da19a42015-08-31 10:42:13 -0700578 fd_set read_set, write_set;
Elliott Hughes857e6592016-05-27 17:51:24 -0700579 int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
580 unique_fd* dead_sfd = nullptr;
David Pursell8da19a42015-08-31 10:42:13 -0700581
582 // Keep calling select() and passing data until an FD closes/errors.
583 while (!dead_sfd) {
584 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
585 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
586 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
587 if (errno == EINTR) {
588 continue;
589 } else {
590 PLOG(ERROR) << "select failed, closing subprocess pipes";
Elliott Hughes857e6592016-05-27 17:51:24 -0700591 stdinout_sfd_.reset(-1);
592 stderr_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700593 return nullptr;
594 }
595 }
596
597 // Read stdout, write to protocol FD.
598 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
599 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
600 }
601
602 // Read stderr, write to protocol FD.
603 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
604 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
605 }
606
607 // Read protocol FD, write to stdin.
608 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
609 dead_sfd = PassInput();
610 // If we didn't finish writing, block on stdin write.
611 if (input_bytes_left_) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700612 FD_CLR(protocol_sfd_, master_read_set_ptr);
613 FD_SET(stdinout_sfd_, master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700614 }
615 }
616
617 // Continue writing to stdin; only happens if a previous write blocked.
618 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
619 dead_sfd = PassInput();
620 // If we finished writing, go back to blocking on protocol read.
621 if (!input_bytes_left_) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700622 FD_SET(protocol_sfd_, master_read_set_ptr);
623 FD_CLR(stdinout_sfd_, master_write_set_ptr);
David Pursell8da19a42015-08-31 10:42:13 -0700624 }
625 }
626 } // while (!dead_sfd)
627
628 return dead_sfd;
629}
630
Elliott Hughes857e6592016-05-27 17:51:24 -0700631unique_fd* Subprocess::PassInput() {
David Pursell8da19a42015-08-31 10:42:13 -0700632 // Only read a new packet if we've finished writing the last one.
633 if (!input_bytes_left_) {
634 if (!input_->Read()) {
635 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
636 if (errno != 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700637 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700638 }
639 return &protocol_sfd_;
640 }
641
Elliott Hughes857e6592016-05-27 17:51:24 -0700642 if (stdinout_sfd_ != -1) {
David Pursell3fe11f62015-10-06 15:30:03 -0700643 switch (input_->id()) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800644 case ShellProtocol::kIdWindowSizeChange:
645 int rows, cols, x_pixels, y_pixels;
646 if (sscanf(input_->data(), "%dx%d,%dx%d",
647 &rows, &cols, &x_pixels, &y_pixels) == 4) {
648 winsize ws;
649 ws.ws_row = rows;
650 ws.ws_col = cols;
651 ws.ws_xpixel = x_pixels;
652 ws.ws_ypixel = y_pixels;
Elliott Hughes857e6592016-05-27 17:51:24 -0700653 ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
Elliott Hughesa8265792015-11-03 11:18:40 -0800654 }
655 break;
David Pursell3fe11f62015-10-06 15:30:03 -0700656 case ShellProtocol::kIdStdin:
657 input_bytes_left_ = input_->data_length();
658 break;
659 case ShellProtocol::kIdCloseStdin:
660 if (type_ == SubprocessType::kRaw) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700661 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
David Pursell3fe11f62015-10-06 15:30:03 -0700662 return nullptr;
663 }
664 PLOG(ERROR) << "failed to shutdown writes to FD "
Elliott Hughes857e6592016-05-27 17:51:24 -0700665 << stdinout_sfd_;
David Pursell3fe11f62015-10-06 15:30:03 -0700666 return &stdinout_sfd_;
667 } else {
668 // PTYs can't close just input, so rather than close the
669 // FD and risk losing subprocess output, leave it open.
670 // This only happens if the client starts a PTY shell
671 // non-interactively which is rare and unsupported.
672 // If necessary, the client can manually close the shell
673 // with `exit` or by killing the adb client process.
Elliott Hughes857e6592016-05-27 17:51:24 -0700674 D("can't close input for PTY FD %d", stdinout_sfd_.get());
David Pursell3fe11f62015-10-06 15:30:03 -0700675 }
676 break;
677 }
David Pursell8da19a42015-08-31 10:42:13 -0700678 }
679 }
680
681 if (input_bytes_left_ > 0) {
682 int index = input_->data_length() - input_bytes_left_;
Elliott Hughes857e6592016-05-27 17:51:24 -0700683 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
David Pursell8da19a42015-08-31 10:42:13 -0700684 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
685 if (bytes < 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700686 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700687 }
688 // stdin is done, mark this packet as finished and we'll just start
689 // dumping any further data received from the protocol FD.
690 input_bytes_left_ = 0;
691 return &stdinout_sfd_;
692 } else if (bytes > 0) {
693 input_bytes_left_ -= bytes;
694 }
695 }
696
697 return nullptr;
698}
699
Elliott Hughes857e6592016-05-27 17:51:24 -0700700unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
701 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
David Pursell8da19a42015-08-31 10:42:13 -0700702 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell3fe11f62015-10-06 15:30:03 -0700703 // read() returns EIO if a PTY closes; don't report this as an error,
704 // it just means the subprocess completed.
705 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700706 PLOG(ERROR) << "error reading output FD " << *sfd;
David Pursell8da19a42015-08-31 10:42:13 -0700707 }
708 return sfd;
709 }
710
711 if (bytes > 0 && !output_->Write(id, bytes)) {
712 if (errno != 0) {
Elliott Hughes857e6592016-05-27 17:51:24 -0700713 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
David Pursell8da19a42015-08-31 10:42:13 -0700714 }
715 return &protocol_sfd_;
716 }
717
718 return nullptr;
719}
720
David Pursell917dcfa2015-08-28 18:31:29 -0700721void Subprocess::WaitForExit() {
David Pursell8da19a42015-08-31 10:42:13 -0700722 int exit_code = 1;
723
David Pursell917dcfa2015-08-28 18:31:29 -0700724 D("waiting for pid %d", pid_);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800725 while (pid_ != -1) {
David Pursell4f344bb2015-08-28 15:08:49 -0700726 int status;
David Pursell917dcfa2015-08-28 18:31:29 -0700727 if (pid_ == waitpid(pid_, &status, 0)) {
728 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell4f344bb2015-08-28 15:08:49 -0700729 if (WIFSIGNALED(status)) {
David Pursell8da19a42015-08-31 10:42:13 -0700730 exit_code = 0x80 | WTERMSIG(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700731 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700732 break;
733 } else if (!WIFEXITED(status)) {
David Pursell917dcfa2015-08-28 18:31:29 -0700734 D("subprocess didn't exit");
David Pursell4f344bb2015-08-28 15:08:49 -0700735 break;
736 } else if (WEXITSTATUS(status) >= 0) {
David Pursell8da19a42015-08-31 10:42:13 -0700737 exit_code = WEXITSTATUS(status);
David Pursell917dcfa2015-08-28 18:31:29 -0700738 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell4f344bb2015-08-28 15:08:49 -0700739 break;
740 }
David Pursell917dcfa2015-08-28 18:31:29 -0700741 }
David Pursell4f344bb2015-08-28 15:08:49 -0700742 }
David Pursell917dcfa2015-08-28 18:31:29 -0700743
David Pursell8da19a42015-08-31 10:42:13 -0700744 // If we have an open protocol FD send an exit packet.
Elliott Hughes857e6592016-05-27 17:51:24 -0700745 if (protocol_sfd_ != -1) {
David Pursell8da19a42015-08-31 10:42:13 -0700746 output_->data()[0] = exit_code;
747 if (output_->Write(ShellProtocol::kIdExit, 1)) {
748 D("wrote the exit code packet: %d", exit_code);
749 } else {
750 PLOG(ERROR) << "failed to write the exit code packet";
751 }
Elliott Hughes857e6592016-05-27 17:51:24 -0700752 protocol_sfd_.reset(-1);
David Pursell8da19a42015-08-31 10:42:13 -0700753 }
David Pursell4f344bb2015-08-28 15:08:49 -0700754}
755
756} // namespace
757
Josh Gao9dc2e932016-01-25 17:11:43 -0800758// Create a pipe containing the error.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800759unique_fd ReportError(SubprocessProtocol protocol, const std::string& message) {
Josh Gao5607e922018-07-25 18:15:52 -0700760 unique_fd read, write;
761 if (!Pipe(&read, &write)) {
762 PLOG(ERROR) << "failed to create pipe to report error";
763 return unique_fd{};
Josh Gao9dc2e932016-01-25 17:11:43 -0800764 }
765
766 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
767 if (protocol == SubprocessProtocol::kShell) {
768 ShellProtocol::Id id = ShellProtocol::kIdStderr;
769 uint32_t length = buf.length();
Josh Gao5607e922018-07-25 18:15:52 -0700770 WriteFdExactly(write.get(), &id, sizeof(id));
771 WriteFdExactly(write.get(), &length, sizeof(length));
Josh Gao9dc2e932016-01-25 17:11:43 -0800772 }
773
Josh Gao5607e922018-07-25 18:15:52 -0700774 WriteFdExactly(write.get(), buf.data(), buf.length());
Josh Gao9dc2e932016-01-25 17:11:43 -0800775
776 if (protocol == SubprocessProtocol::kShell) {
777 ShellProtocol::Id id = ShellProtocol::kIdExit;
778 uint32_t length = 1;
779 char exit_code = 126;
Josh Gao5607e922018-07-25 18:15:52 -0700780 WriteFdExactly(write.get(), &id, sizeof(id));
781 WriteFdExactly(write.get(), &length, sizeof(length));
782 WriteFdExactly(write.get(), &exit_code, sizeof(exit_code));
Josh Gao9dc2e932016-01-25 17:11:43 -0800783 }
784
Josh Gao5607e922018-07-25 18:15:52 -0700785 return read;
Josh Gao9dc2e932016-01-25 17:11:43 -0800786}
787
Josh Gaof0fa1e42018-12-13 13:06:03 -0800788unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
Josh Gao5607e922018-07-25 18:15:52 -0700789 SubprocessProtocol protocol) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800790 // If we aren't using the shell protocol we must allocate a PTY to properly close the
791 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
792 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
793 // e.g. screenrecord, will never notice the broken pipe and terminate.
794 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
795 // with select() and will send SIGHUP manually to the child process.
796 bool make_pty_raw = false;
797 if (protocol == SubprocessProtocol::kNone && type == SubprocessType::kRaw) {
798 // Disable PTY input/output processing since the client is expecting raw data.
799 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
800 type = SubprocessType::kPty;
801 make_pty_raw = true;
802 }
803
804 unique_fd error_fd;
805 unique_fd fd = StartSubprocess(std::move(name), terminal_type, type, protocol, make_pty_raw,
806 protocol, &error_fd);
807 if (fd == -1) {
808 return error_fd;
809 }
810 return fd;
811}
812
813unique_fd StartSubprocess(std::string name, const char* terminal_type, SubprocessType type,
814 SubprocessProtocol protocol, bool make_pty_raw,
815 SubprocessProtocol error_protocol, unique_fd* error_fd) {
Elliott Hughesff444562015-11-16 10:55:34 -0800816 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell8da19a42015-08-31 10:42:13 -0700817 type == SubprocessType::kRaw ? "raw" : "PTY",
Josh Gaof0fa1e42018-12-13 13:06:03 -0800818 protocol == SubprocessProtocol::kNone ? "none" : "shell", terminal_type, name.c_str());
David Pursell4f344bb2015-08-28 15:08:49 -0700819
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800820 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
821 make_pty_raw);
David Pursell917dcfa2015-08-28 18:31:29 -0700822 if (!subprocess) {
823 LOG(ERROR) << "failed to allocate new subprocess";
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800824 *error_fd = ReportError(error_protocol, "failed to allocate new subprocess");
825 return {};
David Pursell4f344bb2015-08-28 15:08:49 -0700826 }
827
Josh Gao9dc2e932016-01-25 17:11:43 -0800828 std::string error;
829 if (!subprocess->ForkAndExec(&error)) {
830 LOG(ERROR) << "failed to start subprocess: " << error;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800831 *error_fd = ReportError(error_protocol, error);
832 return {};
David Pursell917dcfa2015-08-28 18:31:29 -0700833 }
834
Josh Gao8d84a312016-06-23 11:21:11 -0700835 unique_fd local_socket(subprocess->ReleaseLocalSocket());
836 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
837 subprocess->pid());
Josh Gao6d3a75a2016-06-17 14:53:57 -0700838
839 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
840 LOG(ERROR) << "failed to start subprocess management thread: " << error;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800841 *error_fd = ReportError(error_protocol, error);
842 return {};
843 }
844
845 return local_socket;
846}
847
Alex Buynytskyy4f3fa052019-02-21 14:22:51 -0800848unique_fd StartCommandInProcess(std::string name, Command command, SubprocessProtocol protocol) {
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800849 LOG(INFO) << "StartCommandInProcess(" << dump_hex(name.data(), name.size()) << ")";
850
851 constexpr auto terminal_type = "";
852 constexpr auto type = SubprocessType::kRaw;
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800853 constexpr auto make_pty_raw = false;
854
855 auto subprocess = std::make_unique<Subprocess>(std::move(name), terminal_type, type, protocol,
856 make_pty_raw);
857 if (!subprocess) {
858 LOG(ERROR) << "failed to allocate new subprocess";
859 return ReportError(protocol, "failed to allocate new subprocess");
860 }
861
862 std::string error;
863 if (!subprocess->ExecInProcess(std::move(command), &error)) {
864 LOG(ERROR) << "failed to start subprocess: " << error;
865 return ReportError(protocol, error);
866 }
867
868 unique_fd local_socket(subprocess->ReleaseLocalSocket());
869 D("inprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
870 subprocess->pid());
871
872 if (!Subprocess::StartThread(std::move(subprocess), &error)) {
873 LOG(ERROR) << "failed to start inprocess management thread: " << error;
Josh Gao6d3a75a2016-06-17 14:53:57 -0700874 return ReportError(protocol, error);
875 }
876
Josh Gao5607e922018-07-25 18:15:52 -0700877 return local_socket;
David Pursell4f344bb2015-08-28 15:08:49 -0700878}