1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* ***** BEGIN LICENSE BLOCK *****
3
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
5
* The contents of this file are subject to the Netscape Public License
6
* Version 1.1 (the "License"); you may not use this file except in
7
* compliance with the License. You may obtain a copy of the License at
8
* http://www.mozilla.org/NPL/
10
* Software distributed under the License is distributed on an "AS IS" basis,
11
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12
* for the specific language governing rights and limitations under the
15
* The Original Code is Mozilla Communicator client code.
17
* The Initial Developer of the Original Code is
18
* Netscape Communications Corporation.
19
* Portions created by the Initial Developer are Copyright (C) 1998
20
* the Initial Developer. All Rights Reserved.
23
* Steve Dagley <sdagley@netscape.com>
25
* Alternatively, the contents of this file may be used under the terms of
26
* either the GNU General Public License Version 2 or later (the "GPL"), or
27
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28
* in which case the provisions of the GPL or the LGPL are applicable instead
29
* of those above. If you wish to allow use of your version of this file only
30
* under the terms of either the GPL or the LGPL, and not to allow others to
31
* use your version of this file under the terms of the NPL, indicate your
32
* decision by deleting the provisions above and replace them with the notice
33
* and other provisions required by the GPL or the LGPL. If you do not delete
34
* the provisions above, a recipient may use your version of this file under
35
* the terms of any one of the NPL, the GPL or the LGPL.
37
* ***** END LICENSE BLOCK ***** */
39
#include "nsInternetConfigService.h"
41
#include "nsIMIMEInfo.h"
42
#include "nsMIMEInfoMac.h"
43
#include "nsAutoPtr.h"
44
#include "nsIFactory.h"
45
#include "nsIComponentManager.h"
47
#include "nsXPIDLString.h"
48
#include "nsReadableUtils.h"
51
#include "nsILocalFileMac.h"
52
#include "nsMimeTypes.h"
53
#include <TextUtils.h>
54
#include <CodeFragments.h>
55
#include <Processes.h>
59
#include <LaunchServices.h>
62
// helper converter function.....
63
static void ConvertCharStringToStr255(const char* inString, Str255& outString)
68
PRInt32 len = strlen(inString);
69
NS_ASSERTION(len <= 255 , " String is too big");
74
memcpy(&outString[1], inString, len);
78
/* Define Class IDs */
80
nsInternetConfigService::nsInternetConfigService()
84
mRunningOSX = ((err = ::Gestalt(gestaltSystemVersion, &version)) == noErr && version >= 0x00001000);
85
mRunningJaguar = (err == noErr && version >= 0x00001020);
88
nsInternetConfigService::~nsInternetConfigService()
94
* Implement the nsISupports methods...
96
NS_IMPL_ISUPPORTS1(nsInternetConfigService, nsIInternetConfigService)
98
// void LaunchURL (in string url);
99
// Given a url string, call ICLaunchURL using url
100
// Under OS X use LaunchServices instead of IC
101
NS_IMETHODIMP nsInternetConfigService::LaunchURL(const char *url)
103
nsresult rv = NS_ERROR_FAILURE;
106
if (mRunningOSX && ((UInt32)LSOpenCFURLRef != (UInt32)kUnresolvedCFragSymbolAddress))
108
CFURLRef myURLRef = ::CFURLCreateWithBytes(
112
kCFStringEncodingUTF8, NULL);
115
rv = ::LSOpenCFURLRef(myURLRef, NULL);
116
::CFRelease(myURLRef);
122
size_t len = strlen(url);
123
long selStart = 0, selEnd = len;
124
ICInstance inst = nsInternetConfig::GetInstance();
128
if (::ICLaunchURL(inst, "\p", (Ptr)url, (long)len, &selStart, &selEnd) == noErr)
135
// boolean HasMappingForMIMEType (in string mimetype);
136
// given a mime type, search Internet Config database for a mapping for that mime type
137
NS_IMETHODIMP nsInternetConfigService::HasMappingForMIMEType(const char *mimetype, PRBool *_retval)
140
nsresult rv = GetMappingForMIMEType(mimetype, nsnull, &entry);
148
/* boolean hasProtocalHandler (in string protocol); */
149
// returns NS_ERROR_NOT_AVAILABLE if the current application is registered for as the
150
// protocol handler for protocol
151
NS_IMETHODIMP nsInternetConfigService::HasProtocolHandler(const char *protocol, PRBool *_retval)
153
*_retval = PR_FALSE; // Presume failure
154
nsresult rv = NS_ERROR_FAILURE; // Ditto
157
// Use LaunchServices directly when we're running under OS X to avoid the problem of some protocols
158
// apparently not being reflected into the IC mappings (webcal for one). Even better it seems
159
// LaunchServices under 10.1.x will often fail to find an app when using LSGetApplicationForURL
160
// so we only use it for 10.2 or later.
162
// Since protocol comes in with _just_ the protocol we have to add a ':' to the end of it or
163
// LaunchServices will be very unhappy with the CFURLRef created from it (crashes trying to look
164
// up a handler for it with LSGetApplicationForURL, at least under 10.2.1)
167
nsCAutoString scheme(protocol);
169
CFURLRef myURLRef = ::CFURLCreateWithBytes(
171
(const UInt8 *)scheme.get(),
173
kCFStringEncodingUTF8, NULL);
178
if (::LSGetApplicationForURL(myURLRef, kLSRolesAll, &appFSRef, NULL) == noErr)
179
{ // Now see if the FSRef for the found app == the running app
180
ProcessSerialNumber psn;
181
if (::GetCurrentProcess(&psn) == noErr)
183
FSRef runningAppFSRef;
184
if (::GetProcessBundleLocation(&psn, &runningAppFSRef) == noErr)
186
if (::FSCompareFSRefs(&appFSRef, &runningAppFSRef) == noErr)
187
{ // Oops, the current app is the handler which would cause infinite recursion
188
rv = NS_ERROR_NOT_AVAILABLE;
198
::CFRelease(myURLRef);
204
// look for IC pref "\pHelperļæ½<protocol>"
205
Str255 pref = kICHelper;
207
if (nsCRT::strlen(protocol) > 248)
208
rv = NS_ERROR_OUT_OF_MEMORY;
211
memcpy(pref + pref[0] + 1, protocol, nsCRT::strlen(protocol));
212
pref[0] = pref[0] + nsCRT::strlen(protocol);
214
ICInstance instance = nsInternetConfig::GetInstance();
220
long ioSize = sizeof(ICAppSpec);
221
err = ::ICGetPref(instance, pref, &junk, (void *)&spec, &ioSize);
225
// check if registered protocol helper is us
226
// if so, return PR_FALSE because we'll go into infinite recursion
227
// continually launching back into ourselves
228
ProcessSerialNumber psn;
229
OSErr oserr = ::GetCurrentProcess(&psn);
233
info.processInfoLength = sizeof(ProcessInfoRec);
234
info.processName = nsnull;
235
info.processAppSpec = nsnull;
236
err = ::GetProcessInformation(&psn, &info);
239
if (info.processSignature != spec.fCreator)
245
rv = NS_ERROR_NOT_AVAILABLE;
255
// This method does the dirty work of traipsing through IC mappings database
256
// looking for a mapping for mimetype
257
nsresult nsInternetConfigService::GetMappingForMIMEType(const char *mimetype, const char *fileextension, ICMapEntry *entry)
259
ICInstance inst = nsInternetConfig::GetInstance();
260
OSStatus err = noErr;
263
PRBool domimecheck = PR_TRUE;
264
PRBool gotmatch = PR_FALSE;
267
// if mime type is "unknown" or "octet stream" *AND* we have a file extension,
268
// then disable match on mime type
269
if (((nsCRT::strcasecmp(mimetype, UNKNOWN_CONTENT_TYPE) == 0) ||
270
(nsCRT::strcasecmp(mimetype, APPLICATION_OCTET_STREAM) == 0)) &&
272
domimecheck = PR_FALSE;
274
entry->totalLength = 0;
277
err = ::ICBegin(inst, icReadOnlyPerm);
280
prefH = ::NewHandle(2048); // picked 2048 out of thin air
283
err = ::ICFindPrefHandle(inst, kICMapping, &attr, prefH);
287
err = ::ICCountMapEntries(inst, prefH, &count);
291
for (long i = 1; i <= count; ++i)
293
err = ::ICGetIndMapEntry(inst, prefH, i, &pos, &ent);
296
// first, do mime type check
299
nsCAutoString temp((char *)&ent.MIMEType[1], (int)ent.MIMEType[0]);
300
if (!temp.EqualsIgnoreCase(mimetype))
302
// we need to do mime check, and check failed
303
// nothing here to see, move along
309
// if fileextension was passed in, compare that also
310
if (ent.extension[0]) // check for non-empty pascal string
312
nsCAutoString temp((char *)&ent.extension[1], (int)ent.extension[0]);
313
if (temp.EqualsIgnoreCase(fileextension))
315
// mime type and file extension match, we're outta here
317
// copy over ICMapEntry
325
// at this point, we've got our match because
326
// domimecheck is true, the mime strings match, and fileextension isn't passed in
327
// bad thing is we'll stop on first match, but what can you do?
329
// copy over ICMapEntry
337
::DisposeHandle(prefH);
344
if (err == noErr && gotmatch == PR_FALSE)
346
err = fnfErr; // return SOME kind of error
352
return NS_ERROR_FAILURE;
357
nsresult nsInternetConfigService::FillMIMEInfoForICEntry(ICMapEntry& entry, nsIMIMEInfo ** mimeinfo)
359
// create a mime info object and we'll fill it in based on the values from IC mapping entry
361
nsRefPtr<nsMIMEInfoMac> info (new nsMIMEInfoMac());
364
nsCAutoString mimetype ((char *)&entry.MIMEType[1], entry.MIMEType[0]);
365
// check if entry.MIMEType is empty, if so, set mime type to APPLICATION_OCTET_STREAM
366
if (entry.MIMEType[0])
367
info->SetMIMEType(mimetype.get());
369
{ // The IC mappings seem to not be very agressive about determining the mime type if
370
// all we have is a type or creator code. This is a bandaid approach for when we
371
// get a file of type 'TEXT' with no mime type mapping so that we'll display the
372
// file rather than trying to download it.
373
if (entry.fileType == 'TEXT')
374
info->SetMIMEType(TEXT_PLAIN);
376
info->SetMIMEType(APPLICATION_OCTET_STREAM);
379
// convert entry.extension which is a Str255
380
// don't forget to remove the '.' in front of the file extension....
381
nsCAutoString temp((char *)&entry.extension[2], entry.extension[0] > 0 ? (int)entry.extension[0]-1 : 0);
382
info->AppendExtension(temp.get());
383
info->SetMacType(entry.fileType);
384
info->SetMacCreator(entry.fileCreator);
385
temp.Assign((char *) &entry.entryName[1], entry.entryName[0]);
386
info->SetDescription(NS_ConvertASCIItoUCS2(temp.get()).get());
388
temp.Assign((char *) &entry.postAppName[1], entry.postAppName[0]);
389
info->SetDefaultDescription(NS_ConvertASCIItoUCS2(temp.get()).get());
391
if (entry.flags & kICMapPostMask)
393
// there is a post processor app
394
info->SetPreferredAction(nsIMIMEInfo::useSystemDefault);
395
nsCOMPtr<nsILocalFileMac> file (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
398
rv = file->InitToAppWithCreatorCode(entry.postCreator);
401
nsCOMPtr<nsIFile> nsfile = do_QueryInterface(file, &rv);
403
info->SetDefaultApplication(nsfile);
409
// there isn't a post processor app so set the preferred action to be save to disk.
410
info->SetPreferredAction(nsIMIMEInfo::saveToDisk);
414
NS_IF_ADDREF(*mimeinfo);
416
else // we failed to allocate the info object...
417
rv = NS_ERROR_FAILURE;
422
/* void FillInMIMEInfo (in string mimetype, in string fileExtension, out nsIMIMEInfo mimeinfo); */
423
NS_IMETHODIMP nsInternetConfigService::FillInMIMEInfo(const char *mimetype, const char * aFileExtension, nsIMIMEInfo **mimeinfo)
428
NS_ENSURE_ARG_POINTER(mimeinfo);
433
nsCAutoString fileExtension;
434
fileExtension.Assign(".");
435
fileExtension.Append(aFileExtension);
436
rv = GetMappingForMIMEType(mimetype, fileExtension.get(), &entry);
440
rv = GetMappingForMIMEType(mimetype, nsnull, &entry);
444
rv = FillMIMEInfoForICEntry(entry, mimeinfo);
446
rv = NS_ERROR_FAILURE;
451
NS_IMETHODIMP nsInternetConfigService::GetMIMEInfoFromExtension(const char *aFileExt, nsIMIMEInfo **_retval)
453
nsresult rv = NS_ERROR_FAILURE;
454
ICInstance instance = nsInternetConfig::GetInstance();
457
nsCAutoString filename("foobar.");
458
filename += aFileExt;
460
ConvertCharStringToStr255(filename.get(), pFileName);
462
OSStatus err = ::ICMapFilename(instance, pFileName, &entry);
465
rv = FillMIMEInfoForICEntry(entry, _retval);
472
NS_IMETHODIMP nsInternetConfigService::GetMIMEInfoFromTypeCreator(PRUint32 aType, PRUint32 aCreator, const char *aFileExt, nsIMIMEInfo **_retval)
474
nsresult rv = NS_ERROR_FAILURE;
475
ICInstance instance = nsInternetConfig::GetInstance();
478
nsCAutoString filename("foobar.");
479
filename += aFileExt;
481
ConvertCharStringToStr255(filename.get(), pFileName);
483
OSStatus err = ::ICMapTypeCreator(instance, aType, aCreator, pFileName, &entry);
485
rv = FillMIMEInfoForICEntry(entry,_retval);
491
NS_IMETHODIMP nsInternetConfigService::GetFileMappingFlags(FSSpec* fsspec, PRBool lookupByExtensionFirst, PRInt32 *_retval)
493
nsresult rv = NS_ERROR_FAILURE;
494
OSStatus err = noErr;
496
NS_ENSURE_ARG(_retval);
499
ICInstance instance = nsInternetConfig::GetInstance();
504
if (lookupByExtensionFirst)
505
err = ::ICMapFilename(instance, fsspec->name, &entry);
507
if (!lookupByExtensionFirst || err != noErr)
510
err = FSpGetFInfo(fsspec, &info);
512
err = ::ICMapTypeCreator(instance, info.fdType, info.fdCreator, fsspec->name, &entry);
516
*_retval = entry.flags;
524
/* void GetDownloadFolder (out FSSpec fsspec); */
525
NS_IMETHODIMP nsInternetConfigService::GetDownloadFolder(FSSpec *fsspec)
527
ICInstance inst = nsInternetConfig::GetInstance();
530
nsresult rv = NS_ERROR_FAILURE;
532
NS_ENSURE_ARG_POINTER(fsspec);
536
err = ::ICBegin(inst, icReadOnlyPerm);
539
prefH = ::NewHandle(256); // ICFileSpec ~= 112 bytes + variable, 256 bytes hopefully is sufficient
543
err = ::ICFindPrefHandle(inst, kICDownloadFolder, &attr, prefH);
546
err = ::Munger(prefH, 0, NULL, kICFileSpecHeaderSize, (Ptr)-1, 0);
550
err = ::ResolveAlias(NULL, (AliasHandle)prefH, fsspec, &wasChanged);
556
{ // ResolveAlias for the DownloadFolder failed - try grabbing the FSSpec
557
err = ::ICFindPrefHandle(inst, kICDownloadFolder, &attr, prefH);
559
{ // Use FSMakeFSSpec to verify the saved FSSpec is still valid
560
FSSpec tempSpec = (*(ICFileSpecHandle)prefH)->fss;
561
err = ::FSMakeFSSpec(tempSpec.vRefNum, tempSpec.parID, tempSpec.name, fsspec);
568
// Best not to leave that handle laying around
569
DisposeHandle(prefH);
577
nsresult nsInternetConfigService::GetICKeyPascalString(PRUint32 inIndex, const unsigned char*& outICKey)
583
case eICColor_WebBackgroundColour: outICKey = kICWebBackgroundColour; break;
584
case eICColor_WebReadColor: outICKey = kICWebReadColor; break;
585
case eICColor_WebTextColor: outICKey = kICWebTextColor; break;
586
case eICColor_WebUnreadColor: outICKey = kICWebUnreadColor; break;
588
case eICBoolean_WebUnderlineLinks: outICKey = kICWebUnderlineLinks; break;
589
case eICBoolean_UseFTPProxy: outICKey = kICUseFTPProxy; break;
590
case eICBoolean_UsePassiveFTP: outICKey = kICUsePassiveFTP; break;
591
case eICBoolean_UseHTTPProxy: outICKey = kICUseHTTPProxy; break;
592
case eICBoolean_NewMailDialog: outICKey = kICNewMailDialog; break;
593
case eICBoolean_NewMailFlashIcon: outICKey = kICNewMailFlashIcon; break;
594
case eICBoolean_NewMailPlaySound: outICKey = kICNewMailPlaySound; break;
595
case eICBoolean_UseGopherProxy: outICKey = kICUseGopherProxy; break;
596
case eICBoolean_UseSocks: outICKey = kICUseSocks; break;
598
case eICString_WWWHomePage: outICKey = kICWWWHomePage; break;
599
case eICString_WebSearchPagePrefs: outICKey = kICWebSearchPagePrefs; break;
600
case eICString_MacSearchHost: outICKey = kICMacSearchHost; break;
601
case eICString_FTPHost: outICKey = kICFTPHost; break;
602
case eICString_FTPProxyUser: outICKey = kICFTPProxyUser; break;
603
case eICString_FTPProxyAccount: outICKey = kICFTPProxyAccount; break;
604
case eICString_FTPProxyHost: outICKey = kICFTPProxyHost; break;
605
case eICString_FTPProxyPassword: outICKey = kICFTPProxyPassword; break;
606
case eICString_HTTPProxyHost: outICKey = kICHTTPProxyHost; break;
607
case eICString_LDAPSearchbase: outICKey = kICLDAPSearchbase; break;
608
case eICString_LDAPServer: outICKey = kICLDAPServer; break;
609
case eICString_SMTPHost: outICKey = kICSMTPHost; break;
610
case eICString_Email: outICKey = kICEmail; break;
611
case eICString_MailAccount: outICKey = kICMailAccount; break;
612
case eICString_MailPassword: outICKey = kICMailPassword; break;
613
case eICString_NewMailSoundName: outICKey = kICNewMailSoundName; break;
614
case eICString_NNTPHost: outICKey = kICNNTPHost; break;
615
case eICString_NewsAuthUsername: outICKey = kICNewsAuthUsername; break;
616
case eICString_NewsAuthPassword: outICKey = kICNewsAuthPassword; break;
617
case eICString_InfoMacPreferred: outICKey = kICInfoMacPreferred; break;
618
case eICString_Organization: outICKey = kICOrganization; break;
619
case eICString_QuotingString: outICKey = kICQuotingString; break;
620
case eICString_RealName: outICKey = kICRealName; break;
621
case eICString_FingerHost: outICKey = kICFingerHost; break;
622
case eICString_GopherHost: outICKey = kICGopherHost; break;
623
case eICString_GopherProxy: outICKey = kICGopherProxy; break;
624
case eICString_SocksHost: outICKey = kICSocksHost; break;
625
case eICString_TelnetHost: outICKey = kICTelnetHost; break;
626
case eICString_IRCHost: outICKey = kICIRCHost; break;
627
case eICString_UMichPreferred: outICKey = kICUMichPreferred; break;
628
case eICString_WAISGateway: outICKey = kICWAISGateway; break;
629
case eICString_WhoisHost: outICKey = kICWhoisHost; break;
630
case eICString_PhHost: outICKey = kICPhHost; break;
631
case eICString_NTPHost: outICKey = kICNTPHost; break;
632
case eICString_ArchiePreferred: outICKey = kICArchiePreferred; break;
634
case eICText_MailHeaders: outICKey = kICMailHeaders; break;
635
case eICText_Signature: outICKey = kICSignature; break;
636
case eICText_NewsHeaders: outICKey = kICNewsHeaders; break;
637
case eICText_SnailMailAddress: outICKey = kICSnailMailAddress; break;
638
case eICText_Plan: outICKey = kICPlan; break;
641
rv = NS_ERROR_INVALID_ARG;
647
nsresult nsInternetConfigService::GetICPreference(PRUint32 inKey,
648
void *outData, long *ioSize)
650
const unsigned char *icKey;
651
nsresult rv = GetICKeyPascalString(inKey, icKey);
654
ICInstance instance = nsInternetConfig::GetInstance();
659
err = ::ICGetPref(instance, icKey, &junk, outData, ioSize);
661
rv = NS_ERROR_UNEXPECTED;
664
rv = NS_ERROR_FAILURE;
670
NS_IMETHODIMP nsInternetConfigService::GetString(PRUint32 inKey, nsACString& value)
674
nsresult rv = GetICPreference(inKey, (void *)&buffer, &size);
680
rv = NS_ERROR_UNEXPECTED;
683
{ // Buffer is a Pascal string so adjust for length byte when assigning
684
value.Assign(&buffer[1], (unsigned char)buffer[0]);
691
NS_IMETHODIMP nsInternetConfigService::GetColor(PRUint32 inKey, PRUint32 *outColor)
693
// We're 'borrowing' this macro from nscolor.h so that uriloader doesn't depend on gfx.
694
// Make a color out of r,g,b values. This assumes that the r,g,b values are
695
// properly constrained to 0-255. This also assumes that a is 255.
697
#define MAKE_NS_RGB(_r,_g,_b) \
698
((PRUint32) ((255 << 24) | ((_b)<<16) | ((_g)<<8) | (_r)))
701
long size = sizeof(RGBColor);
702
nsresult rv = GetICPreference(inKey, &buffer, &size);
705
if (size != sizeof(RGBColor))
706
{ // default to white if we didn't get the right size
707
*outColor = MAKE_NS_RGB(0xff, 0xff, 0xff);
710
{ // convert to a web color
711
*outColor = MAKE_NS_RGB(buffer.red >> 8, buffer.green >> 8, buffer.blue >> 8);
718
NS_IMETHODIMP nsInternetConfigService::GetBoolean(PRUint32 inKey, PRBool *outFlag)
721
long size = sizeof(Boolean);
722
nsresult rv = GetICPreference(inKey, (void *)&buffer, &size);
725
if ((size_t)size < sizeof(Boolean))
726
*outFlag = PR_FALSE; // default to false if we didn't get the right amount of data