Add ICU message format support
[chromium-blink-merge.git] / content / browser / ppapi_plugin_process_host.cc
blobbe819d6c1ae2aa73f4212cff9b54b6d728ea1668
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/ppapi_plugin_process_host.h"
7 #include <string>
9 #include "base/base_switches.h"
10 #include "base/command_line.h"
11 #include "base/files/file_path.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "content/browser/browser_child_process_host_impl.h"
15 #include "content/browser/plugin_service_impl.h"
16 #include "content/browser/renderer_host/render_message_filter.h"
17 #include "content/common/child_process_host_impl.h"
18 #include "content/common/child_process_messages.h"
19 #include "content/public/browser/content_browser_client.h"
20 #include "content/public/common/content_constants.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/pepper_plugin_info.h"
23 #include "content/public/common/process_type.h"
24 #include "content/public/common/sandbox_type.h"
25 #include "content/public/common/sandboxed_process_launcher_delegate.h"
26 #include "ipc/ipc_switches.h"
27 #include "net/base/network_change_notifier.h"
28 #include "ppapi/proxy/ppapi_messages.h"
29 #include "ui/base/ui_base_switches.h"
31 #if defined(OS_WIN)
32 #include "content/common/sandbox_win.h"
33 #include "sandbox/win/src/sandbox_policy.h"
34 #endif
36 namespace content {
38 // NOTE: changes to this class need to be reviewed by the security team.
39 class PpapiPluginSandboxedProcessLauncherDelegate
40 : public content::SandboxedProcessLauncherDelegate {
41 public:
42 PpapiPluginSandboxedProcessLauncherDelegate(bool is_broker,
43 const PepperPluginInfo& info,
44 ChildProcessHost* host)
46 #if defined(OS_POSIX)
47 info_(info),
48 ipc_fd_(host->TakeClientFileDescriptor()),
49 #endif // OS_POSIX
50 is_broker_(is_broker) {}
52 ~PpapiPluginSandboxedProcessLauncherDelegate() override {}
54 #if defined(OS_WIN)
55 bool ShouldSandbox() override {
56 return !is_broker_;
59 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
60 if (is_broker_)
61 return;
62 // The Pepper process as locked-down as a renderer execpt that it can
63 // create the server side of chrome pipes.
64 sandbox::ResultCode result;
65 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
66 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
67 L"\\\\.\\pipe\\chrome.*");
68 *success = (result == sandbox::SBOX_ALL_OK);
70 const base::string16& sid =
71 GetContentClient()->browser()->GetAppContainerSidForSandboxType(
72 GetSandboxType());
73 if (!sid.empty())
74 AddAppContainerPolicy(policy, sid.c_str());
77 #elif defined(OS_POSIX)
78 bool ShouldUseZygote() override {
79 const base::CommandLine& browser_command_line =
80 *base::CommandLine::ForCurrentProcess();
81 base::CommandLine::StringType plugin_launcher = browser_command_line
82 .GetSwitchValueNative(switches::kPpapiPluginLauncher);
83 return !is_broker_ && plugin_launcher.empty();
85 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
86 #endif // OS_WIN
88 SandboxType GetSandboxType() override {
89 return SANDBOX_TYPE_PPAPI;
92 private:
93 #if defined(OS_POSIX)
94 const PepperPluginInfo& info_;
95 base::ScopedFD ipc_fd_;
96 #endif // OS_POSIX
97 bool is_broker_;
99 DISALLOW_COPY_AND_ASSIGN(PpapiPluginSandboxedProcessLauncherDelegate);
102 class PpapiPluginProcessHost::PluginNetworkObserver
103 : public net::NetworkChangeNotifier::IPAddressObserver,
104 public net::NetworkChangeNotifier::ConnectionTypeObserver {
105 public:
106 explicit PluginNetworkObserver(PpapiPluginProcessHost* process_host)
107 : process_host_(process_host) {
108 net::NetworkChangeNotifier::AddIPAddressObserver(this);
109 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
112 ~PluginNetworkObserver() override {
113 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
114 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
117 // IPAddressObserver implementation.
118 void OnIPAddressChanged() override {
119 // TODO(brettw) bug 90246: This doesn't seem correct. The online/offline
120 // notification seems like it should be sufficient, but I don't see that
121 // when I unplug and replug my network cable. Sending this notification when
122 // "something" changes seems to make Flash reasonably happy, but seems
123 // wrong. We should really be able to provide the real online state in
124 // OnConnectionTypeChanged().
125 process_host_->Send(new PpapiMsg_SetNetworkState(true));
128 // ConnectionTypeObserver implementation.
129 void OnConnectionTypeChanged(
130 net::NetworkChangeNotifier::ConnectionType type) override {
131 process_host_->Send(new PpapiMsg_SetNetworkState(
132 type != net::NetworkChangeNotifier::CONNECTION_NONE));
135 private:
136 PpapiPluginProcessHost* const process_host_;
139 PpapiPluginProcessHost::~PpapiPluginProcessHost() {
140 DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
141 << "~PpapiPluginProcessHost()";
142 CancelRequests();
145 // static
146 PpapiPluginProcessHost* PpapiPluginProcessHost::CreatePluginHost(
147 const PepperPluginInfo& info,
148 const base::FilePath& profile_data_directory) {
149 PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost(
150 info, profile_data_directory);
151 DCHECK(plugin_host);
152 if (plugin_host->Init(info))
153 return plugin_host;
155 NOTREACHED(); // Init is not expected to fail.
156 return NULL;
159 // static
160 PpapiPluginProcessHost* PpapiPluginProcessHost::CreateBrokerHost(
161 const PepperPluginInfo& info) {
162 PpapiPluginProcessHost* plugin_host =
163 new PpapiPluginProcessHost();
164 if (plugin_host->Init(info))
165 return plugin_host;
167 NOTREACHED(); // Init is not expected to fail.
168 return NULL;
171 // static
172 void PpapiPluginProcessHost::DidCreateOutOfProcessInstance(
173 int plugin_process_id,
174 int32 pp_instance,
175 const PepperRendererInstanceData& instance_data) {
176 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
177 if (iter->process_.get() &&
178 iter->process_->GetData().id == plugin_process_id) {
179 // Found the plugin.
180 iter->host_impl_->AddInstance(pp_instance, instance_data);
181 return;
184 // We'll see this passed with a 0 process ID for the browser tag stuff that
185 // is currently in the process of being removed.
187 // TODO(brettw) When old browser tag impl is removed
188 // (PepperPluginDelegateImpl::CreateBrowserPluginModule passes a 0 plugin
189 // process ID) this should be converted to a NOTREACHED().
190 DCHECK(plugin_process_id == 0)
191 << "Renderer sent a bad plugin process host ID";
194 // static
195 void PpapiPluginProcessHost::DidDeleteOutOfProcessInstance(
196 int plugin_process_id,
197 int32 pp_instance) {
198 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
199 if (iter->process_.get() &&
200 iter->process_->GetData().id == plugin_process_id) {
201 // Found the plugin.
202 iter->host_impl_->DeleteInstance(pp_instance);
203 return;
206 // Note: It's possible that the plugin process has already been deleted by
207 // the time this message is received. For example, it could have crashed.
208 // That's OK, we can just ignore this message.
211 // static
212 void PpapiPluginProcessHost::OnPluginInstanceThrottleStateChange(
213 int plugin_process_id,
214 int32 pp_instance,
215 bool is_throttled) {
216 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
217 if (iter->process_.get() &&
218 iter->process_->GetData().id == plugin_process_id) {
219 // Found the plugin.
220 iter->host_impl_->OnThrottleStateChanged(pp_instance, is_throttled);
221 return;
224 // Note: It's possible that the plugin process has already been deleted by
225 // the time this message is received. For example, it could have crashed.
226 // That's OK, we can just ignore this message.
229 // static
230 void PpapiPluginProcessHost::FindByName(
231 const base::string16& name,
232 std::vector<PpapiPluginProcessHost*>* hosts) {
233 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
234 if (iter->process_.get() && iter->process_->GetData().name == name)
235 hosts->push_back(*iter);
239 bool PpapiPluginProcessHost::Send(IPC::Message* message) {
240 return process_->Send(message);
243 void PpapiPluginProcessHost::OpenChannelToPlugin(Client* client) {
244 if (process_->GetHost()->IsChannelOpening()) {
245 // The channel is already in the process of being opened. Put
246 // this "open channel" request into a queue of requests that will
247 // be run once the channel is open.
248 pending_requests_.push_back(client);
249 return;
252 // We already have an open channel, send a request right away to plugin.
253 RequestPluginChannel(client);
256 PpapiPluginProcessHost::PpapiPluginProcessHost(
257 const PepperPluginInfo& info,
258 const base::FilePath& profile_data_directory)
259 : profile_data_directory_(profile_data_directory),
260 is_broker_(false) {
261 uint32 base_permissions = info.permissions;
263 // We don't have to do any whitelisting for APIs in this process host, so
264 // don't bother passing a browser context or document url here.
265 if (GetContentClient()->browser()->IsPluginAllowedToUseDevChannelAPIs(
266 NULL, GURL()))
267 base_permissions |= ppapi::PERMISSION_DEV_CHANNEL;
268 permissions_ = ppapi::PpapiPermissions::GetForCommandLine(base_permissions);
270 process_.reset(new BrowserChildProcessHostImpl(
271 PROCESS_TYPE_PPAPI_PLUGIN, this));
273 host_impl_.reset(new BrowserPpapiHostImpl(this, permissions_, info.name,
274 info.path, profile_data_directory,
275 false /* in_process */,
276 false /* external_plugin */));
278 filter_ = new PepperMessageFilter();
279 process_->AddFilter(filter_.get());
280 process_->GetHost()->AddFilter(host_impl_->message_filter().get());
282 GetContentClient()->browser()->DidCreatePpapiPlugin(host_impl_.get());
284 // Only request network status updates if the plugin has dev permissions.
285 if (permissions_.HasPermission(ppapi::PERMISSION_DEV))
286 network_observer_.reset(new PluginNetworkObserver(this));
289 PpapiPluginProcessHost::PpapiPluginProcessHost()
290 : is_broker_(true) {
291 process_.reset(new BrowserChildProcessHostImpl(
292 PROCESS_TYPE_PPAPI_BROKER, this));
294 ppapi::PpapiPermissions permissions; // No permissions.
295 // The plugin name, path and profile data directory shouldn't be needed for
296 // the broker.
297 host_impl_.reset(new BrowserPpapiHostImpl(this, permissions,
298 std::string(), base::FilePath(),
299 base::FilePath(),
300 false /* in_process */,
301 false /* external_plugin */));
304 bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) {
305 plugin_path_ = info.path;
306 if (info.name.empty()) {
307 process_->SetName(plugin_path_.BaseName().LossyDisplayName());
308 } else {
309 process_->SetName(base::UTF8ToUTF16(info.name));
312 std::string channel_id = process_->GetHost()->CreateChannel();
313 if (channel_id.empty()) {
314 VLOG(1) << "Could not create pepper host channel.";
315 return false;
318 const base::CommandLine& browser_command_line =
319 *base::CommandLine::ForCurrentProcess();
320 base::CommandLine::StringType plugin_launcher =
321 browser_command_line.GetSwitchValueNative(switches::kPpapiPluginLauncher);
323 #if defined(OS_LINUX)
324 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
325 ChildProcessHost::CHILD_NORMAL;
326 #else
327 int flags = ChildProcessHost::CHILD_NORMAL;
328 #endif
329 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
330 if (exe_path.empty()) {
331 VLOG(1) << "Pepper plugin exe path is empty.";
332 return false;
335 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
336 cmd_line->AppendSwitchASCII(switches::kProcessType,
337 is_broker_ ? switches::kPpapiBrokerProcess
338 : switches::kPpapiPluginProcess);
339 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
341 // These switches are forwarded to both plugin and broker pocesses.
342 static const char* kCommonForwardSwitches[] = {
343 switches::kVModule
345 cmd_line->CopySwitchesFrom(browser_command_line, kCommonForwardSwitches,
346 arraysize(kCommonForwardSwitches));
348 if (!is_broker_) {
349 static const char* kPluginForwardSwitches[] = {
350 switches::kDisableSeccompFilterSandbox,
351 #if defined(OS_MACOSX)
352 switches::kEnableSandboxLogging,
353 #endif
354 switches::kNoSandbox,
355 switches::kPpapiStartupDialog,
357 cmd_line->CopySwitchesFrom(browser_command_line, kPluginForwardSwitches,
358 arraysize(kPluginForwardSwitches));
360 // Copy any flash args over and introduce field trials if necessary.
361 // TODO(vtl): Stop passing flash args in the command line, or windows is
362 // going to explode.
363 std::string field_trial =
364 base::FieldTrialList::FindFullName(kFlashHwVideoDecodeFieldTrialName);
365 std::string existing_args =
366 browser_command_line.GetSwitchValueASCII(switches::kPpapiFlashArgs);
367 if (field_trial == kFlashHwVideoDecodeFieldTrialEnabledName) {
368 // Arguments passed to Flash are comma delimited.
369 if (!existing_args.empty())
370 existing_args.append(",");
371 existing_args.append("enable_hw_video_decode=1");
372 #if defined(OS_MACOSX)
373 // TODO(ihf): Remove this once Flash newer than 15.0.0.223 is released.
374 existing_args.append(",enable_hw_video_decode_mac=1");
375 #endif
377 cmd_line->AppendSwitchASCII(switches::kPpapiFlashArgs, existing_args);
380 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
381 if (!locale.empty()) {
382 // Pass on the locale so the plugin will know what language we're using.
383 cmd_line->AppendSwitchASCII(switches::kLang, locale);
386 if (!plugin_launcher.empty())
387 cmd_line->PrependWrapper(plugin_launcher);
389 // On posix, never use the zygote for the broker. Also, only use the zygote if
390 // we are not using a plugin launcher - having a plugin launcher means we need
391 // to use another process instead of just forking the zygote.
392 process_->Launch(
393 new PpapiPluginSandboxedProcessLauncherDelegate(is_broker_,
394 info,
395 process_->GetHost()),
396 cmd_line,
397 true);
398 return true;
401 void PpapiPluginProcessHost::RequestPluginChannel(Client* client) {
402 base::ProcessHandle process_handle;
403 int renderer_child_id;
404 client->GetPpapiChannelInfo(&process_handle, &renderer_child_id);
406 base::ProcessId process_id = (process_handle == base::kNullProcessHandle) ?
407 0 : base::GetProcId(process_handle);
409 // We can't send any sync messages from the browser because it might lead to
410 // a hang. See the similar code in PluginProcessHost for more description.
411 PpapiMsg_CreateChannel* msg = new PpapiMsg_CreateChannel(
412 process_id, renderer_child_id, client->OffTheRecord());
413 msg->set_unblock(true);
414 if (Send(msg)) {
415 sent_requests_.push(client);
416 } else {
417 client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0);
421 void PpapiPluginProcessHost::OnProcessLaunched() {
422 VLOG(2) << "ppapi plugin process launched.";
423 host_impl_->set_plugin_process(process_->GetProcess().Duplicate());
426 void PpapiPluginProcessHost::OnProcessCrashed(int exit_code) {
427 VLOG(1) << "ppapi plugin process crashed.";
428 PluginServiceImpl::GetInstance()->RegisterPluginCrash(plugin_path_);
431 bool PpapiPluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
432 bool handled = true;
433 IPC_BEGIN_MESSAGE_MAP(PpapiPluginProcessHost, msg)
434 IPC_MESSAGE_HANDLER(PpapiHostMsg_ChannelCreated,
435 OnRendererPluginChannelCreated)
436 IPC_MESSAGE_UNHANDLED(handled = false)
437 IPC_END_MESSAGE_MAP()
438 DCHECK(handled);
439 return handled;
442 // Called when the browser <--> plugin channel has been established.
443 void PpapiPluginProcessHost::OnChannelConnected(int32 peer_pid) {
444 // This will actually load the plugin. Errors will actually not be reported
445 // back at this point. Instead, the plugin will fail to establish the
446 // connections when we request them on behalf of the renderer(s).
447 Send(new PpapiMsg_LoadPlugin(plugin_path_, permissions_));
449 // Process all pending channel requests from the renderers.
450 for (size_t i = 0; i < pending_requests_.size(); i++)
451 RequestPluginChannel(pending_requests_[i]);
452 pending_requests_.clear();
455 // Called when the browser <--> plugin channel has an error. This normally
456 // means the plugin has crashed.
457 void PpapiPluginProcessHost::OnChannelError() {
458 VLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
459 << "::OnChannelError()";
460 // We don't need to notify the renderers that were communicating with the
461 // plugin since they have their own channels which will go into the error
462 // state at the same time. Instead, we just need to notify any renderers
463 // that have requested a connection but have not yet received one.
464 CancelRequests();
467 void PpapiPluginProcessHost::CancelRequests() {
468 DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
469 << "CancelRequests()";
470 for (size_t i = 0; i < pending_requests_.size(); i++) {
471 pending_requests_[i]->OnPpapiChannelOpened(IPC::ChannelHandle(),
472 base::kNullProcessId, 0);
474 pending_requests_.clear();
476 while (!sent_requests_.empty()) {
477 sent_requests_.front()->OnPpapiChannelOpened(IPC::ChannelHandle(),
478 base::kNullProcessId, 0);
479 sent_requests_.pop();
483 // Called when a new plugin <--> renderer channel has been created.
484 void PpapiPluginProcessHost::OnRendererPluginChannelCreated(
485 const IPC::ChannelHandle& channel_handle) {
486 if (sent_requests_.empty())
487 return;
489 // All requests should be processed FIFO, so the next item in the
490 // sent_requests_ queue should be the one that the plugin just created.
491 Client* client = sent_requests_.front();
492 sent_requests_.pop();
494 const ChildProcessData& data = process_->GetData();
495 client->OnPpapiChannelOpened(channel_handle, base::GetProcId(data.handle),
496 data.id);
499 } // namespace content