Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / plugin_service_impl.cc
blob253c5c50209c5add2f5fdb1966aa709b7961cd51
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.
5 #include "content/browser/plugin_service_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/compiler_specific.h"
10 #include "base/files/file_path.h"
11 #include "base/location.h"
12 #include "base/metrics/histogram.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/threading/thread.h"
18 #include "content/browser/ppapi_plugin_process_host.h"
19 #include "content/browser/renderer_host/render_process_host_impl.h"
20 #include "content/browser/renderer_host/render_view_host_impl.h"
21 #include "content/common/content_switches_internal.h"
22 #include "content/common/pepper_plugin_list.h"
23 #include "content/common/plugin_list.h"
24 #include "content/common/view_messages.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/content_browser_client.h"
27 #include "content/public/browser/plugin_service_filter.h"
28 #include "content/public/browser/resource_context.h"
29 #include "content/public/common/content_constants.h"
30 #include "content/public/common/content_switches.h"
31 #include "content/public/common/process_type.h"
32 #include "content/public/common/webplugininfo.h"
34 #if defined(OS_WIN)
35 #include "content/common/plugin_constants_win.h"
36 #include "ui/gfx/win/hwnd_util.h"
37 #endif
39 #if defined(OS_POSIX)
40 #include "content/browser/plugin_loader_posix.h"
41 #endif
43 #if defined(OS_POSIX) && !defined(OS_OPENBSD) && !defined(OS_ANDROID)
44 using ::base::FilePathWatcher;
45 #endif
47 namespace content {
48 namespace {
50 // This enum is used to collect Flash usage data.
51 enum FlashUsage {
52 // Number of browser processes that have started at least one NPAPI Flash
53 // process during their lifetime.
54 START_NPAPI_FLASH_AT_LEAST_ONCE,
55 // Number of browser processes that have started at least one PPAPI Flash
56 // process during their lifetime.
57 START_PPAPI_FLASH_AT_LEAST_ONCE,
58 // Total number of browser processes.
59 TOTAL_BROWSER_PROCESSES,
60 FLASH_USAGE_ENUM_COUNT
63 enum NPAPIPluginStatus {
64 // Platform does not support NPAPI.
65 NPAPI_STATUS_UNSUPPORTED,
66 // Platform supports NPAPI and NPAPI is disabled.
67 NPAPI_STATUS_DISABLED,
68 // Platform supports NPAPI and NPAPI is enabled.
69 NPAPI_STATUS_ENABLED,
70 NPAPI_STATUS_ENUM_COUNT
73 bool LoadPluginListInProcess() {
74 #if defined(OS_WIN)
75 return true;
76 #else
77 // If on POSIX, we don't want to load the list of NPAPI plugins in-process as
78 // that causes instability.
80 // Can't load the plugins on the utility thread when in single process mode
81 // since that requires GTK which can only be used on the main thread.
82 if (RenderProcessHost::run_renderer_in_process())
83 return true;
85 return !PluginService::GetInstance()->NPAPIPluginsSupported();
86 #endif
89 // Callback set on the PluginList to assert that plugin loading happens on the
90 // correct thread.
91 void WillLoadPluginsCallback(
92 base::SequencedWorkerPool::SequenceToken token) {
93 if (LoadPluginListInProcess()) {
94 CHECK(BrowserThread::GetBlockingPool()->IsRunningSequenceOnCurrentThread(
95 token));
96 } else {
97 CHECK(false) << "Plugin loading should happen out-of-process.";
101 #if defined(OS_MACOSX)
102 void NotifyPluginsOfActivation() {
103 DCHECK_CURRENTLY_ON(BrowserThread::IO);
105 for (PluginProcessHostIterator iter; !iter.Done(); ++iter)
106 iter->OnAppActivation();
108 #endif
110 #if defined(OS_POSIX)
111 #if !defined(OS_OPENBSD) && !defined(OS_ANDROID)
112 void NotifyPluginDirChanged(const base::FilePath& path, bool error) {
113 if (error) {
114 // TODO(pastarmovj): Add some sensible error handling. Maybe silently
115 // stopping the watcher would be enough. Or possibly restart it.
116 NOTREACHED();
117 return;
119 VLOG(1) << "Watched path changed: " << path.value();
120 // Make the plugin list update itself
121 PluginList::Singleton()->RefreshPlugins();
122 BrowserThread::PostTask(
123 BrowserThread::UI, FROM_HERE,
124 base::Bind(&PluginService::PurgePluginListCache,
125 static_cast<BrowserContext*>(NULL), false));
127 #endif // !defined(OS_OPENBSD) && !defined(OS_ANDROID)
129 void ForwardCallback(base::SingleThreadTaskRunner* target_task_runner,
130 const PluginService::GetPluginsCallback& callback,
131 const std::vector<WebPluginInfo>& plugins) {
132 target_task_runner->PostTask(FROM_HERE, base::Bind(callback, plugins));
134 #endif // defined(OS_POSIX)
136 } // namespace
138 // static
139 PluginService* PluginService::GetInstance() {
140 return PluginServiceImpl::GetInstance();
143 void PluginService::PurgePluginListCache(BrowserContext* browser_context,
144 bool reload_pages) {
145 for (RenderProcessHost::iterator it = RenderProcessHost::AllHostsIterator();
146 !it.IsAtEnd(); it.Advance()) {
147 RenderProcessHost* host = it.GetCurrentValue();
148 if (!browser_context || host->GetBrowserContext() == browser_context)
149 host->Send(new ViewMsg_PurgePluginListCache(reload_pages));
153 // static
154 PluginServiceImpl* PluginServiceImpl::GetInstance() {
155 return Singleton<PluginServiceImpl>::get();
158 PluginServiceImpl::PluginServiceImpl()
159 : npapi_plugins_enabled_(false), filter_(NULL) {
160 // Collect the total number of browser processes (which create
161 // PluginServiceImpl objects, to be precise). The number is used to normalize
162 // the number of processes which start at least one NPAPI/PPAPI Flash process.
163 static bool counted = false;
164 if (!counted) {
165 counted = true;
166 UMA_HISTOGRAM_ENUMERATION("Plugin.FlashUsage", TOTAL_BROWSER_PROCESSES,
167 FLASH_USAGE_ENUM_COUNT);
171 PluginServiceImpl::~PluginServiceImpl() {
172 // Make sure no plugin channel requests have been leaked.
173 DCHECK(pending_plugin_clients_.empty());
176 void PluginServiceImpl::Init() {
177 plugin_list_token_ = BrowserThread::GetBlockingPool()->GetSequenceToken();
178 PluginList::Singleton()->set_will_load_plugins_callback(
179 base::Bind(&WillLoadPluginsCallback, plugin_list_token_));
181 RegisterPepperPlugins();
183 // Load any specified on the command line as well.
184 const base::CommandLine* command_line =
185 base::CommandLine::ForCurrentProcess();
186 base::FilePath path =
187 command_line->GetSwitchValuePath(switches::kLoadPlugin);
188 if (!path.empty())
189 AddExtraPluginPath(path);
190 path = command_line->GetSwitchValuePath(switches::kExtraPluginDir);
191 if (!path.empty())
192 PluginList::Singleton()->AddExtraPluginDir(path);
194 if (command_line->HasSwitch(switches::kDisablePluginsDiscovery))
195 PluginList::Singleton()->DisablePluginsDiscovery();
198 void PluginServiceImpl::StartWatchingPlugins() {
199 // Start watching for changes in the plugin list. This means watching
200 // for changes in the Windows registry keys and on both Windows and POSIX
201 // watch for changes in the paths that are expected to contain plugins.
202 #if defined(OS_WIN)
203 if (hkcu_key_.Create(HKEY_CURRENT_USER,
204 kRegistryMozillaPlugins,
205 KEY_NOTIFY) == ERROR_SUCCESS) {
206 base::win::RegKey::ChangeCallback callback =
207 base::Bind(&PluginServiceImpl::OnKeyChanged, base::Unretained(this),
208 base::Unretained(&hkcu_key_));
209 hkcu_key_.StartWatching(callback);
211 if (hklm_key_.Create(HKEY_LOCAL_MACHINE,
212 kRegistryMozillaPlugins,
213 KEY_NOTIFY) == ERROR_SUCCESS) {
214 base::win::RegKey::ChangeCallback callback =
215 base::Bind(&PluginServiceImpl::OnKeyChanged, base::Unretained(this),
216 base::Unretained(&hklm_key_));
217 hklm_key_.StartWatching(callback);
219 #endif
220 #if defined(OS_POSIX) && !defined(OS_OPENBSD) && !defined(OS_ANDROID)
221 // On ChromeOS the user can't install plugins anyway and on Windows all
222 // important plugins register themselves in the registry so no need to do that.
224 // Get the list of all paths for registering the FilePathWatchers
225 // that will track and if needed reload the list of plugins on runtime.
226 std::vector<base::FilePath> plugin_dirs;
227 PluginList::Singleton()->GetPluginDirectories(&plugin_dirs);
229 for (size_t i = 0; i < plugin_dirs.size(); ++i) {
230 // FilePathWatcher can not handle non-absolute paths under windows.
231 // We don't watch for file changes in windows now but if this should ever
232 // be extended to Windows these lines might save some time of debugging.
233 #if defined(OS_WIN)
234 if (!plugin_dirs[i].IsAbsolute())
235 continue;
236 #endif
237 FilePathWatcher* watcher = new FilePathWatcher();
238 VLOG(1) << "Watching for changes in: " << plugin_dirs[i].value();
239 BrowserThread::PostTask(
240 BrowserThread::FILE, FROM_HERE,
241 base::Bind(&PluginServiceImpl::RegisterFilePathWatcher, watcher,
242 plugin_dirs[i]));
243 file_watchers_.push_back(watcher);
245 #endif
248 PluginProcessHost* PluginServiceImpl::FindNpapiPluginProcess(
249 const base::FilePath& plugin_path) {
250 for (PluginProcessHostIterator iter; !iter.Done(); ++iter) {
251 if (iter->info().path == plugin_path)
252 return *iter;
255 return NULL;
258 PpapiPluginProcessHost* PluginServiceImpl::FindPpapiPluginProcess(
259 const base::FilePath& plugin_path,
260 const base::FilePath& profile_data_directory) {
261 for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
262 if (iter->plugin_path() == plugin_path &&
263 iter->profile_data_directory() == profile_data_directory) {
264 return *iter;
267 return NULL;
270 PpapiPluginProcessHost* PluginServiceImpl::FindPpapiBrokerProcess(
271 const base::FilePath& broker_path) {
272 for (PpapiBrokerProcessHostIterator iter; !iter.Done(); ++iter) {
273 if (iter->plugin_path() == broker_path)
274 return *iter;
277 return NULL;
280 PluginProcessHost* PluginServiceImpl::FindOrStartNpapiPluginProcess(
281 int render_process_id,
282 const base::FilePath& plugin_path) {
283 DCHECK_CURRENTLY_ON(BrowserThread::IO);
285 if (filter_ && !filter_->CanLoadPlugin(render_process_id, plugin_path))
286 return NULL;
288 PluginProcessHost* plugin_host = FindNpapiPluginProcess(plugin_path);
289 if (plugin_host)
290 return plugin_host;
292 WebPluginInfo info;
293 if (!GetPluginInfoByPath(plugin_path, &info)) {
294 return NULL;
297 // Record when NPAPI Flash process is started for the first time.
298 static bool counted = false;
299 if (!counted && base::UTF16ToUTF8(info.name) == kFlashPluginName) {
300 counted = true;
301 UMA_HISTOGRAM_ENUMERATION("Plugin.FlashUsage",
302 START_NPAPI_FLASH_AT_LEAST_ONCE,
303 FLASH_USAGE_ENUM_COUNT);
305 #if defined(OS_CHROMEOS)
306 // TODO(ihf): Move to an earlier place once crbug.com/314301 is fixed. For now
307 // we still want Plugin.FlashUsage recorded if we end up here.
308 LOG(WARNING) << "Refusing to start npapi plugin on ChromeOS.";
309 return NULL;
310 #endif
311 // This plugin isn't loaded by any plugin process, so create a new process.
312 scoped_ptr<PluginProcessHost> new_host(new PluginProcessHost());
313 if (!new_host->Init(info)) {
314 NOTREACHED(); // Init is not expected to fail.
315 return NULL;
317 return new_host.release();
320 PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiPluginProcess(
321 int render_process_id,
322 const base::FilePath& plugin_path,
323 const base::FilePath& profile_data_directory) {
324 DCHECK_CURRENTLY_ON(BrowserThread::IO);
326 if (filter_ && !filter_->CanLoadPlugin(render_process_id, plugin_path)) {
327 VLOG(1) << "Unable to load ppapi plugin: " << plugin_path.MaybeAsASCII();
328 return NULL;
331 PpapiPluginProcessHost* plugin_host =
332 FindPpapiPluginProcess(plugin_path, profile_data_directory);
333 if (plugin_host)
334 return plugin_host;
336 // Validate that the plugin is actually registered.
337 PepperPluginInfo* info = GetRegisteredPpapiPluginInfo(plugin_path);
338 if (!info) {
339 VLOG(1) << "Unable to find ppapi plugin registration for: "
340 << plugin_path.MaybeAsASCII();
341 return NULL;
344 // Record when PPAPI Flash process is started for the first time.
345 static bool counted = false;
346 if (!counted && info->name == kFlashPluginName) {
347 counted = true;
348 UMA_HISTOGRAM_ENUMERATION("Plugin.FlashUsage",
349 START_PPAPI_FLASH_AT_LEAST_ONCE,
350 FLASH_USAGE_ENUM_COUNT);
353 // This plugin isn't loaded by any plugin process, so create a new process.
354 plugin_host = PpapiPluginProcessHost::CreatePluginHost(
355 *info, profile_data_directory);
356 if (!plugin_host) {
357 VLOG(1) << "Unable to create ppapi plugin process for: "
358 << plugin_path.MaybeAsASCII();
361 return plugin_host;
364 PpapiPluginProcessHost* PluginServiceImpl::FindOrStartPpapiBrokerProcess(
365 int render_process_id,
366 const base::FilePath& plugin_path) {
367 DCHECK_CURRENTLY_ON(BrowserThread::IO);
369 if (filter_ && !filter_->CanLoadPlugin(render_process_id, plugin_path))
370 return NULL;
372 PpapiPluginProcessHost* plugin_host = FindPpapiBrokerProcess(plugin_path);
373 if (plugin_host)
374 return plugin_host;
376 // Validate that the plugin is actually registered.
377 PepperPluginInfo* info = GetRegisteredPpapiPluginInfo(plugin_path);
378 if (!info)
379 return NULL;
381 // TODO(ddorwin): Uncomment once out of process is supported.
382 // DCHECK(info->is_out_of_process);
384 // This broker isn't loaded by any broker process, so create a new process.
385 return PpapiPluginProcessHost::CreateBrokerHost(*info);
388 void PluginServiceImpl::OpenChannelToNpapiPlugin(
389 int render_process_id,
390 int render_frame_id,
391 const GURL& url,
392 const GURL& page_url,
393 const std::string& mime_type,
394 PluginProcessHost::Client* client) {
395 DCHECK_CURRENTLY_ON(BrowserThread::IO);
396 DCHECK(!ContainsKey(pending_plugin_clients_, client));
397 pending_plugin_clients_.insert(client);
399 // Make sure plugins are loaded if necessary.
400 PluginServiceFilterParams params = {
401 render_process_id,
402 render_frame_id,
403 page_url,
404 client->GetResourceContext()
406 GetPlugins(base::Bind(
407 &PluginServiceImpl::ForwardGetAllowedPluginForOpenChannelToPlugin,
408 base::Unretained(this), params, url, mime_type, client));
411 void PluginServiceImpl::OpenChannelToPpapiPlugin(
412 int render_process_id,
413 const base::FilePath& plugin_path,
414 const base::FilePath& profile_data_directory,
415 PpapiPluginProcessHost::PluginClient* client) {
416 PpapiPluginProcessHost* plugin_host = FindOrStartPpapiPluginProcess(
417 render_process_id, plugin_path, profile_data_directory);
418 if (plugin_host) {
419 plugin_host->OpenChannelToPlugin(client);
420 } else {
421 // Send error.
422 client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0);
426 void PluginServiceImpl::OpenChannelToPpapiBroker(
427 int render_process_id,
428 const base::FilePath& path,
429 PpapiPluginProcessHost::BrokerClient* client) {
430 PpapiPluginProcessHost* plugin_host = FindOrStartPpapiBrokerProcess(
431 render_process_id, path);
432 if (plugin_host) {
433 plugin_host->OpenChannelToPlugin(client);
434 } else {
435 // Send error.
436 client->OnPpapiChannelOpened(IPC::ChannelHandle(), base::kNullProcessId, 0);
440 void PluginServiceImpl::CancelOpenChannelToNpapiPlugin(
441 PluginProcessHost::Client* client) {
442 DCHECK_CURRENTLY_ON(BrowserThread::IO);
443 DCHECK(ContainsKey(pending_plugin_clients_, client));
444 pending_plugin_clients_.erase(client);
447 void PluginServiceImpl::ForwardGetAllowedPluginForOpenChannelToPlugin(
448 const PluginServiceFilterParams& params,
449 const GURL& url,
450 const std::string& mime_type,
451 PluginProcessHost::Client* client,
452 const std::vector<WebPluginInfo>&) {
453 GetAllowedPluginForOpenChannelToPlugin(
454 params.render_process_id, params.render_frame_id, url, params.page_url,
455 mime_type, client, params.resource_context);
458 void PluginServiceImpl::GetAllowedPluginForOpenChannelToPlugin(
459 int render_process_id,
460 int render_frame_id,
461 const GURL& url,
462 const GURL& page_url,
463 const std::string& mime_type,
464 PluginProcessHost::Client* client,
465 ResourceContext* resource_context) {
466 WebPluginInfo info;
467 bool allow_wildcard = true;
468 bool found = GetPluginInfo(
469 render_process_id, render_frame_id, resource_context,
470 url, page_url, mime_type, allow_wildcard,
471 NULL, &info, NULL);
472 base::FilePath plugin_path;
473 if (found)
474 plugin_path = info.path;
476 // Now we jump back to the IO thread to finish opening the channel.
477 BrowserThread::PostTask(
478 BrowserThread::IO, FROM_HERE,
479 base::Bind(&PluginServiceImpl::FinishOpenChannelToPlugin,
480 base::Unretained(this),
481 render_process_id,
482 plugin_path,
483 client));
484 if (filter_) {
485 DCHECK_EQ(WebPluginInfo::PLUGIN_TYPE_NPAPI, info.type);
486 filter_->NPAPIPluginLoaded(render_process_id, render_frame_id, mime_type,
487 info);
491 void PluginServiceImpl::FinishOpenChannelToPlugin(
492 int render_process_id,
493 const base::FilePath& plugin_path,
494 PluginProcessHost::Client* client) {
495 DCHECK_CURRENTLY_ON(BrowserThread::IO);
497 // Make sure it hasn't been canceled yet.
498 if (!ContainsKey(pending_plugin_clients_, client))
499 return;
500 pending_plugin_clients_.erase(client);
502 PluginProcessHost* plugin_host = FindOrStartNpapiPluginProcess(
503 render_process_id, plugin_path);
504 if (plugin_host) {
505 client->OnFoundPluginProcessHost(plugin_host);
506 plugin_host->OpenChannelToPlugin(client);
507 } else {
508 client->OnError();
512 bool PluginServiceImpl::GetPluginInfoArray(
513 const GURL& url,
514 const std::string& mime_type,
515 bool allow_wildcard,
516 std::vector<WebPluginInfo>* plugins,
517 std::vector<std::string>* actual_mime_types) {
518 bool use_stale = false;
519 PluginList::Singleton()->GetPluginInfoArray(
520 url, mime_type, allow_wildcard, &use_stale, NPAPIPluginsSupported(),
521 plugins, actual_mime_types);
522 return use_stale;
525 bool PluginServiceImpl::GetPluginInfo(int render_process_id,
526 int render_frame_id,
527 ResourceContext* context,
528 const GURL& url,
529 const GURL& page_url,
530 const std::string& mime_type,
531 bool allow_wildcard,
532 bool* is_stale,
533 WebPluginInfo* info,
534 std::string* actual_mime_type) {
535 std::vector<WebPluginInfo> plugins;
536 std::vector<std::string> mime_types;
537 bool stale = GetPluginInfoArray(
538 url, mime_type, allow_wildcard, &plugins, &mime_types);
539 if (is_stale)
540 *is_stale = stale;
542 for (size_t i = 0; i < plugins.size(); ++i) {
543 if (!filter_ || filter_->IsPluginAvailable(render_process_id,
544 render_frame_id,
545 context,
546 url,
547 page_url,
548 &plugins[i])) {
549 *info = plugins[i];
550 if (actual_mime_type)
551 *actual_mime_type = mime_types[i];
552 return true;
555 return false;
558 bool PluginServiceImpl::GetPluginInfoByPath(const base::FilePath& plugin_path,
559 WebPluginInfo* info) {
560 std::vector<WebPluginInfo> plugins;
561 PluginList::Singleton()->GetPluginsNoRefresh(&plugins);
563 for (std::vector<WebPluginInfo>::iterator it = plugins.begin();
564 it != plugins.end();
565 ++it) {
566 if (it->path == plugin_path) {
567 *info = *it;
568 return true;
572 return false;
575 base::string16 PluginServiceImpl::GetPluginDisplayNameByPath(
576 const base::FilePath& path) {
577 base::string16 plugin_name = path.LossyDisplayName();
578 WebPluginInfo info;
579 if (PluginService::GetInstance()->GetPluginInfoByPath(path, &info) &&
580 !info.name.empty()) {
581 plugin_name = info.name;
582 #if defined(OS_MACOSX)
583 // Many plugins on the Mac have .plugin in the actual name, which looks
584 // terrible, so look for that and strip it off if present.
585 const std::string kPluginExtension = ".plugin";
586 if (base::EndsWith(plugin_name, base::ASCIIToUTF16(kPluginExtension),
587 base::CompareCase::SENSITIVE))
588 plugin_name.erase(plugin_name.length() - kPluginExtension.length());
589 #endif // OS_MACOSX
591 return plugin_name;
594 void PluginServiceImpl::GetPlugins(const GetPluginsCallback& callback) {
595 scoped_refptr<base::SingleThreadTaskRunner> target_task_runner(
596 base::ThreadTaskRunnerHandle::Get());
598 if (LoadPluginListInProcess()) {
599 BrowserThread::GetBlockingPool()
600 ->PostSequencedWorkerTaskWithShutdownBehavior(
601 plugin_list_token_, FROM_HERE,
602 base::Bind(&PluginServiceImpl::GetPluginsInternal,
603 base::Unretained(this), target_task_runner, callback),
604 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
605 return;
607 #if defined(OS_POSIX)
608 BrowserThread::PostTask(
609 BrowserThread::IO, FROM_HERE,
610 base::Bind(&PluginServiceImpl::GetPluginsOnIOThread,
611 base::Unretained(this), target_task_runner, callback));
612 #else
613 NOTREACHED();
614 #endif
617 void PluginServiceImpl::GetPluginsInternal(
618 base::SingleThreadTaskRunner* target_task_runner,
619 const PluginService::GetPluginsCallback& callback) {
620 DCHECK(BrowserThread::GetBlockingPool()->IsRunningSequenceOnCurrentThread(
621 plugin_list_token_));
623 std::vector<WebPluginInfo> plugins;
624 PluginList::Singleton()->GetPlugins(&plugins, NPAPIPluginsSupported());
626 target_task_runner->PostTask(FROM_HERE, base::Bind(callback, plugins));
629 #if defined(OS_POSIX)
630 void PluginServiceImpl::GetPluginsOnIOThread(
631 base::SingleThreadTaskRunner* target_task_runner,
632 const GetPluginsCallback& callback) {
633 DCHECK_CURRENTLY_ON(BrowserThread::IO);
635 // If we switch back to loading plugins in process, then we need to make
636 // sure g_thread_init() gets called since plugins may call glib at load.
638 if (!plugin_loader_.get())
639 plugin_loader_ = new PluginLoaderPosix;
641 plugin_loader_->GetPlugins(base::Bind(
642 &ForwardCallback, make_scoped_refptr(target_task_runner), callback));
644 #endif
646 #if defined(OS_WIN)
647 void PluginServiceImpl::OnKeyChanged(base::win::RegKey* key) {
648 key->StartWatching(base::Bind(&PluginServiceImpl::OnKeyChanged,
649 base::Unretained(this),
650 base::Unretained(key)));
652 PluginList::Singleton()->RefreshPlugins();
653 PurgePluginListCache(NULL, false);
655 #endif // defined(OS_WIN)
657 void PluginServiceImpl::RegisterPepperPlugins() {
658 ComputePepperPluginList(&ppapi_plugins_);
659 for (size_t i = 0; i < ppapi_plugins_.size(); ++i) {
660 RegisterInternalPlugin(ppapi_plugins_[i].ToWebPluginInfo(), true);
664 // There should generally be very few plugins so a brute-force search is fine.
665 PepperPluginInfo* PluginServiceImpl::GetRegisteredPpapiPluginInfo(
666 const base::FilePath& plugin_path) {
667 PepperPluginInfo* info = NULL;
668 for (size_t i = 0; i < ppapi_plugins_.size(); ++i) {
669 if (ppapi_plugins_[i].path == plugin_path) {
670 info = &ppapi_plugins_[i];
671 break;
674 if (info)
675 return info;
676 // We did not find the plugin in our list. But wait! the plugin can also
677 // be a latecomer, as it happens with pepper flash. This information
678 // can be obtained from the PluginList singleton and we can use it to
679 // construct it and add it to the list. This same deal needs to be done
680 // in the renderer side in PepperPluginRegistry.
681 WebPluginInfo webplugin_info;
682 if (!GetPluginInfoByPath(plugin_path, &webplugin_info))
683 return NULL;
684 PepperPluginInfo new_pepper_info;
685 if (!MakePepperPluginInfo(webplugin_info, &new_pepper_info))
686 return NULL;
687 ppapi_plugins_.push_back(new_pepper_info);
688 return &ppapi_plugins_[ppapi_plugins_.size() - 1];
691 #if defined(OS_POSIX) && !defined(OS_OPENBSD) && !defined(OS_ANDROID)
692 // static
693 void PluginServiceImpl::RegisterFilePathWatcher(FilePathWatcher* watcher,
694 const base::FilePath& path) {
695 bool result = watcher->Watch(path, false,
696 base::Bind(&NotifyPluginDirChanged));
697 DCHECK(result);
699 #endif
701 void PluginServiceImpl::SetFilter(PluginServiceFilter* filter) {
702 filter_ = filter;
705 PluginServiceFilter* PluginServiceImpl::GetFilter() {
706 return filter_;
709 void PluginServiceImpl::ForcePluginShutdown(const base::FilePath& plugin_path) {
710 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
711 BrowserThread::PostTask(
712 BrowserThread::IO, FROM_HERE,
713 base::Bind(&PluginServiceImpl::ForcePluginShutdown,
714 base::Unretained(this), plugin_path));
715 return;
718 PluginProcessHost* plugin = FindNpapiPluginProcess(plugin_path);
719 if (plugin)
720 plugin->ForceShutdown();
723 static const unsigned int kMaxCrashesPerInterval = 3;
724 static const unsigned int kCrashesInterval = 120;
726 void PluginServiceImpl::RegisterPluginCrash(const base::FilePath& path) {
727 DCHECK_CURRENTLY_ON(BrowserThread::IO);
728 std::map<base::FilePath, std::vector<base::Time> >::iterator i =
729 crash_times_.find(path);
730 if (i == crash_times_.end()) {
731 crash_times_[path] = std::vector<base::Time>();
732 i = crash_times_.find(path);
734 if (i->second.size() == kMaxCrashesPerInterval) {
735 i->second.erase(i->second.begin());
737 base::Time time = base::Time::Now();
738 i->second.push_back(time);
741 bool PluginServiceImpl::IsPluginUnstable(const base::FilePath& path) {
742 DCHECK_CURRENTLY_ON(BrowserThread::IO);
743 std::map<base::FilePath, std::vector<base::Time> >::const_iterator i =
744 crash_times_.find(path);
745 if (i == crash_times_.end()) {
746 return false;
748 if (i->second.size() != kMaxCrashesPerInterval) {
749 return false;
751 base::TimeDelta delta = base::Time::Now() - i->second[0];
752 return delta.InSeconds() <= kCrashesInterval;
755 void PluginServiceImpl::RefreshPlugins() {
756 PluginList::Singleton()->RefreshPlugins();
759 void PluginServiceImpl::AddExtraPluginPath(const base::FilePath& path) {
760 if (!NPAPIPluginsSupported()) {
761 // TODO(jam): remove and just have CHECK once we're sure this doesn't get
762 // triggered.
763 DVLOG(0) << "NPAPI plugins not supported";
764 return;
766 PluginList::Singleton()->AddExtraPluginPath(path);
769 void PluginServiceImpl::RemoveExtraPluginPath(const base::FilePath& path) {
770 PluginList::Singleton()->RemoveExtraPluginPath(path);
773 void PluginServiceImpl::AddExtraPluginDir(const base::FilePath& path) {
774 PluginList::Singleton()->AddExtraPluginDir(path);
777 void PluginServiceImpl::RegisterInternalPlugin(
778 const WebPluginInfo& info,
779 bool add_at_beginning) {
780 // Internal plugins should never be NPAPI.
781 CHECK_NE(info.type, WebPluginInfo::PLUGIN_TYPE_NPAPI);
782 if (info.type == WebPluginInfo::PLUGIN_TYPE_NPAPI) {
783 DVLOG(0) << "Don't register NPAPI plugins when they're not supported";
784 return;
786 PluginList::Singleton()->RegisterInternalPlugin(info, add_at_beginning);
789 void PluginServiceImpl::UnregisterInternalPlugin(const base::FilePath& path) {
790 PluginList::Singleton()->UnregisterInternalPlugin(path);
793 void PluginServiceImpl::GetInternalPlugins(
794 std::vector<WebPluginInfo>* plugins) {
795 PluginList::Singleton()->GetInternalPlugins(plugins);
798 bool PluginServiceImpl::NPAPIPluginsSupported() {
799 #if defined(OS_WIN) || defined(OS_MACOSX)
800 npapi_plugins_enabled_ = GetContentClient()->browser()->IsNPAPIEnabled();
801 #if defined(OS_WIN)
802 // NPAPI plugins don't play well with Win32k renderer lockdown.
803 if (npapi_plugins_enabled_)
804 DisableWin32kRendererLockdown();
805 #endif
806 NPAPIPluginStatus status =
807 npapi_plugins_enabled_ ? NPAPI_STATUS_ENABLED : NPAPI_STATUS_DISABLED;
808 #else
809 NPAPIPluginStatus status = NPAPI_STATUS_UNSUPPORTED;
810 #endif
811 UMA_HISTOGRAM_ENUMERATION("Plugin.NPAPIStatus", status,
812 NPAPI_STATUS_ENUM_COUNT);
814 return npapi_plugins_enabled_;
817 void PluginServiceImpl::DisablePluginsDiscoveryForTesting() {
818 PluginList::Singleton()->DisablePluginsDiscovery();
821 #if defined(OS_MACOSX)
822 void PluginServiceImpl::AppActivated() {
823 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
824 base::Bind(&NotifyPluginsOfActivation));
826 #elif defined(OS_WIN)
828 bool GetPluginPropertyFromWindow(
829 HWND window, const wchar_t* plugin_atom_property,
830 base::string16* plugin_property) {
831 ATOM plugin_atom = static_cast<ATOM>(
832 reinterpret_cast<uintptr_t>(GetPropW(window, plugin_atom_property)));
833 if (plugin_atom != 0) {
834 WCHAR plugin_property_local[MAX_PATH] = {0};
835 GlobalGetAtomNameW(plugin_atom,
836 plugin_property_local,
837 ARRAYSIZE(plugin_property_local));
838 *plugin_property = plugin_property_local;
839 return true;
841 return false;
844 bool PluginServiceImpl::GetPluginInfoFromWindow(
845 HWND window,
846 base::string16* plugin_name,
847 base::string16* plugin_version) {
848 if (!IsPluginWindow(window))
849 return false;
852 DWORD process_id = 0;
853 GetWindowThreadProcessId(window, &process_id);
854 WebPluginInfo info;
855 if (!PluginProcessHost::GetWebPluginInfoFromPluginPid(process_id, &info))
856 return false;
858 *plugin_name = info.name;
859 *plugin_version = info.version;
860 return true;
863 bool PluginServiceImpl::IsPluginWindow(HWND window) {
864 return gfx::GetClassName(window) == base::string16(kNativeWindowClassName);
866 #endif
868 bool PluginServiceImpl::PpapiDevChannelSupported(
869 BrowserContext* browser_context,
870 const GURL& document_url) {
871 return GetContentClient()->browser()->IsPluginAllowedToUseDevChannelAPIs(
872 browser_context, document_url);
875 } // namespace content