[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / plugin_process_host.cc
blob7cc5d8730dbb62af95f227744e6029b5da4d10a2
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/plugin_process_host.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #elif defined(OS_POSIX)
10 #include <utility> // for pair<>
11 #endif
13 #include <vector>
15 #include "base/base_switches.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/files/file_path.h"
19 #include "base/lazy_instance.h"
20 #include "base/logging.h"
21 #include "base/metrics/histogram.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/synchronization/lock.h"
26 #include "components/tracing/tracing_switches.h"
27 #include "content/browser/browser_child_process_host_impl.h"
28 #include "content/browser/gpu/gpu_data_manager_impl.h"
29 #include "content/browser/loader/resource_message_filter.h"
30 #include "content/browser/plugin_service_impl.h"
31 #include "content/common/child_process_host_impl.h"
32 #include "content/common/plugin_process_messages.h"
33 #include "content/common/resource_messages.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "content/public/browser/content_browser_client.h"
36 #include "content/public/browser/notification_types.h"
37 #include "content/public/browser/plugin_service.h"
38 #include "content/public/browser/resource_context.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/process_type.h"
41 #include "content/public/common/sandboxed_process_launcher_delegate.h"
42 #include "ipc/ipc_switches.h"
43 #include "net/url_request/url_request_context_getter.h"
44 #include "ui/base/ui_base_switches.h"
45 #include "ui/gfx/native_widget_types.h"
46 #include "ui/gfx/switches.h"
47 #include "ui/gl/gl_switches.h"
49 #if defined(OS_MACOSX)
50 #include "base/mac/mac_util.h"
51 #include "ui/gfx/geometry/rect.h"
52 #endif
54 #if defined(OS_WIN)
55 #include "base/win/windows_version.h"
56 #include "content/common/plugin_constants_win.h"
57 #endif
59 namespace content {
61 namespace {
63 base::LazyInstance<std::map<base::ProcessId, WebPluginInfo> >
64 g_process_webplugin_info = LAZY_INSTANCE_INITIALIZER;
65 base::LazyInstance<base::Lock>::Leaky
66 g_process_webplugin_info_lock = LAZY_INSTANCE_INITIALIZER;
69 bool PluginProcessHost::GetWebPluginInfoFromPluginPid(base::ProcessId pid,
70 WebPluginInfo* info) {
71 base::AutoLock lock(g_process_webplugin_info_lock.Get());
72 if (!g_process_webplugin_info.Get().count(pid))
73 return false;
75 *info = g_process_webplugin_info.Get()[pid];
76 return true;
79 #if defined(OS_WIN)
80 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
81 // The window is destroyed at this point, we just care about its parent, which
82 // is the intermediate window we created.
83 std::set<HWND>::iterator window_index =
84 plugin_parent_windows_set_.find(parent);
85 if (window_index == plugin_parent_windows_set_.end())
86 return;
88 plugin_parent_windows_set_.erase(window_index);
89 PostMessage(parent, WM_CLOSE, 0, 0);
92 void PluginProcessHost::AddWindow(HWND window) {
93 plugin_parent_windows_set_.insert(window);
95 #endif // defined(OS_WIN)
97 // NOTE: changes to this class need to be reviewed by the security team.
98 class PluginSandboxedProcessLauncherDelegate
99 : public SandboxedProcessLauncherDelegate {
100 public:
101 explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
102 #if defined(OS_POSIX)
103 : ipc_fd_(host->TakeClientFileDescriptor())
104 #endif // OS_POSIX
107 ~PluginSandboxedProcessLauncherDelegate() override {}
109 #if defined(OS_WIN)
110 bool ShouldSandbox() override {
111 return false;
114 #elif defined(OS_POSIX)
115 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
116 #endif // OS_WIN
118 private:
119 #if defined(OS_POSIX)
120 base::ScopedFD ipc_fd_;
121 #endif // OS_POSIX
123 DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
126 PluginProcessHost::PluginProcessHost()
127 : pid_(base::kNullProcessId)
128 #if defined(OS_MACOSX)
129 , plugin_cursor_visible_(true)
130 #endif
132 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
135 PluginProcessHost::~PluginProcessHost() {
136 #if defined(OS_WIN)
137 // We erase HWNDs from the plugin_parent_windows_set_ when we receive a
138 // notification that the window is being destroyed. If we don't receive this
139 // notification and the PluginProcessHost instance is being destroyed, it
140 // means that the plugin process crashed. We paint a sad face in this case in
141 // the renderer process. To ensure that the sad face shows up, and we don't
142 // leak HWNDs, we should destroy existing plugin parent windows.
143 std::set<HWND>::iterator window_index;
144 for (window_index = plugin_parent_windows_set_.begin();
145 window_index != plugin_parent_windows_set_.end();
146 ++window_index) {
147 PostMessage(*window_index, WM_CLOSE, 0, 0);
149 #elif defined(OS_MACOSX)
150 DCHECK_CURRENTLY_ON(BrowserThread::IO);
151 // If the plugin process crashed but had fullscreen windows open at the time,
152 // make sure that the menu bar is visible.
153 for (size_t i = 0; i < plugin_fullscreen_windows_set_.size(); ++i) {
154 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
155 base::Bind(base::mac::ReleaseFullScreen,
156 base::mac::kFullScreenModeHideAll));
158 // If the plugin hid the cursor, reset that.
159 if (!plugin_cursor_visible_) {
160 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
161 base::Bind(base::mac::SetCursorVisibility, true));
163 #endif
164 // Cancel all pending and sent requests.
165 CancelRequests();
168 base::AutoLock lock(g_process_webplugin_info_lock.Get());
169 g_process_webplugin_info.Get()[pid_] = info_;
173 bool PluginProcessHost::Send(IPC::Message* message) {
174 return process_->Send(message);
177 bool PluginProcessHost::Init(const WebPluginInfo& info) {
178 info_ = info;
179 process_->SetName(info_.name);
181 std::string channel_id = process_->GetHost()->CreateChannel();
182 if (channel_id.empty())
183 return false;
185 // Build command line for plugin. When we have a plugin launcher, we can't
186 // allow "self" on linux and we need the real file path.
187 const base::CommandLine& browser_command_line =
188 *base::CommandLine::ForCurrentProcess();
189 base::CommandLine::StringType plugin_launcher =
190 browser_command_line.GetSwitchValueNative(switches::kPluginLauncher);
192 #if defined(OS_LINUX)
193 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
194 ChildProcessHost::CHILD_NORMAL;
195 #else
196 int flags = ChildProcessHost::CHILD_NORMAL;
197 #endif
199 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
200 if (exe_path.empty())
201 return false;
203 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
204 // Put the process type and plugin path first so they're easier to see
205 // in process listings using native process management tools.
206 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kPluginProcess);
207 cmd_line->AppendSwitchPath(switches::kPluginPath, info.path);
209 // Propagate the following switches to the plugin command line (along with
210 // any associated values) if present in the browser command line
211 static const char* const kSwitchNames[] = {
212 switches::kDisableBreakpad,
213 switches::kDisableDirectNPAPIRequests,
214 switches::kEnableStatsTable,
215 switches::kFullMemoryCrashReport,
216 switches::kLoggingLevel,
217 switches::kLogPluginMessages,
218 switches::kNoSandbox,
219 switches::kPluginStartupDialog,
220 switches::kTraceConfigFile,
221 switches::kTraceStartup,
222 switches::kUseGL,
223 switches::kForceDeviceScaleFactor,
224 #if defined(OS_MACOSX)
225 switches::kDisableCoreAnimationPlugins,
226 switches::kEnableSandboxLogging,
227 #endif
230 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
231 arraysize(kSwitchNames));
233 GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
235 // If specified, prepend a launcher program to the command line.
236 if (!plugin_launcher.empty())
237 cmd_line->PrependWrapper(plugin_launcher);
239 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
240 if (!locale.empty()) {
241 // Pass on the locale so the null plugin will use the right language in the
242 // prompt to install the desired plugin.
243 cmd_line->AppendSwitchASCII(switches::kLang, locale);
246 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
248 // The plugin needs to be shutdown gracefully, i.e. NP_Shutdown needs to be
249 // called on the plugin. The plugin process exits when it receives the
250 // OnChannelError notification indicating that the browser plugin channel has
251 // been destroyed.
252 bool terminate_on_shutdown = false;
253 process_->Launch(
254 new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
255 cmd_line,
256 terminate_on_shutdown);
258 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
259 base::Bind(&PluginProcessHost::GetContexts,
260 base::Unretained(this)));
262 // TODO(jam): right now we're passing NULL for appcache, blob storage, file
263 // system and host zoom level context. If NPAPI plugins actually use this,
264 // we'll have to plumb them.
265 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
266 process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL, NULL,
267 get_contexts_callback);
268 process_->AddFilter(resource_message_filter);
269 return true;
272 void PluginProcessHost::ForceShutdown() {
273 DCHECK_CURRENTLY_ON(BrowserThread::IO);
274 Send(new PluginProcessMsg_NotifyRenderersOfPendingShutdown());
275 process_->ForceShutdown();
278 bool PluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
279 bool handled = true;
280 IPC_BEGIN_MESSAGE_MAP(PluginProcessHost, msg)
281 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelCreated, OnChannelCreated)
282 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelDestroyed,
283 OnChannelDestroyed)
284 #if defined(OS_WIN)
285 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginWindowDestroyed,
286 OnPluginWindowDestroyed)
287 #endif
288 #if defined(OS_MACOSX)
289 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
290 OnPluginShowWindow)
291 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
292 OnPluginHideWindow)
293 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
294 OnPluginSetCursorVisibility)
295 #endif
296 IPC_MESSAGE_UNHANDLED(handled = false)
297 IPC_END_MESSAGE_MAP()
299 return handled;
302 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
303 for (size_t i = 0; i < pending_requests_.size(); ++i) {
304 RequestPluginChannel(pending_requests_[i]);
307 pending_requests_.clear();
309 pid_ = peer_pid;
311 base::AutoLock lock(g_process_webplugin_info_lock.Get());
312 g_process_webplugin_info.Get()[pid_] = info_;
316 void PluginProcessHost::OnChannelError() {
317 CancelRequests();
320 bool PluginProcessHost::CanShutdown() {
321 return sent_requests_.empty();
324 void PluginProcessHost::OnProcessCrashed(int exit_code) {
325 PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
328 void PluginProcessHost::CancelRequests() {
329 for (size_t i = 0; i < pending_requests_.size(); ++i)
330 pending_requests_[i]->OnError();
331 pending_requests_.clear();
333 while (!sent_requests_.empty()) {
334 Client* client = sent_requests_.front();
335 if (client)
336 client->OnError();
337 sent_requests_.pop_front();
341 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
342 BrowserThread::PostTask(
343 BrowserThread::UI, FROM_HERE,
344 base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
345 process_->GetData()));
346 client->SetPluginInfo(info_);
347 if (process_->GetHost()->IsChannelOpening()) {
348 // The channel is already in the process of being opened. Put
349 // this "open channel" request into a queue of requests that will
350 // be run once the channel is open.
351 pending_requests_.push_back(client);
352 return;
355 // We already have an open channel, send a request right away to plugin.
356 RequestPluginChannel(client);
359 void PluginProcessHost::CancelPendingRequest(Client* client) {
360 std::vector<Client*>::iterator it = pending_requests_.begin();
361 while (it != pending_requests_.end()) {
362 if (client == *it) {
363 pending_requests_.erase(it);
364 return;
366 ++it;
368 DCHECK(it != pending_requests_.end());
371 void PluginProcessHost::CancelSentRequest(Client* client) {
372 std::list<Client*>::iterator it = sent_requests_.begin();
373 while (it != sent_requests_.end()) {
374 if (client == *it) {
375 *it = NULL;
376 return;
378 ++it;
380 DCHECK(it != sent_requests_.end());
383 void PluginProcessHost::RequestPluginChannel(Client* client) {
384 // We can't send any sync messages from the browser because it might lead to
385 // a hang. However this async messages must be answered right away by the
386 // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
387 // a deadlock can occur if the plugin creation request from the renderer is
388 // a result of a sync message by the plugin process.
389 PluginProcessMsg_CreateChannel* msg =
390 new PluginProcessMsg_CreateChannel(
391 client->ID(),
392 client->OffTheRecord());
393 msg->set_unblock(true);
394 if (Send(msg)) {
395 sent_requests_.push_back(client);
396 client->OnSentPluginChannelRequest();
397 } else {
398 client->OnError();
402 void PluginProcessHost::OnChannelCreated(
403 const IPC::ChannelHandle& channel_handle) {
404 Client* client = sent_requests_.front();
406 if (client) {
407 if (!resource_context_map_.count(client->ID())) {
408 ResourceContextEntry entry;
409 entry.ref_count = 0;
410 entry.resource_context = client->GetResourceContext();
411 resource_context_map_[client->ID()] = entry;
413 resource_context_map_[client->ID()].ref_count++;
414 client->OnChannelOpened(channel_handle);
416 sent_requests_.pop_front();
419 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
420 resource_context_map_[renderer_id].ref_count--;
421 if (!resource_context_map_[renderer_id].ref_count)
422 resource_context_map_.erase(renderer_id);
425 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
426 ResourceContext** resource_context,
427 net::URLRequestContext** request_context) {
428 *resource_context =
429 resource_context_map_[request.origin_pid].resource_context;
430 *request_context = (*resource_context)->GetRequestContext();
433 } // namespace content