1/* -*- Mode: C++; tab-width: 3; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7#include <sys/types.h>
8#include <sys/stat.h>
9#include "mozilla/net/NeckoCommon.h"
10#include "mozilla/StaticPrefs_browser.h"
11#include "nsComponentManagerUtils.h"
12#include "nsOSHelperAppService.h"
13#include "nsObjCExceptions.h"
14#include "nsISupports.h"
15#include "nsString.h"
16#include "nsTArray.h"
17#include "nsIFile.h"
18#include "nsILocalFileMac.h"
19#include "nsMimeTypes.h"
20#include "nsMemory.h"
21#include "nsCRT.h"
22#include "nsMIMEInfoMac.h"
23#include "nsEmbedCID.h"
24
25#import <CoreFoundation/CoreFoundation.h>
26#import <ApplicationServices/ApplicationServices.h>
27
28// chrome URL's
29#define HELPERAPPLAUNCHER_BUNDLE_URL "chrome://global/locale/helperAppLauncher.properties"
30#define BRAND_BUNDLE_URL "chrome://branding/locale/brand.properties"
31
32nsresult GetDefaultBundleURL(const nsACString& aScheme, CFURLRef* aBundleURL) {
33  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
34
35  nsresult rv = NS_ERROR_NOT_AVAILABLE;
36
37  CFStringRef schemeCFString = ::CFStringCreateWithBytes(
38      kCFAllocatorDefault, (const UInt8*)PromiseFlatCString(aScheme).get(), aScheme.Length(),
39      kCFStringEncodingUTF8, false);
40
41  if (schemeCFString) {
42    CFStringRef lookupCFString =
43        ::CFStringCreateWithFormat(NULL, NULL, CFSTR("%@:"), schemeCFString);
44
45    if (lookupCFString) {
46      CFURLRef lookupCFURL = ::CFURLCreateWithString(NULL, lookupCFString, NULL);
47
48      if (lookupCFURL) {
49        if (@available(macOS 10.10, *)) {
50          *aBundleURL = ::LSCopyDefaultApplicationURLForURL(lookupCFURL, kLSRolesAll, NULL);
51          if (*aBundleURL) {
52            rv = NS_OK;
53          }
54        } else {
55          OSStatus theErr = ::LSGetApplicationForURL(lookupCFURL, kLSRolesAll, NULL, aBundleURL);
56          if (theErr == noErr && *aBundleURL) {
57            rv = NS_OK;
58          }
59        }
60
61        ::CFRelease(lookupCFURL);
62      }
63
64      ::CFRelease(lookupCFString);
65    }
66
67    ::CFRelease(schemeCFString);
68  }
69
70  return rv;
71
72  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
73}
74
75using mozilla::LogLevel;
76
77/* This is an undocumented interface (in the Foundation framework) that has
78 * been stable since at least 10.2.8 and is still present on SnowLeopard.
79 * Furthermore WebKit has three public methods (in WebKitSystemInterface.h)
80 * that are thin wrappers around this interface's last three methods.  So
81 * it's unlikely to change anytime soon.  Now that we're no longer using
82 * Internet Config Services, this is the only way to look up a MIME type
83 * from an extension, or vice versa.
84 */
85@class NSURLFileTypeMappingsInternal;
86
87@interface NSURLFileTypeMappings : NSObject {
88  NSURLFileTypeMappingsInternal* _internal;
89}
90
91+ (NSURLFileTypeMappings*)sharedMappings;
92- (NSString*)MIMETypeForExtension:(NSString*)aString;
93- (NSString*)preferredExtensionForMIMEType:(NSString*)aString;
94- (NSArray*)extensionsForMIMEType:(NSString*)aString;
95@end
96
97nsOSHelperAppService::~nsOSHelperAppService() {}
98
99nsresult nsOSHelperAppService::OSProtocolHandlerExists(const char* aProtocolScheme,
100                                                       bool* aHandlerExists) {
101  // CFStringCreateWithBytes() can fail even if we're not out of memory --
102  // for example if the 'bytes' parameter is something very weird (like
103  // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's
104  // specified in the 'encoding' parameter.  See bug 548719.
105  CFStringRef schemeString =
106      ::CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8*)aProtocolScheme,
107                                strlen(aProtocolScheme), kCFStringEncodingUTF8, false);
108  if (schemeString) {
109    // LSCopyDefaultHandlerForURLScheme() can fail to find the default handler
110    // for aProtocolScheme when it's never been explicitly set (using
111    // LSSetDefaultHandlerForURLScheme()).  For example, Safari is the default
112    // handler for the "http" scheme on a newly installed copy of OS X.  But
113    // this (presumably) wasn't done using LSSetDefaultHandlerForURLScheme(),
114    // so LSCopyDefaultHandlerForURLScheme() will fail to find Safari.  To get
115    // around this we use LSCopyAllHandlersForURLScheme() instead -- which seems
116    // never to fail.
117    // http://lists.apple.com/archives/Carbon-dev/2007/May/msg00349.html
118    // http://www.realsoftware.com/listarchives/realbasic-nug/2008-02/msg00119.html
119    CFArrayRef handlerArray = ::LSCopyAllHandlersForURLScheme(schemeString);
120    *aHandlerExists = !!handlerArray;
121    if (handlerArray) ::CFRelease(handlerArray);
122    ::CFRelease(schemeString);
123  } else {
124    *aHandlerExists = false;
125  }
126  return NS_OK;
127}
128
129NS_IMETHODIMP nsOSHelperAppService::GetApplicationDescription(const nsACString& aScheme,
130                                                              nsAString& _retval) {
131  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
132
133  nsresult rv = NS_ERROR_NOT_AVAILABLE;
134
135  CFURLRef handlerBundleURL;
136  rv = GetDefaultBundleURL(aScheme, &handlerBundleURL);
137
138  if (NS_SUCCEEDED(rv) && handlerBundleURL) {
139    CFBundleRef handlerBundle = CFBundleCreate(NULL, handlerBundleURL);
140    if (!handlerBundle) {
141      ::CFRelease(handlerBundleURL);
142      return NS_ERROR_OUT_OF_MEMORY;
143    }
144
145    // Get the human-readable name of the bundle
146    CFStringRef bundleName =
147        (CFStringRef)::CFBundleGetValueForInfoDictionaryKey(handlerBundle, kCFBundleNameKey);
148
149    if (bundleName) {
150      AutoTArray<UniChar, 255> buffer;
151      CFIndex bundleNameLength = ::CFStringGetLength(bundleName);
152      buffer.SetLength(bundleNameLength);
153      ::CFStringGetCharacters(bundleName, CFRangeMake(0, bundleNameLength), buffer.Elements());
154      _retval.Assign(reinterpret_cast<char16_t*>(buffer.Elements()), bundleNameLength);
155      rv = NS_OK;
156    }
157    ::CFRelease(handlerBundle);
158    ::CFRelease(handlerBundleURL);
159  }
160
161  return rv;
162
163  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
164}
165
166NS_IMETHODIMP nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol(const nsACString& aScheme,
167                                                                     bool* _retval) {
168  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
169
170  nsresult rv = NS_ERROR_NOT_AVAILABLE;
171
172  CFURLRef handlerBundleURL;
173  rv = GetDefaultBundleURL(aScheme, &handlerBundleURL);
174  if (NS_SUCCEEDED(rv) && handlerBundleURL) {
175    // Ensure we don't accidentally return success if we can't get an app bundle.
176    rv = NS_ERROR_NOT_AVAILABLE;
177    CFBundleRef appBundle = ::CFBundleGetMainBundle();
178    if (appBundle) {
179      CFURLRef selfURL = ::CFBundleCopyBundleURL(appBundle);
180      *_retval = ::CFEqual(selfURL, handlerBundleURL);
181      rv = NS_OK;
182      ::CFRelease(selfURL);
183    }
184    ::CFRelease(handlerBundleURL);
185  }
186
187  return rv;
188
189  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
190}
191
192nsresult nsOSHelperAppService::GetFileTokenForPath(const char16_t* aPlatformAppPath,
193                                                   nsIFile** aFile) {
194  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
195
196  nsresult rv;
197  nsCOMPtr<nsILocalFileMac> localFile(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
198  NS_ENSURE_SUCCESS(rv, rv);
199
200  CFURLRef pathAsCFURL;
201  CFStringRef pathAsCFString = ::CFStringCreateWithCharacters(
202      NULL, reinterpret_cast<const UniChar*>(aPlatformAppPath), NS_strlen(aPlatformAppPath));
203  if (!pathAsCFString) return NS_ERROR_OUT_OF_MEMORY;
204
205  if (::CFStringGetCharacterAtIndex(pathAsCFString, 0) == '/') {
206    // we have a Posix path
207    pathAsCFURL =
208        ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, kCFURLPOSIXPathStyle, false);
209    if (!pathAsCFURL) {
210      ::CFRelease(pathAsCFString);
211      return NS_ERROR_OUT_OF_MEMORY;
212    }
213  } else {
214    // if it doesn't start with a / it's not an absolute Posix path
215    // let's check if it's a HFS path left over from old preferences
216
217    // If it starts with a ':' char, it's not an absolute HFS path
218    // so bail for that, and also if it's empty
219    if (::CFStringGetLength(pathAsCFString) == 0 ||
220        ::CFStringGetCharacterAtIndex(pathAsCFString, 0) == ':') {
221      ::CFRelease(pathAsCFString);
222      return NS_ERROR_FILE_UNRECOGNIZED_PATH;
223    }
224
225    pathAsCFURL =
226        ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, kCFURLHFSPathStyle, false);
227    if (!pathAsCFURL) {
228      ::CFRelease(pathAsCFString);
229      return NS_ERROR_OUT_OF_MEMORY;
230    }
231  }
232
233  rv = localFile->InitWithCFURL(pathAsCFURL);
234  ::CFRelease(pathAsCFString);
235  ::CFRelease(pathAsCFURL);
236  if (NS_FAILED(rv)) return rv;
237  *aFile = localFile;
238  NS_IF_ADDREF(*aFile);
239
240  return NS_OK;
241
242  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
243}
244
245// Returns the MIME types an application bundle explicitly claims to handle.
246// Returns NULL if aAppRef doesn't explicitly claim to handle any MIME types.
247// If the return value is non-NULL, the caller is responsible for freeing it.
248// This isn't necessarily the same as the MIME types the application bundle
249// is registered to handle in the Launch Services database.  (For example
250// the Preview application is normally registered to handle the application/pdf
251// MIME type, even though it doesn't explicitly claim to handle *any* MIME
252// types in its Info.plist.  This is probably because Preview does explicitly
253// claim to handle the com.adobe.pdf UTI, and Launch Services somehow
254// translates this into a claim to support the application/pdf MIME type.
255// Launch Services doesn't provide any APIs (documented or undocumented) to
256// query which MIME types a given application is registered to handle.  So any
257// app that wants this information (e.g. the Default Apps pref pane) needs to
258// iterate through the entire Launch Services database -- a process which can
259// take several seconds.)
260static CFArrayRef GetMIMETypesHandledByApp(FSRef* aAppRef) {
261  CFURLRef appURL = ::CFURLCreateFromFSRef(kCFAllocatorDefault, aAppRef);
262  if (!appURL) {
263    return NULL;
264  }
265  CFDictionaryRef infoDict = ::CFBundleCopyInfoDictionaryForURL(appURL);
266  ::CFRelease(appURL);
267  if (!infoDict) {
268    return NULL;
269  }
270  CFTypeRef cfObject = ::CFDictionaryGetValue(infoDict, CFSTR("CFBundleDocumentTypes"));
271  if (!cfObject || (::CFGetTypeID(cfObject) != ::CFArrayGetTypeID())) {
272    ::CFRelease(infoDict);
273    return NULL;
274  }
275
276  CFArrayRef docTypes = static_cast<CFArrayRef>(cfObject);
277  CFIndex docTypesCount = ::CFArrayGetCount(docTypes);
278  if (docTypesCount == 0) {
279    ::CFRelease(infoDict);
280    return NULL;
281  }
282
283  CFMutableArrayRef mimeTypes =
284      ::CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
285  for (CFIndex i = 0; i < docTypesCount; ++i) {
286    cfObject = ::CFArrayGetValueAtIndex(docTypes, i);
287    if (!cfObject || (::CFGetTypeID(cfObject) != ::CFDictionaryGetTypeID())) {
288      continue;
289    }
290    CFDictionaryRef typeDict = static_cast<CFDictionaryRef>(cfObject);
291
292    // When this key is present (on OS X 10.5 and later), its contents
293    // take precedence over CFBundleTypeMIMETypes (and CFBundleTypeExtensions
294    // and CFBundleTypeOSTypes).
295    cfObject = ::CFDictionaryGetValue(typeDict, CFSTR("LSItemContentTypes"));
296    if (cfObject && (::CFGetTypeID(cfObject) == ::CFArrayGetTypeID())) {
297      continue;
298    }
299
300    cfObject = ::CFDictionaryGetValue(typeDict, CFSTR("CFBundleTypeMIMETypes"));
301    if (!cfObject || (::CFGetTypeID(cfObject) != ::CFArrayGetTypeID())) {
302      continue;
303    }
304    CFArrayRef mimeTypeHolder = static_cast<CFArrayRef>(cfObject);
305    CFArrayAppendArray(mimeTypes, mimeTypeHolder,
306                       ::CFRangeMake(0, ::CFArrayGetCount(mimeTypeHolder)));
307  }
308
309  ::CFRelease(infoDict);
310  if (!::CFArrayGetCount(mimeTypes)) {
311    ::CFRelease(mimeTypes);
312    mimeTypes = NULL;
313  }
314  return mimeTypes;
315}
316
317nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType,
318                                                 const nsACString& aFileExt, bool* aFound,
319                                                 nsIMIMEInfo** aMIMEInfo) {
320  NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
321  MOZ_ASSERT(XRE_IsParentProcess());
322
323  *aFound = false;
324
325  const nsCString& flatType = PromiseFlatCString(aMIMEType);
326  const nsCString& flatExt = PromiseFlatCString(aFileExt);
327
328  MOZ_LOG(mLog, LogLevel::Debug,
329          ("Mac: HelperAppService lookup for type '%s' ext '%s'\n", flatType.get(), flatExt.get()));
330
331  // Create a Mac-specific MIME info so we can use Mac-specific members.
332  RefPtr<nsMIMEInfoMac> mimeInfoMac = new nsMIMEInfoMac(aMIMEType);
333
334  NSAutoreleasePool* localPool = [[NSAutoreleasePool alloc] init];
335
336  OSStatus err;
337  bool haveAppForType = false;
338  bool haveAppForExt = false;
339  bool typeIsOctetStream = false;
340  bool typeAppIsDefault = false;
341  bool extAppIsDefault = false;
342  FSRef typeAppFSRef;
343  FSRef extAppFSRef;
344
345  CFStringRef cfMIMEType = NULL;
346
347  if (!aMIMEType.IsEmpty()) {
348    typeIsOctetStream = aMIMEType.LowerCaseEqualsLiteral(APPLICATION_OCTET_STREAM);
349    CFURLRef appURL = NULL;
350    // CFStringCreateWithCString() can fail even if we're not out of memory --
351    // for example if the 'cStr' parameter is something very weird (like
352    // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's
353    // specified in the 'encoding' parameter.  See bug 548719.
354    cfMIMEType = ::CFStringCreateWithCString(NULL, flatType.get(), kCFStringEncodingUTF8);
355    if (cfMIMEType) {
356      err = ::LSCopyApplicationForMIMEType(cfMIMEType, kLSRolesAll, &appURL);
357      if ((err == noErr) && appURL && ::CFURLGetFSRef(appURL, &typeAppFSRef)) {
358        haveAppForType = true;
359        MOZ_LOG(mLog, LogLevel::Debug,
360                ("LSCopyApplicationForMIMEType found a default application\n"));
361      }
362      if (appURL) {
363        ::CFRelease(appURL);
364      }
365    }
366  }
367  if (!aFileExt.IsEmpty()) {
368    // CFStringCreateWithCString() can fail even if we're not out of memory --
369    // for example if the 'cStr' parameter is something very weird (like
370    // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's
371    // specified in the 'encoding' parameter.  See bug 548719.
372    CFStringRef cfExt = ::CFStringCreateWithCString(NULL, flatExt.get(), kCFStringEncodingUTF8);
373    if (cfExt) {
374      err = ::LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, cfExt, kLSRolesAll,
375                                      &extAppFSRef, nullptr);
376      if (err == noErr) {
377        haveAppForExt = true;
378        MOZ_LOG(mLog, LogLevel::Debug, ("LSGetApplicationForInfo found a default application\n"));
379      }
380      ::CFRelease(cfExt);
381    }
382  }
383
384  if (haveAppForType && haveAppForExt) {
385    // Do aMIMEType and aFileExt match?
386    if (::FSCompareFSRefs((const FSRef*)&typeAppFSRef, (const FSRef*)&extAppFSRef) == noErr) {
387      typeAppIsDefault = true;
388      *aFound = true;
389    }
390  } else if (haveAppForType) {
391    // If aFileExt isn't empty, it doesn't match aMIMEType.
392    if (aFileExt.IsEmpty()) {
393      typeAppIsDefault = true;
394      *aFound = true;
395    }
396  }
397
398  // If we have an app for the extension, and either don't have one for the
399  // type, or the type is application/octet-stream (ie "binary blob"), rely
400  // on the file extension.
401  if ((!haveAppForType || (!*aFound && typeIsOctetStream)) && haveAppForExt) {
402    // If aMIMEType isn't empty, it doesn't match aFileExt, which should mean
403    // that we haven't found a matching app.  But make an exception for an app
404    // that also explicitly claims to handle aMIMEType, or which doesn't claim
405    // to handle any MIME types.  This helps work around the following Apple
406    // design flaw:
407    //
408    // Launch Services is somewhat unreliable about registering Apple apps to
409    // handle MIME types.  Probably this is because Apple has officially
410    // deprecated support for MIME types (in favor of UTIs).  As a result,
411    // most of Apple's own apps don't explicitly claim to handle any MIME
412    // types (instead they claim to handle one or more UTIs).  So Launch
413    // Services must contain logic to translate support for a given UTI into
414    // support for one or more MIME types, and it doesn't always do this
415    // correctly.  For example DiskImageMounter isn't (by default) registered
416    // to handle the application/x-apple-diskimage MIME type.  See bug 675356.
417    //
418    // Apple has also deprecated support for file extensions, and Apple apps
419    // also don't register to handle them.  But for some reason Launch Services
420    // is (apparently) better about translating support for a given UTI into
421    // support for one or more file extensions.  It's not at all clear why.
422    if (aMIMEType.IsEmpty() || typeIsOctetStream) {
423      extAppIsDefault = true;
424      *aFound = true;
425    } else {
426      CFArrayRef extAppMIMETypes = GetMIMETypesHandledByApp(&extAppFSRef);
427      if (extAppMIMETypes) {
428        if (cfMIMEType) {
429          if (::CFArrayContainsValue(extAppMIMETypes,
430                                     ::CFRangeMake(0, ::CFArrayGetCount(extAppMIMETypes)),
431                                     cfMIMEType)) {
432            extAppIsDefault = true;
433            *aFound = true;
434          }
435        }
436        ::CFRelease(extAppMIMETypes);
437      } else {
438        extAppIsDefault = true;
439        *aFound = true;
440      }
441    }
442  }
443
444  if (cfMIMEType) {
445    ::CFRelease(cfMIMEType);
446  }
447
448  if (aMIMEType.IsEmpty()) {
449    if (haveAppForExt) {
450      // If aMIMEType is empty and we've found a default app for aFileExt, try
451      // to get the MIME type from aFileExt.  (It might also be worth doing
452      // this when aMIMEType isn't empty but haveAppForType is false -- but
453      // the doc for this method says that if we have a MIME type (in
454      // aMIMEType), we need to give it preference.)
455      NSURLFileTypeMappings* map = [NSURLFileTypeMappings sharedMappings];
456      NSString* extStr = [NSString stringWithCString:flatExt.get() encoding:NSASCIIStringEncoding];
457      NSString* typeStr = map ? [map MIMETypeForExtension:extStr] : NULL;
458      if (typeStr) {
459        nsAutoCString mimeType;
460        mimeType.Assign((char*)[typeStr cStringUsingEncoding:NSASCIIStringEncoding]);
461        mimeInfoMac->SetMIMEType(mimeType);
462        haveAppForType = true;
463      } else {
464        // Sometimes the OS won't give us a MIME type for an extension that's
465        // registered with Launch Services and has a default app:  For example
466        // Real Player registers itself for the "ogg" extension and for the
467        // audio/x-ogg and application/x-ogg MIME types, but
468        // MIMETypeForExtension returns nil for the "ogg" extension even on
469        // systems where Real Player is installed.  This is probably an Apple
470        // bug.  But bad things happen if we return an nsIMIMEInfo structure
471        // with an empty MIME type and set *aFound to true.  So in this
472        // case we need to set it to false here.
473        haveAppForExt = false;
474        extAppIsDefault = false;
475        *aFound = false;
476      }
477    } else {
478      // Otherwise set the MIME type to a reasonable fallback.
479      mimeInfoMac->SetMIMEType(nsLiteralCString(APPLICATION_OCTET_STREAM));
480    }
481  }
482
483  if (typeAppIsDefault || extAppIsDefault) {
484    if (haveAppForExt) mimeInfoMac->AppendExtension(aFileExt);
485
486    nsresult rv;
487    nsCOMPtr<nsILocalFileMac> app(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
488    if (NS_FAILED(rv)) {
489      [localPool release];
490      return rv;
491    }
492
493    CFStringRef cfAppName = NULL;
494    if (typeAppIsDefault) {
495      app->InitWithFSRef(&typeAppFSRef);
496      ::LSCopyItemAttribute((const FSRef*)&typeAppFSRef, kLSRolesAll, kLSItemDisplayName,
497                            (CFTypeRef*)&cfAppName);
498    } else {
499      app->InitWithFSRef(&extAppFSRef);
500      ::LSCopyItemAttribute((const FSRef*)&extAppFSRef, kLSRolesAll, kLSItemDisplayName,
501                            (CFTypeRef*)&cfAppName);
502    }
503    if (cfAppName) {
504      AutoTArray<UniChar, 255> buffer;
505      CFIndex appNameLength = ::CFStringGetLength(cfAppName);
506      buffer.SetLength(appNameLength);
507      ::CFStringGetCharacters(cfAppName, CFRangeMake(0, appNameLength), buffer.Elements());
508      nsAutoString appName;
509      appName.Assign(reinterpret_cast<char16_t*>(buffer.Elements()), appNameLength);
510      mimeInfoMac->SetDefaultDescription(appName);
511      ::CFRelease(cfAppName);
512    }
513
514    mimeInfoMac->SetDefaultApplication(app);
515
516    mozilla::StaticPrefs::browser_download_improvements_to_download_panel()
517        ? mimeInfoMac->SetPreferredAction(nsIMIMEInfo::saveToDisk)
518        : mimeInfoMac->SetPreferredAction(nsIMIMEInfo::useSystemDefault);
519
520  } else {
521    mimeInfoMac->SetPreferredAction(nsIMIMEInfo::saveToDisk);
522  }
523
524  nsAutoCString mimeType;
525  mimeInfoMac->GetMIMEType(mimeType);
526  if (*aFound && !mimeType.IsEmpty()) {
527    // If we have a MIME type, make sure its extension list is included in our
528    // list.
529    NSURLFileTypeMappings* map = [NSURLFileTypeMappings sharedMappings];
530    NSString* typeStr = [NSString stringWithCString:mimeType.get() encoding:NSASCIIStringEncoding];
531    NSArray* extensionsList = map ? [map extensionsForMIMEType:typeStr] : NULL;
532    if (extensionsList) {
533      for (NSString* extension in extensionsList) {
534        nsAutoCString ext;
535        ext.Assign((char*)[extension cStringUsingEncoding:NSASCIIStringEncoding]);
536        mimeInfoMac->AppendExtension(ext);
537      }
538    }
539
540    if (CFStringRef cfType =
541            ::CFStringCreateWithCString(NULL, mimeType.get(), kCFStringEncodingUTF8)) {
542      if (CFStringRef cfTypeDesc = ::UTTypeCopyDescription(cfType)) {
543        AutoTArray<UniChar, 255> buffer;
544        CFIndex typeDescLength = ::CFStringGetLength(cfTypeDesc);
545        buffer.SetLength(typeDescLength);
546        ::CFStringGetCharacters(cfTypeDesc, CFRangeMake(0, typeDescLength), buffer.Elements());
547        nsAutoString typeDesc;
548        typeDesc.Assign(reinterpret_cast<char16_t*>(buffer.Elements()), typeDescLength);
549        mimeInfoMac->SetDescription(typeDesc);
550        ::CFRelease(cfTypeDesc);
551      }
552      ::CFRelease(cfType);
553    }
554  }
555
556  MOZ_LOG(mLog, LogLevel::Debug, ("OS gave us: type '%s' found '%i'\n", mimeType.get(), *aFound));
557
558  [localPool release];
559  mimeInfoMac.forget(aMIMEInfo);
560  return NS_OK;
561
562  NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
563}
564
565NS_IMETHODIMP
566nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString& aScheme, bool* found,
567                                                   nsIHandlerInfo** _retval) {
568  NS_ASSERTION(!aScheme.IsEmpty(), "No scheme was specified!");
569
570  nsresult rv = OSProtocolHandlerExists(nsPromiseFlatCString(aScheme).get(), found);
571  if (NS_FAILED(rv)) return rv;
572
573  nsMIMEInfoMac* handlerInfo = new nsMIMEInfoMac(aScheme, nsMIMEInfoBase::eProtocolInfo);
574  NS_ENSURE_TRUE(handlerInfo, NS_ERROR_OUT_OF_MEMORY);
575  NS_ADDREF(*_retval = handlerInfo);
576
577  if (!*found) {
578    // Code that calls this requires an object regardless if the OS has
579    // something for us, so we return the empty object.
580    return NS_OK;
581  }
582
583  // As a workaround for the OS X problem described in bug 1391186, don't
584  // attempt to get/set the application description from the child process.
585  if (!mozilla::net::IsNeckoChild()) {
586    nsAutoString desc;
587    rv = GetApplicationDescription(aScheme, desc);
588    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "GetApplicationDescription failed");
589    handlerInfo->SetDefaultDescription(desc);
590  }
591
592  return NS_OK;
593}
594