[patch 6 of 6] CrossSiteDocumentClassifier bug fixes.
[chromium-blink-merge.git] / content / common / plugin_list_mac.mm
blobd32f1713eaf7a6d03be222a8dc298fa907870691
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/common/plugin_list.h"
7 #import <Carbon/Carbon.h>
8 #import <Foundation/Foundation.h>
10 #include "base/files/file_enumerator.h"
11 #include "base/files/file_util.h"
12 #include "base/mac/mac_util.h"
13 #include "base/mac/scoped_cftyperef.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/native_library.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/sys_string_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
22 using base::ScopedCFTypeRef;
24 namespace content {
26 namespace {
28 void GetPluginCommonDirectory(std::vector<base::FilePath>* plugin_dirs,
29                               bool user) {
30   // Note that there are no NSSearchPathDirectory constants for these
31   // directories so we can't use Cocoa's NSSearchPathForDirectoriesInDomains().
32   // Interestingly, Safari hard-codes the location (see
33   // WebKit/WebKit/mac/Plugins/WebPluginDatabase.mm's +_defaultPlugInPaths).
34   FSRef ref;
35   OSErr err = FSFindFolder(user ? kUserDomain : kLocalDomain,
36                            kInternetPlugInFolderType, false, &ref);
38   if (err)
39     return;
41   plugin_dirs->push_back(base::FilePath(base::mac::PathFromFSRef(ref)));
44 // Returns true if the plugin should be prevented from loading.
45 bool IsBlacklistedPlugin(const WebPluginInfo& info) {
46   // We blacklist Gears by included MIME type, since that is more stable than
47   // its name. Be careful about adding any more plugins to this list though,
48   // since it's easy to accidentally blacklist plugins that support lots of
49   // MIME types.
50   for (std::vector<WebPluginMimeType>::const_iterator i =
51            info.mime_types.begin(); i != info.mime_types.end(); ++i) {
52     // The Gears plugin is Safari-specific, so don't load it.
53     if (i->mime_type == "application/x-googlegears")
54       return true;
55   }
57   // Versions of Flip4Mac 2.3 before 2.3.6 often hang the renderer, so don't
58   // load them.
59   if (base::StartsWith(info.name, base::ASCIIToUTF16("Flip4Mac Windows Media"),
60                        false) &&
61       base::StartsWith(info.version, base::ASCIIToUTF16("2.3"), false)) {
62     std::vector<base::string16> components;
63     base::SplitString(info.version, '.', &components);
64     int bugfix_version = 0;
65     return (components.size() >= 3 &&
66             base::StringToInt(components[2], &bugfix_version) &&
67             bugfix_version < 6);
68   }
70   return false;
73 NSDictionary* GetMIMETypes(CFBundleRef bundle) {
74   NSString* mime_filename =
75       (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle,
76                      CFSTR("WebPluginMIMETypesFilename"));
78   if (mime_filename) {
80     // get the file
82     NSString* mime_path =
83         [NSString stringWithFormat:@"%@/Library/Preferences/%@",
84          NSHomeDirectory(), mime_filename];
85     NSDictionary* mime_file_dict =
86         [NSDictionary dictionaryWithContentsOfFile:mime_path];
88     // is it valid?
90     bool valid_file = false;
91     if (mime_file_dict) {
92       NSString* l10n_name =
93           [mime_file_dict objectForKey:@"WebPluginLocalizationName"];
94       NSString* preferred_l10n = [[NSLocale currentLocale] localeIdentifier];
95       if ([l10n_name isEqualToString:preferred_l10n])
96         valid_file = true;
97     }
99     if (valid_file)
100       return [mime_file_dict objectForKey:@"WebPluginMIMETypes"];
102     // dammit, I didn't want to have to do this
104     typedef void (*CreateMIMETypesPrefsPtr)(void);
105     CreateMIMETypesPrefsPtr create_prefs_file =
106         (CreateMIMETypesPrefsPtr)CFBundleGetFunctionPointerForName(
107         bundle, CFSTR("BP_CreatePluginMIMETypesPreferences"));
108     if (!create_prefs_file)
109       return nil;
110     create_prefs_file();
112     // one more time
114     mime_file_dict = [NSDictionary dictionaryWithContentsOfFile:mime_path];
115     if (mime_file_dict)
116       return [mime_file_dict objectForKey:@"WebPluginMIMETypes"];
117     else
118       return nil;
120   } else {
121     return (NSDictionary*)CFBundleGetValueForInfoDictionaryKey(bundle,
122                               CFSTR("WebPluginMIMETypes"));
123   }
126 bool ReadPlistPluginInfo(const base::FilePath& filename, CFBundleRef bundle,
127                          WebPluginInfo* info) {
128   NSDictionary* mime_types = GetMIMETypes(bundle);
129   if (!mime_types)
130     return false;  // no type info here; try elsewhere
132   for (NSString* mime_type in [mime_types allKeys]) {
133     NSDictionary* mime_dict = [mime_types objectForKey:mime_type];
134     NSNumber* type_enabled = [mime_dict objectForKey:@"WebPluginTypeEnabled"];
135     NSString* mime_desc = [mime_dict objectForKey:@"WebPluginTypeDescription"];
136     NSArray* mime_exts = [mime_dict objectForKey:@"WebPluginExtensions"];
138     // Skip any disabled types.
139     if (type_enabled && ![type_enabled boolValue])
140       continue;
142     WebPluginMimeType mime;
143     mime.mime_type = base::SysNSStringToUTF8([mime_type lowercaseString]);
144     // Remove PDF from the list of types handled by QuickTime, since it provides
145     // a worse experience than just downloading the PDF.
146     if (mime.mime_type == "application/pdf" &&
147         base::StartsWithASCII(filename.BaseName().value(), "QuickTime",
148                               false)) {
149       continue;
150     }
152     if (mime_desc)
153       mime.description = base::SysNSStringToUTF16(mime_desc);
154     for (NSString* ext in mime_exts)
155       mime.file_extensions.push_back(
156           base::SysNSStringToUTF8([ext lowercaseString]));
158     info->mime_types.push_back(mime);
159   }
161   NSString* plugin_name =
162       (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle,
163       CFSTR("WebPluginName"));
164   NSString* plugin_vers =
165       (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle,
166       CFSTR("CFBundleShortVersionString"));
167   NSString* plugin_desc =
168       (NSString*)CFBundleGetValueForInfoDictionaryKey(bundle,
169       CFSTR("WebPluginDescription"));
171   if (plugin_name)
172     info->name = base::SysNSStringToUTF16(plugin_name);
173   else
174     info->name = base::UTF8ToUTF16(filename.BaseName().value());
175   info->path = filename;
176   if (plugin_vers)
177     info->version = base::SysNSStringToUTF16(plugin_vers);
178   if (plugin_desc)
179     info->desc = base::SysNSStringToUTF16(plugin_desc);
180   else
181     info->desc = base::UTF8ToUTF16(filename.BaseName().value());
183   return true;
186 }  // namespace
188 bool PluginList::ReadWebPluginInfo(const base::FilePath &filename,
189                                    WebPluginInfo* info) {
190   // There are three ways to get information about plugin capabilities:
191   // 1) a set of Info.plist keys, documented at
192   // http://developer.apple.com/documentation/InternetWeb/Conceptual/WebKit_PluginProgTopic/Concepts/AboutPlugins.html .
193   // 2) a set of STR# resources, documented at
194   // https://developer.mozilla.org/En/Gecko_Plugin_API_Reference/Plug-in_Development_Overview .
195   // 3) a NP_GetMIMEDescription() entry point, documented at
196   // https://developer.mozilla.org/en/NP_GetMIMEDescription
197   //
198   // Mozilla supported (3), but WebKit never has, so no plugins rely on it. Most
199   // browsers supported (2) and then added support for (1); Chromium originally
200   // supported (2) and (1), but now supports only (1) as (2) is deprecated.
201   //
202   // For the Info.plist version, the data is formatted as follows (in text plist
203   // format):
204   //  {
205   //    ... the usual plist keys ...
206   //    WebPluginDescription = <<plugindescription>>;
207   //    WebPluginMIMETypes = {
208   //      <<type0mimetype>> = {
209   //        WebPluginExtensions = (
210   //                               <<type0fileextension0>>,
211   //                               ...
212   //                               <<type0fileextensionk>>,
213   //                               );
214   //        WebPluginTypeDescription = <<type0description>>;
215   //      };
216   //      <<type1mimetype>> = { ... };
217   //      ...
218   //      <<typenmimetype>> = { ... };
219   //    };
220   //    WebPluginName = <<pluginname>>;
221   //  }
222   //
223   // Alternatively (and this is undocumented), rather than a WebPluginMIMETypes
224   // key, there may be a WebPluginMIMETypesFilename key. If it is present, then
225   // it is the name of a file in the user's preferences folder in which to find
226   // the WebPluginMIMETypes key. If the key is present but the file doesn't
227   // exist, we must load the plugin and call a specific function to have the
228   // plugin create the file.
230   ScopedCFTypeRef<CFURLRef> bundle_url(CFURLCreateFromFileSystemRepresentation(
231       kCFAllocatorDefault, (const UInt8*)filename.value().c_str(),
232       filename.value().length(), true));
233   if (!bundle_url) {
234     LOG_IF(ERROR, PluginList::DebugPluginLoading())
235         << "PluginLib::ReadWebPluginInfo could not create bundle URL";
236     return false;
237   }
238   ScopedCFTypeRef<CFBundleRef> bundle(CFBundleCreate(kCFAllocatorDefault,
239                                                      bundle_url.get()));
240   if (!bundle) {
241     LOG_IF(ERROR, PluginList::DebugPluginLoading())
242         << "PluginLib::ReadWebPluginInfo could not create CFBundleRef";
243     return false;
244   }
246   // preflight
248   OSType type = 0;
249   CFBundleGetPackageInfo(bundle.get(), &type, NULL);
250   if (type != FOUR_CHAR_CODE('BRPL')) {
251     LOG_IF(ERROR, PluginList::DebugPluginLoading())
252         << "PluginLib::ReadWebPluginInfo bundle is not BRPL, is " << type;
253     return false;
254   }
256   CFErrorRef error;
257   Boolean would_load = CFBundlePreflightExecutable(bundle.get(), &error);
258   if (!would_load) {
259     ScopedCFTypeRef<CFStringRef> error_string(CFErrorCopyDescription(error));
260     LOG_IF(ERROR, PluginList::DebugPluginLoading())
261         << "PluginLib::ReadWebPluginInfo bundle failed preflight: "
262         << base::SysCFStringRefToUTF8(error_string);
263     return false;
264   }
266   // get the info
268   if (ReadPlistPluginInfo(filename, bundle.get(), info))
269     return true;
271   // ... or not
273   return false;
276 void PluginList::GetPluginDirectories(
277     std::vector<base::FilePath>* plugin_dirs) {
278   if (PluginList::plugins_discovery_disabled_)
279     return;
281   // Load from the user's area
282   GetPluginCommonDirectory(plugin_dirs, true);
284   // Load from the machine-wide area
285   GetPluginCommonDirectory(plugin_dirs, false);
288 void PluginList::GetPluginsInDir(
289     const base::FilePath& path, std::vector<base::FilePath>* plugins) {
290   base::FileEnumerator enumerator(path,
291                                   false, // not recursive
292                                   base::FileEnumerator::DIRECTORIES);
293   for (base::FilePath path = enumerator.Next(); !path.value().empty();
294        path = enumerator.Next()) {
295     plugins->push_back(path);
296   }
299 bool PluginList::ShouldLoadPluginUsingPluginList(
300     const WebPluginInfo& info,
301     std::vector<WebPluginInfo>* plugins) {
302   return !IsBlacklistedPlugin(info);
305 }  // namespace content