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