1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chromeos/process_proxy/process_proxy.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/process/launch.h"
16 #include "base/process/process.h"
17 #include "base/threading/thread.h"
18 #include "third_party/cros_system_api/switches/chrome_switches.h"
27 enum PseudoTerminalFd
{
32 const int kInvalidFd
= -1;
38 ProcessProxy::ProcessProxy(): process_launched_(false),
40 watcher_started_(false) {
41 // Set pipes to initial, invalid value so we can easily know if a pipe was
46 bool ProcessProxy::Open(const std::string
& command
, pid_t
* pid
) {
47 if (process_launched_
)
50 if (!CreatePseudoTerminalPair(pt_pair_
)) {
54 process_launched_
= LaunchProcess(command
, pt_pair_
[PT_SLAVE_FD
], &pid_
);
56 if (process_launched_
) {
57 // We won't need these anymore. These will be used by the launched process.
58 CloseFd(&pt_pair_
[PT_SLAVE_FD
]);
60 LOG(WARNING
) << "Process launched: " << pid_
;
62 CloseFdPair(pt_pair_
);
64 return process_launched_
;
67 bool ProcessProxy::StartWatchingOnThread(
68 base::Thread
* watch_thread
,
69 const ProcessOutputCallback
& callback
) {
70 DCHECK(process_launched_
);
73 if (pipe(shutdown_pipe_
))
76 // We give ProcessOutputWatcher a copy of master to make life easier during
78 // TODO(tbarzic): improve fd managment.
79 int master_copy
= HANDLE_EINTR(dup(pt_pair_
[PT_MASTER_FD
]));
80 if (master_copy
== -1)
85 callback_runner_
= base::MessageLoopProxy::current();
87 // This object will delete itself once watching is stopped.
88 // It also takes ownership of the passed fds.
89 ProcessOutputWatcher
* output_watcher
=
90 new ProcessOutputWatcher(master_copy
,
91 shutdown_pipe_
[PIPE_END_READ
],
92 base::Bind(&ProcessProxy::OnProcessOutput
,
95 // Output watcher took ownership of the read end of shutdown pipe.
96 shutdown_pipe_
[PIPE_END_READ
] = -1;
98 // |watch| thread is blocked by |output_watcher| from now on.
99 watch_thread
->message_loop()->PostTask(FROM_HERE
,
100 base::Bind(&ProcessOutputWatcher::Start
,
101 base::Unretained(output_watcher
)));
102 watcher_started_
= true;
106 void ProcessProxy::OnProcessOutput(ProcessOutputType type
,
107 const std::string
& output
) {
108 if (!callback_runner_
.get())
111 callback_runner_
->PostTask(
113 base::Bind(&ProcessProxy::CallOnProcessOutputCallback
,
114 this, type
, output
));
117 void ProcessProxy::CallOnProcessOutputCallback(ProcessOutputType type
,
118 const std::string
& output
) {
119 // We may receive some output even after Close was called (crosh process does
120 // not have to quit instantly, or there may be some trailing data left in
121 // output stream fds). In that case owner of the callback may be gone so we
122 // don't want to send it anything. |callback_set_| is reset when this gets
125 callback_
.Run(type
, output
);
128 bool ProcessProxy::StopWatching() {
129 if (!watcher_started_
)
131 // Signal Watcher that we are done. We use self-pipe trick to unblock watcher.
132 // Anything may be written to the pipe.
133 const char message
[] = "q";
134 return base::WriteFileDescriptor(shutdown_pipe_
[PIPE_END_WRITE
],
135 message
, sizeof(message
));
138 void ProcessProxy::Close() {
139 if (!process_launched_
)
142 process_launched_
= false;
143 callback_set_
= false;
144 callback_
= ProcessOutputCallback();
145 callback_runner_
= NULL
;
147 base::Process process
= base::Process::DeprecatedGetProcessFromHandle(pid_
);
148 process
.Terminate(0, true /* wait */);
150 // TODO(tbarzic): What if this fails?
156 bool ProcessProxy::Write(const std::string
& text
) {
157 if (!process_launched_
)
160 // We don't want to write '\0' to the pipe.
161 size_t data_size
= text
.length() * sizeof(*text
.c_str());
162 return base::WriteFileDescriptor(
163 pt_pair_
[PT_MASTER_FD
], text
.c_str(), data_size
);
166 bool ProcessProxy::OnTerminalResize(int width
, int height
) {
167 if (width
< 0 || height
< 0)
173 // Number of columns.
176 return (HANDLE_EINTR(ioctl(pt_pair_
[PT_MASTER_FD
], TIOCSWINSZ
, &ws
)) != -1);
179 ProcessProxy::~ProcessProxy() {
180 // In case watcher did not started, we may get deleted without calling Close.
181 // In that case we have to clean up created pipes. If watcher had been
182 // started, there will be a callback with our reference owned by
183 // process_output_watcher until Close is called, so we know Close has been
184 // called by now (and pipes have been cleaned).
185 if (!watcher_started_
)
189 bool ProcessProxy::CreatePseudoTerminalPair(int *pt_pair
) {
190 ClearFdPair(pt_pair
);
193 pt_pair
[PT_MASTER_FD
] = HANDLE_EINTR(posix_openpt(O_RDWR
| O_NOCTTY
));
194 if (pt_pair
[PT_MASTER_FD
] == -1)
197 if (grantpt(pt_pair_
[PT_MASTER_FD
]) != 0 ||
198 unlockpt(pt_pair_
[PT_MASTER_FD
]) != 0) {
199 CloseFd(&pt_pair
[PT_MASTER_FD
]);
202 char* slave_name
= NULL
;
203 // Per man page, slave_name must not be freed.
204 slave_name
= ptsname(pt_pair_
[PT_MASTER_FD
]);
206 pt_pair_
[PT_SLAVE_FD
] = HANDLE_EINTR(open(slave_name
, O_RDWR
| O_NOCTTY
));
208 if (pt_pair_
[PT_SLAVE_FD
] == -1) {
209 CloseFdPair(pt_pair
);
216 bool ProcessProxy::LaunchProcess(const std::string
& command
, int slave_fd
,
218 // Redirect crosh process' output and input so we can read it.
219 base::FileHandleMappingVector fds_mapping
;
220 fds_mapping
.push_back(std::make_pair(slave_fd
, STDIN_FILENO
));
221 fds_mapping
.push_back(std::make_pair(slave_fd
, STDOUT_FILENO
));
222 fds_mapping
.push_back(std::make_pair(slave_fd
, STDERR_FILENO
));
223 base::LaunchOptions options
;
224 // Do not set NO_NEW_PRIVS on processes if the system is in dev-mode. This
225 // permits sudo in the crosh shell when in developer mode.
226 options
.allow_new_privs
= base::CommandLine::ForCurrentProcess()->
227 HasSwitch(chromeos::switches::kSystemInDevMode
);
228 options
.fds_to_remap
= &fds_mapping
;
229 options
.ctrl_terminal_fd
= slave_fd
;
230 options
.environ
["TERM"] = "xterm";
232 // Launch the process.
233 base::Process process
=
234 base::LaunchProcess(base::CommandLine(base::FilePath(command
)), options
);
236 // TODO(rvargas) crbug/417532: This is somewhat wrong but the interface of
237 // Open vends pid_t* so ownership is quite vague anyway, and Process::Close
238 // doesn't do much in POSIX.
239 *pid
= process
.Pid();
240 return process
.IsValid();
243 void ProcessProxy::CloseAllFdPairs() {
244 CloseFdPair(pt_pair_
);
245 CloseFdPair(shutdown_pipe_
);
248 void ProcessProxy::CloseFdPair(int* pipe
) {
249 CloseFd(&(pipe
[PIPE_END_READ
]));
250 CloseFd(&(pipe
[PIPE_END_WRITE
]));
253 void ProcessProxy::CloseFd(int* fd
) {
254 if (*fd
!= kInvalidFd
) {
255 if (IGNORE_EINTR(close(*fd
)) != 0)
256 DPLOG(WARNING
) << "close fd failed.";
261 void ProcessProxy::ClearAllFdPairs() {
262 ClearFdPair(pt_pair_
);
263 ClearFdPair(shutdown_pipe_
);
266 void ProcessProxy::ClearFdPair(int* pipe
) {
267 pipe
[PIPE_END_READ
] = kInvalidFd
;
268 pipe
[PIPE_END_WRITE
] = kInvalidFd
;
271 } // namespace chromeos