Upstream version 7.36.149.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/gl/gl_switches.h"
45
46 #if defined(OS_MACOSX)
47 #include "base/mac/mac_util.h"
48 #include "content/common/plugin_carbon_interpose_constants_mac.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 #include "ui/gfx/switches.h"
56 #endif
57
58 namespace content {
59
60 #if defined(OS_WIN)
61 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
62   // The window is destroyed at this point, we just care about its parent, which
63   // is the intermediate window we created.
64   std::set<HWND>::iterator window_index =
65       plugin_parent_windows_set_.find(parent);
66   if (window_index == plugin_parent_windows_set_.end())
67     return;
68
69   plugin_parent_windows_set_.erase(window_index);
70   PostMessage(parent, WM_CLOSE, 0, 0);
71 }
72
73 void PluginProcessHost::AddWindow(HWND window) {
74   plugin_parent_windows_set_.insert(window);
75 }
76 #endif  // defined(OS_WIN)
77
78 // NOTE: changes to this class need to be reviewed by the security team.
79 class PluginSandboxedProcessLauncherDelegate
80     : public SandboxedProcessLauncherDelegate {
81  public:
82   explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
83 #if defined(OS_POSIX)
84       : ipc_fd_(host->TakeClientFileDescriptor())
85 #endif  // OS_POSIX
86   {}
87
88   virtual ~PluginSandboxedProcessLauncherDelegate() {}
89
90 #if defined(OS_WIN)
91   virtual bool ShouldSandbox() OVERRIDE {
92     return false;
93   }
94
95 #elif defined(OS_POSIX)
96   virtual int GetIpcFd() OVERRIDE {
97     return ipc_fd_;
98   }
99 #endif  // OS_WIN
100
101  private:
102 #if defined(OS_POSIX)
103   int ipc_fd_;
104 #endif  // OS_POSIX
105
106   DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
107 };
108
109 PluginProcessHost::PluginProcessHost()
110 #if defined(OS_MACOSX)
111     : plugin_cursor_visible_(true)
112 #endif
113 {
114   process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
115 }
116
117 PluginProcessHost::~PluginProcessHost() {
118 #if defined(OS_WIN)
119   // We erase HWNDs from the plugin_parent_windows_set_ when we receive a
120   // notification that the window is being destroyed. If we don't receive this
121   // notification and the PluginProcessHost instance is being destroyed, it
122   // means that the plugin process crashed. We paint a sad face in this case in
123   // the renderer process. To ensure that the sad face shows up, and we don't
124   // leak HWNDs, we should destroy existing plugin parent windows.
125   std::set<HWND>::iterator window_index;
126   for (window_index = plugin_parent_windows_set_.begin();
127        window_index != plugin_parent_windows_set_.end();
128        ++window_index) {
129     PostMessage(*window_index, WM_CLOSE, 0, 0);
130   }
131 #elif defined(OS_MACOSX)
132   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
133   // If the plugin process crashed but had fullscreen windows open at the time,
134   // make sure that the menu bar is visible.
135   for (size_t i = 0; i < plugin_fullscreen_windows_set_.size(); ++i) {
136     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
137                             base::Bind(base::mac::ReleaseFullScreen,
138                                        base::mac::kFullScreenModeHideAll));
139   }
140   // If the plugin hid the cursor, reset that.
141   if (!plugin_cursor_visible_) {
142     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
143                             base::Bind(base::mac::SetCursorVisibility, true));
144   }
145 #endif
146   // Cancel all pending and sent requests.
147   CancelRequests();
148 }
149
150 bool PluginProcessHost::Send(IPC::Message* message) {
151   return process_->Send(message);
152 }
153
154 bool PluginProcessHost::Init(const WebPluginInfo& info) {
155   info_ = info;
156   process_->SetName(info_.name);
157
158   std::string channel_id = process_->GetHost()->CreateChannel();
159   if (channel_id.empty())
160     return false;
161
162   // Build command line for plugin. When we have a plugin launcher, we can't
163   // allow "self" on linux and we need the real file path.
164   const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
165   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   CommandLine* cmd_line = new 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::kTestSandbox,
202     switches::kTraceStartup,
203     switches::kUseGL,
204 #if defined(OS_MACOSX)
205     switches::kDisableCoreAnimationPlugins,
206     switches::kEnableSandboxLogging,
207 #endif
208 #if defined(OS_WIN)
209     switches::kHighDPISupport,
210 #endif
211   };
212
213   cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
214                              arraysize(kSwitchNames));
215
216   GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
217
218   // If specified, prepend a launcher program to the command line.
219   if (!plugin_launcher.empty())
220     cmd_line->PrependWrapper(plugin_launcher);
221
222   std::string locale = GetContentClient()->browser()->GetApplicationLocale();
223   if (!locale.empty()) {
224     // Pass on the locale so the null plugin will use the right language in the
225     // prompt to install the desired plugin.
226     cmd_line->AppendSwitchASCII(switches::kLang, locale);
227   }
228
229   cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
230
231 #if defined(OS_POSIX)
232   base::EnvironmentMap env;
233 #if defined(OS_MACOSX) && !defined(__LP64__)
234   if (browser_command_line.HasSwitch(switches::kEnableCarbonInterposing)) {
235     std::string interpose_list = GetContentClient()->GetCarbonInterposePath();
236     if (!interpose_list.empty()) {
237       // Add our interposing library for Carbon. This is stripped back out in
238       // plugin_main.cc, so changes here should be reflected there.
239       const char* existing_list = getenv(kDYLDInsertLibrariesKey);
240       if (existing_list) {
241         interpose_list.insert(0, ":");
242         interpose_list.insert(0, existing_list);
243       }
244     }
245     env[kDYLDInsertLibrariesKey] = interpose_list;
246   }
247 #endif
248 #endif
249
250   process_->Launch(
251       new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
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, 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(OS_MACOSX)
290     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSelectWindow,
291                         OnPluginSelectWindow)
292     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
293                         OnPluginShowWindow)
294     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
295                         OnPluginHideWindow)
296     IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
297                         OnPluginSetCursorVisibility)
298 #endif
299     IPC_MESSAGE_UNHANDLED(handled = false)
300   IPC_END_MESSAGE_MAP()
301
302   return handled;
303 }
304
305 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
306   for (size_t i = 0; i < pending_requests_.size(); ++i) {
307     RequestPluginChannel(pending_requests_[i]);
308   }
309
310   pending_requests_.clear();
311 }
312
313 void PluginProcessHost::OnChannelError() {
314   CancelRequests();
315 }
316
317 bool PluginProcessHost::CanShutdown() {
318   return sent_requests_.empty();
319 }
320
321 void PluginProcessHost::OnProcessCrashed(int exit_code) {
322   PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
323 }
324
325 void PluginProcessHost::CancelRequests() {
326   for (size_t i = 0; i < pending_requests_.size(); ++i)
327     pending_requests_[i]->OnError();
328   pending_requests_.clear();
329
330   while (!sent_requests_.empty()) {
331     Client* client = sent_requests_.front();
332     if (client)
333       client->OnError();
334     sent_requests_.pop_front();
335   }
336 }
337
338 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
339   BrowserThread::PostTask(
340       BrowserThread::UI, FROM_HERE,
341       base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
342                  process_->GetData()));
343   client->SetPluginInfo(info_);
344   if (process_->GetHost()->IsChannelOpening()) {
345     // The channel is already in the process of being opened.  Put
346     // this "open channel" request into a queue of requests that will
347     // be run once the channel is open.
348     pending_requests_.push_back(client);
349     return;
350   }
351
352   // We already have an open channel, send a request right away to plugin.
353   RequestPluginChannel(client);
354 }
355
356 void PluginProcessHost::CancelPendingRequest(Client* client) {
357   std::vector<Client*>::iterator it = pending_requests_.begin();
358   while (it != pending_requests_.end()) {
359     if (client == *it) {
360       pending_requests_.erase(it);
361       return;
362     }
363     ++it;
364   }
365   DCHECK(it != pending_requests_.end());
366 }
367
368 void PluginProcessHost::CancelSentRequest(Client* client) {
369   std::list<Client*>::iterator it = sent_requests_.begin();
370   while (it != sent_requests_.end()) {
371     if (client == *it) {
372       *it = NULL;
373       return;
374     }
375     ++it;
376   }
377   DCHECK(it != sent_requests_.end());
378 }
379
380 void PluginProcessHost::RequestPluginChannel(Client* client) {
381   // We can't send any sync messages from the browser because it might lead to
382   // a hang.  However this async messages must be answered right away by the
383   // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
384   // a deadlock can occur if the plugin creation request from the renderer is
385   // a result of a sync message by the plugin process.
386   PluginProcessMsg_CreateChannel* msg =
387       new PluginProcessMsg_CreateChannel(
388           client->ID(),
389           client->OffTheRecord());
390   msg->set_unblock(true);
391   if (Send(msg)) {
392     sent_requests_.push_back(client);
393     client->OnSentPluginChannelRequest();
394   } else {
395     client->OnError();
396   }
397 }
398
399 void PluginProcessHost::OnChannelCreated(
400     const IPC::ChannelHandle& channel_handle) {
401   Client* client = sent_requests_.front();
402
403   if (client) {
404     if (!resource_context_map_.count(client->ID())) {
405       ResourceContextEntry entry;
406       entry.ref_count = 0;
407       entry.resource_context = client->GetResourceContext();
408       resource_context_map_[client->ID()] = entry;
409     }
410     resource_context_map_[client->ID()].ref_count++;
411     client->OnChannelOpened(channel_handle);
412   }
413   sent_requests_.pop_front();
414 }
415
416 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
417   resource_context_map_[renderer_id].ref_count--;
418   if (!resource_context_map_[renderer_id].ref_count)
419     resource_context_map_.erase(renderer_id);
420 }
421
422 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
423                                     ResourceContext** resource_context,
424                                     net::URLRequestContext** request_context) {
425   *resource_context =
426       resource_context_map_[request.origin_pid].resource_context;
427   *request_context = (*resource_context)->GetRequestContext();
428 }
429
430 }  // namespace content