fixes bug 166792 "move nsIIOService::GetURLSpecFromFile, etc. to

nsIFileProtocolHandler" r=dougt sr=alecf
This commit is contained in:
darin%netscape.com 2002-09-13 19:32:45 +00:00
Родитель a0e1cf050e
Коммит c8bc7f6793
45 изменённых файлов: 1113 добавлений и 753 удалений

Просмотреть файл

@ -930,6 +930,7 @@ function PromptForSaveLocation(aDoSaveAsText, aEditorType, aMIMEType, ahtmlDocum
// assuming we have information needed (like prior saved location) // assuming we have information needed (like prior saved location)
try { try {
var ioService = GetIOService(); var ioService = GetIOService();
var fileHandler = GetFileProtocolHandler();
var isLocalFile = true; var isLocalFile = true;
try { try {
@ -941,7 +942,7 @@ function PromptForSaveLocation(aDoSaveAsText, aEditorType, aMIMEType, ahtmlDocum
var parentLocation = null; var parentLocation = null;
if (isLocalFile) if (isLocalFile)
{ {
var fileLocation = ioService.getFileFromURLSpec(aDocumentURLString); // this asserts if url is not local var fileLocation = fileHandler.getFileFromURLSpec(aDocumentURLString); // this asserts if url is not local
parentLocation = fileLocation.parent; parentLocation = fileLocation.parent;
} }
if (parentLocation) if (parentLocation)
@ -964,7 +965,7 @@ function PromptForSaveLocation(aDoSaveAsText, aEditorType, aMIMEType, ahtmlDocum
if (dialogResult.filepickerClick != nsIFilePicker.returnCancel) if (dialogResult.filepickerClick != nsIFilePicker.returnCancel)
{ {
// reset urlstring to new save location // reset urlstring to new save location
dialogResult.resultingURIString = ioService.getURLSpecFromFile(fp.file); dialogResult.resultingURIString = fileHandler.getURLSpecFromFile(fp.file);
dialogResult.resultingLocalFile = fp.file; dialogResult.resultingLocalFile = fp.file;
SaveFilePickerDirectory(fp, aEditorType); SaveFilePickerDirectory(fp, aEditorType);
} }
@ -1757,8 +1758,8 @@ function SaveDocument(aSaveAs, aSaveCopy, aMimeType)
if (docURI.schemeIs("file")) if (docURI.schemeIs("file"))
{ {
ioService = GetIOService(); var fileHandler = GetFileProtocolHandler();
tempLocalFile = ioService.getFileFromURLSpec(urlstring).QueryInterface(Components.interfaces.nsILocalFile); tempLocalFile = fileHandler.getFileFromURLSpec(urlstring).QueryInterface(Components.interfaces.nsILocalFile);
} }
} }
@ -2433,8 +2434,8 @@ var nsValidateCommand =
// See if it's a file: // See if it's a file:
var ifile; var ifile;
try { try {
var ioService = GetIOService(); var fileHandler = GetFileProtocolHandler();
ifile = ioService.getFileFromURLSpec(URL2Validate); ifile = fileHandler.getFileFromURLSpec(URL2Validate);
// nsIFile throws an exception if it's not a file url // nsIFile throws an exception if it's not a file url
} catch (e) { ifile = null; } } catch (e) { ifile = null; }
if (ifile) if (ifile)

Просмотреть файл

@ -305,6 +305,13 @@ function GetIOService()
return gIOService; return gIOService;
} }
function GetFileProtocolHandler()
{
var ios = GetIOService();
var handler = ios.getProtocolHandler("file");
return handler.QueryInterface(Components.interfaces.nsIFileProtocolHandler);
}
function GetPrefsService() function GetPrefsService()
{ {
if (gPrefsService) if (gPrefsService)

Просмотреть файл

@ -538,8 +538,8 @@ function GetLocalFileURL(filterType)
} }
SaveFilePickerDirectory(fp, fileType); SaveFilePickerDirectory(fp, fileType);
var ioService = GetIOService(); var fileHandler = GetFileProtocolHandler();
return fp.file ? ioService.getURLSpecFromFile(fp.file) : null; return fp.file ? fileHandler.getURLSpecFromFile(fp.file) : null;
} }
function GetMetaElement(name) function GetMetaElement(name)

Просмотреть файл

@ -550,7 +550,8 @@ nsHelperAppDialog.prototype = {
// Get the data source; load it synchronously if it must be // Get the data source; load it synchronously if it must be
// initialized. // initialized.
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var fileurl = ioService.getURLSpecFromFile(file); var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
var fileurl = fileHandler.getURLSpecFromFile(file);
var ds = rdf.GetDataSourceBlocking( fileurl ); var ds = rdf.GetDataSourceBlocking( fileurl );

Просмотреть файл

@ -175,10 +175,10 @@ InspectorApp.prototype =
var file = FilePickerUtils.pickFile("Find Search File", path, ["filterXML"], "Open"); var file = FilePickerUtils.pickFile("Find Search File", path, ["filterXML"], "Open");
if (file) { if (file) {
var ioService = XPCU.getService("@mozilla.org/network/io-service;1","nsIIOService"); var ioService = XPCU.getService("@mozilla.org/network/io-service;1","nsIIOService");
var fileHandler = XPCU.QI(ioService.getProtocolHandler("file"), "nsIFileProtocolHandler");
var url = fileHandler.getURLSpecFromFile(file);
var url = ioService.getURLSpecFromFile(file);
// XX temporary until 56354 is fixed
url = url.replace("file://", "file:///");
this.startSearchModule(url); this.startSearchModule(url);
} }
}, },

Просмотреть файл

@ -61,7 +61,9 @@ var DiskSearch =
for (var i = 0; i < aExtList.length; i++) { for (var i = 0; i < aExtList.length; i++) {
extHash[aExtList[i]] = true; extHash[aExtList[i]] = true;
} }
this.ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
this.fileHandler = ios.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
// recursively build the list of results // recursively build the list of results
var results = []; var results = [];
@ -81,7 +83,7 @@ var DiskSearch =
ext = this.getExtension(entry.leafName); ext = this.getExtension(entry.leafName);
if (ext) { if (ext) {
if (aExtHash[ext]) if (aExtHash[ext])
aResults.push(this.ioService.getURLSpecFromFile(entry)); aResults.push(this.fileHandler.getURLSpecFromFile(entry));
} }
} }
}, },

Просмотреть файл

@ -145,8 +145,9 @@ SidebarPrefs.prototype =
return null; return null;
var ioService = XPCU.getService("@mozilla.org/network/io-service;1", "nsIIOService"); var ioService = XPCU.getService("@mozilla.org/network/io-service;1", "nsIIOService");
var fileHandler = XPCU.QI(ioService.getProtocolHandler("file"), "nsIFileProtocolHandler");
return ioService.getURLSpecFromFile(file); return fileHandler.getURLSpecFromFile(file);
} catch (ex) { } catch (ex) {
return null; return null;

Просмотреть файл

@ -518,8 +518,9 @@ inSearchModule.prototype =
var file = XPCU.QI(file, "nsIFile"); var file = XPCU.QI(file, "nsIFile");
var ioService = XPCU.getService("@mozilla.org/network/io-service;1", "nsIIOService"); var ioService = XPCU.getService("@mozilla.org/network/io-service;1", "nsIIOService");
var fileHandler = XPCU.QI(ioService.getProtocolHandler("file"), "nsIFileProtocolHandler");
this.mDialogURL = ioService.getURLSpecFromFile(basefile); this.mDialogURL = fileHandler.getURLSpecFromFile(basefile);
*/ */
} }

Просмотреть файл

@ -496,6 +496,7 @@ function getURLSpecFromFile (file)
const nsIIOService = Components.interfaces.nsIIOService; const nsIIOService = Components.interfaces.nsIIOService;
const nsILocalFile = Components.interfaces.nsILocalFile; const nsILocalFile = Components.interfaces.nsILocalFile;
const nsIFileProtocolHandler = Components.interfaces.nsIFileProtocolHandler;
if (typeof file == "string") if (typeof file == "string")
{ {
@ -506,7 +507,9 @@ function getURLSpecFromFile (file)
} }
var service = Components.classes[IOS_CTRID].getService(nsIIOService); var service = Components.classes[IOS_CTRID].getService(nsIIOService);
return service.getURLSpecFromFile(file); var fileHandler = service.getProtocolHandler("file")
.QueryInterface(nsIFileProtocolHandler);
return fileHandler.getURLSpecFromFile(file);
} }
function getCommonPfx (list) function getCommonPfx (list)

Просмотреть файл

@ -2677,7 +2677,9 @@ var attachmentBucketObserver = {
{ {
var ioService = Components.classes["@mozilla.org/network/io-service;1"] var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService); .getService(Components.interfaces.nsIIOService);
rawData = ioService.getURLSpecFromFile(rawData); var fileHandler = ioService.getProtocolHandler("file")
.QueryInterface(Components.interfaces.nsIFileProtocolHandler);
rawData = fileHandler.getURLSpecFromFile(rawData);
} }
else else
{ {

Просмотреть файл

@ -96,7 +96,7 @@ nsJARURI::SetSpec(const nsACString &aSpec)
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
nsCAutoString scheme; nsCAutoString scheme;
rv = ::ExtractURLScheme(aSpec, nsnull, nsnull, &scheme); rv = net_ExtractURLScheme(aSpec, nsnull, nsnull, &scheme);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
if (strcmp("jar", scheme.get()) != 0) if (strcmp("jar", scheme.get()) != 0)
@ -127,9 +127,9 @@ nsJARURI::SetSpec(const nsACString &aSpec)
while (*delim_end == '/') while (*delim_end == '/')
++delim_end; ++delim_end;
rv = ::ResolveRelativePath(Substring(delim_end, end), rv = net_ResolveRelativePath(Substring(delim_end, end),
NS_LITERAL_CSTRING(""), NS_LITERAL_CSTRING(""),
mJAREntry); mJAREntry);
return rv; return rv;
} }
@ -329,7 +329,7 @@ nsJARURI::Resolve(const nsACString &relativePath, nsACString &result)
nsresult rv; nsresult rv;
nsCAutoString scheme; nsCAutoString scheme;
rv = ::ExtractURLScheme(relativePath, nsnull, nsnull, &scheme); rv = net_ExtractURLScheme(relativePath, nsnull, nsnull, &scheme);
if (NS_SUCCEEDED(rv)) { if (NS_SUCCEEDED(rv)) {
// then aSpec is absolute // then aSpec is absolute
result = relativePath; result = relativePath;
@ -344,8 +344,8 @@ nsJARURI::Resolve(const nsACString &relativePath, nsACString &result)
path = ""; path = "";
nsCAutoString resolvedEntry; nsCAutoString resolvedEntry;
rv = ::ResolveRelativePath(relativePath, path, rv = net_ResolveRelativePath(relativePath, path,
resolvedEntry); resolvedEntry);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
return FormatSpec(resolvedEntry, result); return FormatSpec(resolvedEntry, result);
@ -385,9 +385,9 @@ nsJARURI::SetJAREntry(const nsACString &entryPath)
{ {
mJAREntry.Truncate(); mJAREntry.Truncate();
return ::ResolveRelativePath(entryPath, return net_ResolveRelativePath(entryPath,
NS_LITERAL_CSTRING(""), NS_LITERAL_CSTRING(""),
mJAREntry); mJAREntry);
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////

Просмотреть файл

@ -56,10 +56,6 @@ interface nsIFile;
[scriptable, uuid(bddeda3f-9020-4d12-8c70-984ee9f7935e)] [scriptable, uuid(bddeda3f-9020-4d12-8c70-984ee9f7935e)]
interface nsIIOService : nsISupports interface nsIIOService : nsISupports
{ {
/*************************************************************************
* Protocol handler utilities
*/
/** /**
* Returns a protocol handler for a given URI scheme. * Returns a protocol handler for a given URI scheme.
* *
@ -133,44 +129,18 @@ interface nsIIOService : nsISupports
*/ */
boolean allowPort(in long aPort, in string aScheme); boolean allowPort(in long aPort, in string aScheme);
/*************************************************************************
* URL parsing utilities
*
* The set of methods provided here is intentionally limited. Most of
* Necko's URL parsing functionality is provided via nsIURI. This is
* done to ensure a common point of access to URL parsing, which is
* protocol dependent. Do not try to parse a random URL string as the
* result will likely differ (perhaps only in some subtle way) from the
* value of the corresponding nsIURI attribute. Violating this rule
* may make your code vulnerable to various kinds of security exploits.
* DON'T RISK IT! --darin
*/
/** /**
* Utility to extract the scheme from a URL string, consistently and * Utility to extract the scheme from a URL string, consistently and
* according to spec (see RFC 2396). * according to spec (see RFC 2396).
* *
* NOTE: Most URL parsing is done via nsIURI, and in fact the scheme
* can also be extracted from a URL string via nsIURI. This method
* is provided purely as an optimization.
*
* @param aSpec the URL string to parse * @param aSpec the URL string to parse
* @return URL scheme * @return URL scheme
* *
* @throws NS_ERROR_MALFORMED_URI if URL string is not of the right form. * @throws NS_ERROR_MALFORMED_URI if URL string is not of the right form.
*/ */
ACString extractScheme(in AUTF8String urlString); ACString extractScheme(in AUTF8String urlString);
/**
* Converts the nsIFile to the corresponding URL string. NOTE: under
* some platforms this is a lossy conversion (e.g., Mac Carbon build).
* If the nsIFile is a local file, then the result will be a file://
* URL string.
*
* The resulting string may contain URL-escaped characters.
*/
AUTF8String getURLSpecFromFile(in nsIFile file);
/**
* Converts the URL string into the corresponding nsIFile if possible.
* A local file will be created if the URL string begins with file://.
*/
nsIFile getFileFromURLSpec(in AUTF8String url);
}; };

Просмотреть файл

@ -68,6 +68,7 @@
#include "nsIStreamIO.h" #include "nsIStreamIO.h"
#include "nsIPipe.h" #include "nsIPipe.h"
#include "nsIProtocolHandler.h" #include "nsIProtocolHandler.h"
#include "nsIFileProtocolHandler.h"
#include "nsIStringStream.h" #include "nsIStringStream.h"
#include "nsILocalFile.h" #include "nsILocalFile.h"
#include "nsIFileStreams.h" #include "nsIFileStreams.h"
@ -763,31 +764,45 @@ NS_NewProxyInfo(const char* type, const char* host, PRInt32 port, nsIProxyInfo*
} }
inline nsresult inline nsresult
NS_GetFileFromURLSpec(const nsACString &inURL, nsIFile **result, NS_GetFileProtocolHandler(nsIFileProtocolHandler **result,
nsIIOService *ioService=nsnull) nsIIOService *ioService=nsnull)
{ {
nsresult rv;
nsCOMPtr<nsIIOService> serv; nsCOMPtr<nsIIOService> serv;
if (ioService == nsnull) { if (ioService == nsnull) {
nsresult rv;
serv = do_GetIOService(&rv); serv = do_GetIOService(&rv);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
ioService = serv.get(); ioService = serv.get();
} }
return ioService->GetFileFromURLSpec(inURL, result);
nsCOMPtr<nsIProtocolHandler> handler;
rv = ioService->GetProtocolHandler("file", getter_AddRefs(handler));
if (NS_FAILED(rv)) return rv;
return CallQueryInterface(handler, result);
}
inline nsresult
NS_GetFileFromURLSpec(const nsACString &inURL, nsIFile **result,
nsIIOService *ioService=nsnull)
{
nsCOMPtr<nsIFileProtocolHandler> fileHandler;
nsresult rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
if (NS_FAILED(rv)) return rv;
return fileHandler->GetFileFromURLSpec(inURL, result);
} }
inline nsresult inline nsresult
NS_GetURLSpecFromFile(nsIFile* aFile, nsACString &aUrl, NS_GetURLSpecFromFile(nsIFile* aFile, nsACString &aUrl,
nsIIOService *ioService=nsnull) nsIIOService *ioService=nsnull)
{ {
nsCOMPtr<nsIIOService> serv; nsCOMPtr<nsIFileProtocolHandler> fileHandler;
if (ioService == nsnull) { nsresult rv = NS_GetFileProtocolHandler(getter_AddRefs(fileHandler), ioService);
nsresult rv; if (NS_FAILED(rv)) return rv;
serv = do_GetIOService(&rv);
if (NS_FAILED(rv)) return rv; return fileHandler->GetURLSpecFromFile(aFile, aUrl);
ioService = serv.get();
}
return ioService->GetURLSpecFromFile(aFile, aUrl);
} }
inline nsresult inline nsresult

Просмотреть файл

@ -74,14 +74,14 @@ CPPSRCS = \
$(NULL) $(NULL)
ifeq ($(MOZ_WIDGET_TOOLKIT),os2) ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
CPPSRCS += nsIOServiceOS2.cpp CPPSRCS += nsURLHelperOS2.cpp
else else
ifeq ($(MOZ_WIDGET_TOOLKIT),windows) ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
CPPSRCS += nsIOServiceWin.cpp CPPSRCS += nsURLHelperWin.cpp
CPPSRCS += nsNativeConnectionHelper.cpp CPPSRCS += nsNativeConnectionHelper.cpp
CPPSRCS += nsAutodialWin.cpp CPPSRCS += nsAutodialWin.cpp
else else
CPPSRCS += nsIOServiceUnix.cpp CPPSRCS += nsURLHelperUnix.cpp
endif endif
endif endif

Просмотреть файл

@ -62,6 +62,7 @@ static PRLogModuleInfo* gLog;
#include "nsCollationCID.h" #include "nsCollationCID.h"
#include "nsIPlatformCharset.h" #include "nsIPlatformCharset.h"
#include "nsReadableUtils.h" #include "nsReadableUtils.h"
#include "nsURLHelper.h"
#include "nsNetUtil.h" #include "nsNetUtil.h"
#include "nsCRT.h" #include "nsCRT.h"
@ -216,7 +217,7 @@ nsDirectoryIndexStream::Init(nsIFile* aDir)
mBuf.Append("300: "); mBuf.Append("300: ");
nsCAutoString url; nsCAutoString url;
rv = NS_GetURLSpecFromFile(mDir, url); rv = net_GetURLSpecFromFile(mDir, url);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
mBuf.Append(url); mBuf.Append(url);
mBuf.Append('\n'); mBuf.Append('\n');

Просмотреть файл

@ -58,7 +58,6 @@
#include "nsIPrefBranchInternal.h" #include "nsIPrefBranchInternal.h"
#include "nsIPrefLocalizedString.h" #include "nsIPrefLocalizedString.h"
#include "nsICategoryManager.h" #include "nsICategoryManager.h"
#include "nsIURLParser.h"
#include "nsXPCOM.h" #include "nsXPCOM.h"
#include "nsISupportsPrimitives.h" #include "nsISupportsPrimitives.h"
#include "nsIProxiedProtocolHandler.h" #include "nsIProxiedProtocolHandler.h"
@ -267,13 +266,6 @@ nsIOService::Init()
nsIOService::~nsIOService() nsIOService::~nsIOService()
{ {
// mURLParsers is a voidarray; we must release ourselves
for (PRInt32 i = 0; i < mURLParsers.Count(); i++)
{
nsISupports *temp;
temp = NS_STATIC_CAST(nsISupports*, mURLParsers[i]);
NS_IF_RELEASE(temp);
}
} }
NS_METHOD NS_METHOD
@ -324,7 +316,7 @@ NS_IMPL_THREADSAFE_ISUPPORTS3(nsIOService,
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP nsresult
nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler) nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handler)
{ {
for (unsigned int i=0; i<NS_N(gScheme); i++) for (unsigned int i=0; i<NS_N(gScheme); i++)
@ -351,7 +343,7 @@ nsIOService::CacheProtocolHandler(const char *scheme, nsIProtocolHandler *handle
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
} }
NS_IMETHODIMP nsresult
nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, PRUint32 start, PRUint32 end) nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **result, PRUint32 start, PRUint32 end)
{ {
PRUint32 len = end - start - 1; PRUint32 len = end - start - 1;
@ -378,50 +370,6 @@ nsIOService::GetCachedProtocolHandler(const char *scheme, nsIProtocolHandler **r
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
} }
NS_IMETHODIMP
nsIOService::CacheURLParser(const char *scheme, nsIURLParser *parser)
{
NS_ENSURE_ARG_POINTER(scheme);
NS_ENSURE_ARG_POINTER(parser);
for (PRInt32 i=0; i< (PRInt32) NS_N(gScheme); i++)
{
if (!nsCRT::strcasecmp(scheme, gScheme[i]))
{
// we're going to store this in an nsVoidArray, which extends,
// unlike nsSupportsArray, which doesn't. We must release
// them on delete!
// grab this before overwriting it
nsIURLParser *old_parser;
old_parser = NS_STATIC_CAST(nsIURLParser*,mURLParsers.SafeElementAt(i));
NS_ADDREF(parser);
mURLParsers.ReplaceElementAt(parser, i);
// release any old entry, if any, AFTER adding new entry in
// case they were the same (paranoia)
NS_IF_RELEASE(old_parser);
return NS_OK;
}
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsIOService::GetCachedURLParser(const char *scheme, nsIURLParser **result)
{
PRInt32 count = mURLParsers.Count();
for (PRInt32 i=0; i < count; i++)
{
if (!nsCRT::strcasecmp(scheme, gScheme[i]))
{
*result = NS_STATIC_CAST(nsIURLParser*, mURLParsers[i]);
NS_IF_ADDREF(*result);
return *result ? NS_OK : NS_ERROR_FAILURE;
}
}
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP NS_IMETHODIMP
nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result) nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
{ {
@ -473,238 +421,9 @@ nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
NS_IMETHODIMP NS_IMETHODIMP
nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme) nsIOService::ExtractScheme(const nsACString &inURI, nsACString &scheme)
{ {
return ExtractURLScheme(inURI, nsnull, nsnull, &scheme); return net_ExtractURLScheme(inURI, nsnull, nsnull, &scheme);
} }
NS_METHOD
nsIOService::GetParserForScheme(const char *scheme, nsIURLParser **_retval)
{
nsresult rv;
rv = GetCachedURLParser(scheme, _retval);
if (NS_SUCCEEDED(rv) && *_retval) return NS_OK;
if (!scheme) {
if (!mDefaultURLParser) {
rv = nsServiceManager::GetService(kStdURLParserCID,
NS_GET_IID(nsIURLParser),
getter_AddRefs(mDefaultURLParser));
if (NS_FAILED(rv)) return rv;
}
*_retval = mDefaultURLParser;
NS_ADDREF(*_retval);
return NS_OK;
}
nsCOMPtr<nsICategoryManager> catmgr(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsISimpleEnumerator> parserList;
rv = catmgr->EnumerateCategory(NS_IURLPARSER_KEY, getter_AddRefs(parserList));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsISupportsCString> entry;
// Walk the list of parsers...
while (1) {
rv = parserList->GetNext(getter_AddRefs(entry));
if (NS_FAILED(rv)) break;
// get the entry string
nsCAutoString entryString;
rv = entry->GetData(entryString);
if (NS_FAILED(rv)) break;
if (entryString.Equals(scheme)) {
nsXPIDLCString contractID;
rv = catmgr->GetCategoryEntry(NS_IURLPARSER_KEY, entryString.get(), getter_Copies(contractID));
if (NS_FAILED(rv)) break;
rv = nsServiceManager::GetService(contractID, NS_GET_IID(nsIURLParser), (nsISupports **)_retval);
if (NS_FAILED(rv))
return rv;
if (*_retval)
CacheURLParser(scheme, *_retval);
return *_retval ? NS_OK : NS_ERROR_FAILURE;
}
}
// no registered url parser. Just use the default...
if (!mDefaultURLParser) {
rv = nsServiceManager::GetService(kStdURLParserCID,
NS_GET_IID(nsIURLParser),
getter_AddRefs(mDefaultURLParser));
if (NS_FAILED(rv)) return rv;
}
*_retval = mDefaultURLParser;
NS_ADDREF(*_retval);
CacheURLParser(scheme, *_retval);
return NS_OK;
}
#if 0
static inline void
ExtractUrlPart_Helper(const nsACString &src, PRUint32 pos, PRInt32 len, nsACString &result)
{
if (len >= 0)
result = Substring(src, pos, len);
}
NS_IMETHODIMP
nsIOService::ExtractUrlPart(const nsACString &urlString, PRInt16 flag, nsACString &urlPart)
{
nsresult rv;
nsCAutoString scheme;
rv = ExtractURLScheme(urlString, nsnull, nsnull, &scheme);
if (NS_FAILED(rv)) return rv;
if (flag == url_Scheme) {
urlPart = scheme;
return NS_OK;
}
urlPart.Truncate();
nsCOMPtr<nsIURLParser> parser;
rv = GetParserForScheme(scheme.get(), getter_AddRefs(parser));
if (NS_FAILED(rv)) return rv;
// we work only with flat strings around these parts
const nsPromiseFlatCString &flat = PromiseFlatCString(urlString);
const char *url = flat.get();
PRUint32 authPos, pathPos;
PRInt32 authLen, pathLen;
rv = parser->ParseURL(url, -1,
nsnull, nsnull,
&authPos, &authLen,
&pathPos, &pathLen);
if (NS_FAILED(rv)) return rv;
if (flag == url_Path)
ExtractUrlPart_Helper(urlString, pathPos, pathLen, urlPart);
else if (flag < url_Directory || flag & url_Port) {
PRUint32 usernamePos, passwordPos, hostnamePos;
PRInt32 usernameLen, passwordLen, hostnameLen;
PRInt32 port;
if (authLen < 0)
return NS_OK;
rv = parser->ParseAuthority(url + authPos, authLen,
&usernamePos, &usernameLen,
&passwordPos, &passwordLen,
&hostnamePos, &hostnameLen,
&port);
if (NS_FAILED(rv)) return rv;
usernamePos += authPos;
passwordPos += authPos;
hostnamePos += authPos;
switch (flag) {
case url_Username:
ExtractUrlPart_Helper(urlString, usernamePos, usernameLen, urlPart);
break;
case url_Password:
ExtractUrlPart_Helper(urlString, passwordPos, passwordLen, urlPart);
break;
case url_Host:
ExtractUrlPart_Helper(urlString, hostnamePos, hostnameLen, urlPart);
break;
case url_Port:
if (port != -1) {
PRInt32 pos = hostnamePos + hostnameLen + 1;
ExtractUrlPart_Helper(urlString, pos, pathPos - pos, urlPart);
}
break;
case url_Host | url_Port:
if (port != -1 && hostnameLen > 0) {
urlPart = Substring(urlString, hostnamePos, hostnameLen)
+ NS_LITERAL_CSTRING(":")
+ nsPrintfCString("%d", port);
}
else
ExtractUrlPart_Helper(urlString, hostnamePos, hostnameLen, urlPart);
break;
default:
NS_NOTREACHED("unexpected flag");
return NS_ERROR_UNEXPECTED;
}
}
else {
PRUint32 filepathPos, paramPos, queryPos, refPos;
PRInt32 filepathLen, paramLen, queryLen, refLen;
if (pathLen < 0)
return NS_OK;
rv = parser->ParsePath(url + pathPos, pathLen,
&filepathPos, &filepathLen,
&paramPos, &paramLen,
&queryPos, &queryLen,
&refPos, &refLen);
if (NS_FAILED(rv)) return rv;
filepathPos += pathPos;
paramPos += pathPos;
queryPos += pathPos;
refPos += pathPos;
if (flag < url_Param) {
PRUint32 directoryPos, basenamePos, extensionPos;
PRInt32 directoryLen, basenameLen, extensionLen;
rv = parser->ParseFilePath(url + filepathPos, filepathLen,
&directoryPos, &directoryLen,
&basenamePos, &basenameLen,
&extensionPos, &extensionLen);
directoryPos += filepathPos;
basenamePos += filepathPos;
extensionPos += filepathPos;
switch (flag) {
case url_Directory:
ExtractUrlPart_Helper(urlString, directoryPos, directoryLen, urlPart);
break;
case url_FileBaseName:
ExtractUrlPart_Helper(urlString, basenamePos, basenameLen, urlPart);
break;
case url_FileExtension:
ExtractUrlPart_Helper(urlString, extensionPos, extensionLen, urlPart);
break;
default:
NS_NOTREACHED("unexpected flag");
return NS_ERROR_UNEXPECTED;
}
}
else {
switch (flag) {
case url_Param:
ExtractUrlPart_Helper(urlString, paramPos, paramLen, urlPart);
break;
case url_Query:
ExtractUrlPart_Helper(urlString, queryPos, queryLen, urlPart);
break;
case url_Ref:
ExtractUrlPart_Helper(urlString, refPos, refLen, urlPart);
break;
default:
NS_NOTREACHED("unexpected flag");
return NS_ERROR_UNEXPECTED;
}
}
}
return NS_OK;
}
#endif
NS_IMETHODIMP NS_IMETHODIMP
nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags) nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags)
{ {
@ -716,7 +435,6 @@ nsIOService::GetProtocolFlags(const char* scheme, PRUint32 *flags)
return rv; return rv;
} }
nsresult nsresult
nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result) nsIOService::NewURI(const nsACString &aSpec, const char *aCharset, nsIURI *aBaseURI, nsIURI **result)
{ {
@ -1005,71 +723,3 @@ nsIOService::Observe(nsISupports *subject,
} }
return NS_OK; return NS_OK;
} }
nsresult
nsIOService::ParseFileURL(const nsACString &inURL,
nsACString &outDirectory,
nsACString &outFileBaseName,
nsACString &outFileExtension)
{
nsresult rv;
outDirectory.Truncate();
outFileBaseName.Truncate();
outFileExtension.Truncate();
nsCAutoString scheme;
rv = ExtractScheme(inURL, scheme);
if (NS_FAILED(rv)) return rv;
if (strcmp(scheme.get(), "file") != 0) {
NS_ERROR("must be a file:// url");
return NS_ERROR_UNEXPECTED;
}
const nsPromiseFlatCString &flatURL = PromiseFlatCString(inURL);
const char *url = flatURL.get();
nsCOMPtr<nsIURLParser> parser;
rv = GetParserForScheme(scheme.get(), getter_AddRefs(parser));
if (NS_FAILED(rv)) return rv;
PRUint32 pathPos, filepathPos, directoryPos, basenamePos, extensionPos;
PRInt32 pathLen, filepathLen, directoryLen, basenameLen, extensionLen;
// invoke the parser to extract the URL path
rv = parser->ParseURL(url, -1,
nsnull, nsnull, // dont care about scheme
nsnull, nsnull, // dont care about authority
&pathPos, &pathLen);
if (NS_FAILED(rv)) return rv;
// invoke the parser to extract filepath from the path
rv = parser->ParsePath(url + pathPos, pathLen,
&filepathPos, &filepathLen,
nsnull, nsnull, // dont care about param
nsnull, nsnull, // dont care about query
nsnull, nsnull); // dont care about ref
if (NS_FAILED(rv)) return rv;
filepathPos += pathPos;
// invoke the parser to extract the directory and filename from filepath
rv = parser->ParseFilePath(url + filepathPos, filepathLen,
&directoryPos, &directoryLen,
&basenamePos, &basenameLen,
&extensionPos, &extensionLen);
if (NS_FAILED(rv)) return rv;
if (directoryLen > 0)
outDirectory = Substring(inURL, filepathPos + directoryPos, directoryLen);
if (basenameLen > 0)
outFileBaseName = Substring(inURL, filepathPos + basenamePos, basenameLen);
if (extensionLen > 0)
outFileExtension = Substring(inURL, filepathPos + extensionPos, extensionLen);
// since we are using a no-auth url parser, there will never be a host
// XXX not strictly true... file://localhost/foo/bar.html is a valid URL
return NS_OK;
}

Просмотреть файл

@ -87,45 +87,30 @@ public:
nsIURI* *result, nsIProtocolHandler* *hdlrResult); nsIURI* *result, nsIProtocolHandler* *hdlrResult);
protected: protected:
NS_METHOD GetCachedProtocolHandler(const char *scheme, nsresult GetCachedProtocolHandler(const char *scheme,
nsIProtocolHandler* *hdlrResult, nsIProtocolHandler* *hdlrResult,
PRUint32 start=0, PRUint32 start=0,
PRUint32 end=0); PRUint32 end=0);
NS_METHOD CacheProtocolHandler(const char *scheme, nsresult CacheProtocolHandler(const char *scheme,
nsIProtocolHandler* hdlr); nsIProtocolHandler* hdlr);
NS_METHOD GetCachedURLParser(const char *scheme,
nsIURLParser* *hdlrResult);
NS_METHOD CacheURLParser(const char *scheme,
nsIURLParser* hdlr);
NS_METHOD GetParserForScheme(const char *scheme, nsIURLParser **);
// Prefs wrangling // Prefs wrangling
void PrefsChanged(nsIPrefBranch *prefs, const char *pref = nsnull); void PrefsChanged(nsIPrefBranch *prefs, const char *pref = nsnull);
void GetPrefBranch(nsIPrefBranch **); void GetPrefBranch(nsIPrefBranch **);
void ParsePortList(nsIPrefBranch *prefBranch, const char *pref, PRBool remove); void ParsePortList(nsIPrefBranch *prefBranch, const char *pref, PRBool remove);
nsresult ParseFileURL(const nsACString &inURL,
nsACString &outDirectory,
nsACString &outFileBaseName,
nsACString &outFileExtension);
protected: protected:
PRPackedBool mOffline; PRPackedBool mOffline;
PRPackedBool mOfflineForProfileChange; PRPackedBool mOfflineForProfileChange;
nsCOMPtr<nsISocketTransportService> mSocketTransportService; nsCOMPtr<nsISocketTransportService> mSocketTransportService;
nsCOMPtr<nsIFileTransportService> mFileTransportService; nsCOMPtr<nsIFileTransportService> mFileTransportService;
nsCOMPtr<nsIDNSService> mDNSService; nsCOMPtr<nsIDNSService> mDNSService;
nsCOMPtr<nsIProtocolProxyService> mProxyService; nsCOMPtr<nsIProtocolProxyService> mProxyService;
nsCOMPtr<nsIEventQueueService> mEventQueueService; nsCOMPtr<nsIEventQueueService> mEventQueueService;
// Cached protocol handlers // Cached protocol handlers
nsWeakPtr mWeakHandler[NS_N(gScheme)]; nsWeakPtr mWeakHandler[NS_N(gScheme)];
// Cached url handlers
nsCOMPtr<nsIURLParser> mDefaultURLParser;
nsAutoVoidArray mURLParsers;
nsVoidArray mRestrictedPortList; nsVoidArray mRestrictedPortList;
public: public:

Просмотреть файл

Просмотреть файл

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -57,10 +57,6 @@
static NS_DEFINE_CID(kThisImplCID, NS_THIS_STANDARDURL_IMPL_CID); static NS_DEFINE_CID(kThisImplCID, NS_THIS_STANDARDURL_IMPL_CID);
static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID); static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID);
nsIIOService *nsStandardURL::gIOService = nsnull;
nsIURLParser *nsStandardURL::gNoAuthParser = nsnull;
nsIURLParser *nsStandardURL::gAuthParser = nsnull;
nsIURLParser *nsStandardURL::gStdParser = nsnull;
nsIIDNService *nsStandardURL::gIDNService = nsnull; nsIIDNService *nsStandardURL::gIDNService = nsnull;
nsICharsetConverterManager2 *nsStandardURL::gCharsetMgr = nsnull; nsICharsetConverterManager2 *nsStandardURL::gCharsetMgr = nsnull;
PRBool nsStandardURL::gInitialized = PR_FALSE; PRBool nsStandardURL::gInitialized = PR_FALSE;
@ -329,7 +325,7 @@ nsStandardURL::nsStandardURL()
} }
// default parser in case nsIStandardURL::Init is never called // default parser in case nsIStandardURL::Init is never called
mParser = gStdParser; mParser = net_GetStdURLParser();
} }
nsStandardURL::~nsStandardURL() nsStandardURL::~nsStandardURL()
@ -342,36 +338,6 @@ nsStandardURL::~nsStandardURL()
void void
nsStandardURL::InitGlobalObjects() nsStandardURL::InitGlobalObjects()
{ {
nsCOMPtr<nsIURLParser> parser;
parser = do_GetService(NS_NOAUTHURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'noauth' url parser");
if (parser) {
gNoAuthParser = parser.get();
NS_ADDREF(gNoAuthParser);
}
parser = do_GetService(NS_AUTHURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'auth' url parser");
if (parser) {
gAuthParser = parser.get();
NS_ADDREF(gAuthParser);
}
parser = do_GetService(NS_STDURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'std' url parser");
if (parser) {
gStdParser = parser.get();
NS_ADDREF(gStdParser);
}
nsCOMPtr<nsIIOService> serv(do_GetIOService());
NS_ASSERTION(serv, "failed getting IO service");
if (serv) {
gIOService = serv.get();
NS_ADDREF(gIOService);
}
nsCOMPtr<nsIPrefService> prefService( do_GetService(NS_PREFSERVICE_CONTRACTID) ); nsCOMPtr<nsIPrefService> prefService( do_GetService(NS_PREFSERVICE_CONTRACTID) );
if (prefService) { if (prefService) {
nsCOMPtr<nsIPrefBranch> prefBranch; nsCOMPtr<nsIPrefBranch> prefBranch;
@ -390,10 +356,6 @@ nsStandardURL::InitGlobalObjects()
void void
nsStandardURL::ShutdownGlobalObjects() nsStandardURL::ShutdownGlobalObjects()
{ {
NS_IF_RELEASE(gIOService);
NS_IF_RELEASE(gNoAuthParser);
NS_IF_RELEASE(gAuthParser);
NS_IF_RELEASE(gStdParser);
NS_IF_RELEASE(gIDNService); NS_IF_RELEASE(gIDNService);
NS_IF_RELEASE(gCharsetMgr); NS_IF_RELEASE(gCharsetMgr);
} }
@ -453,7 +415,7 @@ nsStandardURL::EncodeHost(const char *host, nsCString &result)
void void
nsStandardURL::CoalescePath(char *path) nsStandardURL::CoalescePath(char *path)
{ {
CoalesceDirsAbs(path); net_CoalesceDirsAbs(path);
PRInt32 newLen = strlen(path); PRInt32 newLen = strlen(path);
if (newLen < mPath.mLen) { if (newLen < mPath.mLen) {
PRInt32 diff = newLen - mPath.mLen; PRInt32 diff = newLen - mPath.mLen;
@ -549,7 +511,7 @@ nsStandardURL::BuildNormalizedSpec(const char *spec)
if (mScheme.mLen > 0) { if (mScheme.mLen > 0) {
i = AppendSegmentToBuf(buf, i, spec, mScheme); i = AppendSegmentToBuf(buf, i, spec, mScheme);
ToLowerCase(buf + mScheme.mPos, mScheme.mLen); net_ToLowerCase(buf + mScheme.mPos, mScheme.mLen);
i = AppendToBuf(buf, i, "://", 3); i = AppendToBuf(buf, i, "://", 3);
} }
@ -567,7 +529,7 @@ nsStandardURL::BuildNormalizedSpec(const char *spec)
} }
if (mHost.mLen > 0) { if (mHost.mLen > 0) {
i = AppendSegmentToBuf(buf, i, spec, mHost); i = AppendSegmentToBuf(buf, i, spec, mHost);
ToLowerCase(buf + mHost.mPos, mHost.mLen); net_ToLowerCase(buf + mHost.mPos, mHost.mLen);
if (mPort != -1 && mPort != mDefaultPort) { if (mPort != -1 && mPort != mDefaultPort) {
nsCAutoString portbuf; nsCAutoString portbuf;
portbuf.AppendInt(mPort); portbuf.AppendInt(mPort);
@ -1087,7 +1049,7 @@ nsStandardURL::SetScheme(const nsACString &input)
return NS_ERROR_NOT_INITIALIZED; return NS_ERROR_NOT_INITIALIZED;
} }
if (!IsValidScheme(scheme)) { if (!net_IsValidScheme(scheme)) {
NS_ERROR("the given url scheme contains invalid characters"); NS_ERROR("the given url scheme contains invalid characters");
return NS_ERROR_UNEXPECTED; return NS_ERROR_UNEXPECTED;
} }
@ -1105,7 +1067,7 @@ nsStandardURL::SetScheme(const nsACString &input)
// //
// XXX the string code unfortunately doesn't provide a ToLowerCase // XXX the string code unfortunately doesn't provide a ToLowerCase
// that operates on a substring. // that operates on a substring.
ToLowerCase((char *) mSpec.get(), mScheme.mLen); net_ToLowerCase((char *) mSpec.get(), mScheme.mLen);
return NS_OK; return NS_OK;
} }
@ -1542,7 +1504,7 @@ nsStandardURL::Resolve(const nsACString &in, nsACString &out)
LOG(("nsStandardURL::Resolve [this=%p spec=%s relpath=%s]\n", LOG(("nsStandardURL::Resolve [this=%p spec=%s relpath=%s]\n",
this, mSpec.get(), relpath)); this, mSpec.get(), relpath));
NS_ASSERTION(gNoAuthParser, "no parser: unitialized"); NS_ASSERTION(mParser, "no parser: unitialized");
// NOTE: there is no need for this function to produce normalized // NOTE: there is no need for this function to produce normalized
// output. normalization will occur when the result is used to // output. normalization will occur when the result is used to
@ -1562,10 +1524,10 @@ nsStandardURL::Resolve(const nsACString &in, nsACString &out)
// relative urls should never contain a host, so we always want to use // relative urls should never contain a host, so we always want to use
// the noauth url parser. // the noauth url parser.
// use it to extract a possible scheme // use it to extract a possible scheme
rv = gNoAuthParser->ParseURL(relpath, flat.Length(), rv = mParser->ParseURL(relpath, flat.Length(),
&scheme.mPos, &scheme.mLen, &scheme.mPos, &scheme.mLen,
nsnull, nsnull, nsnull, nsnull,
nsnull, nsnull); nsnull, nsnull);
// if the parser fails (for example because there is no valid scheme) // if the parser fails (for example because there is no valid scheme)
// reset the scheme and assume a relative url // reset the scheme and assume a relative url
@ -1638,14 +1600,14 @@ nsStandardURL::Resolve(const nsACString &in, nsACString &out)
return NS_ERROR_OUT_OF_MEMORY; return NS_ERROR_OUT_OF_MEMORY;
if (resultPath) if (resultPath)
CoalesceDirsRel(resultPath); net_CoalesceDirsRel(resultPath);
else { else {
// locate result path // locate result path
resultPath = PL_strstr(*result, "://"); resultPath = PL_strstr(*result, "://");
if (resultPath) { if (resultPath) {
resultPath = PL_strchr(resultPath + 3, '/'); resultPath = PL_strchr(resultPath + 3, '/');
if (resultPath) if (resultPath)
CoalesceDirsRel(resultPath); net_CoalesceDirsRel(resultPath);
} }
} }
// XXX avoid extra copy // XXX avoid extra copy
@ -1888,10 +1850,10 @@ nsStandardURL::SetFilePath(const nsACString &input)
PRInt32 dirLen, baseLen, extLen; PRInt32 dirLen, baseLen, extLen;
nsresult rv; nsresult rv;
rv = gNoAuthParser->ParseFilePath(filepath, -1, rv = mParser->ParseFilePath(filepath, -1,
&dirPos, &dirLen, &dirPos, &dirLen,
&basePos, &baseLen, &basePos, &baseLen,
&extPos, &extLen); &extPos, &extLen);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
// build up new candidate spec // build up new candidate spec
@ -2110,9 +2072,9 @@ nsStandardURL::SetFileName(const nsACString &input)
URLSegment basename, extension; URLSegment basename, extension;
// let the parser locate the basename and extension // let the parser locate the basename and extension
rv = gNoAuthParser->ParseFileName(filename, -1, rv = mParser->ParseFileName(filename, -1,
&basename.mPos, &basename.mLen, &basename.mPos, &basename.mLen,
&extension.mPos, &extension.mLen); &extension.mPos, &extension.mLen);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
if (basename.mLen < 0) { if (basename.mLen < 0) {
@ -2207,7 +2169,7 @@ nsStandardURL::GetFile(nsIFile **result)
return NS_ERROR_FAILURE; return NS_ERROR_FAILURE;
} }
nsresult rv = gIOService->GetFileFromURLSpec(mSpec, result); nsresult rv = net_GetFileFromURLSpec(mSpec, result);
// XXX ultimately, we should probably cache this result to speed // XXX ultimately, we should probably cache this result to speed
// up subsequent calls, but past attempts to do so have been // up subsequent calls, but past attempts to do so have been
@ -2240,7 +2202,7 @@ nsStandardURL::SetFile(nsIFile *file)
nsresult rv; nsresult rv;
nsCAutoString url; nsCAutoString url;
rv = gIOService->GetURLSpecFromFile(file, url); rv = net_GetURLSpecFromFile(file, url);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
rv = SetSpec(url); rv = SetSpec(url);
@ -2274,13 +2236,13 @@ nsStandardURL::Init(PRUint32 urlType,
switch (urlType) { switch (urlType) {
case URLTYPE_STANDARD: case URLTYPE_STANDARD:
mParser = gStdParser; mParser = net_GetStdURLParser();
break; break;
case URLTYPE_AUTHORITY: case URLTYPE_AUTHORITY:
mParser = gAuthParser; mParser = net_GetAuthURLParser();
break; break;
case URLTYPE_NO_AUTHORITY: case URLTYPE_NO_AUTHORITY:
mParser = gNoAuthParser; mParser = net_GetNoAuthURLParser();
break; break;
default: default:
NS_NOTREACHED("bad urlType"); NS_NOTREACHED("bad urlType");
@ -2309,11 +2271,11 @@ nsStandardURL::Init(PRUint32 urlType,
if (baseURI) { if (baseURI) {
PRUint32 start, end; PRUint32 start, end;
// pull out the scheme and where it ends // pull out the scheme and where it ends
nsresult rv = ExtractURLScheme(spec, &start, &end, nsnull); nsresult rv = net_ExtractURLScheme(spec, &start, &end, nsnull);
if (NS_SUCCEEDED(rv) && spec.Length() > end+1) { if (NS_SUCCEEDED(rv) && spec.Length() > end+2) {
nsACString::const_iterator slash; nsACString::const_iterator slash;
spec.BeginReading(slash); spec.BeginReading(slash);
slash.advance(end); slash.advance(end+1);
// then check if // follows // then check if // follows
// if it follows, aSpec is really absolute ... // if it follows, aSpec is really absolute ...
// ignore aBaseURI in this case // ignore aBaseURI in this case
@ -2360,13 +2322,13 @@ nsStandardURL::Read(nsIObjectInputStream *stream)
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
switch (mURLType) { switch (mURLType) {
case URLTYPE_STANDARD: case URLTYPE_STANDARD:
mParser = gStdParser; mParser = net_GetStdURLParser();
break; break;
case URLTYPE_AUTHORITY: case URLTYPE_AUTHORITY:
mParser = gAuthParser; mParser = net_GetAuthURLParser();
break; break;
case URLTYPE_NO_AUTHORITY: case URLTYPE_NO_AUTHORITY:
mParser = gNoAuthParser; mParser = net_GetNoAuthURLParser();
break; break;
default: default:
NS_NOTREACHED("bad urlType"); NS_NOTREACHED("bad urlType");

Просмотреть файл

@ -240,10 +240,6 @@ private:
// global objects. don't use COMPtr as its destructor will cause a // global objects. don't use COMPtr as its destructor will cause a
// coredump if we leak it. // coredump if we leak it.
static nsIIOService *gIOService;
static nsIURLParser *gNoAuthParser;
static nsIURLParser *gAuthParser;
static nsIURLParser *gStdParser;
static nsIIDNService *gIDNService; static nsIIDNService *gIDNService;
static nsICharsetConverterManager2 *gCharsetMgr; static nsICharsetConverterManager2 *gCharsetMgr;
static PRBool gInitialized; static PRBool gInitialized;

Просмотреть файл

@ -20,6 +20,7 @@
* the Initial Developer. All Rights Reserved. * the Initial Developer. All Rights Reserved.
* *
* Contributor(s): * Contributor(s):
* Darin Fisher <darin@netscape.com>
* *
* Alternatively, the contents of this file may be used under the terms of * Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or * either the GNU General Public License Version 2 or later (the "GPL"), or
@ -36,22 +37,178 @@
* ***** END LICENSE BLOCK ***** */ * ***** END LICENSE BLOCK ***** */
#include "nsURLHelper.h" #include "nsURLHelper.h"
#include "prprf.h" #include "nsIServiceManager.h"
#include "nsCRT.h"
#include "nsMemory.h"
#include "nsIIOService.h" #include "nsIIOService.h"
#include "nsIURLParser.h"
#include "nsIURI.h" #include "nsIURI.h"
#include "nsMemory.h"
#include "nsEscape.h" #include "nsEscape.h"
#include "nsCOMPtr.h"
#include "nsCRT.h"
#include "nsNetCID.h"
#include "netCore.h" #include "netCore.h"
#include "prprf.h"
#if defined(XP_WIN) #if defined(XP_WIN)
#include <windows.h> // ::IsDBCSLeadByte need #include <windows.h> // ::IsDBCSLeadByte need
#endif #endif
//----------------------------------------------------------------------------
// Init/Shutdown
//----------------------------------------------------------------------------
static PRBool gInitialized = PR_FALSE;
static nsIURLParser *gNoAuthURLParser = nsnull;
static nsIURLParser *gAuthURLParser = nsnull;
static nsIURLParser *gStdURLParser = nsnull;
static void
InitGlobals()
{
nsCOMPtr<nsIURLParser> parser;
parser = do_GetService(NS_NOAUTHURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'noauth' url parser");
if (parser) {
gNoAuthURLParser = parser.get();
NS_ADDREF(gNoAuthURLParser);
}
parser = do_GetService(NS_AUTHURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'auth' url parser");
if (parser) {
gAuthURLParser = parser.get();
NS_ADDREF(gAuthURLParser);
}
parser = do_GetService(NS_STDURLPARSER_CONTRACTID);
NS_ASSERTION(parser, "failed getting 'std' url parser");
if (parser) {
gStdURLParser = parser.get();
NS_ADDREF(gStdURLParser);
}
gInitialized = PR_TRUE;
}
void
net_ShutdownURLHelper()
{
if (gInitialized) {
NS_IF_RELEASE(gNoAuthURLParser);
NS_IF_RELEASE(gAuthURLParser);
NS_IF_RELEASE(gStdURLParser);
gInitialized = PR_FALSE;
}
}
//----------------------------------------------------------------------------
// nsIURLParser getters
//----------------------------------------------------------------------------
nsIURLParser *
net_GetAuthURLParser()
{
if (!gInitialized)
InitGlobals();
return gAuthURLParser;
}
nsIURLParser *
net_GetNoAuthURLParser()
{
if (!gInitialized)
InitGlobals();
return gNoAuthURLParser;
}
nsIURLParser *
net_GetStdURLParser()
{
if (!gInitialized)
InitGlobals();
return gStdURLParser;
}
//----------------------------------------------------------------------------
// file:// URL parsing
//----------------------------------------------------------------------------
nsresult
net_ParseFileURL(const nsACString &inURL,
nsACString &outDirectory,
nsACString &outFileBaseName,
nsACString &outFileExtension)
{
nsresult rv;
outDirectory.Truncate();
outFileBaseName.Truncate();
outFileExtension.Truncate();
// XXX optimization: no need to copy scheme
PRUint32 schemeBeg, schemeEnd;
rv = net_ExtractURLScheme(inURL, &schemeBeg, &schemeEnd, nsnull);
if (NS_FAILED(rv)) return rv;
if (Substring(inURL, schemeBeg, schemeBeg + schemeEnd) != NS_LITERAL_CSTRING("file")) {
NS_ERROR("must be a file:// url");
return NS_ERROR_UNEXPECTED;
}
const nsPromiseFlatCString &flatURL = PromiseFlatCString(inURL);
const char *url = flatURL.get();
nsIURLParser *parser = net_GetNoAuthURLParser();
NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);
PRUint32 pathPos, filepathPos, directoryPos, basenamePos, extensionPos;
PRInt32 pathLen, filepathLen, directoryLen, basenameLen, extensionLen;
// invoke the parser to extract the URL path
rv = parser->ParseURL(url, flatURL.Length(),
nsnull, nsnull, // dont care about scheme
nsnull, nsnull, // dont care about authority
&pathPos, &pathLen);
if (NS_FAILED(rv)) return rv;
// invoke the parser to extract filepath from the path
rv = parser->ParsePath(url + pathPos, pathLen,
&filepathPos, &filepathLen,
nsnull, nsnull, // dont care about param
nsnull, nsnull, // dont care about query
nsnull, nsnull); // dont care about ref
if (NS_FAILED(rv)) return rv;
filepathPos += pathPos;
// invoke the parser to extract the directory and filename from filepath
rv = parser->ParseFilePath(url + filepathPos, filepathLen,
&directoryPos, &directoryLen,
&basenamePos, &basenameLen,
&extensionPos, &extensionLen);
if (NS_FAILED(rv)) return rv;
if (directoryLen > 0)
outDirectory = Substring(inURL, filepathPos + directoryPos, directoryLen);
if (basenameLen > 0)
outFileBaseName = Substring(inURL, filepathPos + basenamePos, basenameLen);
if (extensionLen > 0)
outFileExtension = Substring(inURL, filepathPos + extensionPos, extensionLen);
// since we are using a no-auth url parser, there will never be a host
// XXX not strictly true... file://localhost/foo/bar.html is a valid URL
return NS_OK;
}
//----------------------------------------------------------------------------
// path manipulation functions
//----------------------------------------------------------------------------
// Replace all /./ with a / while resolving relative URLs // Replace all /./ with a / while resolving relative URLs
// But only till #? // But only till #?
void void
CoalesceDirsRel(char* io_Path) net_CoalesceDirsRel(char* io_Path)
{ {
/* Stolen from the old netlib's mkparse.c. /* Stolen from the old netlib's mkparse.c.
* *
@ -125,7 +282,7 @@ CoalesceDirsRel(char* io_Path)
// Replace all /./ with a / while resolving absolute URLs // Replace all /./ with a / while resolving absolute URLs
// But only till #? // But only till #?
void void
CoalesceDirsAbs(char* io_Path) net_CoalesceDirsAbs(char* io_Path)
{ {
/* Stolen from the old netlib's mkparse.c. /* Stolen from the old netlib's mkparse.c.
* *
@ -214,97 +371,10 @@ CoalesceDirsAbs(char* io_Path)
*(urlPtr-1) = '\0'; *(urlPtr-1) = '\0';
} }
static inline
void ToLower(char &c)
{
if ((unsigned)(c - 'A') <= (unsigned)('Z' - 'A'))
c += 'a' - 'A';
}
void
ToLowerCase(char *str, PRUint32 length)
{
for (char *end = str + length; str < end; ++str)
ToLower(*str);
}
void
ToLowerCase(char *str)
{
for (; *str; ++str)
ToLower(*str);
}
/* Extract URI-Scheme if possible */
nsresult ExtractURLScheme(const nsACString &inURI, PRUint32 *startPos,
PRUint32 *endPos, nsACString *scheme)
{
// search for something up to a colon, and call it the scheme
const nsPromiseFlatCString flatURI( PromiseFlatCString(inURI) );
const char* uri_start = flatURI.get();
const char* uri = uri_start;
// skip leading white space
while (nsCRT::IsAsciiSpace(*uri))
uri++;
PRUint32 start = uri - uri_start;
if (startPos) {
*startPos = start;
}
PRUint32 length = 0;
char c;
while ((c = *uri++) != '\0') {
// First char must be Alpha
if (length == 0 && nsCRT::IsAsciiAlpha(c)) {
length++;
}
// Next chars can be alpha + digit + some special chars
else if (length > 0 && (nsCRT::IsAsciiAlpha(c) ||
nsCRT::IsAsciiDigit(c) || c == '+' ||
c == '.' || c == '-')) {
length++;
}
// stop if colon reached but not as first char
else if (c == ':' && length > 0) {
if (endPos) {
*endPos = start + length + 1;
}
if (scheme)
scheme->Assign(Substring(inURI, start, length));
return NS_OK;
}
else
break;
}
return NS_ERROR_MALFORMED_URI;
}
PRBool
IsValidScheme(const char *scheme, PRUint32 schemeLen)
{
// first char much be alpha
if (!nsCRT::IsAsciiAlpha(*scheme))
return PR_FALSE;
for (; schemeLen && *scheme; ++scheme, --schemeLen) {
if (!(nsCRT::IsAsciiAlpha(*scheme) ||
nsCRT::IsAsciiDigit(*scheme) ||
*scheme == '+' ||
*scheme == '.' ||
*scheme == '-'))
return PR_FALSE;
}
return PR_TRUE;
}
nsresult nsresult
ResolveRelativePath(const nsACString &relativePath, net_ResolveRelativePath(const nsACString &relativePath,
const nsACString &basePath, const nsACString &basePath,
nsACString &result) nsACString &result)
{ {
nsCAutoString name; nsCAutoString name;
nsCAutoString path(basePath); nsCAutoString path(basePath);
@ -370,3 +440,101 @@ ResolveRelativePath(const nsACString &relativePath,
result = path; result = path;
return NS_OK; return NS_OK;
} }
//----------------------------------------------------------------------------
// scheme fu
//----------------------------------------------------------------------------
/* Extract URI-Scheme if possible */
nsresult
net_ExtractURLScheme(const nsACString &inURI,
PRUint32 *startPos,
PRUint32 *endPos,
nsACString *scheme)
{
// search for something up to a colon, and call it the scheme
const nsPromiseFlatCString flatURI( PromiseFlatCString(inURI) );
const char* uri_start = flatURI.get();
const char* uri = uri_start;
// skip leading white space
while (nsCRT::IsAsciiSpace(*uri))
uri++;
PRUint32 start = uri - uri_start;
if (startPos) {
*startPos = start;
}
PRUint32 length = 0;
char c;
while ((c = *uri++) != '\0') {
// First char must be Alpha
if (length == 0 && nsCRT::IsAsciiAlpha(c)) {
length++;
}
// Next chars can be alpha + digit + some special chars
else if (length > 0 && (nsCRT::IsAsciiAlpha(c) ||
nsCRT::IsAsciiDigit(c) || c == '+' ||
c == '.' || c == '-')) {
length++;
}
// stop if colon reached but not as first char
else if (c == ':' && length > 0) {
if (endPos) {
*endPos = start + length;
}
if (scheme)
scheme->Assign(Substring(inURI, start, length));
return NS_OK;
}
else
break;
}
return NS_ERROR_MALFORMED_URI;
}
PRBool
net_IsValidScheme(const char *scheme, PRUint32 schemeLen)
{
// first char much be alpha
if (!nsCRT::IsAsciiAlpha(*scheme))
return PR_FALSE;
for (; schemeLen && *scheme; ++scheme, --schemeLen) {
if (!(nsCRT::IsAsciiAlpha(*scheme) ||
nsCRT::IsAsciiDigit(*scheme) ||
*scheme == '+' ||
*scheme == '.' ||
*scheme == '-'))
return PR_FALSE;
}
return PR_TRUE;
}
//----------------------------------------------------------------------------
// miscellaneous (i.e., stuff that should really be elsewhere)
//----------------------------------------------------------------------------
static inline
void ToLower(char &c)
{
if ((unsigned)(c - 'A') <= (unsigned)('Z' - 'A'))
c += 'a' - 'A';
}
void
net_ToLowerCase(char *str, PRUint32 length)
{
for (char *end = str + length; str < end; ++str)
ToLower(*str);
}
void
net_ToLowerCase(char *str)
{
for (; *str; ++str)
ToLower(*str);
}

Просмотреть файл

@ -35,35 +35,41 @@
* *
* ***** END LICENSE BLOCK ***** */ * ***** END LICENSE BLOCK ***** */
#ifndef _nsURLHelper_h_ #ifndef nsURLHelper_h__
#define _nsURLHelper_h_ #define nsURLHelper_h__
#include "prtypes.h"
#include "nscore.h"
#include "nsCRT.h"
#include "nsString.h" #include "nsString.h"
class nsIFile;
class nsIURLParser;
//----------------------------------------------------------------------------
// This module contains some private helper functions related to URL parsing.
//----------------------------------------------------------------------------
/* shutdown frees URL parser */
void net_ShutdownURLHelper();
/* access URL parsers */
nsIURLParser *net_GetAuthURLParser();
nsIURLParser *net_GetNoAuthURLParser();
nsIURLParser *net_GetStdURLParser();
/* convert between nsIFile and file:// URL spec */
nsresult net_GetURLSpecFromFile(nsIFile *, nsACString &);
nsresult net_GetFileFromURLSpec(const nsACString &, nsIFile **);
/* extract file path components from file:// URL */
nsresult net_ParseFileURL(const nsACString &inURL,
nsACString &outDirectory,
nsACString &outFileBaseName,
nsACString &outFileExtension);
/* handle .. in dirs while resolving relative URLs */ /* handle .. in dirs while resolving relative URLs */
void CoalesceDirsRel(char* io_Path); void net_CoalesceDirsRel(char* io_Path);
/* handle .. in dirs while resolving absolute URLs */ /* handle .. in dirs while resolving absolute URLs */
void CoalesceDirsAbs(char* io_Path); void net_CoalesceDirsAbs(char* io_Path);
/* convert to lower case */
void ToLowerCase(char* str, PRUint32 length);
void ToLowerCase(char* str);
/* Extract URI-Scheme if possible */
nsresult ExtractURLScheme(const nsACString &inURI, PRUint32 *startPos,
PRUint32 *endPos, nsACString *scheme = nsnull);
/* check that the given scheme conforms to RFC 2396 */
PRBool IsValidScheme(const char *scheme, PRUint32 schemeLen);
inline PRBool IsValidScheme(const nsAFlatCString &scheme)
{
return IsValidScheme(scheme.get(), scheme.Length());
}
/** /**
* Resolves a relative path string containing "." and ".." * Resolves a relative path string containing "." and ".."
@ -78,8 +84,33 @@ inline PRBool IsValidScheme(const nsAFlatCString &scheme)
* *
* @return a new string, representing canonical uri * @return a new string, representing canonical uri
*/ */
nsresult ResolveRelativePath(const nsACString &relativePath, nsresult net_ResolveRelativePath(const nsACString &relativePath,
const nsACString &basePath, const nsACString &basePath,
nsACString &result); nsACString &result);
#endif /**
* Extract URI-Scheme if possible
*
* @param inURI URI spec
* @param startPos start of scheme (may be null)
* @param endPos end of scheme; index of colon (may be null)
* @param scheme scheme copied to this buffer on return (may be null)
*/
nsresult net_ExtractURLScheme(const nsACString &inURI,
PRUint32 *startPos,
PRUint32 *endPos,
nsACString *scheme = nsnull);
/* check that the given scheme conforms to RFC 2396 */
PRBool net_IsValidScheme(const char *scheme, PRUint32 schemeLen);
inline PRBool net_IsValidScheme(const nsAFlatCString &scheme)
{
return net_IsValidScheme(scheme.get(), scheme.Length());
}
/* convert to lower case (XXX this needs to be factored out) */
void net_ToLowerCase(char* str, PRUint32 length);
void net_ToLowerCase(char* str);
#endif // !nsURLHelper_h__

Просмотреть файл

@ -0,0 +1,160 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* Mac-specific local file url parsing */
#include "nsURLHelper.h"
#include "nsEscape.h"
#include "nsILocalFile.h"
static void SwapSlashColon(char *s)
{
while (*s) {
if (*s == '/')
*s++ = ':';
else if (*s == ':')
*s++ = '/';
else
*s++;
}
}
static void PascalStringCopy(Str255 dst, const char *src)
{
int srcLength = strlen(src);
NS_ASSERTION(srcLength <= 255, "Oops, Str255 can't hold >255 chars");
if (srcLength > 255)
srcLength = 255;
dst[0] = srcLength;
memcpy(&dst[1], src, srcLength);
}
nsresult
net_GetURLSpecFromFile(nsIFile *aFile, nsACString &aURL)
{
nsresult rv;
NS_ENSURE_ARG(aFile);
nsCAutoString ePath;
// construct URL spec from native file path
rv = aFile->GetNativePath(ePath);
if (NS_FAILED(rv)) return rv;
SwapSlashColon((char *) ePath.get());
nsCAutoString escPath;
NS_NAMED_LITERAL_CSTRING(prefix, "file:///");
// Escape the path with the directory mask
NS_EscapeURL(ePath, esc_Directory|esc_Forced|esc_AlwaysCopy, escPath);
// colons [originally slashes, before SwapSlashColon() usage above]
// need encoding; use %2F which is a forward slash
escPath.ReplaceSubstring(":", "%2F");
escPath.Insert(prefix, 0);
// XXX this should be unnecessary
if (escPath[escPath.Length() - 1] != '/') {
PRBool dir;
rv = aFile->IsDirectory(&dir);
if (NS_FAILED(rv))
NS_WARNING(PromiseFlatCString(
NS_LITERAL_CSTRING("Cannot tell if ") + escPath +
NS_LITERAL_CSTRING(" is a directory or file")).get());
else if (dir) {
// make sure we have a trailing slash
escPath += "/";
}
}
aURL = escPath;
return NS_OK;
}
nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
nsresult rv;
nsCOMPtr<nsILocalFile> localFile(
do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
if (NS_FAILED(rv)) {
NS_ERROR("Only nsILocalFile supported right now");
return rv;
}
nsCAutoString directory, fileBaseName, fileExtension;
rv = net_ParseFileURL(aURL, directory, fileBaseName, fileExtension);
if (NS_FAILED(rv)) return rv;
nsCAutoString path;
if (!directory.IsEmpty()) {
NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
// "%2F"s need to become slashes, while all other slashes need to
// become colons. If we start out by changing "%2F"s to colons, we
// can reply on SwapSlashColon() to do what we need
path.ReplaceSubstring("%2F", ":");
SwapSlashColon((char *) path.get());
}
if (!fileBaseName.IsEmpty())
NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
if (!fileExtension.IsEmpty()) {
path += '.';
NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
}
NS_UnescapeURL(path);
// wack off leading :'s
if (path.CharAt(0) == ':')
path.Cut(0, 1);
// assuming path is encoded in the native charset
rv = localFile->InitWithNativePath(path);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = localFile);
return NS_OK;
}

Просмотреть файл

@ -0,0 +1,179 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* OS/2-specific local file uri parsing */
#define INCL_DOSERRORS
#define INCL_DOS
#include "nsURLHelper.h"
#include "nsEscape.h"
#include "nsILocalFile.h"
static int isleadbyte(int c);
nsresult
net_GetURLSpecFromFile(nsIFile *aFile, nsACString &result)
{
nsresult rv;
nsCAutoString ePath;
// construct URL spec from native file path
rv = aFile->GetNativePath(ePath);
if (NS_FAILED(rv)) return rv;
// Replace \ with / to convert to an url
for (char *s = (char *) ePath.get(); *s; ++s) {
// We need to call isleadbyte because
// Japanese windows can have 0x5C in the sencond byte
// of a Japanese character, for example 0x8F 0x5C is
// one Japanese character
if(isleadbyte(*s) && *(s+1))
++s;
else if (*s == '\\')
*s = '/';
}
nsCAutoString escPath;
NS_NAMED_LITERAL_CSTRING(prefix, "file:///");
// Escape the path with the directory mask
if (NS_EscapeURL(ePath.get(), ePath.Length(), esc_Directory+esc_Forced, escPath))
escPath.Insert(prefix, 0);
else
escPath.Assign(prefix + ePath);
// XXX this should be unnecessary
if (escPath[escPath.Length() - 1] != '/') {
PRBool dir;
rv = aFile->IsDirectory(&dir);
if (NS_FAILED(rv))
NS_WARNING(PromiseFlatCString(
NS_LITERAL_CSTRING("Cannot tell if ") + escPath +
NS_LITERAL_CSTRING(" is a directory or file")).get());
else if (dir) {
// make sure we have a trailing slash
escPath += "/";
}
}
result = escPath;
return NS_OK;
}
nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
nsresult rv;
nsCOMPtr<nsILocalFile> localFile(
do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
if (NS_FAILED(rv)) {
NS_ERROR("Only nsILocalFile supported right now");
return rv;
}
nsCAutoString directory, fileBaseName, fileExtension;
rv = net_ParseFileURL(aURL, directory, fileBaseName, fileExtension);
if (NS_FAILED(rv)) return rv;
nsCAutoString path;
if (!directory.IsEmpty()) {
NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
if (path.Length() > 2 && path.CharAt(2) == '|')
path.SetCharAt(':', 2);
path.ReplaceChar('/', '\\');
}
if (!fileBaseName.IsEmpty())
NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
if (!fileExtension.IsEmpty()) {
path += '.';
NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
}
NS_UnescapeURL(path);
// remove leading '\'
if (path.CharAt(0) == '\\')
path.Cut(0, 1);
// assuming path is encoded in the native charset
rv = localFile->InitWithNativePath(path);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = localFile);
return NS_OK;
}
static int isleadbyte(int c)
{
static BOOL bDBCSFilled=FALSE;
static BYTE DBCSInfo[12] = { 0 }; /* According to the Control Program Guide&Ref,
12 bytes is sufficient */
BYTE *curr;
BOOL retval = FALSE;
if( !bDBCSFilled ) {
COUNTRYCODE ctrycodeInfo = { 0 };
APIRET rc = NO_ERROR;
ctrycodeInfo.country = 0; /* Current Country */
ctrycodeInfo.codepage = 0; /* Current Codepage */
rc = DosQueryDBCSEnv( sizeof( DBCSInfo ),
&ctrycodeInfo,
DBCSInfo );
if( rc != NO_ERROR ) {
/* we had an error, do something? */
return FALSE;
}
bDBCSFilled=TRUE;
}
curr = DBCSInfo;
/* DBCSInfo returned by DosQueryDBCSEnv is terminated with two '0' bytes in a row */
while(( *curr != 0 ) && ( *(curr+1) != 0)) {
if(( c >= *curr ) && ( c <= *(curr+1) )) {
retval=TRUE;
break;
}
curr+=2;
}
return retval;
}

Просмотреть файл

@ -0,0 +1,116 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* Unix-specific local file uri parsing */
#include "nsURLHelper.h"
#include "nsEscape.h"
#include "nsILocalFile.h"
nsresult
net_GetURLSpecFromFile(nsIFile *aFile, nsACString &result)
{
nsresult rv;
nsCAutoString ePath;
// construct URL spec from native file path
rv = aFile->GetNativePath(ePath);
if (NS_FAILED(rv)) return rv;
nsCAutoString escPath;
NS_NAMED_LITERAL_CSTRING(prefix, "file://");
// Escape the path with the directory mask
if (NS_EscapeURL(ePath.get(), ePath.Length(), esc_Directory+esc_Forced, escPath))
escPath.Insert(prefix, 0);
else
escPath.Assign(prefix + ePath);
// XXX this should be unnecessary
if (escPath[escPath.Length() - 1] != '/') {
PRBool dir;
rv = aFile->IsDirectory(&dir);
if (NS_FAILED(rv))
NS_WARNING(PromiseFlatCString(
NS_LITERAL_CSTRING("Cannot tell if ") + escPath +
NS_LITERAL_CSTRING(" is a directory or file")).get());
else if (dir) {
// make sure we have a trailing slash
escPath += "/";
}
}
result = escPath;
return NS_OK;
}
nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
nsresult rv;
nsCOMPtr<nsILocalFile> localFile(
do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
if (NS_FAILED(rv)) {
NS_ERROR("Only nsILocalFile supported right now");
return rv;
}
nsCAutoString directory, fileBaseName, fileExtension, path;
rv = net_ParseFileURL(aURL, directory, fileBaseName, fileExtension);
if (NS_FAILED(rv)) return rv;
if (!directory.IsEmpty())
NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
if (!fileBaseName.IsEmpty())
NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
if (!fileExtension.IsEmpty()) {
path += '.';
NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
}
NS_UnescapeURL(path);
// assuming path is encoded in the native charset
rv = localFile->InitWithNativePath(path);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = localFile);
return NS_OK;
}

Просмотреть файл

@ -0,0 +1,139 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Alec Flett <alecf@netscape.com>
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* Windows-specific local file uri parsing */
#include "nsURLHelper.h"
#include "nsEscape.h"
#include "nsILocalFile.h"
#include <windows.h>
nsresult
net_GetURLSpecFromFile(nsIFile *aFile, nsACString &result)
{
nsresult rv;
nsCAutoString ePath;
// construct URL spec from native file path
rv = aFile->GetNativePath(ePath);
if (NS_FAILED(rv)) return rv;
// Replace \ with / to convert to an url
for (char *s = (char *) ePath.get(); *s; ++s) {
// We need to call IsDBCSLeadByte because
// Japanese windows can have 0x5C in the second byte
// of a Japanese character, for example 0x8F 0x5C is
// one Japanese character
if(::IsDBCSLeadByte(*s) && *(s+1))
++s;
else if (*s == '\\')
*s = '/';
}
nsCAutoString escPath;
NS_NAMED_LITERAL_CSTRING(prefix, "file:///");
// Escape the path with the directory mask
if (NS_EscapeURL(ePath.get(), ePath.Length(), esc_Directory+esc_Forced, escPath))
escPath.Insert(prefix, 0);
else
escPath.Assign(prefix + ePath);
// XXX this should be unnecessary
if (escPath[escPath.Length() - 1] != '/') {
PRBool dir;
rv = aFile->IsDirectory(&dir);
if (NS_FAILED(rv))
NS_WARNING(PromiseFlatCString(
NS_LITERAL_CSTRING("Cannot tell if ") + escPath +
NS_LITERAL_CSTRING(" is a directory or file")).get());
else if (dir) {
// make sure we have a trailing slash
escPath += "/";
}
}
result = escPath;
return NS_OK;
}
nsresult
net_GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
nsresult rv;
nsCOMPtr<nsILocalFile> localFile(
do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
if (NS_FAILED(rv)) {
NS_ERROR("Only nsILocalFile supported right now");
return rv;
}
nsCAutoString directory, fileBaseName, fileExtension;
rv = net_ParseFileURL(aURL, directory, fileBaseName, fileExtension);
if (NS_FAILED(rv)) return rv;
nsCAutoString path;
if (!directory.IsEmpty()) {
NS_EscapeURL(directory, esc_Directory|esc_AlwaysCopy, path);
if (path.Length() > 2 && path.CharAt(2) == '|')
path.SetCharAt(':', 2);
path.ReplaceChar('/', '\\');
}
if (!fileBaseName.IsEmpty())
NS_EscapeURL(fileBaseName, esc_FileBaseName|esc_AlwaysCopy, path);
if (!fileExtension.IsEmpty()) {
path += '.';
NS_EscapeURL(fileExtension, esc_FileExtension|esc_AlwaysCopy, path);
}
NS_UnescapeURL(path);
// remove leading '\'
if (path.CharAt(0) == '\\')
path.Cut(0, 1);
// assuming path is encoded in the native charset
rv = localFile->InitWithNativePath(path);
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = localFile);
return NS_OK;
}

Просмотреть файл

@ -144,7 +144,7 @@ nsBaseURLParser::ParseURL(const char *spec, PRInt32 specLen,
// spec = <scheme>:<authority> // spec = <scheme>:<authority>
// spec = <scheme>:<path-no-slashes> // spec = <scheme>:<path-no-slashes>
// //
if (!IsValidScheme(spec, colon - spec) || (*(colon+1) == ':')) { if (!net_IsValidScheme(spec, colon - spec) || (*(colon+1) == ':')) {
NS_WARNING("malformed uri"); NS_WARNING("malformed uri");
return NS_ERROR_MALFORMED_URI; return NS_ERROR_MALFORMED_URI;
} }

Просмотреть файл

@ -147,71 +147,6 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsResumableEntityID)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
static NS_METHOD
RegisterBuiltInURLParsers(nsIComponentManager *aCompMgr,
nsIFile *aPath,
const char *registryLocation,
const char *componentType,
const nsModuleComponentInfo *info)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsXPIDLCString previous;
catman->AddCategoryEntry(NS_IURLPARSER_KEY,
"file",
NS_NOAUTHURLPARSER_CONTRACTID,
PR_TRUE,
PR_TRUE,
getter_Copies(previous));
catman->AddCategoryEntry(NS_IURLPARSER_KEY,
"ftp",
NS_AUTHURLPARSER_CONTRACTID,
PR_TRUE,
PR_TRUE,
getter_Copies(previous));
catman->AddCategoryEntry(NS_IURLPARSER_KEY,
"http",
NS_AUTHURLPARSER_CONTRACTID,
PR_TRUE,
PR_TRUE,
getter_Copies(previous));
catman->AddCategoryEntry(NS_IURLPARSER_KEY,
"https",
NS_AUTHURLPARSER_CONTRACTID,
PR_TRUE,
PR_TRUE,
getter_Copies(previous));
return NS_OK;
}
static NS_METHOD
UnregisterBuiltInURLParsers(nsIComponentManager *aCompMgr,
nsIFile *aPath,
const char *registryLocation,
const nsModuleComponentInfo *info)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> catman =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
catman->DeleteCategoryEntry(NS_IURLPARSER_KEY, "file", PR_TRUE);
catman->DeleteCategoryEntry(NS_IURLPARSER_KEY, "ftp", PR_TRUE);
catman->DeleteCategoryEntry(NS_IURLPARSER_KEY, "http", PR_TRUE);
catman->DeleteCategoryEntry(NS_IURLPARSER_KEY, "https", PR_TRUE);
return NS_OK;
}
///////////////////////////////////////////////////////////////////////////////
#include "nsFileChannel.h" #include "nsFileChannel.h"
#include "nsFileProtocolHandler.h" #include "nsFileProtocolHandler.h"
#include "nsDataHandler.h" #include "nsDataHandler.h"
@ -554,6 +489,9 @@ static void PR_CALLBACK nsNeckoShutdown(nsIModule *neckoModule)
// Release buffer cache // Release buffer cache
NS_IF_RELEASE(nsIOService::gBufferCache); NS_IF_RELEASE(nsIOService::gBufferCache);
// Release global state used by the URL helper module.
net_ShutdownURLHelper();
} }
static const nsModuleComponentInfo gNetModuleInfo[] = { static const nsModuleComponentInfo gNetModuleInfo[] = {
@ -671,9 +609,7 @@ static const nsModuleComponentInfo gNetModuleInfo[] = {
{ NS_STDURLPARSER_CLASSNAME, { NS_STDURLPARSER_CLASSNAME,
NS_STDURLPARSER_CID, NS_STDURLPARSER_CID,
NS_STDURLPARSER_CONTRACTID, NS_STDURLPARSER_CONTRACTID,
nsStdURLParserConstructor, nsStdURLParserConstructor},
RegisterBuiltInURLParsers,
UnregisterBuiltInURLParsers},
{ NS_NOAUTHURLPARSER_CLASSNAME, { NS_NOAUTHURLPARSER_CLASSNAME,
NS_NOAUTHURLPARSER_CID, NS_NOAUTHURLPARSER_CID,
NS_NOAUTHURLPARSER_CONTRACTID, NS_NOAUTHURLPARSER_CONTRACTID,

Просмотреть файл

@ -1599,7 +1599,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS>Debug</FILEFLAGS> <FILEFLAGS>Debug</FILEFLAGS>
@ -2065,7 +2065,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -3621,7 +3621,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS>Debug</FILEFLAGS> <FILEFLAGS>Debug</FILEFLAGS>
@ -4087,7 +4087,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -5629,7 +5629,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS>Debug</FILEFLAGS> <FILEFLAGS>Debug</FILEFLAGS>
@ -6085,7 +6085,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -7627,7 +7627,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS>Debug</FILEFLAGS> <FILEFLAGS>Debug</FILEFLAGS>
@ -8083,7 +8083,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -8161,7 +8161,7 @@
<FILEREF> <FILEREF>
<TARGETNAME>Necko.shlb</TARGETNAME> <TARGETNAME>Necko.shlb</TARGETNAME>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>nsIOServiceMac.cpp</PATH> <PATH>nsURLHelperMac.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>

Просмотреть файл

@ -50,4 +50,20 @@ interface nsIFileProtocolHandler : nsIProtocolHandler
* @return reference to a new nsIURI object * @return reference to a new nsIURI object
*/ */
nsIURI newFileURI(in nsIFile aFile); nsIURI newFileURI(in nsIFile aFile);
/**
* Converts the nsIFile to the corresponding URL string. NOTE: under
* some platforms this is a lossy conversion (e.g., Mac Carbon build).
* If the nsIFile is a local file, then the result will be a file://
* URL string.
*
* The resulting string may contain URL-escaped characters.
*/
AUTF8String getURLSpecFromFile(in nsIFile file);
/**
* Converts the URL string into the corresponding nsIFile if possible.
* A local file will be created if the URL string begins with file://.
*/
nsIFile getFileFromURLSpec(in AUTF8String url);
}; };

Просмотреть файл

@ -44,6 +44,10 @@ CPPSRCS = \
# static lib. # static lib.
FORCE_STATIC_LIB = 1 FORCE_STATIC_LIB = 1
LOCAL_INCLUDES = \
-I$(topsrcdir)/netwerk/base/src \
$(NULL)
include $(topsrcdir)/config/rules.mk include $(topsrcdir)/config/rules.mk
ifeq ($(OS_ARCH),WINNT) ifeq ($(OS_ARCH),WINNT)

Просмотреть файл

@ -55,6 +55,7 @@
#include "nsAutoLock.h" #include "nsAutoLock.h"
#include "nsXPIDLString.h" #include "nsXPIDLString.h"
#include "nsNetCID.h" #include "nsNetCID.h"
#include "nsURLHelper.h"
static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID); static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID);
static NS_DEFINE_CID(kPrefCID, NS_PREF_CID); static NS_DEFINE_CID(kPrefCID, NS_PREF_CID);
@ -204,3 +205,15 @@ nsFileProtocolHandler::NewFileURI(nsIFile *file, nsIURI **result)
return CallQueryInterface(url, result); return CallQueryInterface(url, result);
} }
NS_IMETHODIMP
nsFileProtocolHandler::GetURLSpecFromFile(nsIFile *aFile, nsACString &result)
{
return net_GetURLSpecFromFile(aFile, result);
}
NS_IMETHODIMP
nsFileProtocolHandler::GetFileFromURLSpec(const nsACString &aURL, nsIFile **result)
{
return net_GetFileFromURLSpec(aURL, result);
}

Просмотреть файл

@ -123,14 +123,6 @@ struct nsHttp
// utilities... // utilities...
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
static inline nsresult
DupString(const char *src, char **dst)
{
NS_ENSURE_ARG_POINTER(dst);
*dst = PL_strdup(src);
return *dst ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
static inline PRUint32 static inline PRUint32
PRTimeToSeconds(PRTime t_usec) PRTimeToSeconds(PRTime t_usec)
{ {

Просмотреть файл

@ -96,7 +96,7 @@ nsJARURI::SetSpec(const nsACString &aSpec)
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
nsCAutoString scheme; nsCAutoString scheme;
rv = ::ExtractURLScheme(aSpec, nsnull, nsnull, &scheme); rv = net_ExtractURLScheme(aSpec, nsnull, nsnull, &scheme);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
if (strcmp("jar", scheme.get()) != 0) if (strcmp("jar", scheme.get()) != 0)
@ -127,9 +127,9 @@ nsJARURI::SetSpec(const nsACString &aSpec)
while (*delim_end == '/') while (*delim_end == '/')
++delim_end; ++delim_end;
rv = ::ResolveRelativePath(Substring(delim_end, end), rv = net_ResolveRelativePath(Substring(delim_end, end),
NS_LITERAL_CSTRING(""), NS_LITERAL_CSTRING(""),
mJAREntry); mJAREntry);
return rv; return rv;
} }
@ -329,7 +329,7 @@ nsJARURI::Resolve(const nsACString &relativePath, nsACString &result)
nsresult rv; nsresult rv;
nsCAutoString scheme; nsCAutoString scheme;
rv = ::ExtractURLScheme(relativePath, nsnull, nsnull, &scheme); rv = net_ExtractURLScheme(relativePath, nsnull, nsnull, &scheme);
if (NS_SUCCEEDED(rv)) { if (NS_SUCCEEDED(rv)) {
// then aSpec is absolute // then aSpec is absolute
result = relativePath; result = relativePath;
@ -344,8 +344,8 @@ nsJARURI::Resolve(const nsACString &relativePath, nsACString &result)
path = ""; path = "";
nsCAutoString resolvedEntry; nsCAutoString resolvedEntry;
rv = ::ResolveRelativePath(relativePath, path, rv = net_ResolveRelativePath(relativePath, path,
resolvedEntry); resolvedEntry);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
return FormatSpec(resolvedEntry, result); return FormatSpec(resolvedEntry, result);
@ -385,9 +385,9 @@ nsJARURI::SetJAREntry(const nsACString &entryPath)
{ {
mJAREntry.Truncate(); mJAREntry.Truncate();
return ::ResolveRelativePath(entryPath, return net_ResolveRelativePath(entryPath,
NS_LITERAL_CSTRING(""), NS_LITERAL_CSTRING(""),
mJAREntry); mJAREntry);
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////

Просмотреть файл

@ -49,6 +49,7 @@
#include "nsIFile.h" #include "nsIFile.h"
#include "nsDirectoryServiceDefs.h" #include "nsDirectoryServiceDefs.h"
#include "nsNetUtil.h" #include "nsNetUtil.h"
#include "nsURLHelper.h"
static nsResProtocolHandler *gResHandler = nsnull; static nsResProtocolHandler *gResHandler = nsnull;
@ -91,7 +92,7 @@ nsResURL::GetFile(nsIFile **result)
rv = gResHandler->ResolveURI(this, spec); rv = gResHandler->ResolveURI(this, spec);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
return NS_GetFileFromURLSpec(spec, result, gResHandler->mIOService); return net_GetFileFromURLSpec(spec, result);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------

Просмотреть файл

@ -44,6 +44,7 @@
#include "nsIDirIndex.h" #include "nsIDirIndex.h"
#include "prtime.h" #include "prtime.h"
#include "nsDateTimeFormatCID.h" #include "nsDateTimeFormatCID.h"
#include "nsURLHelper.h"
#include "nsCRT.h" #include "nsCRT.h"
NS_IMPL_THREADSAFE_ISUPPORTS4(nsIndexedToHTML, NS_IMPL_THREADSAFE_ISUPPORTS4(nsIndexedToHTML,
@ -208,7 +209,7 @@ nsIndexedToHTML::OnStartRequest(nsIRequest* request, nsISupports *aContext) {
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
nsCAutoString url; nsCAutoString url;
rv = NS_GetURLSpecFromFile(file, url); rv = net_GetURLSpecFromFile(file, url);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
baseUri.Assign(url); baseUri.Assign(url);
@ -216,7 +217,7 @@ nsIndexedToHTML::OnStartRequest(nsIRequest* request, nsISupports *aContext) {
rv = file->GetParent(getter_AddRefs(parent)); rv = file->GetParent(getter_AddRefs(parent));
if (parent && NS_SUCCEEDED(rv)) { if (parent && NS_SUCCEEDED(rv)) {
NS_GetURLSpecFromFile(parent, url); net_GetURLSpecFromFile(parent, url);
if (NS_FAILED(rv)) return rv; if (NS_FAILED(rv)) return rv;
parentStr.Assign(url); parentStr.Assign(url);
} }

Просмотреть файл

@ -281,7 +281,9 @@ function getNormalizedURL(url)
kLF.initWithPath(url); kLF.initWithPath(url);
if (kLF.exists()) { if (kLF.exists()) {
var ioService = Components.classes["@mozilla.org/network/io-service;1"] var ioService = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.classes.nsIIOService); .getService(Components.interfaces.nsIIOService);
var fileHandler = ioService.getProtocolHandler("file")
.QueryInterface(Components.interfaces.nsIFileProtocolHandler);
url = ioService.getURLSpecFromFile(kLF); url = ioService.getURLSpecFromFile(kLF);
} }

Просмотреть файл

@ -183,7 +183,8 @@
fileLocator = fileLocator.QueryInterface(Components.interfaces.nsIProperties); fileLocator = fileLocator.QueryInterface(Components.interfaces.nsIProperties);
var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile); var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile);
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
gDS = gRDF.GetDataSource(ioService.getURLSpecFromFile(file)); var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
gDS = gRDF.GetDataSource(fileHandler.getURLSpecFromFile(file));
} }
function onAccept() function onAccept()

Просмотреть файл

@ -99,8 +99,9 @@ function onOK()
var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile); var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile);
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
gDS = gRDF.GetDataSource(ioService.getURLSpecFromFile(file)); gDS = gRDF.GetDataSource(fileHandler.getURLSpecFromFile(file));
gMIMEField.value = gMIMEField.value.toLowerCase(); gMIMEField.value = gMIMEField.value.toLowerCase();

Просмотреть файл

@ -89,8 +89,9 @@ function Startup()
var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile); var file = fileLocator.get(mimeTypes, Components.interfaces.nsIFile);
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
dump("spec is " + ioService.getURLSpecFromFile(file)); var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
gDS = gRDF.GetDataSource(ioService.getURLSpecFromFile(file)); dump("spec is " + fileHandler.getURLSpecFromFile(file));
gDS = gRDF.GetDataSource(fileHandler.getURLSpecFromFile(file));
// intialize the listbox // intialize the listbox
gList.database.AddDataSource(gDS); gList.database.AddDataSource(gDS);

Просмотреть файл

@ -868,8 +868,9 @@ function get_sidebar_datasource_uri() {
var sidebar_file = sidebar_get_panels_file(); var sidebar_file = sidebar_get_panels_file();
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
return ioService.getURLSpecFromFile(sidebar_file); return fileHandler.getURLSpecFromFile(sidebar_file);
} catch (ex) { } catch (ex) {
// This should not happen // This should not happen
debug("Error: Unable to load panels file.\n"); debug("Error: Unable to load panels file.\n");

Просмотреть файл

@ -429,7 +429,8 @@ function getSidebarDatasourceURI(panels_file_id)
} }
var io_service = Components.classes[IO_SERV_CONTRACTID].getService(Components.interfaces.nsIIOService); var io_service = Components.classes[IO_SERV_CONTRACTID].getService(Components.interfaces.nsIIOService);
var sidebar_uri = io_service.getURLSpecFromFile(sidebar_file); var file_handler = io_service.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler);
var sidebar_uri = file_handler.getURLSpecFromFile(sidebar_file);
debug("sidebar uri is " + sidebar_uri); debug("sidebar uri is " + sidebar_uri);
return sidebar_uri; return sidebar_uri;
} }