[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / utility_process_host_impl.cc
bloba43fa5d7aa096486b23c0729fd36ed5eb6c21aa8
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 "content/browser/utility_process_host_impl.h"
7 #include "base/base_switches.h"
8 #include "base/bind.h"
9 #include "base/bind_helpers.h"
10 #include "base/command_line.h"
11 #include "base/lazy_instance.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/process/process_handle.h"
14 #include "base/run_loop.h"
15 #include "base/sequenced_task_runner.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/synchronization/lock.h"
18 #include "base/synchronization/waitable_event.h"
19 #include "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/mojo/mojo_application_host.h"
21 #include "content/browser/renderer_host/render_process_host_impl.h"
22 #include "content/common/child_process_host_impl.h"
23 #include "content/common/in_process_child_thread_params.h"
24 #include "content/common/utility_messages.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/content_browser_client.h"
27 #include "content/public/browser/utility_process_host_client.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/common/process_type.h"
30 #include "content/public/common/sandbox_type.h"
31 #include "content/public/common/sandboxed_process_launcher_delegate.h"
32 #include "ipc/ipc_switches.h"
33 #include "ui/base/ui_base_switches.h"
35 namespace content {
37 // NOTE: changes to this class need to be reviewed by the security team.
38 class UtilitySandboxedProcessLauncherDelegate
39 : public SandboxedProcessLauncherDelegate {
40 public:
41 UtilitySandboxedProcessLauncherDelegate(const base::FilePath& exposed_dir,
42 bool launch_elevated,
43 bool no_sandbox,
44 const base::EnvironmentMap& env,
45 ChildProcessHost* host)
46 : exposed_dir_(exposed_dir),
47 #if defined(OS_WIN)
48 launch_elevated_(launch_elevated)
49 #elif defined(OS_POSIX)
50 env_(env),
51 no_sandbox_(no_sandbox),
52 ipc_fd_(host->TakeClientFileDescriptor())
53 #endif // OS_WIN
56 ~UtilitySandboxedProcessLauncherDelegate() override {}
58 #if defined(OS_WIN)
59 bool ShouldLaunchElevated() override { return launch_elevated_; }
60 void PreSandbox(bool* disable_default_policy,
61 base::FilePath* exposed_dir) override {
62 *exposed_dir = exposed_dir_;
64 #elif defined(OS_POSIX)
66 bool ShouldUseZygote() override {
67 return !no_sandbox_ && exposed_dir_.empty();
69 base::EnvironmentMap GetEnvironment() override { return env_; }
70 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
71 #endif // OS_WIN
73 SandboxType GetSandboxType() override {
74 return SANDBOX_TYPE_UTILITY;
77 private:
78 base::FilePath exposed_dir_;
80 #if defined(OS_WIN)
81 bool launch_elevated_;
82 #elif defined(OS_POSIX)
83 base::EnvironmentMap env_;
84 bool no_sandbox_;
85 base::ScopedFD ipc_fd_;
86 #endif // OS_WIN
89 UtilityMainThreadFactoryFunction g_utility_main_thread_factory = NULL;
91 UtilityProcessHost* UtilityProcessHost::Create(
92 const scoped_refptr<UtilityProcessHostClient>& client,
93 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner) {
94 return new UtilityProcessHostImpl(client, client_task_runner);
97 void UtilityProcessHostImpl::RegisterUtilityMainThreadFactory(
98 UtilityMainThreadFactoryFunction create) {
99 g_utility_main_thread_factory = create;
102 UtilityProcessHostImpl::UtilityProcessHostImpl(
103 const scoped_refptr<UtilityProcessHostClient>& client,
104 const scoped_refptr<base::SequencedTaskRunner>& client_task_runner)
105 : client_(client),
106 client_task_runner_(client_task_runner),
107 is_batch_mode_(false),
108 is_mdns_enabled_(false),
109 no_sandbox_(false),
110 run_elevated_(false),
111 #if defined(OS_LINUX)
112 child_flags_(ChildProcessHost::CHILD_ALLOW_SELF),
113 #else
114 child_flags_(ChildProcessHost::CHILD_NORMAL),
115 #endif
116 started_(false),
117 name_(base::ASCIIToUTF16("utility process")),
118 weak_ptr_factory_(this) {
121 UtilityProcessHostImpl::~UtilityProcessHostImpl() {
122 DCHECK_CURRENTLY_ON(BrowserThread::IO);
123 if (is_batch_mode_)
124 EndBatchMode();
126 // We could be destroyed as a result of Chrome shutdown. When that happens,
127 // the Mojo channel doesn't get the opportunity to shut down cleanly because
128 // it posts to the IO thread (the current thread) which is being destroyed.
129 // To guarantee proper shutdown of the Mojo channel, do it explicitly here.
130 if (mojo_application_host_)
131 mojo_application_host_->ShutdownOnIOThread();
134 base::WeakPtr<UtilityProcessHost> UtilityProcessHostImpl::AsWeakPtr() {
135 return weak_ptr_factory_.GetWeakPtr();
138 bool UtilityProcessHostImpl::Send(IPC::Message* message) {
139 if (!StartProcess())
140 return false;
142 return process_->Send(message);
145 bool UtilityProcessHostImpl::StartBatchMode() {
146 CHECK(!is_batch_mode_);
147 is_batch_mode_ = StartProcess();
148 Send(new UtilityMsg_BatchMode_Started());
149 return is_batch_mode_;
152 void UtilityProcessHostImpl::EndBatchMode() {
153 CHECK(is_batch_mode_);
154 is_batch_mode_ = false;
155 Send(new UtilityMsg_BatchMode_Finished());
158 void UtilityProcessHostImpl::SetExposedDir(const base::FilePath& dir) {
159 exposed_dir_ = dir;
162 void UtilityProcessHostImpl::EnableMDns() {
163 is_mdns_enabled_ = true;
166 void UtilityProcessHostImpl::DisableSandbox() {
167 no_sandbox_ = true;
170 #if defined(OS_WIN)
171 void UtilityProcessHostImpl::ElevatePrivileges() {
172 no_sandbox_ = true;
173 run_elevated_ = true;
175 #endif
177 const ChildProcessData& UtilityProcessHostImpl::GetData() {
178 return process_->GetData();
181 #if defined(OS_POSIX)
183 void UtilityProcessHostImpl::SetEnv(const base::EnvironmentMap& env) {
184 env_ = env;
187 #endif // OS_POSIX
189 bool UtilityProcessHostImpl::StartMojoMode() {
190 CHECK(!mojo_application_host_);
191 mojo_application_host_.reset(new MojoApplicationHost);
193 bool mojo_result = mojo_application_host_->Init();
194 if (!mojo_result)
195 return false;
197 return StartProcess();
200 ServiceRegistry* UtilityProcessHostImpl::GetServiceRegistry() {
201 if (mojo_application_host_)
202 return mojo_application_host_->service_registry();
203 return nullptr;
206 void UtilityProcessHostImpl::SetName(const base::string16& name) {
207 name_ = name;
210 bool UtilityProcessHostImpl::StartProcess() {
211 if (started_)
212 return true;
213 started_ = true;
215 if (is_batch_mode_)
216 return true;
218 // Name must be set or metrics_service will crash in any test which
219 // launches a UtilityProcessHost.
220 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_UTILITY, this));
221 process_->SetName(name_);
223 std::string channel_id = process_->GetHost()->CreateChannel();
224 if (channel_id.empty())
225 return false;
227 if (RenderProcessHost::run_renderer_in_process()) {
228 DCHECK(g_utility_main_thread_factory);
229 // See comment in RenderProcessHostImpl::Init() for the background on why we
230 // support single process mode this way.
231 in_process_thread_.reset(
232 g_utility_main_thread_factory(InProcessChildThreadParams(
233 channel_id, BrowserThread::UnsafeGetMessageLoopForThread(
234 BrowserThread::IO)->task_runner())));
235 in_process_thread_->Start();
236 OnProcessLaunched();
237 } else {
238 const base::CommandLine& browser_command_line =
239 *base::CommandLine::ForCurrentProcess();
240 int child_flags = child_flags_;
242 bool has_cmd_prefix = browser_command_line.HasSwitch(
243 switches::kUtilityCmdPrefix);
245 // When running under gdb, forking /proc/self/exe ends up forking the gdb
246 // executable instead of Chromium. It is almost safe to assume that no
247 // updates will happen while a developer is running with
248 // |switches::kUtilityCmdPrefix|. See ChildProcessHost::GetChildPath() for
249 // a similar case with Valgrind.
250 if (has_cmd_prefix)
251 child_flags = ChildProcessHost::CHILD_NORMAL;
253 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
254 if (exe_path.empty()) {
255 NOTREACHED() << "Unable to get utility process binary name.";
256 return false;
259 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
260 cmd_line->AppendSwitchASCII(switches::kProcessType,
261 switches::kUtilityProcess);
262 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
263 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
264 cmd_line->AppendSwitchASCII(switches::kLang, locale);
266 if (no_sandbox_)
267 cmd_line->AppendSwitch(switches::kNoSandbox);
269 // Browser command-line switches to propagate to the utility process.
270 static const char* const kSwitchNames[] = {
271 switches::kDebugPluginLoading,
272 switches::kNoSandbox,
273 switches::kProfilerTiming,
274 #if defined(OS_MACOSX)
275 switches::kEnableSandboxLogging,
276 #endif
278 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
279 arraysize(kSwitchNames));
281 if (has_cmd_prefix) {
282 // Launch the utility child process with some prefix
283 // (usually "xterm -e gdb --args").
284 cmd_line->PrependWrapper(browser_command_line.GetSwitchValueNative(
285 switches::kUtilityCmdPrefix));
288 if (!exposed_dir_.empty()) {
289 cmd_line->AppendSwitchPath(switches::kUtilityProcessAllowedDir,
290 exposed_dir_);
293 if (is_mdns_enabled_)
294 cmd_line->AppendSwitch(switches::kUtilityProcessEnableMDns);
296 #if defined(OS_WIN)
297 // Let the utility process know if it is intended to be elevated.
298 if (run_elevated_)
299 cmd_line->AppendSwitch(switches::kUtilityProcessRunningElevated);
300 #endif
302 process_->Launch(
303 new UtilitySandboxedProcessLauncherDelegate(exposed_dir_,
304 run_elevated_,
305 no_sandbox_, env_,
306 process_->GetHost()),
307 cmd_line,
308 true);
311 return true;
314 bool UtilityProcessHostImpl::OnMessageReceived(const IPC::Message& message) {
315 if (!client_.get())
316 return true;
318 client_task_runner_->PostTask(
319 FROM_HERE,
320 base::Bind(
321 base::IgnoreResult(&UtilityProcessHostClient::OnMessageReceived),
322 client_.get(),
323 message));
325 return true;
328 void UtilityProcessHostImpl::OnProcessLaunchFailed() {
329 if (!client_.get())
330 return;
332 client_task_runner_->PostTask(
333 FROM_HERE,
334 base::Bind(&UtilityProcessHostClient::OnProcessLaunchFailed,
335 client_.get()));
338 void UtilityProcessHostImpl::OnProcessCrashed(int exit_code) {
339 if (!client_.get())
340 return;
342 client_task_runner_->PostTask(
343 FROM_HERE,
344 base::Bind(&UtilityProcessHostClient::OnProcessCrashed, client_.get(),
345 exit_code));
348 void UtilityProcessHostImpl::OnProcessLaunched() {
349 if (mojo_application_host_) {
350 base::ProcessHandle handle;
351 if (RenderProcessHost::run_renderer_in_process())
352 handle = base::GetCurrentProcessHandle();
353 else
354 handle = process_->GetData().handle;
356 mojo_application_host_->Activate(this, handle);
360 } // namespace content