plugin_list_win.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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/common/plugin_list.h"
6
7#include <set>
8
9#include "base/basictypes.h"
10#include "base/file_version_info.h"
11#include "base/file_version_info_win.h"
12#include "base/files/file_util.h"
13#include "base/files/memory_mapped_file.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/path_service.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/string_split.h"
18#include "base/strings/string_util.h"
19#include "base/strings/utf_string_conversions.h"
20#include "base/win/pe_image.h"
21#include "base/win/registry.h"
22#include "base/win/scoped_handle.h"
23#include "base/win/windows_version.h"
24#include "content/common/plugin_constants_win.h"
25
26namespace content {
27namespace {
28
29const base::char16 kRegistryApps[] =
30    L"Software\\Microsoft\\Windows\\CurrentVersion\\App Paths";
31const base::char16 kRegistryFirefox[] = L"firefox.exe";
32const base::char16 kRegistryAcrobat[] = L"Acrobat.exe";
33const base::char16 kRegistryAcrobatReader[] = L"AcroRd32.exe";
34const base::char16 kRegistryWindowsMedia[] = L"wmplayer.exe";
35const base::char16 kRegistryQuickTime[] = L"QuickTimePlayer.exe";
36const base::char16 kRegistryPath[] = L"Path";
37const base::char16 kRegistryFirefoxInstalled[] =
38    L"SOFTWARE\\Mozilla\\Mozilla Firefox";
39const base::char16 kRegistryJava[] =
40    L"Software\\JavaSoft\\Java Runtime Environment";
41const base::char16 kRegistryBrowserJavaVersion[] = L"BrowserJavaVersion";
42const base::char16 kRegistryCurrentJavaVersion[] = L"CurrentVersion";
43const base::char16 kRegistryJavaHome[] = L"JavaHome";
44const base::char16 kJavaDeploy1[] = L"npdeploytk.dll";
45const base::char16 kJavaDeploy2[] = L"npdeployjava1.dll";
46
47base::FilePath AppendPluginsDir(const base::FilePath& path) {
48  return path.AppendASCII("plugins");
49}
50
51// Gets the directory where the application data and libraries exist.  This
52// may be a versioned subdirectory, or it may be the same directory as the
53// GetExeDirectory(), depending on the embedder's implementation.
54// Path is an output parameter to receive the path.
55void GetAppDirectory(std::set<base::FilePath>* plugin_dirs) {
56  base::FilePath app_path;
57  if (!PathService::Get(base::DIR_MODULE, &app_path))
58    return;
59  plugin_dirs->insert(AppendPluginsDir(app_path));
60}
61
62// Gets the directory where the launching executable resides on disk.
63// Path is an output parameter to receive the path.
64void GetExeDirectory(std::set<base::FilePath>* plugin_dirs) {
65  base::FilePath exe_path;
66  if (!PathService::Get(base::DIR_EXE, &exe_path))
67    return;
68  plugin_dirs->insert(AppendPluginsDir(exe_path));
69}
70
71// Gets the installed path for a registered app.
72bool GetInstalledPath(const base::char16* app, base::FilePath* out) {
73  base::string16 reg_path(kRegistryApps);
74  reg_path.append(L"\\");
75  reg_path.append(app);
76
77  base::win::RegKey hkcu_key(HKEY_CURRENT_USER, reg_path.c_str(), KEY_READ);
78  base::string16 path;
79  // As of Win7 AppPaths can also be registered in HKCU: http://goo.gl/UgFOf.
80  if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
81      hkcu_key.ReadValue(kRegistryPath, &path) == ERROR_SUCCESS) {
82    *out = base::FilePath(path);
83    return true;
84  } else {
85    base::win::RegKey hklm_key(HKEY_LOCAL_MACHINE, reg_path.c_str(), KEY_READ);
86    if (hklm_key.ReadValue(kRegistryPath, &path) == ERROR_SUCCESS) {
87      *out = base::FilePath(path);
88      return true;
89    }
90  }
91
92  return false;
93}
94
95// Search the registry at the given path and detect plugin directories.
96void GetPluginsInRegistryDirectory(
97    HKEY root_key,
98    const base::string16& registry_folder,
99    std::set<base::FilePath>* plugin_dirs) {
100  for (base::win::RegistryKeyIterator iter(root_key, registry_folder.c_str());
101       iter.Valid(); ++iter) {
102    // Use the registry to gather plugin across the file system.
103    base::string16 reg_path = registry_folder;
104    reg_path.append(L"\\");
105    reg_path.append(iter.Name());
106    base::win::RegKey key(root_key, reg_path.c_str(), KEY_READ);
107
108    base::string16 path;
109    if (key.ReadValue(kRegistryPath, &path) == ERROR_SUCCESS)
110      plugin_dirs->insert(base::FilePath(path));
111  }
112}
113
114// Enumerate through the registry key to find all installed FireFox paths.
115// FireFox 3 beta and version 2 can coexist. See bug: 1025003
116void GetFirefoxInstalledPaths(std::vector<base::FilePath>* out) {
117  base::win::RegistryKeyIterator it(HKEY_LOCAL_MACHINE,
118                                    kRegistryFirefoxInstalled);
119  for (; it.Valid(); ++it) {
120    base::string16 full_path = base::string16(kRegistryFirefoxInstalled) +
121        L"\\" + it.Name() + L"\\Main";
122    base::win::RegKey key(HKEY_LOCAL_MACHINE, full_path.c_str(), KEY_READ);
123    base::string16 install_dir;
124    if (key.ReadValue(L"Install Directory", &install_dir) != ERROR_SUCCESS)
125      continue;
126    out->push_back(base::FilePath(install_dir));
127  }
128}
129
130// Get plugin directory locations from the Firefox install path.  This is kind
131// of a kludge, but it helps us locate the flash player for users that
132// already have it for firefox.  Not having to download yet-another-plugin
133// is a good thing.
134void GetFirefoxDirectory(std::set<base::FilePath>* plugin_dirs) {
135  std::vector<base::FilePath> paths;
136  GetFirefoxInstalledPaths(&paths);
137  for (unsigned int i = 0; i < paths.size(); ++i) {
138    plugin_dirs->insert(AppendPluginsDir(paths[i]));
139  }
140
141  base::FilePath firefox_app_data_plugin_path;
142  if (PathService::Get(base::DIR_APP_DATA, &firefox_app_data_plugin_path)) {
143    firefox_app_data_plugin_path =
144        firefox_app_data_plugin_path.AppendASCII("Mozilla");
145    plugin_dirs->insert(AppendPluginsDir(firefox_app_data_plugin_path));
146  }
147}
148
149// Hardcoded logic to detect Acrobat plugins locations.
150void GetAcrobatDirectory(std::set<base::FilePath>* plugin_dirs) {
151  base::FilePath path;
152  if (!GetInstalledPath(kRegistryAcrobatReader, &path) &&
153      !GetInstalledPath(kRegistryAcrobat, &path)) {
154    return;
155  }
156
157  plugin_dirs->insert(path.Append(L"Browser"));
158}
159
160// Hardcoded logic to detect QuickTime plugin location.
161void GetQuicktimeDirectory(std::set<base::FilePath>* plugin_dirs) {
162  base::FilePath path;
163  if (GetInstalledPath(kRegistryQuickTime, &path))
164    plugin_dirs->insert(AppendPluginsDir(path));
165}
166
167// Hardcoded logic to detect Windows Media Player plugin location.
168void GetWindowsMediaDirectory(std::set<base::FilePath>* plugin_dirs) {
169  base::FilePath path;
170  if (GetInstalledPath(kRegistryWindowsMedia, &path))
171    plugin_dirs->insert(path);
172}
173
174// Hardcoded logic to detect Java plugin location.
175void GetJavaDirectory(std::set<base::FilePath>* plugin_dirs) {
176  // Load the new NPAPI Java plugin
177  // 1. Open the main JRE key under HKLM
178  base::win::RegKey java_key(HKEY_LOCAL_MACHINE, kRegistryJava,
179                             KEY_QUERY_VALUE);
180
181  // 2. Read the current Java version
182  base::string16 java_version;
183  if (java_key.ReadValue(kRegistryBrowserJavaVersion, &java_version) !=
184      ERROR_SUCCESS) {
185    java_key.ReadValue(kRegistryCurrentJavaVersion, &java_version);
186  }
187
188  if (!java_version.empty()) {
189    java_key.OpenKey(java_version.c_str(), KEY_QUERY_VALUE);
190
191    // 3. Install path of the JRE binaries is specified in "JavaHome"
192    //    value under the Java version key.
193    base::string16 java_plugin_directory;
194    if (java_key.ReadValue(kRegistryJavaHome, &java_plugin_directory) ==
195        ERROR_SUCCESS) {
196      // 4. The new plugin resides under the 'bin/new_plugin'
197      //    subdirectory.
198      DCHECK(!java_plugin_directory.empty());
199      java_plugin_directory.append(L"\\bin\\new_plugin");
200
201      // 5. We don't know the exact name of the DLL but it's in the form
202      //    NP*.dll so just invoke LoadPlugins on this path.
203      plugin_dirs->insert(base::FilePath(java_plugin_directory));
204    }
205  }
206}
207
208bool IsValid32BitImage(const base::FilePath& path) {
209  base::MemoryMappedFile plugin_image;
210
211  if (!plugin_image.InitializeAsImageSection(path))
212    return false;
213
214  base::win::PEImage image(plugin_image.data());
215
216  PIMAGE_NT_HEADERS nt_headers = image.GetNTHeaders();
217  return (nt_headers->FileHeader.Machine == IMAGE_FILE_MACHINE_I386);
218}
219
220// Returns true if the given plugins share at least one mime type.  This is used
221// to differentiate newer versions of a plugin vs two plugins which happen to
222// have the same filename.
223bool HaveSharedMimeType(const WebPluginInfo& plugin1,
224                        const WebPluginInfo& plugin2) {
225  for (size_t i = 0; i < plugin1.mime_types.size(); ++i) {
226    for (size_t j = 0; j < plugin2.mime_types.size(); ++j) {
227      if (plugin1.mime_types[i].mime_type == plugin2.mime_types[j].mime_type)
228        return true;
229    }
230  }
231
232  return false;
233}
234
235// Compares Windows style version strings (i.e. 1,2,3,4).  Returns true if b's
236// version is newer than a's, or false if it's equal or older.
237bool IsNewerVersion(const base::string16& a, const base::string16& b) {
238  std::vector<base::string16> a_ver, b_ver;
239  base::SplitString(a, ',', &a_ver);
240  base::SplitString(b, ',', &b_ver);
241  if (a_ver.size() == 1 && b_ver.size() == 1) {
242    base::SplitString(a, '.', &a_ver);
243    base::SplitString(b, '.', &b_ver);
244  }
245  if (a_ver.size() != b_ver.size())
246    return false;
247  for (size_t i = 0; i < a_ver.size(); i++) {
248    int cur_a, cur_b;
249    base::StringToInt(a_ver[i], &cur_a);
250    base::StringToInt(b_ver[i], &cur_b);
251
252    if (cur_a > cur_b)
253      return false;
254    if (cur_a < cur_b)
255      return true;
256  }
257  return false;
258}
259
260}  // namespace
261
262bool PluginList::ReadWebPluginInfo(const base::FilePath& filename,
263                                   WebPluginInfo* info) {
264  // On windows, the way we get the mime types for the library is
265  // to check the version information in the DLL itself.  This
266  // will be a string of the format:  <type1>|<type2>|<type3>|...
267  // For example:
268  //     video/quicktime|audio/aiff|image/jpeg
269  scoped_ptr<FileVersionInfo> version_info(
270      FileVersionInfo::CreateFileVersionInfo(filename));
271  if (!version_info) {
272    LOG_IF(ERROR, PluginList::DebugPluginLoading())
273        << "Could not get version info for plugin "
274        << filename.value();
275    return false;
276  }
277
278  FileVersionInfoWin* version_info_win =
279      static_cast<FileVersionInfoWin*>(version_info.get());
280
281  info->name = version_info->product_name();
282  info->desc = version_info->file_description();
283  info->version = version_info->file_version();
284  info->path = filename;
285
286  // TODO(evan): Move the ParseMimeTypes code inline once Pepper is updated.
287  if (!PluginList::ParseMimeTypes(
288          base::UTF16ToASCII(version_info_win->GetStringValue(L"MIMEType")),
289          base::UTF16ToASCII(version_info_win->GetStringValue(L"FileExtents")),
290          version_info_win->GetStringValue(L"FileOpenName"),
291          &info->mime_types)) {
292    LOG_IF(ERROR, PluginList::DebugPluginLoading())
293        << "Plugin " << info->name << " has bad MIME types, skipping";
294    return false;
295  }
296
297  return true;
298}
299
300void PluginList::GetPluginDirectories(
301    std::vector<base::FilePath>* plugin_dirs) {
302  if (PluginList::plugins_discovery_disabled_)
303    return;
304
305  // We use a set for uniqueness, which we require, over order, which we do not.
306  std::set<base::FilePath> dirs;
307
308  // Load from the application-specific area
309  GetAppDirectory(&dirs);
310
311  // Load from the executable area
312  GetExeDirectory(&dirs);
313
314  // Load Java
315  GetJavaDirectory(&dirs);
316
317  // Load firefox plugins too.  This is mainly to try to locate
318  // a pre-installed Flash player.
319  GetFirefoxDirectory(&dirs);
320
321  // Firefox hard-codes the paths of some popular plugins to ensure that
322  // the plugins are found.  We are going to copy this as well.
323  GetAcrobatDirectory(&dirs);
324  GetQuicktimeDirectory(&dirs);
325  GetWindowsMediaDirectory(&dirs);
326
327  for (std::set<base::FilePath>::iterator i = dirs.begin(); i != dirs.end(); ++i)
328    plugin_dirs->push_back(*i);
329}
330
331void PluginList::GetPluginsInDir(
332    const base::FilePath& path, std::vector<base::FilePath>* plugins) {
333  WIN32_FIND_DATA find_file_data;
334  HANDLE find_handle;
335
336  base::string16 dir = path.value();
337  // FindFirstFile requires that you specify a wildcard for directories.
338  dir.append(L"\\NP*.DLL");
339
340  find_handle = FindFirstFile(dir.c_str(), &find_file_data);
341  if (find_handle == INVALID_HANDLE_VALUE)
342    return;
343
344  do {
345    if (!(find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
346      base::FilePath filename = path.Append(find_file_data.cFileName);
347      plugins->push_back(filename);
348    }
349  } while (FindNextFile(find_handle, &find_file_data) != 0);
350
351  DCHECK(GetLastError() == ERROR_NO_MORE_FILES);
352  FindClose(find_handle);
353}
354
355void PluginList::GetPluginPathsFromRegistry(
356    std::vector<base::FilePath>* plugins) {
357  if (PluginList::plugins_discovery_disabled_)
358    return;
359
360  std::set<base::FilePath> plugin_dirs;
361
362  GetPluginsInRegistryDirectory(
363      HKEY_CURRENT_USER, kRegistryMozillaPlugins, &plugin_dirs);
364  GetPluginsInRegistryDirectory(
365      HKEY_LOCAL_MACHINE, kRegistryMozillaPlugins, &plugin_dirs);
366
367  for (std::set<base::FilePath>::iterator i = plugin_dirs.begin();
368       i != plugin_dirs.end(); ++i) {
369    plugins->push_back(*i);
370  }
371}
372
373bool PluginList::ShouldLoadPluginUsingPluginList(
374    const WebPluginInfo& info,
375    std::vector<WebPluginInfo>* plugins) {
376  bool should_check_version = true;
377  {
378    base::AutoLock lock(lock_);
379    should_check_version =
380        std::find(extra_plugin_paths_.begin(), extra_plugin_paths_.end(),
381                  info.path) == extra_plugin_paths_.end();
382  }
383  // Version check for plugins that are not coming from |extra_plugin_paths_|.
384  if (should_check_version) {
385    for (size_t j = 0; j < plugins->size(); ++j) {
386      base::FilePath::StringType plugin1 =
387          base::StringToLowerASCII((*plugins)[j].path.BaseName().value());
388      base::FilePath::StringType plugin2 =
389          base::StringToLowerASCII(info.path.BaseName().value());
390      if ((plugin1 == plugin2 && HaveSharedMimeType((*plugins)[j], info)) ||
391          (plugin1 == kJavaDeploy1 && plugin2 == kJavaDeploy2) ||
392          (plugin1 == kJavaDeploy2 && plugin2 == kJavaDeploy1)) {
393        if (IsNewerVersion(info.version, (*plugins)[j].version))
394          return false;  // We have loaded a plugin whose version is newer.
395        plugins->erase(plugins->begin() + j);
396        break;
397      }
398    }
399  }
400
401  // The checks below only apply to NPAPI plugins.
402  if (info.type != WebPluginInfo::PLUGIN_TYPE_NPAPI)
403    return true;
404
405  {
406    base::AutoLock lock(lock_);
407    // If the plugin is in our internal list we should load it.
408    for (size_t i = 0; i < internal_plugins_.size(); ++i) {
409      if (info.path == internal_plugins_[i].path)
410        return true;
411    }
412  }
413
414  // Troublemakers.
415  base::FilePath::StringType filename =
416      base::StringToLowerASCII(info.path.BaseName().value());
417  // Depends on XPCOM.
418  if (filename == kMozillaActiveXPlugin)
419    return false;
420
421  // Disable the Yahoo Application State plugin as it crashes the plugin
422  // process on return from NPObjectStub::OnInvoke. Please refer to
423  // http://b/issue?id=1372124 for more information.
424  if (filename == kYahooApplicationStatePlugin)
425    return false;
426
427  // Disable the WangWang protocol handler plugin (npww.dll) as it crashes
428  // chrome during shutdown. Firefox also disables this plugin.
429  // Please refer to http://code.google.com/p/chromium/issues/detail?id=3953
430  // for more information.
431  if (filename == kWanWangProtocolHandlerPlugin)
432    return false;
433
434  // We only work with newer versions of the Java plugin which use NPAPI only
435  // and don't depend on XPCOM.
436  if (filename == kJavaPlugin1 || filename == kJavaPlugin2) {
437    std::vector<base::FilePath::StringType> ver;
438    base::SplitString(info.version, '.', &ver);
439    int major, minor, update;
440    if (ver.size() == 4 &&
441        base::StringToInt(ver[0], &major) &&
442        base::StringToInt(ver[1], &minor) &&
443        base::StringToInt(ver[2], &update)) {
444      if (major == 6 && minor == 0 && update < 120)
445        return false;  // Java SE6 Update 11 or older.
446    }
447  }
448
449  // Special WMP handling:
450  // If both the new and old WMP plugins exist, only load the new one.
451  if (filename == kNewWMPPlugin) {
452    for (size_t j = 0; j < plugins->size(); ++j) {
453      if ((*plugins)[j].path.BaseName().value() == kOldWMPPlugin) {
454        plugins->erase(plugins->begin() + j);
455        break;
456      }
457    }
458
459  } else if (filename == kOldWMPPlugin) {
460    for (size_t j = 0; j < plugins->size(); ++j) {
461      if ((*plugins)[j].path.BaseName().value() == kNewWMPPlugin)
462        return false;
463    }
464  }
465
466  base::FilePath plugin_path(info.path);
467#if defined(ARCH_CPU_X86_64)
468  // The plugin in question could be a 32 bit plugin which we cannot load.
469  if (IsValid32BitImage(base::MakeAbsoluteFilePath(plugin_path)))
470    return false;
471#else
472  // The plugin in question could be a 64 bit plugin which we cannot load.
473  if (!IsValid32BitImage(base::MakeAbsoluteFilePath(plugin_path)))
474    return false;
475#endif
476  return true;
477}
478
479}  // namespace content
480