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