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