Upstream version 9.38.198.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 "content/public/common/sandboxed_process_launcher_delegate.h"
40 #include "ipc/ipc_switches.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "ui/base/ui_base_switches.h"
43 #include "ui/gfx/native_widget_types.h"
44 #include "ui/gfx/switches.h"
45 #include "ui/gl/gl_switches.h"
46
47 #if defined(OS_MACOSX)
48 #include "base/mac/mac_util.h"
49 #include "ui/gfx/rect.h"
50 #endif
51
52 #if defined(OS_WIN)
53 #include "base/win/windows_version.h"
54 #include "content/common/plugin_constants_win.h"
55 #endif
56
57 namespace content {
58
59 #if defined(OS_WIN)
60 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
61   // The window is destroyed at this point, we just care about its parent, which
62   // is the intermediate window we created.
63   std::set<HWND>::iterator window_index =
64       plugin_parent_windows_set_.find(parent);
65   if (window_index == plugin_parent_windows_set_.end())
66     return;
67
68   plugin_parent_windows_set_.erase(window_index);
69   PostMessage(parent, WM_CLOSE, 0, 0);
70 }
71
72 void PluginProcessHost::AddWindow(HWND window) {
73   plugin_parent_windows_set_.insert(window);
74 }
75 #endif  // defined(OS_WIN)
76
77 // NOTE: changes to this class need to be reviewed by the security team.
78 class PluginSandboxedProcessLauncherDelegate
79     : public SandboxedProcessLauncherDelegate {
80  public:
81   explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
82 #if defined(OS_POSIX)
83       : ipc_fd_(host->TakeClientFileDescriptor())
84 #endif  // OS_POSIX
85   {}
86
87   virtual ~PluginSandboxedProcessLauncherDelegate() {}
88
89 #if defined(OS_WIN)
90   virtual bool ShouldSandbox() OVERRIDE {
91     return false;
92   }
93
94 #elif defined(OS_POSIX)
95   virtual int GetIpcFd() OVERRIDE {
96     return ipc_fd_;
97   }
98 #endif  // OS_WIN
99
100  private:
101 #if defined(OS_POSIX)
102   int ipc_fd_;
103 #endif  // OS_POSIX
104
105   DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
106 };
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 base::CommandLine& browser_command_line =
164       *base::CommandLine::ForCurrentProcess();
165   base::CommandLine::StringType plugin_launcher =
166       browser_command_line.GetSwitchValueNative(switches::kPluginLauncher);
167
168 #if defined(OS_MACOSX)
169   // Run the plug-in process in a mode tolerant of heap execution without
170   // explicit mprotect calls. Some plug-ins still rely on this quaint and
171   // archaic "feature." See http://crbug.com/93551.
172   int flags = ChildProcessHost::CHILD_ALLOW_HEAP_EXECUTION;
173 #elif defined(OS_LINUX)
174   int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
175                                         ChildProcessHost::CHILD_NORMAL;
176 #else
177   int flags = ChildProcessHost::CHILD_NORMAL;
178 #endif
179
180   base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
181   if (exe_path.empty())
182     return false;
183
184   base::CommandLine* cmd_line = new base::CommandLine(exe_path);
185   // Put the process type and plugin path first so they're easier to see
186   // in process listings using native process management tools.
187   cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kPluginProcess);
188   cmd_line->AppendSwitchPath(switches::kPluginPath, info.path);
189
190   // Propagate the following switches to the plugin command line (along with
191   // any associated values) if present in the browser command line
192   static const char* const kSwitchNames[] = {
193     switches::kDisableBreakpad,
194     switches::kDisableDirectNPAPIRequests,
195     switches::kEnableStatsTable,
196     switches::kFullMemoryCrashReport,
197     switches::kLoggingLevel,
198     switches::kLogPluginMessages,
199     switches::kNoSandbox,
200     switches::kPluginStartupDialog,
201     switches::kTraceStartup,
202     switches::kUseGL,
203     switches::kForceDeviceScaleFactor,
204 #if defined(OS_MACOSX)
205     switches::kDisableCoreAnimationPlugins,
206     switches::kEnableSandboxLogging,
207 #endif
208   };
209
210   cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
211                              arraysize(kSwitchNames));
212
213   GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
214
215   // If specified, prepend a launcher program to the command line.
216   if (!plugin_launcher.empty())
217     cmd_line->PrependWrapper(plugin_launcher);
218
219   std::string locale = GetContentClient()->browser()->GetApplicationLocale();
220   if (!locale.empty()) {
221     // Pass on the locale so the null plugin will use the right language in the
222     // prompt to install the desired plugin.
223     cmd_line->AppendSwitchASCII(switches::kLang, locale);
224   }
225
226   cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
227
228   process_->Launch(
229       new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
230       cmd_line);
231
232   // The plugin needs to be shutdown gracefully, i.e. NP_Shutdown needs to be
233   // called on the plugin. The plugin process exits when it receives the
234   // OnChannelError notification indicating that the browser plugin channel has
235   // been destroyed.
236   process_->SetTerminateChildOnShutdown(false);
237
238   ResourceMessageFilter::GetContextsCallback get_contexts_callback(
239       base::Bind(&PluginProcessHost::GetContexts,
240       base::Unretained(this)));
241
242   // TODO(jam): right now we're passing NULL for appcache, blob storage, and
243   // file system. If NPAPI plugins actually use this, we'll have to plumb them.
244   ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
245       process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL,
246       get_contexts_callback);
247   process_->AddFilter(resource_message_filter);
248   return true;
249 }
250
251 void PluginProcessHost::ForceShutdown() {
252   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
253   Send(new PluginProcessMsg_NotifyRenderersOfPendingShutdown());
254   process_->ForceShutdown();
255 }
256
257 bool PluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
258   bool handled = true;
259   IPC_BEGIN_MESSAGE_MAP(PluginProcessHost, msg)
260     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelCreated, OnChannelCreated)
261     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelDestroyed,
262                         OnChannelDestroyed)
263 #if defined(OS_WIN)
264     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginWindowDestroyed,
265                         OnPluginWindowDestroyed)
266 #endif
267 #if defined(OS_MACOSX)
268     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
269                         OnPluginShowWindow)
270     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
271                         OnPluginHideWindow)
272     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
273                         OnPluginSetCursorVisibility)
274 #endif
275     IPC_MESSAGE_UNHANDLED(handled = false)
276   IPC_END_MESSAGE_MAP()
277
278   return handled;
279 }
280
281 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
282   for (size_t i = 0; i < pending_requests_.size(); ++i) {
283     RequestPluginChannel(pending_requests_[i]);
284   }
285
286   pending_requests_.clear();
287 }
288
289 void PluginProcessHost::OnChannelError() {
290   CancelRequests();
291 }
292
293 bool PluginProcessHost::CanShutdown() {
294   return sent_requests_.empty();
295 }
296
297 void PluginProcessHost::OnProcessCrashed(int exit_code) {
298   PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
299 }
300
301 void PluginProcessHost::CancelRequests() {
302   for (size_t i = 0; i < pending_requests_.size(); ++i)
303     pending_requests_[i]->OnError();
304   pending_requests_.clear();
305
306   while (!sent_requests_.empty()) {
307     Client* client = sent_requests_.front();
308     if (client)
309       client->OnError();
310     sent_requests_.pop_front();
311   }
312 }
313
314 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
315   BrowserThread::PostTask(
316       BrowserThread::UI, FROM_HERE,
317       base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
318                  process_->GetData()));
319   client->SetPluginInfo(info_);
320   if (process_->GetHost()->IsChannelOpening()) {
321     // The channel is already in the process of being opened.  Put
322     // this "open channel" request into a queue of requests that will
323     // be run once the channel is open.
324     pending_requests_.push_back(client);
325     return;
326   }
327
328   // We already have an open channel, send a request right away to plugin.
329   RequestPluginChannel(client);
330 }
331
332 void PluginProcessHost::CancelPendingRequest(Client* client) {
333   std::vector<Client*>::iterator it = pending_requests_.begin();
334   while (it != pending_requests_.end()) {
335     if (client == *it) {
336       pending_requests_.erase(it);
337       return;
338     }
339     ++it;
340   }
341   DCHECK(it != pending_requests_.end());
342 }
343
344 void PluginProcessHost::CancelSentRequest(Client* client) {
345   std::list<Client*>::iterator it = sent_requests_.begin();
346   while (it != sent_requests_.end()) {
347     if (client == *it) {
348       *it = NULL;
349       return;
350     }
351     ++it;
352   }
353   DCHECK(it != sent_requests_.end());
354 }
355
356 void PluginProcessHost::RequestPluginChannel(Client* client) {
357   // We can't send any sync messages from the browser because it might lead to
358   // a hang.  However this async messages must be answered right away by the
359   // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
360   // a deadlock can occur if the plugin creation request from the renderer is
361   // a result of a sync message by the plugin process.
362   PluginProcessMsg_CreateChannel* msg =
363       new PluginProcessMsg_CreateChannel(
364           client->ID(),
365           client->OffTheRecord());
366   msg->set_unblock(true);
367   if (Send(msg)) {
368     sent_requests_.push_back(client);
369     client->OnSentPluginChannelRequest();
370   } else {
371     client->OnError();
372   }
373 }
374
375 void PluginProcessHost::OnChannelCreated(
376     const IPC::ChannelHandle& channel_handle) {
377   Client* client = sent_requests_.front();
378
379   if (client) {
380     if (!resource_context_map_.count(client->ID())) {
381       ResourceContextEntry entry;
382       entry.ref_count = 0;
383       entry.resource_context = client->GetResourceContext();
384       resource_context_map_[client->ID()] = entry;
385     }
386     resource_context_map_[client->ID()].ref_count++;
387     client->OnChannelOpened(channel_handle);
388   }
389   sent_requests_.pop_front();
390 }
391
392 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
393   resource_context_map_[renderer_id].ref_count--;
394   if (!resource_context_map_[renderer_id].ref_count)
395     resource_context_map_.erase(renderer_id);
396 }
397
398 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
399                                     ResourceContext** resource_context,
400                                     net::URLRequestContext** request_context) {
401   *resource_context =
402       resource_context_map_[request.origin_pid].resource_context;
403   *request_context = (*resource_context)->GetRequestContext();
404 }
405
406 }  // namespace content