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