Add remoting and PPAPI tests to GN build
[chromium-blink-merge.git] / content / browser / ppapi_plugin_process_host.cc
blob480296fd03134ab1800ebb5ec6cac3f8640dd3e4
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/sandboxed_process_launcher_delegate.h"
25 #include "ipc/ipc_switches.h"
26 #include "net/base/network_change_notifier.h"
27 #include "ppapi/proxy/ppapi_messages.h"
28 #include "ui/base/ui_base_switches.h"
30 #if defined(OS_WIN)
31 #include "content/common/sandbox_win.h"
32 #include "sandbox/win/src/sandbox_policy.h"
33 #endif
35 namespace content {
37 // NOTE: changes to this class need to be reviewed by the security team.
38 class PpapiPluginSandboxedProcessLauncherDelegate
39 : public content::SandboxedProcessLauncherDelegate {
40 public:
41 PpapiPluginSandboxedProcessLauncherDelegate(bool is_broker,
42 const PepperPluginInfo& info,
43 ChildProcessHost* host)
45 #if defined(OS_POSIX)
46 info_(info),
47 ipc_fd_(host->TakeClientFileDescriptor()),
48 #endif // OS_POSIX
49 is_broker_(is_broker) {}
51 ~PpapiPluginSandboxedProcessLauncherDelegate() override {}
53 #if defined(OS_WIN)
54 virtual bool ShouldSandbox() override {
55 return !is_broker_;
58 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
59 bool* success) {
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);
71 #elif defined(OS_POSIX)
72 bool ShouldUseZygote() override {
73 const base::CommandLine& browser_command_line =
74 *base::CommandLine::ForCurrentProcess();
75 base::CommandLine::StringType plugin_launcher = browser_command_line
76 .GetSwitchValueNative(switches::kPpapiPluginLauncher);
77 return !is_broker_ && plugin_launcher.empty() && info_.is_sandboxed;
79 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
80 #endif // OS_WIN
82 private:
83 #if defined(OS_POSIX)
84 const PepperPluginInfo& info_;
85 base::ScopedFD ipc_fd_;
86 #endif // OS_POSIX
87 bool is_broker_;
89 DISALLOW_COPY_AND_ASSIGN(PpapiPluginSandboxedProcessLauncherDelegate);
92 class PpapiPluginProcessHost::PluginNetworkObserver
93 : public net::NetworkChangeNotifier::IPAddressObserver,
94 public net::NetworkChangeNotifier::ConnectionTypeObserver {
95 public:
96 explicit PluginNetworkObserver(PpapiPluginProcessHost* process_host)
97 : process_host_(process_host) {
98 net::NetworkChangeNotifier::AddIPAddressObserver(this);
99 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
102 ~PluginNetworkObserver() override {
103 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
104 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
107 // IPAddressObserver implementation.
108 void OnIPAddressChanged() override {
109 // TODO(brettw) bug 90246: This doesn't seem correct. The online/offline
110 // notification seems like it should be sufficient, but I don't see that
111 // when I unplug and replug my network cable. Sending this notification when
112 // "something" changes seems to make Flash reasonably happy, but seems
113 // wrong. We should really be able to provide the real online state in
114 // OnConnectionTypeChanged().
115 process_host_->Send(new PpapiMsg_SetNetworkState(true));
118 // ConnectionTypeObserver implementation.
119 void OnConnectionTypeChanged(
120 net::NetworkChangeNotifier::ConnectionType type) override {
121 process_host_->Send(new PpapiMsg_SetNetworkState(
122 type != net::NetworkChangeNotifier::CONNECTION_NONE));
125 private:
126 PpapiPluginProcessHost* const process_host_;
129 PpapiPluginProcessHost::~PpapiPluginProcessHost() {
130 DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
131 << "~PpapiPluginProcessHost()";
132 CancelRequests();
135 // static
136 PpapiPluginProcessHost* PpapiPluginProcessHost::CreatePluginHost(
137 const PepperPluginInfo& info,
138 const base::FilePath& profile_data_directory) {
139 PpapiPluginProcessHost* plugin_host = new PpapiPluginProcessHost(
140 info, profile_data_directory);
141 DCHECK(plugin_host);
142 if (plugin_host->Init(info))
143 return plugin_host;
145 NOTREACHED(); // Init is not expected to fail.
146 return NULL;
149 // static
150 PpapiPluginProcessHost* PpapiPluginProcessHost::CreateBrokerHost(
151 const PepperPluginInfo& info) {
152 PpapiPluginProcessHost* plugin_host =
153 new PpapiPluginProcessHost();
154 if (plugin_host->Init(info))
155 return plugin_host;
157 NOTREACHED(); // Init is not expected to fail.
158 return NULL;
161 // static
162 void PpapiPluginProcessHost::DidCreateOutOfProcessInstance(
163 int plugin_process_id,
164 int32 pp_instance,
165 const PepperRendererInstanceData& instance_data) {
166 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
167 if (iter->process_.get() &&
168 iter->process_->GetData().id == plugin_process_id) {
169 // Found the plugin.
170 iter->host_impl_->AddInstance(pp_instance, instance_data);
171 return;
174 // We'll see this passed with a 0 process ID for the browser tag stuff that
175 // is currently in the process of being removed.
177 // TODO(brettw) When old browser tag impl is removed
178 // (PepperPluginDelegateImpl::CreateBrowserPluginModule passes a 0 plugin
179 // process ID) this should be converted to a NOTREACHED().
180 DCHECK(plugin_process_id == 0)
181 << "Renderer sent a bad plugin process host ID";
184 // static
185 void PpapiPluginProcessHost::DidDeleteOutOfProcessInstance(
186 int plugin_process_id,
187 int32 pp_instance) {
188 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
189 if (iter->process_.get() &&
190 iter->process_->GetData().id == plugin_process_id) {
191 // Found the plugin.
192 iter->host_impl_->DeleteInstance(pp_instance);
193 return;
196 // Note: It's possible that the plugin process has already been deleted by
197 // the time this message is received. For example, it could have crashed.
198 // That's OK, we can just ignore this message.
201 // static
202 void PpapiPluginProcessHost::OnPluginInstanceThrottleStateChange(
203 int plugin_process_id,
204 int32 pp_instance,
205 bool is_throttled) {
206 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
207 if (iter->process_.get() &&
208 iter->process_->GetData().id == plugin_process_id) {
209 // Found the plugin.
210 iter->host_impl_->OnThrottleStateChanged(pp_instance, is_throttled);
211 return;
214 // Note: It's possible that the plugin process has already been deleted by
215 // the time this message is received. For example, it could have crashed.
216 // That's OK, we can just ignore this message.
219 // static
220 void PpapiPluginProcessHost::FindByName(
221 const base::string16& name,
222 std::vector<PpapiPluginProcessHost*>* hosts) {
223 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
224 if (iter->process_.get() && iter->process_->GetData().name == name)
225 hosts->push_back(*iter);
229 bool PpapiPluginProcessHost::Send(IPC::Message* message) {
230 return process_->Send(message);
233 void PpapiPluginProcessHost::OpenChannelToPlugin(Client* client) {
234 if (process_->GetHost()->IsChannelOpening()) {
235 // The channel is already in the process of being opened. Put
236 // this "open channel" request into a queue of requests that will
237 // be run once the channel is open.
238 pending_requests_.push_back(client);
239 return;
242 // We already have an open channel, send a request right away to plugin.
243 RequestPluginChannel(client);
246 PpapiPluginProcessHost::PpapiPluginProcessHost(
247 const PepperPluginInfo& info,
248 const base::FilePath& profile_data_directory)
249 : profile_data_directory_(profile_data_directory),
250 is_broker_(false) {
251 uint32 base_permissions = info.permissions;
253 // We don't have to do any whitelisting for APIs in this process host, so
254 // don't bother passing a browser context or document url here.
255 if (GetContentClient()->browser()->IsPluginAllowedToUseDevChannelAPIs(
256 NULL, GURL()))
257 base_permissions |= ppapi::PERMISSION_DEV_CHANNEL;
258 permissions_ = ppapi::PpapiPermissions::GetForCommandLine(base_permissions);
260 process_.reset(new BrowserChildProcessHostImpl(
261 PROCESS_TYPE_PPAPI_PLUGIN, this));
263 host_impl_.reset(new BrowserPpapiHostImpl(this, permissions_, info.name,
264 info.path, profile_data_directory,
265 false /* in_process */,
266 false /* external_plugin */));
268 filter_ = new PepperMessageFilter();
269 process_->AddFilter(filter_.get());
270 process_->GetHost()->AddFilter(host_impl_->message_filter().get());
272 GetContentClient()->browser()->DidCreatePpapiPlugin(host_impl_.get());
274 // Only request network status updates if the plugin has dev permissions.
275 if (permissions_.HasPermission(ppapi::PERMISSION_DEV))
276 network_observer_.reset(new PluginNetworkObserver(this));
279 PpapiPluginProcessHost::PpapiPluginProcessHost()
280 : is_broker_(true) {
281 process_.reset(new BrowserChildProcessHostImpl(
282 PROCESS_TYPE_PPAPI_BROKER, this));
284 ppapi::PpapiPermissions permissions; // No permissions.
285 // The plugin name, path and profile data directory shouldn't be needed for
286 // the broker.
287 host_impl_.reset(new BrowserPpapiHostImpl(this, permissions,
288 std::string(), base::FilePath(),
289 base::FilePath(),
290 false /* in_process */,
291 false /* external_plugin */));
294 bool PpapiPluginProcessHost::Init(const PepperPluginInfo& info) {
295 plugin_path_ = info.path;
296 if (info.name.empty()) {
297 process_->SetName(plugin_path_.BaseName().LossyDisplayName());
298 } else {
299 process_->SetName(base::UTF8ToUTF16(info.name));
302 std::string channel_id = process_->GetHost()->CreateChannel();
303 if (channel_id.empty()) {
304 VLOG(1) << "Could not create pepper host channel.";
305 return false;
308 const base::CommandLine& browser_command_line =
309 *base::CommandLine::ForCurrentProcess();
310 base::CommandLine::StringType plugin_launcher =
311 browser_command_line.GetSwitchValueNative(switches::kPpapiPluginLauncher);
313 #if defined(OS_LINUX)
314 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
315 ChildProcessHost::CHILD_NORMAL;
316 #else
317 int flags = ChildProcessHost::CHILD_NORMAL;
318 #endif
319 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
320 if (exe_path.empty()) {
321 VLOG(1) << "Pepper plugin exe path is empty.";
322 return false;
325 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
326 cmd_line->AppendSwitchASCII(switches::kProcessType,
327 is_broker_ ? switches::kPpapiBrokerProcess
328 : switches::kPpapiPluginProcess);
329 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
331 // These switches are forwarded to both plugin and broker pocesses.
332 static const char* kCommonForwardSwitches[] = {
333 switches::kVModule
335 cmd_line->CopySwitchesFrom(browser_command_line, kCommonForwardSwitches,
336 arraysize(kCommonForwardSwitches));
338 if (!is_broker_) {
339 static const char* kPluginForwardSwitches[] = {
340 switches::kDisableSeccompFilterSandbox,
341 #if defined(OS_MACOSX)
342 switches::kEnableSandboxLogging,
343 #endif
344 switches::kNoSandbox,
345 switches::kPpapiStartupDialog,
347 cmd_line->CopySwitchesFrom(browser_command_line, kPluginForwardSwitches,
348 arraysize(kPluginForwardSwitches));
350 // Copy any flash args over and introduce field trials if necessary.
351 // TODO(vtl): Stop passing flash args in the command line, or windows is
352 // going to explode.
353 std::string field_trial =
354 base::FieldTrialList::FindFullName(kFlashHwVideoDecodeFieldTrialName);
355 std::string existing_args =
356 browser_command_line.GetSwitchValueASCII(switches::kPpapiFlashArgs);
357 if (field_trial == kFlashHwVideoDecodeFieldTrialEnabledName) {
358 // Arguments passed to Flash are comma delimited.
359 if (!existing_args.empty())
360 existing_args.append(",");
361 existing_args.append("enable_hw_video_decode=1");
362 #if defined(OS_MACOSX)
363 // TODO(ihf): Remove this once Flash newer than 15.0.0.223 is released.
364 existing_args.append(",enable_hw_video_decode_mac=1");
365 #endif
367 cmd_line->AppendSwitchASCII(switches::kPpapiFlashArgs, existing_args);
370 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
371 if (!locale.empty()) {
372 // Pass on the locale so the plugin will know what language we're using.
373 cmd_line->AppendSwitchASCII(switches::kLang, locale);
376 if (!plugin_launcher.empty())
377 cmd_line->PrependWrapper(plugin_launcher);
379 // On posix, never use the zygote for the broker. Also, only use the zygote if
380 // the plugin is sandboxed, and we are not using a plugin launcher - having a
381 // plugin launcher means we need to use another process instead of just
382 // forking the zygote.
383 #if defined(OS_POSIX)
384 if (!info.is_sandboxed)
385 cmd_line->AppendSwitchASCII(switches::kNoSandbox, std::string());
386 #endif // OS_POSIX
387 process_->Launch(
388 new PpapiPluginSandboxedProcessLauncherDelegate(is_broker_,
389 info,
390 process_->GetHost()),
391 cmd_line);
392 return true;
395 void PpapiPluginProcessHost::RequestPluginChannel(Client* client) {
396 base::ProcessHandle process_handle;
397 int renderer_child_id;
398 client->GetPpapiChannelInfo(&process_handle, &renderer_child_id);
400 base::ProcessId process_id = (process_handle == base::kNullProcessHandle) ?
401 0 : base::GetProcId(process_handle);
403 // We can't send any sync messages from the browser because it might lead to
404 // a hang. See the similar code in PluginProcessHost for more description.
405 PpapiMsg_CreateChannel* msg = new PpapiMsg_CreateChannel(
406 process_id, renderer_child_id, client->OffTheRecord());
407 msg->set_unblock(true);
408 if (Send(msg)) {
409 sent_requests_.push(client);
410 } else {
411 client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0);
415 void PpapiPluginProcessHost::OnProcessLaunched() {
416 VLOG(2) << "ppapi plugin process launched.";
417 host_impl_->set_plugin_process(process_->GetProcess().Duplicate());
420 void PpapiPluginProcessHost::OnProcessCrashed(int exit_code) {
421 VLOG(1) << "ppapi plugin process crashed.";
422 PluginServiceImpl::GetInstance()->RegisterPluginCrash(plugin_path_);
425 bool PpapiPluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
426 bool handled = true;
427 IPC_BEGIN_MESSAGE_MAP(PpapiPluginProcessHost, msg)
428 IPC_MESSAGE_HANDLER(PpapiHostMsg_ChannelCreated,
429 OnRendererPluginChannelCreated)
430 IPC_MESSAGE_UNHANDLED(handled = false)
431 IPC_END_MESSAGE_MAP()
432 DCHECK(handled);
433 return handled;
436 // Called when the browser <--> plugin channel has been established.
437 void PpapiPluginProcessHost::OnChannelConnected(int32 peer_pid) {
438 // This will actually load the plugin. Errors will actually not be reported
439 // back at this point. Instead, the plugin will fail to establish the
440 // connections when we request them on behalf of the renderer(s).
441 Send(new PpapiMsg_LoadPlugin(plugin_path_, permissions_));
443 // Process all pending channel requests from the renderers.
444 for (size_t i = 0; i < pending_requests_.size(); i++)
445 RequestPluginChannel(pending_requests_[i]);
446 pending_requests_.clear();
449 // Called when the browser <--> plugin channel has an error. This normally
450 // means the plugin has crashed.
451 void PpapiPluginProcessHost::OnChannelError() {
452 VLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
453 << "::OnChannelError()";
454 // We don't need to notify the renderers that were communicating with the
455 // plugin since they have their own channels which will go into the error
456 // state at the same time. Instead, we just need to notify any renderers
457 // that have requested a connection but have not yet received one.
458 CancelRequests();
461 void PpapiPluginProcessHost::CancelRequests() {
462 DVLOG(1) << "PpapiPluginProcessHost" << (is_broker_ ? "[broker]" : "")
463 << "CancelRequests()";
464 for (size_t i = 0; i < pending_requests_.size(); i++) {
465 pending_requests_[i]->OnPpapiChannelOpened(IPC::ChannelHandle(),
466 base::kNullProcessId, 0);
468 pending_requests_.clear();
470 while (!sent_requests_.empty()) {
471 sent_requests_.front()->OnPpapiChannelOpened(IPC::ChannelHandle(),
472 base::kNullProcessId, 0);
473 sent_requests_.pop();
477 // Called when a new plugin <--> renderer channel has been created.
478 void PpapiPluginProcessHost::OnRendererPluginChannelCreated(
479 const IPC::ChannelHandle& channel_handle) {
480 if (sent_requests_.empty())
481 return;
483 // All requests should be processed FIFO, so the next item in the
484 // sent_requests_ queue should be the one that the plugin just created.
485 Client* client = sent_requests_.front();
486 sent_requests_.pop();
488 const ChildProcessData& data = process_->GetData();
489 client->OnPpapiChannelOpened(channel_handle, base::GetProcId(data.handle),
490 data.id);
493 } // namespace content