Compare commits

..

10 Commits

Author SHA1 Message Date
ruslan%netscape.com
ff633f8d60 Merging the last change
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62499 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-09 22:49:20 +00:00
ruslan%netscape.com
22361789fb Preparing form carpool. Merge resent changes from the tip
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62491 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-09 21:54:50 +00:00
ruslan%netscape.com
9c456185f6 Remove erroneous comment
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62410 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-08 23:59:50 +00:00
ruslan%netscape.com
b36ebbf0e0 Fix chunk-encoding case of 1.1 with keep-alive
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62404 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-08 21:09:36 +00:00
ruslan%netscape.com
49f393c539 Finalize keep-alive business
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62369 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-08 02:47:40 +00:00
(no author)
65fc46a090 This commit was manufactured by cvs2svn to create branch
'http11_tmp_branch'.

git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62264 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-06 15:09:50 +00:00
ruslan%netscape.com
28927614a1 More of 1.1 changes
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62202 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-04 01:59:47 +00:00
ruslan%netscape.com
0a0b6a0cd3 Forgot IDL and make files/http11_tmp_branch
git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62156 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-03 21:34:41 +00:00
ruslan%netscape.com
193207cbf5 Hook up chunk-encoding and some keep-alive changes; http11_tmp_branch till
the tree opens up again.


git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62150 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-03 20:06:30 +00:00
(no author)
4da7d69865 This commit was manufactured by cvs2svn to create branch
'http11_tmp_branch'.

git-svn-id: svn://10.0.0.236/branches/http11_tmp_branch@62125 18797224-902f-48f8-a5cc-f745e15eee43
2000-03-03 06:49:24 +00:00
486 changed files with 69665 additions and 33 deletions

View File

@@ -0,0 +1,41 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
LIBRARY_NAME = necko_datetime
IS_COMPONENT = 1
CPPSRCS = \
nsDateTimeHandler.cpp \
nsDateTimeChannel.cpp \
nsDateTimeModule.cpp \
$(NULL)
EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,333 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
// datetime implementation
#include "nsDateTimeChannel.h"
#include "nsIServiceManager.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsXPIDLString.h"
#include "nsISocketTransportService.h"
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
// nsDateTimeChannel methods
nsDateTimeChannel::nsDateTimeChannel() {
NS_INIT_REFCNT();
mContentLength = -1;
mPort = -1;
}
nsDateTimeChannel::~nsDateTimeChannel() {
}
NS_IMPL_ISUPPORTS4(nsDateTimeChannel, nsIChannel, nsIRequest, nsIStreamListener, nsIStreamObserver)
nsresult
nsDateTimeChannel::Init(const char* verb,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize)
{
nsresult rv;
NS_ASSERTION(uri, "no uri");
mOriginalURI = originalURI ? originalURI : uri;
mUrl = uri;
rv = mUrl->GetPort(&mPort);
if (NS_FAILED(rv) || mPort < 1)
mPort = DATETIME_PORT;
rv = mUrl->GetPath(getter_Copies(mHost));
if (NS_FAILED(rv)) return rv;
if (!*(const char *)mHost) return NS_ERROR_NOT_INITIALIZED;
rv = SetLoadAttributes(loadAttributes);
if (NS_FAILED(rv)) return rv;
rv = SetLoadGroup(aLoadGroup);
if (NS_FAILED(rv)) return rv;
rv = SetNotificationCallbacks(notificationCallbacks);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
NS_METHOD
nsDateTimeChannel::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
{
nsDateTimeChannel* dc = new nsDateTimeChannel();
if (dc == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(dc);
nsresult rv = dc->QueryInterface(aIID, aResult);
NS_RELEASE(dc);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsDateTimeChannel::IsPending(PRBool *result)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::Cancel(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::Suspend(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::Resume(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods:
NS_IMETHODIMP
nsDateTimeChannel::GetOriginalURI(nsIURI * *aURI)
{
*aURI = mOriginalURI;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetURI(nsIURI * *aURI)
{
*aURI = mUrl;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::OpenInputStream(PRUint32 startPosition, PRInt32 readCount,
nsIInputStream **_retval)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->OpenInputStream(startPosition, readCount, _retval);
}
NS_IMETHODIMP
nsDateTimeChannel::OpenOutputStream(PRUint32 startPosition, nsIOutputStream **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncOpen(nsIStreamObserver *observer, nsISupports* ctxt)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->AsyncOpen(observer, ctxt);
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncRead(PRUint32 startPosition, PRInt32 readCount,
nsISupports *ctxt,
nsIStreamListener *aListener)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
mListener = aListener;
return channel->AsyncRead(startPosition, readCount, ctxt, this);
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncWrite(nsIInputStream *fromStream,
PRUint32 startPosition,
PRInt32 writeCount,
nsISupports *ctxt,
nsIStreamObserver *observer)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetLoadAttributes(PRUint32 *aLoadAttributes)
{
*aLoadAttributes = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetLoadAttributes(PRUint32 aLoadAttributes)
{
mLoadAttributes = aLoadAttributes;
return NS_OK;
}
#define DATETIME_TYPE "text/plain"
NS_IMETHODIMP
nsDateTimeChannel::GetContentType(char* *aContentType) {
if (!aContentType) return NS_ERROR_NULL_POINTER;
*aContentType = nsCRT::strdup(DATETIME_TYPE);
if (!*aContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetContentType(const char *aContentType)
{
//It doesn't make sense to set the content-type on this type
// of channel...
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsDateTimeChannel::GetContentLength(PRInt32 *aContentLength)
{
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
if (mLoadGroup) // if we already had a load group remove ourselves...
(void)mLoadGroup->RemoveChannel(this, nsnull, nsnull, nsnull);
mLoadGroup = aLoadGroup;
if (mLoadGroup) {
return mLoadGroup->AddChannel(this, nsnull);
}
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetOwner(nsISupports* *aOwner)
{
*aOwner = mOwner.get();
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHODIMP
nsDateTimeChannel::OnStartRequest(nsIChannel *aChannel, nsISupports *aContext) {
return mListener->OnStartRequest(this, aContext);
}
NS_IMETHODIMP
nsDateTimeChannel::OnStopRequest(nsIChannel* aChannel, nsISupports* aContext,
nsresult aStatus, const PRUnichar* aMsg) {
if (mLoadGroup) {
nsresult rv = mLoadGroup->RemoveChannel(this, nsnull, aStatus, aMsg);
if (NS_FAILED(rv)) return rv;
}
return mListener->OnStopRequest(this, aContext, aStatus, aMsg);
}
// nsIStreamListener method
NS_IMETHODIMP
nsDateTimeChannel::OnDataAvailable(nsIChannel* aChannel, nsISupports* aContext,
nsIInputStream *aInputStream, PRUint32 aSourceOffset,
PRUint32 aLength) {
mContentLength = aLength;
return mListener->OnDataAvailable(this, aContext, aInputStream, aSourceOffset, aLength);
}

View File

@@ -0,0 +1,84 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
// A datetime channel retrieves date time information from
// RFC 867 compliant datetime servers. The date/time returned
// to the caller is of MIME type "text/plain".
#ifndef nsDateTimeChannel_h___
#define nsDateTimeChannel_h___
#include "nsString2.h"
#include "nsILoadGroup.h"
#include "nsIInputStream.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsDateTimeHandler.h"
#include "nsIStreamListener.h"
class nsDateTimeChannel : public nsIChannel, public nsIStreamListener {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMOBSERVER
// nsDateTimeChannel methods:
nsDateTimeChannel();
virtual ~nsDateTimeChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
nsresult Init(const char* verb,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsCOMPtr<nsIURI> mUrl;
nsCOMPtr<nsIStreamListener> mListener;
PRUint32 mLoadAttributes;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCString mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsISupports> mOwner;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRInt32 mPort;
nsXPIDLCString mHost;
};
#endif /* nsDateTimeChannel_h___ */

View File

@@ -0,0 +1,124 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nspr.h"
#include "nsDateTimeChannel.h"
#include "nsDateTimeHandler.h"
#include "nsIURL.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIProgressEventSink.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsDateTimeHandler::nsDateTimeHandler() {
NS_INIT_REFCNT();
}
nsDateTimeHandler::~nsDateTimeHandler() {
}
NS_IMPL_ISUPPORTS(nsDateTimeHandler, NS_GET_IID(nsIProtocolHandler));
NS_METHOD
nsDateTimeHandler::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult) {
nsDateTimeHandler* ph = new nsDateTimeHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->QueryInterface(aIID, aResult);
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsDateTimeHandler::GetScheme(char* *result) {
*result = nsCRT::strdup("datetime");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeHandler::GetDefaultPort(PRInt32 *result) {
*result = DATETIME_PORT;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result) {
nsresult rv;
// no concept of a relative datetime url
NS_ASSERTION(!aBaseURI, "base url passed into datetime protocol handler");
nsIURI* url;
rv = nsComponentManager::CreateInstance(kSimpleURICID, nsnull,
NS_GET_IID(nsIURI),
(void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsDateTimeHandler::NewChannel(const char* verb, nsIURI* url,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel* *result)
{
nsresult rv;
nsDateTimeChannel* channel;
rv = nsDateTimeChannel::Create(nsnull, NS_GET_IID(nsIChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(verb, url, aLoadGroup, notificationCallbacks,
loadAttributes, originalURI, bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,51 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
// The datetime protocol handler creates "datetime" URIs of the form
// "datetime:RFC867Server".
#ifndef nsDateTimeHandler_h___
#define nsDateTimeHandler_h___
#include "nsIProtocolHandler.h"
#define DATETIME_PORT 13
// {AA27D2A0-B71B-11d3-A1A0-0050041CAF44}
#define NS_DATETIMEHANDLER_CID \
{ 0xaa27d2a0, 0xb71b, 0x11d3, { 0xa1, 0xa0, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
class nsDateTimeHandler : public nsIProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsDateTimeHandler methods:
nsDateTimeHandler();
virtual ~nsDateTimeHandler();
// Define a Create method to be used with a factory:
static NS_METHOD Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
};
#endif /* nsDateTimeHandler_h___ */

View File

@@ -0,0 +1,34 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIGenericFactory.h"
#include "nsDateTimeHandler.h"
static nsModuleComponentInfo gResComponents[] = {
{ "The DateTime Protocol Handler",
NS_DATETIMEHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "datetime",
nsDateTimeHandler::Create
}
};
NS_IMPL_NSGETMODULE("datetime", gResComponents)

View File

@@ -0,0 +1,41 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
LIBRARY_NAME = necko_finger
IS_COMPONENT = 1
CPPSRCS = \
nsFingerHandler.cpp \
nsFingerChannel.cpp \
nsFingerModule.cpp \
$(NULL)
EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,423 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
// finger implementation
#include "nsFingerChannel.h"
#include "nsIServiceManager.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsXPIDLString.h"
#include "nsISocketTransportService.h"
#include "nsIStringStream.h"
#include "nsMimeTypes.h"
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
#define BUFFER_SEG_SIZE (4*1024)
#define BUFFER_MAX_SIZE (64*1024)
// nsFingerChannel methods
nsFingerChannel::nsFingerChannel():
mContentLength(-1),
mActAsObserver(PR_TRUE),
mPort(-1)
{
NS_INIT_REFCNT();
}
nsFingerChannel::~nsFingerChannel() {
}
NS_IMPL_ISUPPORTS4(nsFingerChannel, nsIChannel, nsIRequest,
nsIStreamListener, nsIStreamObserver)
nsresult
nsFingerChannel::Init(const char* verb,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize)
{
nsresult rv;
nsXPIDLCString autoBuffer;
NS_ASSERTION(uri, "no uri");
mOriginalURI = originalURI ? originalURI : uri;
mUrl = uri;
rv = mUrl->GetPort(&mPort);
if (NS_FAILED(rv) || mPort < 1)
mPort = FINGER_PORT;
rv = mUrl->GetPath(getter_Copies(autoBuffer)); // autoBuffer = user@host
if (NS_FAILED(rv)) return rv;
nsCString cString(autoBuffer);
nsCString tempBuf;
PRUint32 i;
// Now parse out the user and host
for (i=0; cString[i] != '\0'; i++) {
if (cString[i] == '@') {
cString.Left(tempBuf, i);
mUser = tempBuf;
cString.Right(tempBuf, cString.Length() - i - 1);
mHost = tempBuf;
break;
}
}
// Catch the case of just the host being given
if (cString[i] == '\0') {
mHost = cString;
}
#ifdef DEBUG_bryner
printf("Status:mUser = %s, mHost = %s\n", (const char*)mUser,
(const char*)mHost);
#endif
if (!*(const char *)mHost) return NS_ERROR_NOT_INITIALIZED;
rv = SetLoadAttributes(loadAttributes);
if (NS_FAILED(rv)) return rv;
rv = SetLoadGroup(aLoadGroup);
if (NS_FAILED(rv)) return rv;
rv = SetNotificationCallbacks(notificationCallbacks);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
NS_METHOD
nsFingerChannel::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
{
nsFingerChannel* fc = new nsFingerChannel();
if (fc == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(fc);
nsresult rv = fc->QueryInterface(aIID, aResult);
NS_RELEASE(fc);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsFingerChannel::IsPending(PRBool *result)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::Cancel(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::Suspend(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::Resume(void)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods:
NS_IMETHODIMP
nsFingerChannel::GetOriginalURI(nsIURI * *aURI)
{
*aURI = mOriginalURI;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetURI(nsIURI * *aURI)
{
*aURI = mUrl;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::OpenInputStream(PRUint32 startPosition, PRInt32 readCount,
nsIInputStream **_retval)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, BUFFER_SEG_SIZE,
BUFFER_MAX_SIZE, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->OpenInputStream(startPosition, readCount, _retval);
}
NS_IMETHODIMP
nsFingerChannel::OpenOutputStream(PRUint32 startPosition, nsIOutputStream **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::AsyncOpen(nsIStreamObserver *observer, nsISupports* ctxt)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, BUFFER_SEG_SIZE,
BUFFER_MAX_SIZE, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->AsyncOpen(observer, ctxt);
}
NS_IMETHODIMP
nsFingerChannel::AsyncRead(PRUint32 startPosition, PRInt32 readCount,
nsISupports *ctxt,
nsIStreamListener *aListener)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, BUFFER_SEG_SIZE,
BUFFER_MAX_SIZE, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
mListener = aListener;
return SendRequest(channel);
}
NS_IMETHODIMP
nsFingerChannel::AsyncWrite(nsIInputStream *fromStream,
PRUint32 startPosition,
PRInt32 writeCount,
nsISupports *ctxt,
nsIStreamObserver *observer)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetLoadAttributes(PRUint32 *aLoadAttributes)
{
*aLoadAttributes = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetLoadAttributes(PRUint32 aLoadAttributes)
{
mLoadAttributes = aLoadAttributes;
return NS_OK;
}
#define FINGER_TYPE TEXT_PLAIN
NS_IMETHODIMP
nsFingerChannel::GetContentType(char* *aContentType) {
if (!aContentType) return NS_ERROR_NULL_POINTER;
*aContentType = nsCRT::strdup(FINGER_TYPE);
if (!*aContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetContentType(const char *aContentType)
{
//It doesn't make sense to set the content-type on this type
// of channel...
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsFingerChannel::GetContentLength(PRInt32 *aContentLength)
{
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
if (mLoadGroup) // if we already had a load group remove ourselves...
(void)mLoadGroup->RemoveChannel(this, nsnull, nsnull, nsnull);
mLoadGroup = aLoadGroup;
if (mLoadGroup) {
return mLoadGroup->AddChannel(this, nsnull);
}
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetOwner(nsISupports* *aOwner)
{
*aOwner = mOwner.get();
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHODIMP
nsFingerChannel::OnStartRequest(nsIChannel *aChannel, nsISupports *aContext) {
if (!mActAsObserver) {
// acting as a listener
return mListener->OnStartRequest(this, aContext);
} else {
// we don't want to pass our AsyncWrite's OnStart through
// we just ignore this
return NS_OK;
}
}
NS_IMETHODIMP
nsFingerChannel::OnStopRequest(nsIChannel* aChannel, nsISupports* aContext,
nsresult aStatus, const PRUnichar* aMsg) {
#ifdef DEBUG_bryner
printf("nsFingerChannel::OnStopRequest, mActAsObserver=%d\n",
mActAsObserver);
printf(" aChannel = %p\n", aChannel);
#endif
nsresult rv = NS_OK;
if (!mActAsObserver) {
if (mLoadGroup) {
rv = mLoadGroup->RemoveChannel(this, nsnull, aStatus, aMsg);
if (NS_FAILED(rv)) return rv;
}
return mListener->OnStopRequest(this, aContext, aStatus, aMsg);
} else {
// at this point we know the request has been sent.
// we're no longer acting as an observer.
mActAsObserver = PR_FALSE;
return aChannel->AsyncRead(0, -1, 0, this);
}
}
// nsIStreamListener method
NS_IMETHODIMP
nsFingerChannel::OnDataAvailable(nsIChannel* aChannel, nsISupports* aContext,
nsIInputStream *aInputStream, PRUint32 aSourceOffset,
PRUint32 aLength) {
mContentLength = aLength;
return mListener->OnDataAvailable(this, aContext, aInputStream, aSourceOffset, aLength);
}
nsresult
nsFingerChannel::SendRequest(nsIChannel* aChannel) {
// The text to send should already be in mUser
nsresult rv = NS_OK;
nsCOMPtr<nsISupports> result;
nsCOMPtr<nsIInputStream> charstream;
nsCString requestBuffer(mUser);
requestBuffer.Append(CRLF);
mRequest = requestBuffer.ToNewCString();
rv = NS_NewCharInputStream(getter_AddRefs(result), mRequest);
if (NS_FAILED(rv)) return rv;
charstream = do_QueryInterface(result, &rv);
if (NS_FAILED(rv)) return rv;
#ifdef DEBUG_bryner
printf("Sending: %s\n", requestBuffer.GetBuffer());
#endif
rv = aChannel->AsyncWrite(charstream, 0, requestBuffer.Length(), 0,
this);
return rv;
}

View File

@@ -0,0 +1,87 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsFingerChannel_h___
#define nsFingerChannel_h___
#include "nsString2.h"
#include "nsILoadGroup.h"
#include "nsIInputStream.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsFingerHandler.h"
#include "nsIStreamListener.h"
class nsFingerChannel : public nsIChannel, public nsIStreamListener {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMOBSERVER
// nsFingerChannel methods:
nsFingerChannel();
virtual ~nsFingerChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
nsresult Init(const char* verb,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsCOMPtr<nsIURI> mUrl;
nsCOMPtr<nsIStreamListener> mListener;
PRUint32 mLoadAttributes;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCString mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsISupports> mOwner;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRBool mActAsObserver;
PRInt32 mPort;
nsXPIDLCString mHost;
nsXPIDLCString mUser;
nsXPIDLCString mRequest;
protected:
nsresult SendRequest(nsIChannel* aChannel);
};
#endif /* nsFingerChannel_h___ */

View File

@@ -0,0 +1,124 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nspr.h"
#include "nsFingerChannel.h"
#include "nsFingerHandler.h"
#include "nsIURL.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIProgressEventSink.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsFingerHandler::nsFingerHandler() {
NS_INIT_REFCNT();
}
nsFingerHandler::~nsFingerHandler() {
}
NS_IMPL_ISUPPORTS(nsFingerHandler, NS_GET_IID(nsIProtocolHandler));
NS_METHOD
nsFingerHandler::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult) {
nsFingerHandler* ph = new nsFingerHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->QueryInterface(aIID, aResult);
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsFingerHandler::GetScheme(char* *result) {
*result = nsCRT::strdup("finger");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsFingerHandler::GetDefaultPort(PRInt32 *result) {
*result = FINGER_PORT;
return NS_OK;
}
NS_IMETHODIMP
nsFingerHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result) {
nsresult rv;
// no concept of a relative finger url
NS_ASSERTION(!aBaseURI, "base url passed into finger protocol handler");
nsIURI* url;
rv = nsComponentManager::CreateInstance(kSimpleURICID, nsnull,
NS_GET_IID(nsIURI),
(void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsFingerHandler::NewChannel(const char* verb, nsIURI* url,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel* *result)
{
nsresult rv;
nsFingerChannel* channel;
rv = nsFingerChannel::Create(nsnull, NS_GET_IID(nsIChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(verb, url, aLoadGroup, notificationCallbacks,
loadAttributes, originalURI, bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,52 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
// The finger protocol handler creates "finger" URIs of the form
// "finger:user@host" or "finger:host".
#ifndef nsFingerHandler_h___
#define nsFingerHandler_h___
#include "nsIProtocolHandler.h"
#define FINGER_PORT 79
// {0x76d6d5d8-1dd2-11b2-b361-850ddf15ef07}
#define NS_FINGERHANDLER_CID \
{ 0x76d6d5d8, 0x1dd2, 0x11b2, \
{0xb3, 0x61, 0x85, 0x0d, 0xdf, 0x15, 0xef, 0x07} }
class nsFingerHandler : public nsIProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsFingerHandler methods:
nsFingerHandler();
virtual ~nsFingerHandler();
// Define a Create method to be used with a factory:
static NS_METHOD Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
};
#endif /* nsFingerHandler_h___ */

View File

@@ -0,0 +1,34 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIGenericFactory.h"
#include "nsFingerHandler.h"
static nsModuleComponentInfo gResComponents[] = {
{ "The Finger Protocol Handler",
NS_FINGERHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "finger",
nsFingerHandler::Create
}
};
NS_IMPL_NSGETMODULE("finger", gResComponents)

View File

@@ -0,0 +1,39 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIChannel.idl"
interface nsISimpleEnumerator;
[scriptable, uuid(c7e410d1-85f2-11d3-9f63-006008a6efe9)]
interface nsIJARChannel : nsIChannel
{
/**
* Enumerates all the entries in the JAR (the root URI).
* ARGUMENTS:
* aRoot - a string representing the root dir to enumerate from
* or null to enumerate the whole thing.
*/
nsISimpleEnumerator EnumerateEntries(in string aRoot);
};

View File

@@ -0,0 +1,32 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIProtocolHandler.idl"
[scriptable, uuid(92c3b42c-98c4-11d3-8cd9-0060b0fc14a3)]
interface nsIJARProtocolHandler : nsIProtocolHandler {
/**
* Add any jar-specific methods here later.
*/
};

View File

@@ -0,0 +1,42 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsIURI.idl"
/**
* JAR URLs have the following syntax
*
* jar:<jar-file-uri>!/<jar-entry>
*
* EXAMPLE: jar:http://www.big.com/blue.jar!/ocean.html
*/
[scriptable, uuid(c7e410d3-85f2-11d3-9f63-006008a6efe9)]
interface nsIJARURI : nsIURI {
/**
* Returns the root URI (the one for the actual JAR file) for this JAR.
* eg http://www.big.com/blue.jar
*/
attribute nsIURI JARFile;
/**
* Returns the entry specified for this JAR URI.
* eg ocean.html
*/
attribute string JAREntry;
};

View File

@@ -0,0 +1,690 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*
*/
#include "nsNetUtil.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsSpecialSystemDirectory.h"
#include "nsJARChannel.h"
#include "nsCRT.h"
#include "nsIFileTransportService.h"
#include "nsIURL.h"
#include "nsIMIMEService.h"
#include "nsAutoLock.h"
#include "nsIFileStreams.h"
#include "nsIPrincipal.h"
#include "nsMimeTypes.h"
static NS_DEFINE_CID(kFileTransportServiceCID, NS_FILETRANSPORTSERVICE_CID);
static NS_DEFINE_CID(kMIMEServiceCID, NS_MIMESERVICE_CID);
static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID);
static NS_DEFINE_CID(kFileChannelCID, NS_FILECHANNEL_CID);
////////////////////////////////////////////////////////////////////////////////
class nsJARDownloadObserver : public nsIStreamObserver
{
public:
NS_DECL_ISUPPORTS
NS_IMETHOD OnStartRequest(nsIChannel* jarCacheTransport,
nsISupports* context) {
return NS_OK;
}
NS_IMETHOD OnStopRequest(nsIChannel* jarCacheTransport,
nsISupports* context,
nsresult status,
const PRUnichar* aMsg) {
nsresult rv = NS_OK;
nsAutoMonitor monitor(mJARChannel->mMonitor);
if (NS_SUCCEEDED(status) && mJARChannel->mJarCacheTransport) {
NS_ASSERTION(jarCacheTransport == (mJARChannel->mJarCacheTransport).get(),
"wrong transport");
// after successfully downloading the jar file to the cache,
// start the extraction process:
nsCOMPtr<nsIFileChannel> jarCacheFile;
rv = NS_NewFileChannel(mJarCacheFile,
PR_RDONLY,
nsnull, // XXX content type
0, // XXX content length
mJARChannel->mLoadGroup,
mJARChannel->mCallbacks,
mJARChannel->mLoadAttributes,
nsnull,
mJARChannel->mBufferSegmentSize,
mJARChannel->mBufferMaxSize,
getter_AddRefs(jarCacheFile));
if (NS_FAILED(rv)) return rv;
rv = mJARChannel->ExtractJARElement(jarCacheFile);
}
mJARChannel->mJarCacheTransport = nsnull;
return rv;
}
nsJARDownloadObserver(nsIFile* jarCacheFile, nsJARChannel* jarChannel) {
NS_INIT_REFCNT();
mJarCacheFile = jarCacheFile;
mJARChannel = jarChannel;
NS_ADDREF(mJARChannel);
}
virtual ~nsJARDownloadObserver() {
NS_RELEASE(mJARChannel);
}
protected:
nsCOMPtr<nsIFile> mJarCacheFile;
nsJARChannel* mJARChannel;
};
NS_IMPL_ISUPPORTS1(nsJARDownloadObserver, nsIStreamObserver)
////////////////////////////////////////////////////////////////////////////////
nsJARChannel::nsJARChannel()
: mCommand(nsnull),
mContentType(nsnull),
mJAREntry(nsnull),
mMonitor(nsnull)
{
NS_INIT_REFCNT();
}
nsJARChannel::~nsJARChannel()
{
if (mCommand)
nsCRT::free(mCommand);
if (mContentType)
nsCRT::free(mContentType);
if (mJAREntry)
nsCRT::free(mJAREntry);
if (mMonitor)
PR_DestroyMonitor(mMonitor);
}
NS_IMPL_ISUPPORTS6(nsJARChannel,
nsIJARChannel,
nsIChannel,
nsIRequest,
nsIStreamObserver,
nsIStreamListener,
nsIFileSystem)
NS_METHOD
nsJARChannel::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARChannel* jarChannel = new nsJARChannel();
if (jarChannel == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(jarChannel);
rv = jarChannel->QueryInterface(aIID, aResult);
NS_RELEASE(jarChannel);
return rv;
}
nsresult
nsJARChannel::Init(nsIJARProtocolHandler* aHandler,
const char* command,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize)
{
nsresult rv;
mURI = do_QueryInterface(uri, &rv);
if (NS_FAILED(rv)) return rv;
mCommand = nsCRT::strdup(command);
if (mCommand == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
mOriginalURI = originalURI ? originalURI : uri;
mBufferSegmentSize = bufferSegmentSize;
mBufferMaxSize = bufferMaxSize;
rv = SetLoadAttributes(loadAttributes);
if (NS_FAILED(rv)) return rv;
rv = SetLoadGroup(aLoadGroup);
if (NS_FAILED(rv)) return rv;
rv = SetNotificationCallbacks(notificationCallbacks);
if (NS_FAILED(rv)) return rv;
mMonitor = PR_NewMonitor();
if (mMonitor == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods
NS_IMETHODIMP
nsJARChannel::IsPending(PRBool* result)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::Cancel()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Cancel();
if (NS_FAILED(rv)) return rv;
mJarCacheTransport = nsnull;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Cancel();
if (NS_FAILED(rv)) return rv;
mJarExtractionTransport = nsnull;
}
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::Suspend()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Suspend();
if (NS_FAILED(rv)) return rv;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Suspend();
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::Resume()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Resume();
if (NS_FAILED(rv)) return rv;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Resume();
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods
NS_IMETHODIMP
nsJARChannel::GetOriginalURI(nsIURI* *aOriginalURI)
{
*aOriginalURI = mOriginalURI;
NS_ADDREF(*aOriginalURI);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetURI(nsIURI* *aURI)
{
*aURI = mURI;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::OpenInputStream(PRUint32 startPosition, PRInt32 readCount,
nsIInputStream* *result)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::OpenOutputStream(PRUint32 startPosition, nsIOutputStream* *result)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::AsyncOpen(nsIStreamObserver* observer, nsISupports* ctxt)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::AsyncRead(PRUint32 startPosition, PRInt32 readCount,
nsISupports* ctxt,
nsIStreamListener* listener)
{
nsresult rv;
rv = mURI->GetJARFile(getter_AddRefs(mJARBaseURI));
if (NS_FAILED(rv)) return rv;
rv = mURI->GetJAREntry(&mJAREntry);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> jarBaseChannel;
rv = NS_OpenURI(getter_AddRefs(jarBaseChannel),
mJARBaseURI, mLoadGroup, mCallbacks, mLoadAttributes);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIFileChannel> jarBaseFile = do_QueryInterface(jarBaseChannel, &rv);
// XXX need to set a state variable here to say we're reading
mStartPosition = startPosition;
mReadCount = readCount;
mUserContext = ctxt;
mUserListener = listener;
if (NS_SUCCEEDED(rv)) {
// then we've already got a local jar file -- no need to download it
rv = ExtractJARElement(jarBaseFile);
}
else {
// otherwise, we need to download the jar file
nsCOMPtr<nsIFile> jarCacheFile;
rv = GetCacheFile(getter_AddRefs(jarCacheFile));
if (NS_FAILED(rv)) return rv;
PRBool filePresent;
rv = jarCacheFile->IsFile(&filePresent);
if (NS_SUCCEEDED(rv) && filePresent)
{
// then we've already got the file in the local cache -- no need to download it
nsCOMPtr<nsIFileChannel> fileChannel;
rv = nsComponentManager::CreateInstance(kFileChannelCID,
nsnull,
NS_GET_IID(nsIFileChannel),
getter_AddRefs(fileChannel));
if (NS_FAILED(rv)) return rv;
rv = fileChannel->Init(jarCacheFile,
PR_RDONLY,
nsnull, // contentType
-1, // contentLength
nsnull, // loadGroup
nsnull, // notificationCallbacks
nsIChannel::LOAD_NORMAL,
nsnull, // originalURI
mBufferSegmentSize,
mBufferMaxSize);
if (NS_FAILED(rv)) return rv;
rv = ExtractJARElement(fileChannel);
return rv;
}
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsAutoMonitor monitor(mMonitor);
// use a file transport to serve as a data pump for the download (done
// on some other thread)
nsCOMPtr<nsIChannel> jarCacheTransport;
rv = fts->CreateTransport(jarCacheFile, PR_RDONLY, mCommand,
mBufferSegmentSize, mBufferMaxSize,
getter_AddRefs(mJarCacheTransport));
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamObserver> downloadObserver = new nsJARDownloadObserver(jarCacheFile, this);
if (downloadObserver == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIInputStream> jarBaseIn;
rv = jarBaseChannel->OpenInputStream(0, -1, getter_AddRefs(jarBaseIn));
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->AsyncWrite(jarBaseIn, 0, -1, nsnull, downloadObserver);
}
return rv;
}
nsresult
nsJARChannel::GetCacheFile(nsIFile* *cacheFile)
{
// XXX change later to use the real network cache
nsresult rv;
nsCOMPtr<nsIFile> jarCacheFile;
rv = NS_GetSpecialDirectory("xpcom.currentProcess.componentDirectory",
getter_AddRefs(jarCacheFile));
if (NS_FAILED(rv)) return rv;
jarCacheFile->Append("jarCache");
PRBool exists;
rv = jarCacheFile->Exists(&exists);
if (NS_FAILED(rv)) return rv;
if (!exists) {
rv = jarCacheFile->Create(nsIFile::DIRECTORY_TYPE, 0664);
if (NS_FAILED(rv)) return rv;
}
nsCOMPtr<nsIURL> jarBaseURL = do_QueryInterface(mJARBaseURI, &rv);
if (NS_FAILED(rv)) return rv;
char* jarFileName;
rv = jarBaseURL->GetFileName(&jarFileName);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->Append(jarFileName);
nsCRT::free(jarFileName);
if (NS_FAILED(rv)) return rv;
*cacheFile = jarCacheFile;
NS_ADDREF(*cacheFile);
return rv;
}
nsresult
nsJARChannel::ExtractJARElement(nsIFileChannel* jarBaseFile)
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
mJARBaseFile = jarBaseFile;
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = fts->CreateTransportFromFileSystem(this, mCommand,
mBufferSegmentSize, mBufferMaxSize,
getter_AddRefs(mJarExtractionTransport));
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->AsyncRead(mStartPosition, mReadCount, nsnull, this);
return rv;
}
NS_IMETHODIMP
nsJARChannel::AsyncWrite(nsIInputStream* fromStream, PRUint32 startPosition,
PRInt32 writeCount,
nsISupports* ctxt,
nsIStreamObserver* observer)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::GetLoadAttributes(PRUint32* aLoadFlags)
{
*aLoadFlags = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetLoadAttributes(PRUint32 aLoadFlags)
{
mLoadAttributes = aLoadFlags;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetContentType(char* *aContentType)
{
nsresult rv = NS_OK;
if (mContentType == nsnull) {
char* fileName = new char[PL_strlen(mJAREntry)+1];
PL_strcpy(fileName, mJAREntry);
if (fileName != nsnull) {
PRInt32 len = nsCRT::strlen(fileName);
const char* ext = nsnull;
for (PRInt32 i = len; i >= 0; i--) {
if (fileName[i] == '.') {
ext = &fileName[i + 1];
break;
}
}
if (ext) {
NS_WITH_SERVICE(nsIMIMEService, mimeServ, kMIMEServiceCID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = mimeServ->GetTypeFromExtension(ext, &mContentType);
}
}
else
rv = NS_ERROR_FAILURE;
nsCRT::free(fileName);
}
else {
rv = NS_ERROR_FAILURE;
}
if (NS_FAILED(rv)) {
mContentType = nsCRT::strdup(UNKNOWN_CONTENT_TYPE);
if (mContentType == nsnull)
rv = NS_ERROR_OUT_OF_MEMORY;
else
rv = NS_OK;
}
}
if (NS_SUCCEEDED(rv)) {
*aContentType = nsCRT::strdup(mContentType);
if (*aContentType == nsnull)
rv = NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
NS_IMETHODIMP
nsJARChannel::SetContentType(const char *aContentType)
{
if (mContentType) {
nsCRT::free(mContentType);
}
mContentType = nsCRT::strdup(aContentType);
if (!mContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetContentLength(PRInt32* aContentLength)
{
if (mContentLength == -1)
return NS_ERROR_FAILURE;
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
mLoadGroup = aLoadGroup;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetOwner(nsISupports* *aOwner)
{
nsCOMPtr<nsIPrincipal> principal;
nsresult rv = mJAR->GetPrincipal(mJAREntry, getter_AddRefs(principal));
if (NS_SUCCEEDED(rv) && principal)
rv = principal->QueryInterface(NS_GET_IID(nsISupports), (void **)aOwner);
else
*aOwner = nsnull;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetOwner(nsISupports* aOwner)
{
//XXX: is this OK?
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIStreamObserver methods:
NS_IMETHODIMP
nsJARChannel::OnStartRequest(nsIChannel* jarExtractionTransport,
nsISupports* context)
{
return mUserListener->OnStartRequest(this, mUserContext);
}
NS_IMETHODIMP
nsJARChannel::OnStopRequest(nsIChannel* jarExtractionTransport,
nsISupports* context,
nsresult status,
const PRUnichar* aMsg)
{
nsresult rv;
rv = mUserListener->OnStopRequest(this, mUserContext, status, aMsg);
mJarExtractionTransport = nsnull;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIStreamListener methods:
NS_IMETHODIMP
nsJARChannel::OnDataAvailable(nsIChannel* jarCacheTransport,
nsISupports* context,
nsIInputStream *inStr,
PRUint32 sourceOffset,
PRUint32 count)
{
return mUserListener->OnDataAvailable(this, mUserContext,
inStr, sourceOffset, count);
}
////////////////////////////////////////////////////////////////////////////////
// nsIFileSystem methods:
NS_IMETHODIMP
nsJARChannel::Open(char* *contentType, PRInt32 *contentLength)
{
nsresult rv;
rv = nsComponentManager::CreateInstance(kZipReaderCID,
nsnull,
NS_GET_IID(nsIZipReader),
getter_AddRefs(mJAR));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIFile> fs;
rv = mJARBaseFile->GetFile(getter_AddRefs(fs));
if (NS_FAILED(rv)) return rv;
rv = mJAR->Init(fs);
if (NS_FAILED(rv)) return rv;
rv = mJAR->Open();
if (NS_FAILED(rv)) return rv;
// If this fails, GetOwner will fail, but otherwise we can continue.
mJAR->ParseManifest();
nsCOMPtr<nsIZipEntry> entry;
rv = mJAR->GetEntry(mJAREntry, getter_AddRefs(entry));
if (NS_FAILED(rv)) return rv;
rv = entry->GetRealSize((PRUint32*)contentLength);
if (NS_FAILED(rv)) return rv;
return GetContentType(contentType);
}
NS_IMETHODIMP
nsJARChannel::Close(nsresult status)
{
mJAR = null_nsCOMPtr();
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetInputStream(nsIInputStream* *aInputStream)
{
return mJAR->GetInputStream(mJAREntry, aInputStream);
}
NS_IMETHODIMP
nsJARChannel::GetOutputStream(nsIOutputStream* *aOutputStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIJARChannel methods:
NS_IMETHODIMP
nsJARChannel::EnumerateEntries(const char *aRoot, nsISimpleEnumerator **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,115 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsJARChannel_h__
#define nsJARChannel_h__
#include "nsIJARChannel.h"
#include "nsIStreamListener.h"
#include "nsIJARProtocolHandler.h"
#include "nsIJARURI.h"
#include "nsIFileSystem.h"
#include "nsIChannel.h"
#include "nsIZipReader.h"
#include "nsIChannel.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsIFile.h"
#include "prmon.h"
class nsIFileChannel;
#define NS_JARCHANNEL_CID \
{ /* 0xc7e410d5-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d5, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
#define JAR_DIRECTORY "jarCache"
class nsJARChannel : public nsIJARChannel,
public nsIStreamListener,
public nsIFileSystem
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSIJARCHANNEL
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSIFILESYSTEM
nsJARChannel();
virtual ~nsJARChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, REFNSIID aIID, void **aResult);
nsresult Init(nsIJARProtocolHandler* aHandler,
const char* command,
nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
nsresult ExtractJARElement(nsIFileChannel* jarFileChannel);
nsresult GetCacheFile(nsIFile* *cacheFile);
friend class nsJARDownloadObserver;
protected:
char* mCommand;
nsCOMPtr<nsIJARURI> mURI;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsLoadFlags mLoadAttributes;
PRUint32 mStartPosition;
PRInt32 mReadCount;
nsCOMPtr<nsISupports> mUserContext;
nsCOMPtr<nsIStreamListener> mUserListener;
char* mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsIURI> mJARBaseURI;
nsCOMPtr<nsIFileChannel> mJARBaseFile;
char* mJAREntry;
nsCOMPtr<nsIZipReader> mJAR;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRMonitor* mMonitor;
nsCOMPtr<nsIChannel> mJarCacheTransport;
nsCOMPtr<nsIChannel> mJarExtractionTransport;
};
#endif // nsJARChannel_h__

View File

@@ -0,0 +1,146 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsJARProtocolHandler.h"
#include "nsIIOService.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsJARURI.h"
#include "nsIURL.h"
#include "nsJARChannel.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
static NS_DEFINE_CID(kJARUriCID, NS_JARURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsJARProtocolHandler::nsJARProtocolHandler()
{
NS_INIT_REFCNT();
}
nsresult
nsJARProtocolHandler::Init()
{
return NS_OK;
}
nsJARProtocolHandler::~nsJARProtocolHandler()
{
}
NS_IMPL_ISUPPORTS2(nsJARProtocolHandler,
nsIJARProtocolHandler,
nsIProtocolHandler)
NS_METHOD
nsJARProtocolHandler::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARProtocolHandler* ph = new nsJARProtocolHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->Init();
if (NS_SUCCEEDED(rv)) {
rv = ph->QueryInterface(aIID, aResult);
}
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsJARProtocolHandler::GetScheme(char* *result)
{
*result = nsCRT::strdup("jar");
if (*result == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsJARProtocolHandler::GetDefaultPort(PRInt32 *result)
{
*result = -1; // no port for JAR: URLs
return NS_OK;
}
NS_IMETHODIMP
nsJARProtocolHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result)
{
nsresult rv;
nsIURI* url;
if (aBaseURI) {
rv = aBaseURI->Clone(&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetRelativePath(aSpec);
}
else {
rv = nsJARURI::Create(nsnull, NS_GET_IID(nsIJARURI), (void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
}
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsJARProtocolHandler::NewChannel(const char* verb, nsIURI* uri,
nsILoadGroup* aLoadGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel* *result)
{
nsresult rv;
nsJARChannel* channel;
rv = nsJARChannel::Create(nsnull, NS_GET_IID(nsIJARChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(this, verb, uri, aLoadGroup, notificationCallbacks,
loadAttributes, originalURI, bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,57 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsJARProtocolHandler_h___
#define nsJARProtocolHandler_h___
#include "nsIJARProtocolHandler.h"
#include "nsIProtocolHandler.h"
#include "nsIJARURI.h"
#define NS_JARPROTOCOLHANDLER_CID \
{ /* 0xc7e410d4-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d4, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
class nsJARProtocolHandler : public nsIJARProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsJARProtocolHandler methods:
nsJARProtocolHandler();
virtual ~nsJARProtocolHandler();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
protected:
};
#endif /* nsJARProtocolHandler_h___ */

View File

@@ -0,0 +1,38 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsJARProtocolHandler.h"
static nsModuleComponentInfo components[] =
{
{ "JAR Protocol Handler",
NS_JARPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "jar",
nsJARProtocolHandler::Create
},
};
NS_IMPL_NSGETMODULE("nsJarProtocolModule", components);

View File

@@ -0,0 +1,384 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "nsJARURI.h"
#include "nsNetUtil.h"
#include "nsIIOService.h"
#include "nsFileSpec.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIZipReader.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
////////////////////////////////////////////////////////////////////////////////
nsJARURI::nsJARURI()
: mJAREntry(nsnull)
{
NS_INIT_REFCNT();
}
nsJARURI::~nsJARURI()
{
}
NS_IMPL_ISUPPORTS2(nsJARURI, nsIJARURI, nsIURI)
NS_METHOD
nsJARURI::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARURI* uri = new nsJARURI();
if (uri == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(uri);
nsresult rv = uri->Init();
if (NS_SUCCEEDED(rv)) {
rv = uri->QueryInterface(aIID, aResult);
}
NS_RELEASE(uri);
return rv;
}
nsresult
nsJARURI::Init()
{
return NS_OK;
}
#define NS_JAR_SCHEME "jar:"
#define NS_JAR_DELIMITER "!/"
nsresult
nsJARURI::FormatSpec(const char* entryPath, char* *result)
{
nsresult rv;
char* jarFileSpec;
rv = mJARFile->GetSpec(&jarFileSpec);
if (NS_FAILED(rv)) return rv;
nsCString spec(NS_JAR_SCHEME);
spec += jarFileSpec;
nsCRT::free(jarFileSpec);
spec += NS_JAR_DELIMITER;
spec += entryPath;
*result = nsCRT::strdup(spec);
return *result ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
////////////////////////////////////////////////////////////////////////////////
// nsURI methods:
NS_IMETHODIMP
nsJARURI::GetSpec(char* *aSpec)
{
return FormatSpec(mJAREntry, aSpec);
}
NS_IMETHODIMP
nsJARURI::SetSpec(const char * aSpec)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
PRUint32 startPos, endPos;
rv = serv->ExtractScheme(aSpec, &startPos, &endPos, nsnull);
if (NS_FAILED(rv)) return rv;
if (nsCRT::strncmp("jar", &aSpec[startPos], endPos - startPos - 1) != 0)
return NS_ERROR_MALFORMED_URI;
// Search backward from the end for the "!/" delimiter. Remember, jar URLs
// can nest, e.g.:
// jar:jar:http://www.foo.com/bar.jar!/a.jar!/b.html
// This gets the b.html document from out of the a.jar file, that's
// contained within the bar.jar file.
nsCAutoString jarPath(aSpec);
PRInt32 pos = jarPath.RFind(NS_JAR_DELIMITER);
if (pos == -1 || endPos + 1 > (PRUint32)pos)
return NS_ERROR_MALFORMED_URI;
jarPath.Cut(pos, jarPath.Length());
jarPath.Cut(0, endPos);
rv = serv->NewURI(jarPath, nsnull, getter_AddRefs(mJARFile));
if (NS_FAILED(rv)) return rv;
nsCAutoString entry(aSpec);
entry.Cut(0, pos + 2); // 2 == strlen(NS_JAR_DELIMITER)
rv = serv->ResolveRelativePath(entry, nsnull, &mJAREntry);
return rv;
}
NS_IMETHODIMP
nsJARURI::GetScheme(char * *aScheme)
{
*aScheme = nsCRT::strdup("jar");
return *aScheme ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsJARURI::SetScheme(const char * aScheme)
{
// doesn't make sense to set the scheme of a jar: URL
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetUsername(char * *aUsername)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetUsername(const char * aUsername)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPassword(char * *aPassword)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPassword(const char * aPassword)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPreHost(char * *aPreHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPreHost(const char * aPreHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetHost(char * *aHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetHost(const char * aHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPort(PRInt32 *aPort)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPort(PRInt32 aPort)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPath(char * *aPath)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPath(const char * aPath)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetURLParser(nsIURLParser * *aURLParser)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetURLParser(nsIURLParser * aURLParser)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::Equals(nsIURI *other, PRBool *result)
{
nsresult rv;
*result = PR_FALSE;
nsJARURI* otherJAR;
rv = other->QueryInterface(NS_GET_IID(nsIJARURI), (void**)&otherJAR);
if (NS_FAILED(rv))
return NS_OK; // not equal
nsCOMPtr<nsIURI> otherJARFile;
rv = otherJAR->GetJARFile(getter_AddRefs(otherJARFile));
if (NS_FAILED(rv)) return rv;
PRBool equal;
rv = mJARFile->Equals(otherJARFile, &equal);
if (NS_FAILED(rv)) return rv;
if (!equal)
return NS_OK; // not equal
char* otherJAREntry;
rv = otherJAR->GetJAREntry(&otherJAREntry);
if (NS_FAILED(rv)) return rv;
*result = nsCRT::strcmp(mJAREntry, otherJAREntry) == 0;
nsCRT::free(otherJAREntry);
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::Clone(nsIURI **result)
{
nsresult rv;
nsCOMPtr<nsIURI> newJARFile;
rv = mJARFile->Clone(getter_AddRefs(newJARFile));
if (NS_FAILED(rv)) return rv;
char* newJAREntry = nsCRT::strdup(mJAREntry);
if (newJAREntry == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsJARURI* uri = new nsJARURI();
if (uri == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(uri);
uri->mJARFile = newJARFile;
uri->mJAREntry = newJAREntry;
*result = uri;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::SetRelativePath(const char *relativePath)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCAutoString path(mJAREntry);
PRInt32 pos = path.RFind("/");
if (pos >= 0)
path.Truncate(pos + 1);
else
path = "";
char* resolvedEntry;
rv = serv->ResolveRelativePath(relativePath, path.GetBuffer(),
&resolvedEntry);
if (NS_FAILED(rv)) return rv;
nsCRT::free(mJAREntry);
mJAREntry = resolvedEntry;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::Resolve(const char *relativePath, char **result)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCAutoString path(mJAREntry);
PRInt32 pos = path.RFind("/");
if (pos >= 0)
path.Truncate(pos + 1);
else
path = "";
char* resolvedEntry;
rv = serv->ResolveRelativePath(relativePath, path.GetBuffer(),
&resolvedEntry);
if (NS_FAILED(rv)) return rv;
rv = FormatSpec(resolvedEntry, result);
nsCRT::free(resolvedEntry);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIJARUri methods:
NS_IMETHODIMP
nsJARURI::GetJARFile(nsIURI* *jarFile)
{
*jarFile = mJARFile;
NS_ADDREF(*jarFile);
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::SetJARFile(nsIURI* jarFile)
{
mJARFile = jarFile;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::GetJAREntry(char* *entryPath)
{
nsCAutoString entry(mJAREntry);
PRInt32 pos = entry.RFindCharInSet("#?;");
if (pos >= 0)
entry.Truncate(pos);
*entryPath = entry.ToNewCString();
return *entryPath ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsJARURI::SetJAREntry(const char* entryPath)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
if (mJAREntry)
nsCRT::free(mJAREntry);
rv = serv->ResolveRelativePath(entryPath, nsnull, &mJAREntry);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,55 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef nsJARURI_h__
#define nsJARURI_h__
#include "nsIJARURI.h"
#include "nsCOMPtr.h"
#define NS_JARURI_CID \
{ /* 0xc7e410d7-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d7, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
class nsJARURI : public nsIJARURI
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIURI
NS_DECL_NSIJARURI
// nsJARURI
nsJARURI();
virtual ~nsJARURI();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
nsresult FormatSpec(const char* entryPath, char* *result);
protected:
nsCOMPtr<nsIURI> mJARFile;
char *mJAREntry;
};
#endif // nsJARURI_h__

View File

@@ -0,0 +1,45 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = \
cache \
base \
dns \
socket \
build \
protocol \
mime \
streamconv \
$(NULL)
ifdef ENABLE_TESTS
DIRS += test
endif
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,32 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public src
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,31 @@
#!gmake
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
DEPTH = ..\..
MODULE = necko
DIRS= \
public \
src \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -0,0 +1,7 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
netCore.h
nsNetUtil.h
nsUnixColorPrintf.h

View File

@@ -0,0 +1,17 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
nsIStreamListener.idl
nsIStreamObserver.idl
nsIURI.idl
nsIURL.idl
nsIChannel.idl
nsIRequest.idl
nsISocketTransportService.idl
nsIFileTransportService.idl
nsIFileSystem.idl
nsIPrompt.idl
nsIStreamLoader.idl
nsIURLParser.idl
nsIProtocolProxyService.idl

View File

@@ -0,0 +1,67 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
XPIDL_MODULE = necko_base
XPIDLSRCS = \
nsIFileStreams.idl \
nsIRequest.idl \
nsIChannel.idl \
nsIURI.idl \
nsIURL.idl \
nsIStreamObserver.idl \
nsIStreamListener.idl \
nsIIOService.idl \
nsIPrompt.idl \
nsIProtocolHandler.idl \
nsIProgressEventSink.idl \
nsINetModRegEntry.idl \
nsINetModuleMgr.idl \
nsINetNotify.idl \
nsILoadGroup.idl \
nsIFileTransportService.idl \
nsISocketTransportService.idl \
nsIStatusCodeEventSink.idl \
nsIFileSystem.idl \
nsIStreamLoader.idl \
nsINetPrompt.idl \
nsISocketTransport.idl \
nsIURLParser.idl \
nsIProxy.idl \
nsIProtocolProxyService.idl \
$(NULL)
EXPORTS = \
netCore.h \
nsNetUtil.h \
nsUnixColorPrintf.h \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,66 @@
#!gmake
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
MODULE = necko
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
EXPORTS = \
netCore.h \
nsNetUtil.h \
nsUnixColorPrintf.h \
$(NULL)
XPIDLSRCS = \
.\nsIFileStreams.idl \
.\nsIRequest.idl \
.\nsIChannel.idl \
.\nsIURI.idl \
.\nsIURL.idl \
.\nsIStreamObserver.idl \
.\nsIStreamListener.idl \
.\nsIIOService.idl \
.\nsIPrompt.idl \
.\nsIProtocolHandler.idl \
.\nsIProgressEventSink.idl \
.\nsINetModRegEntry.idl \
.\nsINetModuleMgr.idl \
.\nsINetNotify.idl \
.\nsILoadGroup.idl \
.\nsISocketTransportService.idl \
.\nsIFileTransportService.idl \
.\nsIStatusCodeEventSink.idl \
.\nsIFileSystem.idl \
.\nsIStreamLoader.idl \
.\nsINetPrompt.idl \
.\nsISocketTransport.idl \
.\nsIURLParser.idl \
.\nsIProxy.idl \
.\nsIProtocolProxyService.idl \
$(NULL)
include <$(DEPTH)/config/rules.mak>
$(DEPTH)\netwerk\dist\include:
-mkdir $(DEPTH)\netwerk\dist
-mkdir $(DEPTH)\netwerk\dist\include

View File

@@ -0,0 +1,64 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef __netCore_h__
#define __netCore_h__
#include "nsError.h"
/* networking error codes */
// NET RANGE: 1 -20
// FTP RANGE: 21-30
// HTTP RANGE: 31-40
// DNS RANGE: 41-50
#define NS_ERROR_ALREADY_CONNECTED \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 11)
#define NS_ERROR_NOT_CONNECTED \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 12)
/* NS_ERROR_CONNECTION_REFUSED and NS_ERROR_NET_TIMEOUT moved to nsISocketTransportService.idl */
#define NS_ERROR_IN_PROGRESS \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 15)
#define NS_ERROR_OFFLINE \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 16)
#undef NS_NET
#ifdef _IMPL_NS_NET
#ifdef XP_PC
#define NS_NET _declspec(dllexport)
#else /* !XP_PC */
#define NS_NET
#endif /* !XP_PC */
#else /* !_IMPL_NS_NET */
#ifdef XP_PC
#define NS_NET _declspec(dllimport)
#else /* !XP_PC */
#define NS_NET
#endif /* !XP_PC */
#endif /* !_IMPL_NS_NET */
#endif // __netCore_h__

View File

@@ -0,0 +1,289 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIRequest.idl"
interface nsIURI;
interface nsIInputStream;
interface nsIOutputStream;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsILoadGroup;
interface nsIInterfaceRequestor;
interface nsIFile;
typedef unsigned long nsLoadFlags;
/**
* nsIChannel is the abstract base class for transports and URLs.
* It's abstract in that it doesn't provide a means to specify the
* location/destination of the data being accessed.
*/
[scriptable, uuid(2d905684-8b5c-11d3-8cd9-0060b0fc14a3)]
interface nsIChannel : nsIRequest
{
/**
* Returns the original URL used to construct the channel.
*/
readonly attribute nsIURI originalURI;
/**
* Returns the URL to which the channel currently refers.
*/
readonly attribute nsIURI URI;
/**
* Opens a blocking input stream to the URL's specified source.
* @param startPosition - The offset from the start of the data
* from which to read.
* @param readCount - The number of bytes to read. If -1, everything
* up to the end of the data is read. If greater than the end of
* the data, the amount available is returned in the stream.
*/
nsIInputStream openInputStream(in unsigned long startPosition,
in long readCount);
/**
* Opens a blocking output stream to the URL's specified destination.
* @param startPosition - The offset from the start of the data
* from which to begin writing.
*/
nsIOutputStream openOutputStream(in unsigned long startPosition);
/**
* Opens the channel asynchronously. The nsIStreamObserver's OnStartRequest
* method is called back when the channel actually becomes open, providing
* the content type. Its OnStopRequest method is called when the channel
* becomes closed.
*/
void asyncOpen(in nsIStreamObserver observer,
in nsISupports ctxt);
/**
* Reads asynchronously from the URL's specified source. Notifications
* are provided to the stream listener on the thread of the specified
* event queue.
* The startPosition argument designates the offset in the source where
* the data will be read.
* If the readCount == -1 then all the available data is delivered to
* the stream listener.
*/
void asyncRead(in unsigned long startPosition,
in long readCount,
in nsISupports ctxt,
in nsIStreamListener listener);
/**
* Writes asynchronously to the URL's specified destination. Notifications
* are provided to the stream observer on the thread of the specified
* event queue.
* The startPosition argument designates the offset in the destination where
* the data will be written.
* If the writeCount == -1, then all the available data in the input
* stream is written.
*/
void asyncWrite(in nsIInputStream fromStream,
in unsigned long startPosition,
in long writeCount,
in nsISupports ctxt,
in nsIStreamObserver observer);
/**
* Load attribute flags. These may be or'd together.
*
* Note that more will follow for each protocol's implementation of a channel,
* although channel writers have to be careful to not let the flag bits
* overlap. Otherwise, users won't be able to create a single flag word
* of load attributes that applies to a number of different channel types.
*/
const unsigned long LOAD_NORMAL = 0; /* no special load attributes -- use defaults */
const unsigned long LOAD_BACKGROUND = 1 << 0; /* don't deliver status notifications to the
* nsIProgressEventSink, or keep this load from
* completing the nsILoadGroup it may belong to */
const unsigned long LOAD_DOCUMENT_URI = 1 << 1;
const unsigned long LOAD_RETARGETED_DOCUMENT_URI = 1 << 2; /* if the end consumer for this
load has been retargeted after
discovering it's content, this flag
will be set */
//
// The following flags control caching behavior. Not all protocols pay
// attention to all these flags, but they are applicable to more than one
// protocol, so they are defined here.
//
// Don't store data in the disk cache. This can be used to preserve
// privacy, e.g. so that no https transactions are recorded, or to avoid
// caching a stream to disk that is already stored in a local file,
// e.g. the mailbox: protocol.
const unsigned long INHIBIT_PERSISTENT_CACHING = 1 << 8;
// Force an end-to-end download of content data from the origin server (and
// any intervening proxies that sit between it and the client), e.g. this
// flag is used for a shift-reload.
const unsigned long FORCE_RELOAD = 1 << 9;
// Force revalidation with server (or proxy) to verify that cached content
// is up-to-date, e.g. by comparing last-modified date on server with that
// of the cached version. For example, this flag is used when the reload
// button is pressed.
const unsigned long FORCE_VALIDATION = 1 << 10;
// If the CACHE_AS_FILE flag is set, any stream content is stored in the
// cache as a single disk file. Content will not be cached in the memory
// cache nor will it be stored in any other type of cache, e.g. a flat-file
// cache database. This is used to implement the jar protocol handler and
// to provide the stream-as-file semantics required by the classic browser
// plugin API.
const unsigned long CACHE_AS_FILE = 1 << 11;
// When cache data is potentially out of date, it can be revalidated with
// the origin server to see if the content needs to be reloaded. The
// following four flags control how often this validation occurs.
// These flags are commonly used for "normal" loading. Note that
// the VALIDATE_HEURISTICALLY and VALIDATE_ONCE_PER_SESSION flags can be
// combined to validate heuristically but no more than once per session.
//
const unsigned long VALIDATE_NEVER = 1 << 12;
const unsigned long VALIDATE_ALWAYS = 1 << 13;
const unsigned long VALIDATE_ONCE_PER_SESSION = 1 << 14;
const unsigned long VALIDATE_HEURISTICALLY = 1 << 15;
/**
* Accesses the load attributes for the channel. E.g. setting the load
* attributes with the LOAD_QUIET bit set causes the loading process to
* not deliver status notifications to the program performing the load,
* and to not contribute to keeping any nsILoadGroup it may be contained
* in from firing its OnLoadComplete notification.
*/
attribute nsLoadFlags loadAttributes;
/**
* Returns the content MIME type of the channel if available. Note that the
* content type can often be wrongly specified (wrong file extension, wrong
* MIME type, wrong document type stored on a server, etc.) and the caller
* most likely wants to verify with the actual data.
*/
attribute string contentType;
/**
* Returns the length of the data assiciated with the channel if available.
* If the length is unknown then -1 is returned.
*/
readonly attribute long contentLength;
/**
* Accesses the owner corresponding to the entity that is
* responsible for this channel. Used by security code to grant
* or diminish privileges to mobile code loaded from this channel.
*/
attribute nsISupports owner;
/**
* Accesses the load group in which the channel is a currently a member.
*/
attribute nsILoadGroup loadGroup;
/**
* Accesses the capabilities callbacks of the channel. This is set by clients
* who wish to provide a means to receive progress, status and protocol-specific
* notifications.
*/
attribute nsIInterfaceRequestor notificationCallbacks;
};
////////////////////////////////////////////////////////////////////////////////
/**
* nsIInputStreamChannel is an interface that allows for the initialization
* of a simple nsIChannel that is constructed from a single input stream and
* associated content type. Input stream channels only allow the input stream
* to be accessed, not the output stream.
*/
[scriptable, uuid(bfbf843a-8b89-11d3-8cd9-0060b0fc14a3)]
interface nsIInputStreamChannel : nsIChannel
{
void init(in nsIURI uri,
in string contentType,
in long contentLength,
in nsIInputStream inStr,
in nsILoadGroup aLoadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in nsIURI originalURI,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
};
%{C++
#define NS_INPUTSTREAMCHANNEL_CID \
{ /* 436d84f8-8b8a-11d3-8cd9-0060b0fc14a3 */ \
0x436d84f8, \
0x8b8a, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}
////////////////////////////////////////////////////////////////////////////////
/**
* nsIFileChannel is an interface that allows for the initialization
* of a simple nsIChannel that is constructed from a single nsIFile and
* associated content type.
*/
[scriptable, uuid(6eef6444-c7e3-11d3-8cda-0060b0fc14a3)]
interface nsIFileChannel : nsIChannel
{
void init(in nsIFile file,
in long mode,
in string contentType,
in long contentLength,
in nsILoadGroup aLoadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in nsIURI originalURI,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
readonly attribute nsIFile file;
};
%{C++
#define NS_FILECHANNEL_CLASSNAME "File Channel"
#define NS_FILECHANNEL_PROGID "component://netscape/network/file-channel"
#define NS_FILECHANNEL_CID \
{ /* 7036066e-c7e3-11d3-8cda-0060b0fc14a3 */ \
0x7036066e, \
0xc7e3, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,30 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[scriptable, uuid(fb65fd70-1881-11d3-9337-00104ba0fd40)]
interface nsIEventSinkGetter : nsISupports
{
nsISupports getEventSink(in string command, in nsIIDRef eventSinkIID);
};

View File

@@ -0,0 +1,244 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIInputStream.idl"
#include "nsIOutputStream.idl"
#include "nsILocalFile.idl"
[scriptable, uuid(e3d56a20-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsIFileInputStream : nsIInputStream
{
void init(in nsILocalFile file);
};
[scriptable, uuid(e6f68040-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsIFileOutputStream : nsIOutputStream
{
void init(in nsILocalFile file, in long flags, in long mode);
};
[scriptable, uuid(e9de5df0-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsISeekableStream : nsISupports
{
// correspond to PRSeekWhence values
const long NS_SEEK_SET = 0;
const long NS_SEEK_CUR = 1;
const long NS_SEEK_END = 2;
void seek(in long whence, in long offset);
unsigned long tell();
};
[scriptable, uuid(616f5b48-da09-11d3-8cda-0060b0fc14a3)]
interface nsIBufferedInputStream : nsIInputStream
{
void init(in nsIInputStream fillFromStream,
in unsigned long bufferSize);
};
[scriptable, uuid(6476378a-da09-11d3-8cda-0060b0fc14a3)]
interface nsIBufferedOutputStream : nsIOutputStream
{
void init(in nsIOutputStream sinkToStream,
in unsigned long bufferSize);
};
%{C++
////////////////////////////////////////////////////////////////////////////////
#define NS_FILEINPUTSTREAM_CLASSNAME "File Input Stream"
#define NS_FILEINPUTSTREAM_PROGID "component://netscape/network/file-input-stream"
#define NS_FILEINPUTSTREAM_CID \
{ /* be9a53ae-c7e9-11d3-8cda-0060b0fc14a3 */ \
0xbe9a53ae, \
0xc7e9, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
#define NS_FILEOUTPUTSTREAM_CLASSNAME "File Output Stream"
#define NS_FILEOUTPUTSTREAM_PROGID "component://netscape/network/file-output-stream"
#define NS_FILEOUTPUTSTREAM_CID \
{ /* c272fee0-c7e9-11d3-8cda-0060b0fc14a3 */ \
0xc272fee0, \
0xc7e9, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
#define NS_BUFFEREDINPUTSTREAM_CLASSNAME "Buffered Input Stream"
#define NS_BUFFEREDINPUTSTREAM_PROGID "component://netscape/network/buffered-input-stream"
#define NS_BUFFEREDINPUTSTREAM_CID \
{ /* 9226888e-da08-11d3-8cda-0060b0fc14a3 */ \
0x9226888e, \
0xda08, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
#define NS_BUFFEREDOUTPUTSTREAM_CLASSNAME "Buffered Output Stream"
#define NS_BUFFEREDOUTPUTSTREAM_PROGID "component://netscape/network/buffered-output-stream"
#define NS_BUFFEREDOUTPUTSTREAM_CID \
{ /* 9868b4ce-da08-11d3-8cda-0060b0fc14a3 */ \
0x9868b4ce, \
0xda08, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
// move to nsNetUtil.h later...
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "nsILocalFile.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "prio.h" // for read/write modes, etc.
inline nsresult
NS_NewFileChannel(nsIFile* file,
PRInt32 mode,
const char* contentType,
PRUint32 contentLength,
nsILoadGroup* group,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIFileChannel **result)
{
nsresult rv;
nsCOMPtr<nsIFileChannel> channel;
static NS_DEFINE_CID(kFileChannelCID, NS_FILECHANNEL_CID);
rv = nsComponentManager::CreateInstance(kFileChannelCID,
nsnull,
NS_GET_IID(nsIFileChannel),
getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->Init(file, mode, contentType, contentLength, group,
notificationCallbacks, loadAttributes, originalURI,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
*result = channel;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewFileInputStream(nsIFile* file, nsIInputStream* *result)
{
nsresult rv;
nsCOMPtr<nsIFileInputStream> in;
static NS_DEFINE_CID(kFileInputStreamCID, NS_FILEINPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kFileInputStreamCID,
nsnull,
NS_GET_IID(nsIFileInputStream),
getter_AddRefs(in));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(file, &rv);
if (NS_FAILED(rv)) return rv;
rv = in->Init(localFile);
if (NS_FAILED(rv)) return rv;
*result = in;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewFileOutputStream(nsIFile* file, PRInt32 flags, PRInt32 mode,
nsIOutputStream* *result)
{
nsresult rv;
nsCOMPtr<nsIFileOutputStream> out;
static NS_DEFINE_CID(kFileOutputStreamCID, NS_FILEOUTPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kFileOutputStreamCID,
nsnull,
NS_GET_IID(nsIFileOutputStream),
getter_AddRefs(out));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(file, &rv);
if (NS_FAILED(rv)) return rv;
rv = out->Init(localFile, flags, mode);
if (NS_FAILED(rv)) return rv;
*result = out;
NS_ADDREF(*result);
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
inline nsresult
NS_NewBufferedInputStream(nsIInputStream* str, PRUint32 bufferSize,
nsIInputStream* *result)
{
nsresult rv;
nsCOMPtr<nsIBufferedInputStream> in;
static NS_DEFINE_CID(kBufferedInputStreamCID, NS_BUFFEREDINPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kBufferedInputStreamCID,
nsnull,
NS_GET_IID(nsIBufferedInputStream),
getter_AddRefs(in));
if (NS_FAILED(rv)) return rv;
rv = in->Init(str, bufferSize);
if (NS_FAILED(rv)) return rv;
*result = in;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewBufferedOutputStream(nsIOutputStream* str, PRUint32 bufferSize,
nsIOutputStream* *result)
{
nsresult rv;
nsCOMPtr<nsIBufferedOutputStream> out;
static NS_DEFINE_CID(kBufferedOutputStreamCID, NS_BUFFEREDOUTPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kBufferedOutputStreamCID,
nsnull,
NS_GET_IID(nsIBufferedOutputStream),
getter_AddRefs(out));
if (NS_FAILED(rv)) return rv;
rv = out->Init(str, bufferSize);
if (NS_FAILED(rv)) return rv;
*result = out;
NS_ADDREF(*result);
return NS_OK;
}
%}

View File

@@ -0,0 +1,40 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
interface nsIInputStream;
interface nsIOutputStream;
[scriptable, uuid(818e1370-77c4-11d3-9395-00104ba0fd40)]
interface nsIFileSystem : nsISupports
{
void open(out string contentType,
out long contentLength);
void close(in nsresult status);
readonly attribute nsIInputStream inputStream;
readonly attribute nsIOutputStream outputStream;
};

View File

@@ -0,0 +1,73 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
%{C++
#include "nsFileSpec.h"
%}
interface nsIChannel;
interface nsIFileSystem;
interface nsIEventSinkGetter;
interface nsIInputStream;
interface nsIRunnable;
interface nsIFile;
[scriptable, uuid(57211a60-8c45-11d3-93ac-00104ba0fd40)]
interface nsIFileTransportService : nsISupports
{
nsIChannel createTransport(in nsIFile file,
in long mode,
in string command,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
// This version can be used with an existing input stream to serve
// as a data pump:
nsIChannel createTransportFromStream(in nsIInputStream fromStream,
in string contentType,
in long contentLength,
in string command,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
nsIChannel createTransportFromFileSystem(in nsIFileSystem fsObj,
in string command,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
void dispatchRequest(in nsIRunnable runnable);
void suspend(in nsIRunnable trans);
void resume(in nsIRunnable trans);
void processPendingRequests();
void shutdown();
};
%{C++
#define NS_FILETRANSPORTSERVICE_CID \
{ /* 2bb2b250-ea35-11d2-931b-00104ba0fd40 */ \
0x2bb2b250, \
0xea35, \
0x11d2, \
{0x93, 0x1b, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
%}

View File

@@ -0,0 +1,175 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIProtocolHandler;
interface nsIURI;
interface nsIInterfaceRequestor;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsIEventQueue;
interface nsIBufferInputStream;
interface nsIInputStream;
interface nsIBufferOutputStream;
interface nsIFileChannel;
interface nsILoadGroup;
interface nsILoadGroupObserver;
interface nsIFile;
interface nsIInputStream;
interface nsIOutputStream;
[scriptable, uuid(ab7c3a84-d488-11d3-8cda-0060b0fc14a3)]
interface nsIIOService : nsISupports
{
/**
* constants for the Escape mask in the call to URLEscape
*/
const short url_Scheme = (1<<0);
const short url_Username = (1<<1);
const short url_Password = (1<<2);
const short url_Host = (1<<3);
const short url_Directory = (1<<4);
const short url_FileBaseName = (1<<5);
const short url_FileExtension = (1<<6);
const short url_Param = (1<<7);
const short url_Query = (1<<8);
const short url_Ref = (1<<9);
/**
* Returns a protocol handler for a given URI scheme.
*/
nsIProtocolHandler getProtocolHandler(in string scheme);
/**
* This method constructs a new URI by first determining the scheme
* of the URI spec, and then delegating the construction of the URI
* to the protocol handler for that scheme. QueryInterface can be used
* on the resulting URI object to obtain a more specific type of URI.
*/
nsIURI newURI(in string aSpec, in nsIURI aBaseURI);
/**
* Creates a channel for a given URI. The notificationCallbacks argument
* is used to obtain the appropriate callbacks for the URI's protocol from the
* application.
*
* @param originalURI - Specifies the original URI which caused the creation
* of this channel. This can occur when the construction of one channel
* (e.g. for resource:) causes another channel to be created on its behalf
* (e.g. a file: channel), or if a redirect occurs, causing the current
* URL to become different from the original URL. If NULL, the aURI parameter
* will be used as the originalURI instead.
*/
nsIChannel newChannelFromURI(in string verb,
in nsIURI aURI,
in nsILoadGroup aLoadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in nsIURI originalURI,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Convenience routine that first creates a URI by calling NewURI, and
* then passes the URI to NewChannelFromURI.
*/
nsIChannel newChannel(in string verb,
in string aSpec,
in nsIURI aBaseURI,
in nsILoadGroup aLoadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in nsIURI originalURI,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Returns true if networking is in "offline" mode. When in offline mode, attempts
* to access the network will fail (although this is not necessarily corrolated with
* whether there is actually a network available -- that's hard to detect without
* causing the dialer to come up).
*/
attribute boolean offline;
////////////////////////////////////////////////////////////////////////////
// URL parsing utilities
/**
* Utility for protocol implementors -- extracts the scheme from a URL
* string, consistently and according to spec.
* @param urlString - the URL string to parse
* @param schemeStartPos - the resulting starting position of the scheme substring
* (may skip over whitespace)
* @param schemeEndPos - the resulting ending position of the scheme substring
* (the position of the colon)
* @param scheme - an allocated substring containing the scheme. If this parameter
* is null going into the routine, then the scheme is not allocated and
* returned. Free with nsCRT::free.
*
* @return NS_OK - if successful
* @return NS_ERROR_MALFORMED_URI - if the urlString is not of the right form
*/
void extractScheme(in string urlString,
out unsigned long schemeStartPos,
out unsigned long schemeEndPos,
out string scheme);
/**
* Encode characters into % escaped hexcodes.
*/
string escape(in string str, in short mask);
/**
* Decode % escaped hex codes into character values.
*/
string unescape(in string str);
/**
* Get port from string.
*/
long extractPort(in string str);
/**
* Resolves a relative path string containing "." and ".."
* with respect to a base path (assumed to already be resolved).
* For example, resolving "../../foo/./bar/../baz.html" w.r.t.
* "/a/b/c/d/e/" yields "/a/b/c/foo/baz.html". Attempting to
* ascend above the base results in the NS_ERROR_MALFORMED_URI
* exception. If basePath is null, it treats it as "/".
*/
string resolveRelativePath(in string relativePath,
in string basePath);
};
%{C++
#define NS_IOSERVICE_CID \
{ /* 9ac9e770-18bc-11d3-9337-00104ba0fd40 */ \
0x9ac9e770, \
0x18bc, \
0x11d3, \
{0x93, 0x37, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
%}

View File

@@ -0,0 +1,104 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIRequest.idl"
interface nsIChannel;
interface nsISimpleEnumerator;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsIInputStream;
[scriptable, uuid(60fdf550-5392-11d3-9a97-0080c7cb1080)]
interface nsILoadGroupListenerFactory : nsISupports
{
nsIStreamListener createLoadGroupListener(in nsIStreamListener alistener);
};
/**
* A load group maintains a collection of active URL requests.
*/
[scriptable, uuid(19845248-29ab-11d3-8cce-0060b0fc14a3)]
interface nsILoadGroup : nsIRequest
{
void init(in nsIStreamObserver observer);
/**
* Accesses the default load attributes for the group, returned as
* a flag word. Setting the default load attributes will cause them
* to be applied to each new channel inserted into the group.
*/
attribute unsigned long defaultLoadAttributes;
/**
* Accesses the default load channel for the group. Each time a number
* of channels are added to a group, the DefaultLoadChannel may be set
* to indicate that all of the channels are related to a particular URL.
*/
attribute nsIChannel defaultLoadChannel;
/**
* Adds a new channel to the group. This will cause the default load
* attributes to be applied to that channel. If the channel added is
* the first channel in the group, the group's observer's OnStartRequest
* method is called.
*/
void addChannel(in nsIChannel channel,
in nsISupports ctxt);
/**
* Removes a channel from the group. If the channel removed is
* the last channel in the group, the group's observer's OnStopRequest
* method is called.
*/
void removeChannel(in nsIChannel channel,
in nsISupports ctxt,
in nsresult status,
in wstring errorMsg);
/**
* Returns the channels contained directly in this group.
* Enumerator element type: nsIChannel.
*/
readonly attribute nsISimpleEnumerator channels;
attribute nsIStreamObserver groupObserver;
attribute nsILoadGroupListenerFactory groupListenerFactory;
readonly attribute unsigned long activeCount;
};
%{C++
#define NS_LOADGROUP_CID \
{ /* e1c61582-2a84-11d3-8cce-0060b0fc14a3 */ \
0xe1c61582, \
0x2a84, \
0x11d3, \
{0x8c, 0xce, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -0,0 +1,47 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
/* This interface defines a registry entry for the networking libraries
* external module registry. */
#include "nsISupports.idl"
#include "nsINetNotify.idl"
interface nsIEventQueue;
interface nsINetModRegEntry;
interface nsINetNotify;
%{ C++
// {F126BD90-1472-11d3-A15A-0050041CAF44}
#define NS_NETMODREGENTRY_CID \
{ 0xf126bd90, 0x1472, 0x11d3, { 0xa1, 0x5a, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
%}
[scriptable, uuid(9F482BD0-1476-11d3-A15A-0050041CAF44)]
interface nsINetModRegEntry : nsISupports
{
readonly attribute nsINetNotify syncProxy;
readonly attribute nsINetNotify asyncProxy;
readonly attribute string topic;
boolean equals(in nsINetModRegEntry aEntry);
};

View File

@@ -0,0 +1,80 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
/* The nsINetModuleMgr singleton service allows external module to register
* themselves with the networking library to receive events they want to
* receive.
*
* An external module that is interested in being notified when a particular
* networking level event occurs would register with this service, and
* implement the appropriate interface(s) that correspond to the events they
* want to receive. These interfaces are defined by networking internal
* components (for example, http would define a notification interface that
* the external cookies module would implement).
*/
#include "nsISupports.idl"
#include "nsIEnumerator.idl"
#include "nsINetNotify.idl"
interface nsIEventQueue;
%{ C++
// {4EBDAFE0-13BA-11d3-A15A-0050041CAF44}
#define NS_NETMODULEMGR_CID \
{ 0x4ebdafe0, 0x13ba, 0x11d3, { 0xa1, 0x5a, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
// The list of available PROGIDS to register for notification on.
#define NS_NETWORK_MODULE_MANAGER_HTTP_REQUEST_PROGID "component://netscape/network/moduleMgr/http/request"
#define NS_NETWORK_MODULE_MANAGER_HTTP_RESPONSE_PROGID "component://netscape/network/moduleMgr/http/response"
%}
[scriptable, uuid(ff9ead40-0ef2-11d3-9de6-0010a4053fd0)]
interface nsINetModuleMgr : nsISupports {
// Register the external module to receive notifications.
//
// ARGUMENTS:
// aTopic: The internal component that the external module wants to monitor.
// aNotify: The external module interface methods to be called when an event is fired.
//
// RETURNS: nsresult
void registerModule(in string aTopic, in nsINetNotify aNotify);
// Unregister the external module. Removes the nsINetModuleMgr binding between
// internal component and external module.
//
// ARGUMENTS:
// aTopic: The internal component being monitored.
// aNotify: The external modules notification module.
//
// RETURNS: nsresult
void unregisterModule(in string aTopic, in nsINetNotify aNotify);
// Enumerates all the registered modules for the specified topic.
//
// ARGUMENTS:
// aTopic: the component to get all the notifiers for.
// aEnumerator: the array of notifiers.
void enumerateModules(in string aTopic, out nsISimpleEnumerator aEnumerator);
};

View File

@@ -0,0 +1,28 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[uuid(4A3019E0-1CF3-11d3-A15B-0050041CAF44)]
interface nsINetNotify : nsISupports {
};

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[scriptable, uuid(edd8be01-8e0d-11d3-b7a0-c46e946292bc)]
interface nsINetPrompt : nsISupports
{
/**
* Puts up an alert dialog with an OK button.
*/
void alert( in string url, in boolean stripurl, in wstring title, in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean confirm( in string url, in boolean stripurl, in wstring title, in wstring text);
/**
* Puts up a username/password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptUsernameAndPassword(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring user,
out wstring pwd);
/**
* Puts up a password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptPassword(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring pwd);
/**
* Puts up a prompt dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean prompt(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring pwd);
};

View File

@@ -0,0 +1,51 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
interface nsIURI;
interface nsIChannel;
/**
* An instance of nsIFfpEventSink should be passed as the eventSink
* argument of nsINetService::NewConnection for ftp URLs. It defines
* the callbacks to the application program (the html parser).
*/
[scriptable, uuid(dd47ee00-18c2-11d3-9337-00104ba0fd40)]
interface nsIProgressEventSink : nsISupports
{
/**
* Notify the EventSink that progress as occurred for the URL load.<BR>
*/
void onProgress(in nsIChannel channel,
in nsISupports ctxt,
in unsigned long aProgress,
in unsigned long aProgressMax);
/**
* Notify the EventSink with a status message for the URL load.<BR>
*/
void onStatus(in nsIChannel channel,
in nsISupports ctxt,
in wstring aMsg);
};

View File

@@ -0,0 +1,102 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[scriptable, uuid(a63f70c0-148b-11d3-9333-00104ba0fd40)]
interface nsIPrompt : nsISupports
{
/**
* Puts up an alert dialog with an OK button.
*/
void alert(in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean confirm(in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons, and
* a message with a single checkbox.
* @return true for OK, false for Cancel
*/
boolean confirmCheck(in wstring text,
in wstring checkMsg,
out boolean checkValue);
/**
* Puts up a text input dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean prompt(in wstring text,
in wstring defaultText,
out wstring result);
/**
* Puts up a username/password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptUsernameAndPassword(in wstring text,
out wstring user,
out wstring pwd);
/**
* Puts up a password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptPassword(in wstring text,
in wstring title,
out wstring pwd);
/**
* Puts up a dialog box which has a list box of strings
*/
boolean select(in wstring inDialogTitle,
in wstring inMsg,
in PRUint32 inCount,
[array, size_is(inCount)] in wstring inList,
out long outSelection);
/**
* Put up a universal dialog
*/
void universalDialog(in wstring inTitleMessage,
in wstring inDialogTitle, /* e.g., alert, confirm, prompt, prompt password */
in wstring inMsg, /* main message for dialog */
in wstring inCheckboxMsg, /* message for checkbox */
in wstring inButton0Text, /* text for first button */
in wstring inButton1Text, /* text for second button */
in wstring inButton2Text, /* text for third button */
in wstring inButton3Text, /* text for fourth button */
in wstring inEditfield1Msg, /*message for first edit field */
in wstring inEditfield2Msg, /* message for second edit field */
inout wstring inoutEditfield1Value, /* initial and final value for first edit field */
inout wstring inoutEditfield2Value, /* initial and final value for second edit field */
in wstring inIConURL, /* url of icon to be displayed in dialog */
inout boolean inoutCheckboxState, /* initial and final state of checkbox */
in PRInt32 inNumberButtons, /* total number of buttons (0 to 4) */
in PRInt32 inNumberEditfields, /* total number of edit fields (0 to 2) */
in PRInt32 inEditField1Password, /* ??? */
out PRInt32 outButtonPressed); /* number of button that was pressed (0 to 3) */
};

View File

@@ -0,0 +1,74 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIURI;
interface nsIInterfaceRequestor;
interface nsILoadGroup;
[scriptable, uuid(15fd6940-8ea7-11d3-93ad-00104ba0fd40)]
interface nsIProtocolHandler : nsISupports
{
readonly attribute string scheme;
readonly attribute long defaultPort;
/**
* Makes a URI object that is suitable for loading by this protocol.
* In the usual case (when only the accessors provided by nsIURI are
* needed), this method just constructs a standard URI using the
* component manager with kStandardURLCID.
*/
nsIURI newURI(in string aSpec, in nsIURI aBaseURI);
/**
* Constructs a new channel for this protocol handler.
*
* @param originalURI - Specifies the original URI which caused the creation
* of this channel. This can occur when the construction of one channel
* (e.g. for resource:) causes another channel to be created on its behalf
* (e.g. a file: channel), or if a redirect occurs, causing the current
* URL to become different from the original URL. If NULL, the aURI parameter
* will be used as the originalURI instead.
*/
nsIChannel newChannel(in string verb,
in nsIURI aURI,
in nsILoadGroup aLoadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in nsIURI originalURI,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
};
%{C++
#define NS_NETWORK_PROTOCOL_PROGID "component://netscape/network/protocol"
#define NS_NETWORK_PROTOCOL_PROGID_PREFIX NS_NETWORK_PROTOCOL_PROGID "?name="
#define NS_NETWORK_PROTOCOL_PROGID_PREFIX_LENGTH 43 // nsCRT::strlen(NS_NETWORK_PROTOCOL_PROGID_PREFIX)
// Unknown Protocol Error
#define NS_ERROR_UNKNOWN_PROTOCOL NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 18)
%}

View File

@@ -0,0 +1,40 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsIURI.idl"
#include "nsIProxy.idl"
%{C++
#define NS_PROTOCOLPROXYSERVICE_CID \
{ /* E9B301C0-E0E4-11d3-A1A8-0050041CAF44 */ \
0xe9b301c0, 0xe0e4, 0x11d3, { 0xa1, 0xa8, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
%}
[scriptable, uuid(495CC980-E0D4-11d3-A1A8-0050041CAF44)]
interface nsIProtocolProxyService : nsISupports
{
readonly attribute PRBool proxyEnabled;
void examineForProxy(in nsIURI aURI, in nsIProxy aProxy);
};

View File

@@ -0,0 +1,41 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
/*
The nsIProxy interface allows setting and getting of proxy host and port.
This is for use by protocol handlers. If you are writing a protocol handler
and would like to support proxy behaviour then derive from this as well as
the nsIProtocolHandler class.
-Gagan Saksena 02/25/99
*/
#include "nsISupports.idl"
[scriptable, uuid(0492D011-CD2F-11d2-B013-006097BFC036)]
interface nsIProxy : nsISupports
{
attribute string proxyHost;
/* -1 on Set call indicates switch to default port */
attribute long proxyPort;
};

View File

@@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[scriptable, uuid(F2CAABA0-2F25-11d3-A164-0050041CAF44)]
interface nsIRequest : nsISupports
{
/**
* Returns true if the request is pending (active). Returns false
* after completion or successful calling Cancel. Suspended requests
* are still considered pending.
*/
boolean isPending();
/**
* Cancels the current request. This will close any open input or
* output streams and terminate any async requests.
*/
void cancel();
/**
* Suspends the current requests. This may have the effect of closing
* any underlying transport (in order to free up resources), although
* any open streams remain logically opened and will continue delivering
* data when the transport is resumed.
*/
void suspend();
/**
* Resumes the current request. This may have the effect of re-opening
* any underlying transport and will resume the delivery of data to
* any open streams.
*/
void resume();
};

View File

@@ -0,0 +1,35 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
[scriptable, uuid(785CA0F0-C39E-11d3-9ED6-0010A4053FD0)]
interface nsISocketTransport : nsISupports
{
attribute boolean reuseConnection;
/**
* Is used to tell the channel to stop reading data after a certain point;
* needed by HTTP/1.1
*/
attribute long bytesAllowed;
};

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
interface nsIChannel;
interface nsIEventSinkGetter;
[scriptable, uuid(05331390-6884-11d3-9382-00104ba0fd40)]
interface nsISocketTransportService : nsISupports
{
/**
* Creates a transport for a specified host and port.
* The eventSinkGetter is used to get the appropriate callbacks
* for the socket activity from the application. These include
* the progress and the status messages like "Contacting host.."
* etc. The printHost contains the actual hostname (and not the
* proxy) for displaying in status messages.
*/
nsIChannel createTransport(in string host,
in long port,
in string printHost,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
nsIChannel createTransportOfType(in string socketType,
in string host,
in long port,
in string printHost,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Returns true if the specified transport is good enough for
* being used again. The situations in which this may return false
* include- an error including server resets, an explicit
* Connection: close header (for HTTP) and timeouts!
*/
boolean reuseTransport(in nsIChannel i_Transport);
void shutdown ();
void wakeup (in nsIChannel i_Transport);
};
%{C++
#define NS_SOCKETTRANSPORTSERVICE_CID \
{ /* c07e81e0-ef12-11d2-92b6-00105a1b0d64 */ \
0xc07e81e0, \
0xef12, \
0x11d2, \
{0x92, 0xb6, 0x00, 0x10, 0x5a, 0x1b, 0x0d, 0x64} \
}
#define NS_ERROR_CONNECTION_REFUSED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 13)
#define NS_ERROR_NET_TIMEOUT NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 14)
%}

View File

@@ -0,0 +1,48 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
interface nsIProgressEventSink;
interface nsIChannel;
/**
* The nsIStatusCodeEventSink is a temporary interface to allow passing
* status codes from the socket threads onto the UI without having to
* pass strings. This could eventually go away if the proxy events
* stuff can handle nested event loop. dougt is working on that.
* We could continue to use this if this seems reasonable enough.
*/
[scriptable, uuid(6998ff36-1dd2-11b2-9ab7-e72a0f9fdd8c)]
interface nsIStatusCodeEventSink : nsISupports
{
/**
* Notify the EventSink with a status code for the URL load.<BR>
* Use IOService to request converting that code to a string.
*/
void onStatus(in nsIProgressEventSink sink,
in nsIChannel channel,
in nsISupports ctxt,
in unsigned long aCode);
};

View File

@@ -0,0 +1,96 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIStreamObserver.idl"
interface nsIBufferInputStream;
interface nsIInputStream;
interface nsIBufferOutputStream;
interface nsIEventQueue;
[scriptable, uuid(1a637020-1482-11d3-9333-00104ba0fd40)]
interface nsIStreamListener : nsIStreamObserver
{
void onDataAvailable(in nsIChannel channel,
in nsISupports ctxt,
in nsIInputStream inStr,
in unsigned long sourceOffset,
in unsigned long count);
};
/**
* An asynchronous stream listener is used to ship data over to another thread specified
* by the thread's event queue. The receiver stream listener is then used to receive
* the notifications on the other thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamListener.
*/
[scriptable, uuid(1b012ade-91bf-11d3-8cd9-0060b0fc14a3)]
interface nsIAsyncStreamListener : nsIStreamListener
{
/**
* Initializes an nsIAsyncStreamListener.
* @param eventQueue - may be null indicating the calling thread's event queue
*/
void init(in nsIStreamListener receiver,
in nsIEventQueue eventQueue);
};
/**
* A synchronous stream listener pushes data through a pipe that ends up
* in an input stream to be read by another thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamListener.
*/
[scriptable, uuid(1f9fb93e-91bf-11d3-8cd9-0060b0fc14a3)]
interface nsISyncStreamListener : nsIStreamListener
{
/**
* Initializes an nsISyncStreamListener.
*/
void init(out nsIInputStream inStream,
out nsIBufferOutputStream outStream);
};
%{C++
// Use this CID to construct an nsIAsyncStreamListener
#define NS_ASYNCSTREAMLISTENER_CID \
{ /* 60047bb2-91c0-11d3-8cd9-0060b0fc14a3 */ \
0x60047bb2, \
0x91c0, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
// Use this CID to construct an nsISyncStreamListener
#define NS_SYNCSTREAMLISTENER_CID \
{ /* 65fa5cb2-91c0-11d3-8cd9-0060b0fc14a3 */ \
0x65fa5cb2, \
0x91c0, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -0,0 +1,67 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIURI;
interface nsILoadGroup;
interface nsIStreamObserver;
interface nsIStreamLoader;
interface nsIInterfaceRequestor;
[scriptable, uuid(359F7990-D4E9-11d3-A1A5-0050041CAF44)]
interface nsIStreamLoaderObserver : nsISupports
{
void onStreamComplete(in nsIStreamLoader loader,
in nsISupports ctxt,
in nsresult status,
in unsigned long resultLength,
[size_is(resultLength)] in string result);
};
[scriptable, uuid(31d37360-8e5a-11d3-93ad-00104ba0fd40)]
interface nsIStreamLoader : nsISupports
{
void init(in nsIURI uri,
in nsIStreamLoaderObserver completionObserver,
in nsISupports ctxt,
in nsILoadGroup loadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Gets the number of bytes read so far.
*/
readonly attribute unsigned long numBytesRead;
};
%{C++
#define NS_STREAMLOADER_CID \
{ /* 5BA6D920-D4E9-11d3-A1A5-0050041CAF44 */ \
0x5ba6d920, 0xd4e9, 0x11d3, { 0xa1, 0xa5, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } \
}
%}

View File

@@ -0,0 +1,78 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
interface nsIEventQueue;
interface nsIChannel;
[scriptable, uuid(fd91e2e0-1481-11d3-9333-00104ba0fd40)]
interface nsIStreamObserver : nsISupports
{
void onStartRequest(in nsIChannel channel,
in nsISupports ctxt);
void onStopRequest(in nsIChannel channel,
in nsISupports ctxt,
in nsresult status,
in wstring errorMsg);
};
/**
* An asynchronous stream observer is used to ship data over to another thread specified
* by the thread's event queue. The receiver stream observer is then used to receive
* the notifications on the other thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamObservers.
*/
[scriptable, uuid(a28dc590-91b3-11d3-8cd9-0060b0fc14a3)]
interface nsIAsyncStreamObserver : nsIStreamObserver
{
/**
* Initializes an nsIAsyncStreamObserver.
* @param eventQueue - may be null indicating the calling thread's event queue
*/
void init(in nsIStreamObserver receiver,
in nsIEventQueue eventQueue);
};
%{C++
// Use this CID to construct an nsIAsyncStreamObserver
#define NS_ASYNCSTREAMOBSERVER_CID \
{ /* fcc7c380-91b3-11d3-8cd9-0060b0fc14a3 */ \
0xfcc7c380, \
0x91b3, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
// Generic status codes for OnStopRequest:
#define NS_BINDING_SUCCEEDED NS_OK
#define NS_BINDING_FAILED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 1)
#define NS_BINDING_ABORTED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 2)
%}

View File

@@ -0,0 +1,183 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsIURLParser.idl"
/**
* URIs are essentially structured names for things -- anything.
* This interface provides accessors to destructure those names.
*
* This interface follows Tim Berners-Lee's URI spec:
*
* http://www.w3.org/Addressing/URI/URI_Overview.html
*
* essentially:
*
* ftp://username:password@hostname:portnumber/pathname
* \ / \ / \ / \ /\ /
* - --------------- ------ -------- -------
* | | | | |
* | | | | Path
* | | | Port
* | | Host
* | PreHost
* Scheme
*
* The subclass nsIURL provides a means to open an input or output
* stream to a URI as a source/destination, as well as providing additional
* accessors to destructure the path, query and reference portions typically
* associated with URLs.
*/
%{C++
#undef GetPort // XXX Windows!
#undef SetPort // XXX Windows!
%}
[scriptable, uuid(07a22cc0-0ce5-11d3-9331-00104ba0fd40)]
interface nsIURI : nsISupports
{
/**
* Returns a string representation of the URI. Setting the spec
* causes the new spec to be parsed, initializing the URI. Setting
* the spec (or any of the accessors) causes also any currently
* open streams on the URI's channel to be closed.
*/
attribute string spec;
/**
* The Scheme is the protocol to which this URI refers. Setting
* the scheme is a special operation that builds up an equivalent
* URI string from the new scheme and all the other URI attributes
* and passes the it to the nsIOService to create a new URI for
* the new scheme.
*/
attribute string scheme;
/**
* The PreHost portion includes elements like the optional
* username:password, or maybe other scheme specific items.
*/
attribute string preHost;
attribute string username;
attribute string password;
/**
* The Host is the internet domain name to which this URI refers.
* Note that it could be an IP address as well.
*/
attribute string host;
/**
* A return value of -1 indicates that no port value is set and the
* implementor of the specific scheme will use its default port.
* Similarly setting a value of -1 indicates that the default is to be used.
* Thus as an example:
* for HTTP, Port 80 is same as a return value of -1.
* However after setting a port (even if its default), the port number will
* appear in the ToNewCString function.
*/
attribute long port;
/**
* Note that the path includes the leading '/' Thus if no path is
* available the Path accessor will return a "/"
* For SetPath if none is provided, one would be prefixed to the path.
*/
attribute string path;
/**
* This is a handle to the Parser used to parse the URI
*/
attribute nsIURLParser URLParser;
/**
* Note that this comparison is only on char* level. Use
* the scheme specific URI to do a more thorough check. For example,
* in HTTP:
* http://foo.com:80 == http://foo.com
* but this function through nsIURI alone will not return equality
* for this case.
*/
boolean equals(in nsIURI other);
/**
* Clones the current URI. The newly created URI will be in a closed
* state even if the underlying channel of the cloned URI is open.
* Cloning allows the current location to be retained since once the
* channel is opened the URI may get redirected to a new location.
*/
nsIURI clone();
/**
* Sets the given string to be a relative path for this URI, and
* changes this to read relative. Thus for example- if this =
* http://foo.com/bar/index.html, then calling SetRelativePath("/baz") will
* change this to http://foo.com/baz and calling it with "baz" will
* change this to http://foo.com/bar/baz.
*/
void setRelativePath(in string relativePath);
/**
* This method resolves a relative string into an absolute URI string,
* using the URI as the base.
*
* This method subsumes the deprecated method nsIIOService::MakeAbsolute.
*/
string resolve(in string relativePath);
};
%{C++
// Malformed URI Error
#define NS_ERROR_MALFORMED_URI NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 10)
/**
* Protocol writers can obtain a very basic (ok, degenerate) implementation
* of nsIURI by calling the component manager with NS_SIMPLEURI_CID. The
* implementation returned will only parse things of the form:
*
* about:cache
* \ / \ /
* --- ---
* | |
* Scheme Path
*
* where the path is everything after the colon. Note that this is probably
* only useful for cases like about: or javascript: URIs.
*
* *** What you most likely will want is NS_STANDARDURL_CID which is much more
* full featured. Look at nsIURL.idl for more details.
*/
#define NS_SIMPLEURI_CID \
{ /* e0da1d70-2f7b-11d3-8cd0-0060b0fc14a3 */ \
0xe0da1d70, \
0x2f7b, \
0x11d3, \
{0x8c, 0xd0, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -0,0 +1,148 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIURI.idl"
interface nsIChannel;
interface nsIEventSinkGetter;
/**
* The nsIURL interface provides convenience methods that further
* break down the path portion of nsIURI:
*
* http://directory/fileBaseName.fileExtension?query
* http://directory/fileBaseName.fileExtension#ref
* http://directory/fileBaseName.fileExtension;param
* \ \ /
* \ -----------------------
* \ | /
* \ fileName /
* ----------------------------
* |
* filePath
*/
[scriptable, uuid(d6116970-8034-11d3-9399-00104ba0fd40)]
interface nsIURL : nsIURI
{
////////////////////////////////////////////////////////////////////////////
// The path attribute is broken down into the following attributes:
// filePath, param, query, and ref:
/**
* Returns a path including the directory and file portions of a
* URL. E.g. The filePath of "http://foo/bar.html#baz" is
* "/foo/bar.html".
*/
attribute string filePath;
/**
* Returns the parameters specified after the ; in the URL.
*
*/
attribute string param;
/**
* Returns the query portion (the part after the "?") of the URL.
* If there isn't one, an empty string is returned.
*/
attribute string query;
/**
* Returns the reference portion (the part after the "#") of the URL.
* If there isn't one, an empty string is returned.
*/
attribute string ref;
////////////////////////////////////////////////////////////////////////////
// The filePath attribute is further broken down into the following
// attributes: directory, file:
/**
* Returns the directory portion of a URL.
* If the URL denotes a path to a directory and not a file,
* e.g. http://foo/bar/, then the Directory attribute accesses
* the complete /foo/bar/ portion, and the FileName is the
* empty string. If the trailing slash is omitted, then the
* Directory is /foo/ and the file is bar (i.e. this is a
* syntactic, not a semantic breakdown of the Path).
* And hence dont rely on this for something to be a definitely
* be a file. But you can get just the leading directory portion
* for sure.
*/
attribute string directory;
/**
* Returns the file name portion of a URL.
* If the URL denotes a path to a directory and not a file,
* e.g. http://foo/bar/, then the Directory attribute accesses
* the complete /foo/bar/ portion, and the FileName is the
* empty string. Note that this is purely based on searching
* for the last trailing slash. And hence dont rely on this to
* be a definite file.
*/
attribute string fileName;
////////////////////////////////////////////////////////////////////////////
// The fileName attribute is further broken down into the following
// attributes: fileName, fileExtension:
attribute string fileBaseName;
/**
* Returns the file extension portion of a filename in a url.
* If a file extension does not exist, the empty string is returned.
*/
attribute string fileExtension;
};
%{C++
/**
* Protocol writers can obtain a default nsIURL implementation by calling the
* component manager with NS_STANDARDURL_CID. The implementation returned will
* only implement the set of accessors specified by nsIURL. After obtaining the
* instance from the component manager, the Init routine must be called on it
* to initialize it from the user's URL spec.
*/
#define NS_STANDARDURL_CID \
{ /* de9472d0-8034-11d3-9399-00104ba0fd40 */ \
0xde9472d0, \
0x8034, \
0x11d3, \
{0x93, 0x99, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
%}
////////////////////////////////////////////////////////////////////////////////
interface nsIFile;
/**
* nsIFileURL is used for the file: protocol, and gives access to the
* underlying nsIFile object.
*/
interface nsIFileURL : nsIURL
{
attribute nsIFile file;
};

View File

@@ -0,0 +1,125 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Andreas Otte
*
* Contributor(s):
*/
#include "nsISupports.idl"
/**
* nsIURLParser is the abstract base class for parsing URLs
*/
[scriptable, uuid(4b4975f9-f128-47fd-b11e-88402233cbdf)]
interface nsIURLParser : nsISupports
{
/**
* Parses a URL and thinks it is parsing the scheme
*/
void ParseAtScheme(in string i_Spec,
out string o_Scheme,
out string o_Username,
out string o_Password,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the prehost
*/
void ParseAtPreHost(in string i_Spec,
out string o_Username,
out string o_Password,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the host
*/
void ParseAtHost(in string i_Spec,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the port
*/
void ParseAtPort(in string i_Spec,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the path
*/
void ParseAtPath(in string i_Spec,
out string o_Path);
/**
* Parses a URL-path and thinks it is parsing the directory
*/
void ParseAtDirectory(in string i_Path,
out string o_Directory,
out string o_FileBaseName,
out string o_FileExtension,
out string o_Param,
out string o_Query,
out string o_Ref);
/**
* Parses the URL-PreHost into its components
*/
void ParsePreHost(in string i_PreHost,
out string o_Username,
out string o_Password);
/**
* Parses the URL-Filename into its components
*/
void ParseFileName(in string i_FileName,
out string o_FileBaseName,
out string o_FileExtension);
};
%{C++
#define NS_STANDARDURLPARSER_CID \
{ /* dbf72351-4fd8-46f0-9dbc-fa5ba60a30c5 */ \
0xdbf72351, \
0x4fd8, \
0x46f0, \
{0x9d, 0xbc, 0xfa, 0x5b, 0xa6, 0x0a, 0x30, 0x5c} \
}
#define NS_AUTHORITYURLPARSER_CID \
{ /* 90012125-1616-4fa1-ae14-4e7fa5766eb6 */ \
0x90012125, \
0x1616, \
0x4fa1, \
{0xae, 0x14, 0x4e, 0x7f, 0xa5, 0x76, 0x6e, 0xb6} \
}
#define NS_NOAUTHORITYURLPARSER_CID \
{ /* 9eeb1b89-c87e-4404-9de6-dbd41aeaf3d7 */ \
0x9eeb1b89, \
0xc87e, \
0x4404, \
{0x9d, 0xe6, 0xdb, 0xd4, 0x1a, 0xea, 0xf3, 0xd7} \
}
%}

View File

@@ -0,0 +1,322 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsNetUtil_h__
#define nsNetUtil_h__
#include "nsIURI.h"
#include "netCore.h"
#include "nsIInputStream.h"
#include "nsIStreamListener.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsString.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "nsIAllocator.h"
#include "nsCOMPtr.h"
#include "nsIHTTPProtocolHandler.h"
#include "nsIStreamLoader.h"
inline nsresult
NS_NewURI(nsIURI* *result, const char* spec, nsIURI* baseURI = nsnull)
{
nsresult rv;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = serv->NewURI(spec, baseURI, result);
return rv;
}
inline nsresult
NS_NewURI(nsIURI* *result, const nsString& spec, nsIURI* baseURI = nsnull)
{
char* specStr = spec.ToNewUTF8String(); // this forces a single byte char*
if (specStr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = NS_NewURI(result, specStr, baseURI);
nsAllocator::Free(specStr);
return rv;
}
inline nsresult
NS_OpenURI(nsIChannel* *result, nsIURI* uri, nsILoadGroup *aGroup,
nsIInterfaceRequestor *capabilities = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsIChannel* channel;
rv = serv->NewChannelFromURI("load", uri, aGroup, capabilities,
loadAttributes, nsnull,
bufferSegmentSize, bufferMaxSize, &channel);
if (NS_FAILED(rv)) return rv;
*result = channel;
return rv;
}
// Use this function with CAUTION. And do not use it on
// the UI thread. It creates a stream that blocks when
// you Read() from it and blocking the UI thread is
// illegal. If you don't want to implement a full
// blown asyncrhonous consumer (via nsIStreamListener)
// look at nsIStreamLoader instead.
inline nsresult
NS_OpenURI(nsIInputStream* *result, nsIURI* uri)
{
nsresult rv;
nsIChannel* channel;
rv = NS_OpenURI(&channel, uri, nsnull);
if (NS_FAILED(rv)) return rv;
nsIInputStream* inStr;
rv = channel->OpenInputStream(0, -1, &inStr);
NS_RELEASE(channel);
if (NS_FAILED(rv)) return rv;
*result = inStr;
return rv;
}
inline nsresult
NS_OpenURI(nsIStreamListener* aConsumer, nsISupports* context, nsIURI* uri,
nsILoadGroup *aGroup)
{
nsresult rv;
nsIChannel* channel;
rv = NS_OpenURI(&channel, uri, aGroup);
if (NS_FAILED(rv)) return rv;
rv = channel->AsyncRead(0, -1, context, aConsumer);
NS_RELEASE(channel);
return rv;
}
inline nsresult
NS_MakeAbsoluteURI(const char* spec, nsIURI* baseURI, char* *result)
{
nsresult rv;
NS_ASSERTION(baseURI, "It doesn't make sense to not supply a base URI");
if (spec == nsnull)
return baseURI->GetSpec(result);
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
PRUint32 startPos, endPos;
rv = serv->ExtractScheme(spec, &startPos, &endPos, nsnull);
if (NS_SUCCEEDED(rv)) {
// if spec has a scheme, then it's already absolute
*result = nsCRT::strdup(spec);
return (*result == nsnull) ? NS_ERROR_OUT_OF_MEMORY : NS_OK;
}
return baseURI->Resolve(spec, result);
}
inline nsresult
NS_MakeAbsoluteURI(const nsString& spec, nsIURI* baseURI, nsString& result)
{
char* resultStr;
char* specStr = spec.ToNewUTF8String();
if (!specStr) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv = NS_MakeAbsoluteURI(specStr, baseURI, &resultStr);
nsAllocator::Free(specStr);
if (NS_FAILED(rv)) return rv;
result = resultStr;
nsAllocator::Free(resultStr);
return rv;
}
inline nsresult
NS_NewPostDataStream(PRBool isFile, const char *data, PRUint32 encodeFlags,
nsIInputStream **result)
{
nsresult rv;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIProtocolHandler> handler;
rv = serv->GetProtocolHandler("http", getter_AddRefs(handler));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIHTTPProtocolHandler> http = do_QueryInterface(handler, &rv);
if (NS_FAILED(rv)) return rv;
return http->NewPostDataStream(isFile, data, encodeFlags, result);
}
inline nsresult
NS_NewInputStreamChannel(nsIURI* uri,
const char* contentType,
PRInt32 contentLength,
nsIInputStream* inStr,
nsILoadGroup* group,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel **result)
{
nsresult rv;
nsCOMPtr<nsIInputStreamChannel> channel;
static NS_DEFINE_CID(kInputStreamChannelCID, NS_INPUTSTREAMCHANNEL_CID);
rv = nsComponentManager::CreateInstance(kInputStreamChannelCID,
nsnull,
NS_GET_IID(nsIInputStreamChannel),
getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->Init(uri, contentType, contentLength, inStr, group,
notificationCallbacks, loadAttributes, originalURI,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
*result = channel;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewLoadGroup(nsIStreamObserver* obs, nsILoadGroup* *result)
{
nsresult rv;
nsCOMPtr<nsILoadGroup> group;
static NS_DEFINE_CID(kLoadGroupCID, NS_LOADGROUP_CID);
rv = nsComponentManager::CreateInstance(kLoadGroupCID, nsnull,
NS_GET_IID(nsILoadGroup),
getter_AddRefs(group));
if (NS_FAILED(rv)) return rv;
rv = group->Init(obs);
if (NS_FAILED(rv)) return rv;
*result = group;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewStreamLoader(nsIStreamLoader* *result,
nsIURI* uri,
nsIStreamLoaderObserver* observer,
nsISupports* context = nsnull,
nsILoadGroup* loadGroup = nsnull,
nsIInterfaceRequestor* notificationCallbacks = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
nsCOMPtr<nsIStreamLoader> loader;
static NS_DEFINE_CID(kStreamLoaderCID, NS_STREAMLOADER_CID);
rv = nsComponentManager::CreateInstance(kStreamLoaderCID,
nsnull,
NS_GET_IID(nsIStreamLoader),
getter_AddRefs(loader));
if (NS_FAILED(rv)) return rv;
rv = loader->Init(uri, observer, context, loadGroup, notificationCallbacks, loadAttributes,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
*result = loader;
NS_ADDREF(*result);
return rv;
}
inline nsresult
NS_NewAsyncStreamObserver(nsIStreamObserver *receiver, nsIEventQueue *eventQueue,
nsIStreamObserver **result)
{
nsresult rv;
nsCOMPtr<nsIAsyncStreamObserver> obs;
static NS_DEFINE_CID(kAsyncStreamObserverCID, NS_ASYNCSTREAMOBSERVER_CID);
rv = nsComponentManager::CreateInstance(kAsyncStreamObserverCID,
nsnull,
NS_GET_IID(nsIAsyncStreamObserver),
getter_AddRefs(obs));
if (NS_FAILED(rv)) return rv;
rv = obs->Init(receiver, eventQueue);
if (NS_FAILED(rv)) return rv;
*result = obs;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewAsyncStreamListener(nsIStreamListener *receiver, nsIEventQueue *eventQueue,
nsIStreamListener **result)
{
nsresult rv;
nsCOMPtr<nsIAsyncStreamListener> lsnr;
static NS_DEFINE_CID(kAsyncStreamListenerCID, NS_ASYNCSTREAMLISTENER_CID);
rv = nsComponentManager::CreateInstance(kAsyncStreamListenerCID,
nsnull,
NS_GET_IID(nsIAsyncStreamListener),
getter_AddRefs(lsnr));
if (NS_FAILED(rv)) return rv;
rv = lsnr->Init(receiver, eventQueue);
if (NS_FAILED(rv)) return rv;
*result = lsnr;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewSyncStreamListener(nsIInputStream **inStream,
nsIBufferOutputStream **outStream,
nsIStreamListener **listener)
{
nsresult rv;
nsCOMPtr<nsISyncStreamListener> lsnr;
static NS_DEFINE_CID(kSyncStreamListenerCID, NS_SYNCSTREAMLISTENER_CID);
rv = nsComponentManager::CreateInstance(kSyncStreamListenerCID,
nsnull,
NS_GET_IID(nsISyncStreamListener),
getter_AddRefs(lsnr));
if (NS_FAILED(rv)) return rv;
rv = lsnr->Init(inStream, outStream);
if (NS_FAILED(rv)) return rv;
*listener = lsnr;
NS_ADDREF(*listener);
return NS_OK;
}
#endif // nsNetUtil_h__

View File

@@ -0,0 +1,100 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef _nsUnixColorPrintf_h_
#define _nsUnixColorPrintf_h_
#if defined(XP_UNIX) && defined(NS_DEBUG)
#define STARTGRAY "\033[1;30m"
#define STARTRED "\033[1;31m"
#define STARTGREEN "\033[1;32m"
#define STARTYELLOW "\033[1;33m"
#define STARTBLUE "\033[1;34m"
#define STARTMAGENTA "\033[1;35m"
#define STARTCYAN "\033[1;36m"
#define STARTUNDERLINE "\033[4m"
#define STARTREVERSE "\033[7m"
#define ENDCOLOR "\033[0m"
#define PRINTF_GRAY nsUnixColorPrintf __color_printf(STARTGREY)
#define PRINTF_RED nsUnixColorPrintf __color_printf(STARTRED)
#define PRINTF_GREEN nsUnixColorPrintf __color_printf(STARTGREEN)
#define PRINTF_YELLOW nsUnixColorPrintf __color_printf(STARTYELLOW)
#define PRINTF_BLUE nsUnixColorPrintf __color_printf(STARTBLUE)
#define PRINTF_MAGENTA nsUnixColorPrintf __color_printf(STARTMAGENTA)
#define PRINTF_CYAN nsUnixColorPrintf __color_printf(STARTCYAN)
#define PRINTF_UNDERLINE nsUnixColorPrintf __color_printf(STARTUNDERLINE)
#define PRINTF_REVERSE nsUnixColorPrintf __color_printf(STARTREVERSE)
/*
The nsUnixColorPrintf is a handy set of color term codes to change
the color of console texts for easier spotting. As of now this is
Unix and Debug only.
Usage is simple.
See examples in
mozilla/netwerk/protocol/http/src/nsHTTPHandler.cpp
-Gagan Saksena 11/01/99
*/
class nsUnixColorPrintf
{
public:
nsUnixColorPrintf(const char* colorCode)
{
printf("%s",colorCode);
}
~nsUnixColorPrintf()
{
printf("%s",ENDCOLOR);
}
};
#else // XP_UNIX
#define STARTGRAY ""
#define STARTRED ""
#define STARTGREEN ""
#define STARTYELLOW ""
#define STARTBLUE ""
#define STARTMAGENTA ""
#define STARTCYAN ""
#define STARTUNDERLINE ""
#define STARTREVERSE ""
#define ENDCOLOR ""
#define PRINTF_GRAY
#define PRINTF_RED
#define PRINTF_GREEN
#define PRINTF_YELLOW
#define PRINTF_BLUE
#define PRINTF_MAGENTA
#define PRINTF_CYAN
#define PRINTF_UNDERLINE
#define PRINTF_REVERSE
#endif // XP_UNIX
#endif // nsUnixColorPrintf

View File

@@ -0,0 +1,63 @@
#
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = necko
LIBRARY_NAME = neckobase_s
CPPSRCS = \
nsURLHelper.cpp \
nsFileStreams.cpp \
nsBufferedStreams.cpp \
nsAsyncStreamListener.cpp \
nsSyncStreamListener.cpp \
nsIOService.cpp \
nsSocketTransport.cpp \
nsSocketTransportService.cpp \
nsFileTransport.cpp \
nsFileTransportService.cpp \
nsStdURLParser.cpp \
nsAuthURLParser.cpp \
nsNoAuthURLParser.cpp \
nsStdURL.cpp \
nsSimpleURI.cpp \
nsNetModuleMgr.cpp \
nsNetModRegEntry.cpp \
nsLoadGroup.cpp \
nsInputStreamChannel.cpp \
nsDirectoryIndexStream.cpp \
nsStreamLoader.cpp \
nsProtocolProxyService.cpp \
$(NULL)
# we don't want the shared lib, but we want to force the creation of a
# static lib.
override NO_SHARED_LIB=1
override NO_STATIC_LIB=
include $(topsrcdir)/config/rules.mk

View File

@@ -0,0 +1,64 @@
# 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 Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
MODULE = necko
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
LCFLAGS = -DWIN32_LEAN_AND_MEAN -D_IMPL_NS_NET
LIBRARY_NAME=neckobase_s
CPP_OBJS = \
.\$(OBJDIR)\nsURLHelper.obj \
.\$(OBJDIR)\nsFileStreams.obj \
.\$(OBJDIR)\nsBufferedStreams.obj \
.\$(OBJDIR)\nsAsyncStreamListener.obj \
.\$(OBJDIR)\nsSyncStreamListener.obj \
.\$(OBJDIR)\nsIOService.obj \
.\$(OBJDIR)\nsSocketTransport.obj \
.\$(OBJDIR)\nsSocketTransportService.obj \
.\$(OBJDIR)\nsFileTransport.obj \
.\$(OBJDIR)\nsFileTransportService.obj \
.\$(OBJDIR)\nsStdURLParser.obj \
.\$(OBJDIR)\nsAuthURLParser.obj \
.\$(OBJDIR)\nsNoAuthURLParser.obj \
.\$(OBJDIR)\nsStdURL.obj \
.\$(OBJDIR)\nsSimpleURI.obj \
.\$(OBJDIR)\nsNetModuleMgr.obj \
.\$(OBJDIR)\nsNetModRegEntry.obj \
.\$(OBJDIR)\nsLoadGroup.obj \
.\$(OBJDIR)\nsInputStreamChannel.obj \
.\$(OBJDIR)\nsDirectoryIndexStream.obj \
.\$(OBJDIR)\nsStreamLoader.obj \
.\$(OBJDIR)\nsProtocolProxyService.obj \
$(NULL)
INCS = $(INCS) \
-I$(DEPTH)\dist\include \
$(NULL)
include <$(DEPTH)\config\rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
clobber::
rm -f $(DIST)\lib\$(LIBRARY_NAME).lib

View File

@@ -0,0 +1,468 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsAsyncStreamListener.h"
#include "nsIBufferInputStream.h"
#include "nsString.h"
#include "nsCRT.h"
#include "nsIEventQueueService.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "prlog.h"
static NS_DEFINE_CID(kEventQueueService, NS_EVENTQUEUESERVICE_CID);
#if defined(PR_LOGGING)
PRLogModuleInfo* gStreamEventLog = 0;
#endif
////////////////////////////////////////////////////////////////////////////////
class nsStreamListenerEvent
{
public:
nsStreamListenerEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context);
virtual ~nsStreamListenerEvent();
nsresult Fire(nsIEventQueue* aEventQ);
NS_IMETHOD HandleEvent() = 0;
protected:
static void PR_CALLBACK HandlePLEvent(PLEvent* aEvent);
static void PR_CALLBACK DestroyPLEvent(PLEvent* aEvent);
nsAsyncStreamObserver* mListener;
nsIChannel* mChannel;
nsISupports* mContext;
PLEvent * mEvent;
};
////////////////////////////////////////////////////////////////////////////////
nsStreamListenerEvent::nsStreamListenerEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: mListener(listener), mChannel(channel), mContext(context), mEvent(nsnull)
{
MOZ_COUNT_CTOR(nsStreamListenerEvent);
NS_IF_ADDREF(mListener);
NS_IF_ADDREF(mChannel);
NS_IF_ADDREF(mContext);
}
nsStreamListenerEvent::~nsStreamListenerEvent()
{
MOZ_COUNT_DTOR(nsStreamListenerEvent);
NS_IF_RELEASE(mListener);
NS_IF_RELEASE(mChannel);
NS_IF_RELEASE(mContext);
if (nsnull != mEvent)
{
delete mEvent;
mEvent = nsnull;
}
}
void PR_CALLBACK nsStreamListenerEvent::HandlePLEvent(PLEvent* aEvent)
{
nsStreamListenerEvent * ev =
(nsStreamListenerEvent *) PL_GetEventOwner(aEvent);
NS_ASSERTION(nsnull != ev,"null event.");
nsresult rv = ev->HandleEvent();
ev->mListener->SetStatus(rv);
}
void PR_CALLBACK nsStreamListenerEvent::DestroyPLEvent(PLEvent* aEvent)
{
nsStreamListenerEvent * ev =
(nsStreamListenerEvent *) PL_GetEventOwner(aEvent);
NS_ASSERTION(nsnull != ev,"null event.");
delete ev;
}
nsresult
nsStreamListenerEvent::Fire(nsIEventQueue* aEventQueue)
{
NS_PRECONDITION(nsnull != aEventQueue, "nsIEventQueue for thread is null");
NS_PRECONDITION(nsnull == mEvent, "Init plevent only once.");
mEvent = new PLEvent;
PL_InitEvent(mEvent,
this,
(PLHandleEventProc) nsStreamListenerEvent::HandlePLEvent,
(PLDestroyEventProc) nsStreamListenerEvent::DestroyPLEvent);
PRStatus status = aEventQueue->PostEvent(mEvent);
return status == PR_SUCCESS ? NS_OK : NS_ERROR_FAILURE;
}
////////////////////////////////////////////////////////////////////////////////
nsAsyncStreamObserver::~nsAsyncStreamObserver()
{
}
NS_IMPL_THREADSAFE_ADDREF(nsAsyncStreamObserver)
NS_IMPL_THREADSAFE_RELEASE(nsAsyncStreamObserver)
NS_IMPL_QUERY_INTERFACE2(nsAsyncStreamObserver,
nsIAsyncStreamObserver,
nsIStreamObserver)
NS_IMPL_ADDREF_INHERITED(nsAsyncStreamListener, nsAsyncStreamObserver);
NS_IMPL_RELEASE_INHERITED(nsAsyncStreamListener, nsAsyncStreamObserver);
NS_IMETHODIMP
nsAsyncStreamListener::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (!aInstancePtr) return NS_ERROR_NULL_POINTER;
if (aIID.Equals(NS_GET_IID(nsIAsyncStreamListener))) {
*aInstancePtr = NS_STATIC_CAST(nsIAsyncStreamListener*, this);
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(NS_GET_IID(nsIStreamListener))) {
*aInstancePtr = NS_STATIC_CAST(nsIStreamListener*, this);
NS_ADDREF_THIS();
return NS_OK;
}
return nsAsyncStreamObserver::QueryInterface(aIID, aInstancePtr);
}
NS_IMETHODIMP
nsAsyncStreamObserver::Init(nsIStreamObserver* aObserver, nsIEventQueue* aEventQ)
{
nsresult rv = NS_OK;
mReceiver = aObserver;
NS_WITH_SERVICE(nsIEventQueueService, eventQService, kEventQueueService, &rv);
if (NS_FAILED(rv))
return rv;
rv = eventQService->ResolveEventQueue(aEventQ, getter_AddRefs(mEventQueue));
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnStartRequest...
//
////////////////////////////////////////////////////////////////////////////////
class nsOnStartRequestEvent : public nsStreamListenerEvent
{
public:
nsOnStartRequestEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: nsStreamListenerEvent(listener, channel, context) {}
virtual ~nsOnStartRequestEvent() {}
NS_IMETHOD HandleEvent();
};
NS_IMETHODIMP
nsOnStartRequestEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Start [event=%x]", this));
#endif
nsIStreamObserver* receiver = (nsIStreamObserver*)mListener->GetReceiver();
return receiver->OnStartRequest(mChannel, mContext);
}
NS_IMETHODIMP
nsAsyncStreamObserver::OnStartRequest(nsIChannel* channel, nsISupports* context)
{
nsresult rv = GetStatus();
if (NS_FAILED(rv)) return rv;
nsOnStartRequestEvent* event =
new nsOnStartRequestEvent(this, channel, context);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
char ts[80];
sprintf(ts, "nsAsyncStreamObserver: Start [this=%lx queue=%lx",
(long)this, (long)equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Start [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnStopRequest
//
////////////////////////////////////////////////////////////////////////////////
class nsOnStopRequestEvent : public nsStreamListenerEvent
{
public:
nsOnStopRequestEvent(nsAsyncStreamObserver* listener,
nsISupports* context, nsIChannel* channel)
: nsStreamListenerEvent(listener, channel, context),
mStatus(NS_OK), mMessage(nsnull) {}
virtual ~nsOnStopRequestEvent();
nsresult Init(nsresult status, const PRUnichar* aMsg);
NS_IMETHOD HandleEvent();
protected:
nsresult mStatus;
PRUnichar* mMessage;
};
nsOnStopRequestEvent::~nsOnStopRequestEvent()
{
}
nsresult
nsOnStopRequestEvent::Init(nsresult status, const PRUnichar* aMsg)
{
mStatus = status;
mMessage = (PRUnichar*)aMsg;
return NS_OK;
}
NS_IMETHODIMP
nsOnStopRequestEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Stop [event=%x]", this));
#endif
nsIStreamObserver* receiver = (nsIStreamObserver*)mListener->GetReceiver();
nsresult rv = mListener->GetStatus();
//
// If the consumer returned a failure code, then pass it out in the
// OnStopRequest(...) notification...
//
if (NS_FAILED(rv)) {
mStatus = rv;
}
return receiver->OnStopRequest(mChannel, mContext, mStatus, mMessage);
}
NS_IMETHODIMP
nsAsyncStreamObserver::OnStopRequest(nsIChannel* channel, nsISupports* context,
nsresult aStatus,
const PRUnichar* aMsg)
{
nsresult rv;
//
// Fire the OnStopRequest(...) regardless of what the current
// Status is...
//
nsOnStopRequestEvent* event =
new nsOnStopRequestEvent(this, context, channel);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = event->Init(aStatus, aMsg);
if (NS_FAILED(rv)) goto failed;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Stop [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnDataAvailable
//
////////////////////////////////////////////////////////////////////////////////
class nsOnDataAvailableEvent : public nsStreamListenerEvent
{
public:
nsOnDataAvailableEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: nsStreamListenerEvent(listener, channel, context),
mIStream(nsnull), mLength(0) {}
virtual ~nsOnDataAvailableEvent();
nsresult Init(nsIInputStream* aIStream, PRUint32 aSourceOffset,
PRUint32 aLength);
NS_IMETHOD HandleEvent();
protected:
nsIInputStream* mIStream;
PRUint32 mSourceOffset;
PRUint32 mLength;
};
nsOnDataAvailableEvent::~nsOnDataAvailableEvent()
{
NS_RELEASE(mIStream);
}
nsresult
nsOnDataAvailableEvent::Init(nsIInputStream* aIStream, PRUint32 aSourceOffset,
PRUint32 aLength)
{
mSourceOffset = aSourceOffset;
mLength = aLength;
mIStream = aIStream;
NS_ADDREF(mIStream);
return NS_OK;
}
NS_IMETHODIMP
nsOnDataAvailableEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Data [event=%x]", this));
#endif
nsIStreamListener* receiver = (nsIStreamListener*)mListener->GetReceiver();
nsresult rv = mListener->GetStatus();
//
// Only send OnDataAvailable(... ) notifications if all previous calls
// have succeeded...
//
if (NS_SUCCEEDED(rv)) {
rv = receiver->OnDataAvailable(mChannel, mContext,
mIStream, mSourceOffset, mLength);
//
// If the consumer fails, then cancel the transport. This is necessary
// in case where the socket transport is blocked waiting for room in the
// pipe, but the consumer fails without consuming all the data.
//
// Unless the transport is cancelled, it will block forever, waiting for
// the pipe to empty...
//
if (NS_FAILED(rv)) {
mChannel->Cancel();
}
}
return rv;
}
NS_IMETHODIMP
nsAsyncStreamListener::OnDataAvailable(nsIChannel* channel, nsISupports* context,
nsIInputStream *aIStream,
PRUint32 aSourceOffset,
PRUint32 aLength)
{
nsresult rv = GetStatus();
if (NS_FAILED(rv)) return rv;
nsOnDataAvailableEvent* event =
new nsOnDataAvailableEvent(this, channel, context);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = event->Init(aIStream, aSourceOffset, aLength);
if (NS_FAILED(rv)) goto failed;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Data [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
NS_METHOD
nsAsyncStreamObserver::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAsyncStreamObserver* l = new nsAsyncStreamObserver();
if (l == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(l);
nsresult rv = l->QueryInterface(aIID, aResult);
NS_RELEASE(l);
return rv;
}
NS_METHOD
nsAsyncStreamListener::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAsyncStreamListener* l = new nsAsyncStreamListener();
if (l == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(l);
nsresult rv = l->QueryInterface(aIID, aResult);
NS_RELEASE(l);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,106 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsAsyncStreamListener_h__
#define nsAsyncStreamListener_h__
#include "nsIStreamListener.h"
#include "nsCOMPtr.h"
#include "nsIEventQueue.h"
#include "nsIStreamObserver.h"
#include "nsIStreamListener.h"
////////////////////////////////////////////////////////////////////////////////
class nsAsyncStreamObserver : public nsIAsyncStreamObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSIASYNCSTREAMOBSERVER
// nsAsyncStreamObserver methods:
nsAsyncStreamObserver()
: mStatus(NS_OK)
{
NS_INIT_REFCNT();
}
virtual ~nsAsyncStreamObserver();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsISupports* GetReceiver() { return mReceiver.get(); }
nsresult GetStatus() { return mStatus; }
void SetStatus(nsresult value) { if (NS_SUCCEEDED(mStatus)) mStatus = value; }
protected:
nsCOMPtr<nsIEventQueue> mEventQueue;
nsCOMPtr<nsIStreamObserver> mReceiver;
nsresult mStatus;
};
////////////////////////////////////////////////////////////////////////////////
class nsAsyncStreamListener : public nsAsyncStreamObserver,
public nsIAsyncStreamListener
{
public:
NS_DECL_ISUPPORTS_INHERITED
// nsIStreamListener methods:
NS_IMETHOD OnStartRequest(nsIChannel* channel,
nsISupports* context)
{
return nsAsyncStreamObserver::OnStartRequest(channel, context);
}
NS_IMETHOD OnStopRequest(nsIChannel* channel,
nsISupports* context,
nsresult aStatus,
const PRUnichar* aMsg)
{
return nsAsyncStreamObserver::OnStopRequest(channel, context, aStatus, aMsg);
}
NS_IMETHOD OnDataAvailable(nsIChannel* channel, nsISupports* context,
nsIInputStream *aIStream,
PRUint32 aSourceOffset,
PRUint32 aLength);
// nsIAsyncStreamListener methods:
NS_IMETHOD Init(nsIStreamListener* aListener, nsIEventQueue* aEventQ) {
return nsAsyncStreamObserver::Init(aListener, aEventQ);
}
// nsAsyncStreamListener methods:
nsAsyncStreamListener() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsAsyncStreamListener_h__

View File

@@ -0,0 +1,497 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Andreas Otte.
*
* Contributor(s):
*/
#include "nsAuthURLParser.h"
#include "nsURLHelper.h"
#include "nsCRT.h"
#include "nsString.h"
#include "prprf.h"
NS_IMPL_THREADSAFE_ISUPPORTS(nsAuthURLParser, NS_GET_IID(nsIURLParser))
nsAuthURLParser::~nsAuthURLParser()
{
}
NS_METHOD
nsAuthURLParser::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAuthURLParser* p = new nsAuthURLParser();
if (p == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(p);
nsresult rv = p->QueryInterface(aIID, aResult);
NS_RELEASE(p);
return rv;
}
nsresult
nsAuthURLParser::ParseAtScheme(const char* i_Spec, char* *o_Scheme,
char* *o_Username, char* *o_Password,
char* *o_Host, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
NS_PRECONDITION( (nsnull != i_Spec), "Parse called on empty url!");
if (!i_Spec)
return NS_ERROR_MALFORMED_URI;
int len = PL_strlen(i_Spec);
if (len >= 2 && *i_Spec == '/' && *(i_Spec+1) == '/') // No Scheme
{
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host, o_Port,
o_Path);
return rv;
}
static const char delimiters[] = "/:@?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
ToLowerCase(*o_Host);
return rv;
} else
len = PL_strlen(brk);
switch (*brk)
{
case '/' :
case '?' :
// If the URL starts with a slash then everything is a path
if (brk == i_Spec)
{
rv = ParseAtPath(brk, o_Path);
return rv;
}
else // The first part is host, so its host/path
{
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
}
break;
case ':' :
if (len >= 2 && *(brk+1) == '/') {
// Standard http://... or malformed http:/...
rv = ExtractString((char*)i_Spec, o_Scheme, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
} else {
// Could be host:port, so try conversion to number
PRInt32 port = ExtractPortFrom(brk+1);
if (port > 0)
{
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
} else {
// No, it's not a number try scheme:host...
rv = ExtractString((char*)i_Spec, o_Scheme,
(brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
}
}
break;
case '@' :
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPreHost(const char* i_Spec, char* *o_Username,
char* *o_Password, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// Skip leading two slashes
char* fwdPtr= (char*) i_Spec;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
static const char delimiters[] = "/:@?";
char* brk = PL_strpbrk(fwdPtr, delimiters);
char* brk2 = nsnull;
if (!brk)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
char* e_PreHost = nsnull;
switch (*brk)
{
case ':' :
// this maybe the : of host:port or username:password
// look if the next special char is @
brk2 = PL_strpbrk(brk+1, delimiters);
if (!brk2)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
switch (*brk2)
{
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk2 - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk2+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
break;
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
}
return rv;
}
nsresult
nsAuthURLParser::ParseAtHost(const char* i_Spec, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
int len = PL_strlen(i_Spec);
static const char delimiters[] = ":/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
ToLowerCase(*o_Host);
return rv;
}
switch (*brk)
{
case '/' :
case '?' :
// Get the Host, the rest is Path
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
break;
case ':' :
// Get the Host
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPort(const char* i_Spec, PRInt32 *o_Port,
char* *o_Path)
{
nsresult rv = NS_OK;
static const char delimiters[] = "/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a Port
{
*o_Port = ExtractPortFrom(i_Spec);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
else
return NS_OK;
}
switch (*brk)
{
case '/' :
case '?' :
// Get the Port, the rest is Path
*o_Port = ExtractPortFrom(i_Spec);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
rv = ParseAtPath(brk, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPath(const char* i_Spec, char* *o_Path)
{
// Just write the path and check for a starting /
nsCAutoString dir;
if ('/' != *i_Spec)
dir += "/";
dir += i_Spec;
*o_Path = dir.ToNewCString();
return (*o_Path ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
nsresult
nsAuthURLParser::ParseAtDirectory(const char* i_Path, char* *o_Directory,
char* *o_FileBaseName, char* *o_FileExtension,
char* *o_Param, char* *o_Query, char* *o_Ref)
{
// Cleanout
CRTFREEIF(*o_Directory);
CRTFREEIF(*o_FileBaseName);
CRTFREEIF(*o_FileExtension);
CRTFREEIF(*o_Param);
CRTFREEIF(*o_Query);
CRTFREEIF(*o_Ref);
nsresult rv = NS_OK;
// Parse the Path into its components
if (!i_Path)
{
DupString(o_Directory, "/");
return (o_Directory ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
char* dirfile = nsnull;
char* options = nsnull;
int len = PL_strlen(i_Path);
/* Factor out the optionpart with ;?# */
static const char delimiters[] = ";?#"; // for param, query and ref
char* brk = PL_strpbrk(i_Path, delimiters);
if (!brk) // Everything is just path and filename
{
DupString(&dirfile, i_Path);
}
else
{
int dirfileLen = brk - i_Path;
ExtractString((char*)i_Path, &dirfile, dirfileLen);
len -= dirfileLen;
ExtractString((char*)i_Path + dirfileLen, &options, len);
brk = options;
}
/* now that we have broken up the path treat every part differently */
/* first dir+file */
char* file;
int dlen = PL_strlen(dirfile);
if (dlen == 0)
{
DupString(o_Directory, "/");
file = dirfile;
} else {
CoaleseDirs(dirfile);
// Get length again
dlen = PL_strlen(dirfile);
// First find the last slash
file = PL_strrchr(dirfile, '/');
if (!file)
{
DupString(o_Directory, "/");
file = dirfile;
}
// If its not the same as the first slash then extract directory
if (file != dirfile)
{
ExtractString(dirfile, o_Directory, (file - dirfile)+1);
} else {
DupString(o_Directory, "/");
}
}
/* Extract FileBaseName and FileExtension */
if (dlen > 0) {
// Look again if there was a slash
char* slash = PL_strrchr(dirfile, '/');
char* e_FileName = nsnull;
if (slash) {
if (dirfile+dlen-1>slash)
ExtractString(slash+1, &e_FileName, dlen-(slash-dirfile+1));
} else {
// Use the full String as Filename
ExtractString(dirfile, &e_FileName, dlen);
}
rv = ParseFileName(e_FileName,o_FileBaseName,o_FileExtension);
CRTFREEIF(e_FileName);
}
// Now take a look at the options. "#" has precedence over "?"
// which has precedence over ";"
if (options) {
// Look for "#" first. Everything following it is in the ref
brk = PL_strchr(options, '#');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Ref, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for "?"
brk = PL_strchr(options, '?');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Query, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for ';'
brk = PL_strchr(options, ';');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Param, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
}
nsCRT::free(dirfile);
nsCRT::free(options);
return rv;
}
nsresult
nsAuthURLParser::ParsePreHost(const char* i_PreHost, char* *o_Username,
char* *o_Password)
{
nsresult rv = NS_OK;
if (!i_PreHost) {
*o_Username = nsnull;
*o_Password = nsnull;
return rv;
}
// Search for :
static const char delimiters[] = ":";
char* brk = PL_strpbrk(i_PreHost, delimiters);
if (brk)
{
rv = ExtractString((char*)i_PreHost, o_Username, (brk - i_PreHost));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk+1, o_Password,
(i_PreHost+PL_strlen(i_PreHost) - brk - 1));
} else {
CRTFREEIF(*o_Password);
rv = DupString(o_Username, i_PreHost);
}
return rv;
}
nsresult
nsAuthURLParser::ParseFileName(const char* i_FileName, char* *o_FileBaseName,
char* *o_FileExtension)
{
nsresult rv = NS_OK;
if (!i_FileName) {
*o_FileBaseName = nsnull;
*o_FileExtension = nsnull;
return rv;
}
// Search for FileExtension
// Search for last .
// Ignore . at the beginning
char* brk = PL_strrchr(i_FileName+1, '.');
if (brk)
{
rv = ExtractString((char*)i_FileName, o_FileBaseName,
(brk - i_FileName));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk + 1, o_FileExtension,
(i_FileName+PL_strlen(i_FileName) - brk - 1));
} else {
rv = DupString(o_FileBaseName, i_FileName);
}
return rv;
}

View File

@@ -0,0 +1,51 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsAuthURLParser_h__
#define nsAuthURLParser_h__
#include "nsIURLParser.h"
#include "nsIURI.h"
#include "nsAgg.h"
#include "nsCRT.h"
class nsAuthURLParser : public nsIURLParser
{
public:
NS_DECL_ISUPPORTS
///////////////////////////////////////////////////////////////////////////
// nsAuthURLParser methods:
nsAuthURLParser() {
NS_INIT_REFCNT();
}
virtual ~nsAuthURLParser();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
///////////////////////////////////////////////////////////////////////////
// nsIURLParser methods:
NS_DECL_NSIURLPARSER
};
#endif // nsAuthURLParser_h__

View File

@@ -0,0 +1,318 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsBufferedStreams.h"
#include "nsCRT.h"
////////////////////////////////////////////////////////////////////////////////
// nsBufferedStream
nsBufferedStream::nsBufferedStream()
: mBuffer(nsnull),
mBufferStartOffset(0),
mCursor(0),
mFillPoint(0),
mStream(nsnull)
{
NS_INIT_REFCNT();
}
nsBufferedStream::~nsBufferedStream()
{
Close();
}
NS_IMPL_THREADSAFE_ISUPPORTS2(nsBufferedStream,
nsIBaseStream,
nsISeekableStream);
nsresult
nsBufferedStream::Init(nsIBaseStream* stream, PRUint32 bufferSize)
{
NS_ASSERTION(stream, "need to supply a stream");
NS_ASSERTION(mStream == nsnull, "already inited");
mStream = stream;
NS_ADDREF(mStream);
mBufferSize = bufferSize;
mBufferStartOffset = 0;
mCursor = 0;
mBuffer = new char[bufferSize];
if (mBuffer == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsBufferedStream::Close()
{
nsresult rv = NS_OK;
if (mStream) {
rv = mStream->Close();
NS_RELEASE(mStream);
mStream = nsnull;
delete[] mBuffer;
mBuffer = nsnull;
mBufferSize = 0;
mBufferStartOffset = 0;
mCursor = 0;
}
return rv;
}
NS_IMETHODIMP
nsBufferedStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mStream == nsnull)
return NS_BASE_STREAM_CLOSED;
// If the underlying stream isn't a random access store, then fail early.
// We could possibly succeed for the case where the seek position denotes
// something that happens to be read into the buffer, but that would make
// the failure data-dependent.
nsresult rv;
nsCOMPtr<nsISeekableStream> ras = do_QueryInterface(mStream, &rv);
if (NS_FAILED(rv)) return rv;
PRInt32 absPos;
switch (whence) {
case nsISeekableStream::NS_SEEK_SET:
absPos = offset;
break;
case nsISeekableStream::NS_SEEK_CUR:
absPos = mBufferStartOffset + mCursor + offset;
break;
case nsISeekableStream::NS_SEEK_END:
absPos = -1;
break;
default:
NS_NOTREACHED("bogus seek whence parameter");
return NS_ERROR_UNEXPECTED;
}
if ((PRInt32)mBufferStartOffset <= absPos
&& absPos < (PRInt32)(mBufferStartOffset + mFillPoint)) {
mCursor = absPos - mBufferStartOffset;
return NS_OK;
}
rv = Flush();
if (NS_FAILED(rv)) return rv;
rv = ras->Seek(whence, offset);
if (NS_FAILED(rv)) return rv;
if (absPos == -1) {
// then we had the SEEK_END case, above
rv = ras->Tell(&mBufferStartOffset);
if (NS_FAILED(rv)) return rv;
}
else {
mBufferStartOffset = absPos;
}
mCursor = 0;
mFillPoint = 0;
return Fill();
}
NS_IMETHODIMP
nsBufferedStream::Tell(PRUint32 *result)
{
if (mStream == nsnull)
return NS_BASE_STREAM_CLOSED;
*result = mBufferStartOffset + mCursor;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsBufferedInputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsBufferedInputStream,
nsBufferedStream,
nsIInputStream,
nsIBufferedInputStream);
NS_METHOD
nsBufferedInputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsBufferedInputStream* stream = new nsBufferedInputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsBufferedInputStream::Init(nsIInputStream* stream, PRUint32 bufferSize)
{
return nsBufferedStream::Init(stream, bufferSize);
}
NS_IMETHODIMP
nsBufferedInputStream::Close()
{
return nsBufferedStream::Close();
}
NS_IMETHODIMP
nsBufferedInputStream::Available(PRUint32 *result)
{
*result = mFillPoint - mCursor;
return NS_OK;
}
NS_IMETHODIMP
nsBufferedInputStream::Read(char * buf, PRUint32 count, PRUint32 *result)
{
nsresult rv = NS_OK;
PRUint32 read = 0;
while (count > 0) {
PRUint32 amt = PR_MIN(count, mFillPoint - mCursor);
if (amt > 0) {
nsCRT::memcpy(buf, mBuffer + mCursor, amt);
read += amt;
count -= amt;
mCursor += amt;
}
else {
rv = Fill();
if (NS_FAILED(rv)) break;
}
}
*result = read;
return (read > 0 || rv == NS_BASE_STREAM_CLOSED) ? NS_OK : rv;
}
NS_IMETHODIMP
nsBufferedInputStream::Fill()
{
nsresult rv;
PRUint32 rem = mFillPoint - mCursor;
if (rem > 0) {
// slide the remainder down to the start of the buffer
// |<------------->|<--rem-->|<--->|
// b c f s
nsCRT::memcpy(mBuffer, mBuffer + mCursor, rem);
}
mBufferStartOffset += mCursor;
mFillPoint = rem;
mCursor = 0;
PRUint32 amt;
rv = Source()->Read(mBuffer + mFillPoint, mBufferSize - mFillPoint, &amt);
if (NS_FAILED(rv)) return rv;
mFillPoint += amt;
return amt > 0 ? NS_OK : NS_BASE_STREAM_CLOSED;
}
////////////////////////////////////////////////////////////////////////////////
// nsBufferedOutputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsBufferedOutputStream,
nsBufferedStream,
nsIOutputStream,
nsIBufferedOutputStream);
NS_METHOD
nsBufferedOutputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsBufferedOutputStream* stream = new nsBufferedOutputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsBufferedOutputStream::Init(nsIOutputStream* stream, PRUint32 bufferSize)
{
mFillPoint = bufferSize; // always fill to the end for buffered output streams
return nsBufferedStream::Init(stream, bufferSize);
}
NS_IMETHODIMP
nsBufferedOutputStream::Close()
{
nsresult rv1, rv2;
rv1 = Flush();
// If we fail to Flush all the data, then we close anyway and drop the
// remaining data in the buffer. We do this because it's what Unix does
// for fclose and close. However, we report the error from Flush anyway.
rv2 = nsBufferedStream::Close();
if (NS_FAILED(rv1)) return rv1;
return rv2;
}
NS_IMETHODIMP
nsBufferedOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *result)
{
nsresult rv = NS_OK;
PRUint32 written = 0;
while (count > 0) {
PRUint32 amt = PR_MIN(count, mFillPoint - mCursor);
if (amt > 0) {
nsCRT::memcpy(mBuffer + mCursor, buf, amt);
written += amt;
count -= amt;
mCursor += amt;
}
else {
rv = Flush();
if (NS_FAILED(rv)) break;
}
}
*result = written;
return (written > 0) ? NS_OK : rv;
}
NS_IMETHODIMP
nsBufferedOutputStream::Flush(void)
{
nsresult rv;
PRUint32 amt;
rv = Sink()->Write(mBuffer, mCursor, &amt);
if (NS_FAILED(rv)) return rv;
mBufferStartOffset += amt;
if (mCursor == amt) {
mCursor = 0;
return NS_OK; // flushed everything
}
// slide the remainder down to the start of the buffer
// |<-------------->|<---|----->|
// b a c s
PRUint32 rem = mCursor - amt;
nsCRT::memcpy(mBuffer, mBuffer + amt, rem);
mCursor = rem;
return NS_ERROR_FAILURE; // didn't flush all
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,117 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsBufferedStreams_h__
#define nsBufferedStreams_h__
#include "nsIFileStreams.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsCOMPtr.h"
////////////////////////////////////////////////////////////////////////////////
class nsBufferedStream : public nsIBaseStream,
public nsISeekableStream
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIBASESTREAM
NS_DECL_NSISEEKABLESTREAM
nsBufferedStream();
virtual ~nsBufferedStream();
protected:
nsresult Init(nsIBaseStream* stream, PRUint32 bufferSize);
NS_IMETHOD Fill() = 0;
NS_IMETHOD Flush() = 0;
protected:
PRUint32 mBufferSize;
char* mBuffer;
// mBufferStartOffset is the offset relative to the start of mStream:
PRUint32 mBufferStartOffset;
// mCursor is the read cursor for input streams, or write cursor for
// output streams, and is relative to mBufferStartOffset:
PRUint32 mCursor;
// mFillPoint is the amount available in the buffer for input streams,
// or the end of the buffer for output streams, and is relative to
// mBufferStartOffset:
PRUint32 mFillPoint;
nsIBaseStream* mStream; // cast to appropriate subclass
};
////////////////////////////////////////////////////////////////////////////////
class nsBufferedInputStream : public nsBufferedStream,
public nsIBufferedInputStream
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIBASESTREAM
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSIBUFFEREDINPUTSTREAM
nsBufferedInputStream() : nsBufferedStream() {}
virtual ~nsBufferedInputStream() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsIInputStream* Source() {
return (nsIInputStream*)mStream;
}
protected:
NS_IMETHOD Fill();
NS_IMETHOD Flush() { return NS_OK; } // no-op for input streams
};
////////////////////////////////////////////////////////////////////////////////
class nsBufferedOutputStream : public nsBufferedStream,
public nsIBufferedOutputStream
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIBASESTREAM
NS_DECL_NSIOUTPUTSTREAM
NS_DECL_NSIBUFFEREDOUTPUTSTREAM
nsBufferedOutputStream() : nsBufferedStream() {}
virtual ~nsBufferedOutputStream() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsIOutputStream* Sink() {
return (nsIOutputStream*)mStream;
}
protected:
NS_IMETHOD Fill() { return NS_OK; } // no-op for output streams
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsBufferedStreams_h__

View File

@@ -0,0 +1,272 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
/*
The converts a filesystem directory into an "HTTP index" stream per
Lou Montulli's original spec:
http://www.area.com/~roeber/file_format.html
*/
#include "nsEscape.h"
#include "nsDirectoryIndexStream.h"
#include "nsXPIDLString.h"
#include "prio.h"
#include "prlog.h"
#include "prlong.h"
#ifdef PR_LOGGING
static PRLogModuleInfo* gLog;
#endif
nsDirectoryIndexStream::nsDirectoryIndexStream()
: mOffset(0)
{
NS_INIT_REFCNT();
#ifdef PR_LOGGING
if (! gLog)
gLog = PR_NewLogModule("nsDirectoryIndexStream");
#endif
PR_LOG(gLog, PR_LOG_DEBUG,
("nsDirectoryIndexStream[%p]: created", this));
}
nsresult
nsDirectoryIndexStream::Init(nsIFile* aDir)
{
nsresult rv;
PRBool isDir;
rv = aDir->IsDirectory(&isDir);
if (NS_FAILED(rv)) return rv;
NS_PRECONDITION(isDir, "not a directory");
if (!isDir)
return NS_ERROR_ILLEGAL_VALUE;
#ifdef PR_LOGGING
if (PR_LOG_TEST(gLog, PR_LOG_DEBUG)) {
nsXPIDLCString path;
aDir->GetPath(getter_Copies(path));
PR_LOG(gLog, PR_LOG_DEBUG,
("nsDirectoryIndexStream[%p]: initialized on %s",
this, (const char*) path));
}
#endif
mDir = aDir;
// Sigh. We have to allocate on the heap because there are no
// assignment operators defined.
rv = mDir->GetDirectoryEntries(getter_AddRefs(mIter));
if (NS_FAILED(rv)) return rv;
mBuf = "200: filename content-length last-modified file-type\n";
return NS_OK;
}
nsDirectoryIndexStream::~nsDirectoryIndexStream()
{
PR_LOG(gLog, PR_LOG_DEBUG,
("nsDirectoryIndexStream[%p]: destroyed", this));
}
nsresult
nsDirectoryIndexStream::Create(nsIFile* aDir, nsIInputStream** aResult)
{
nsDirectoryIndexStream* result = new nsDirectoryIndexStream();
if (! result)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv;
rv = result->Init(aDir);
if (NS_FAILED(rv)) {
delete result;
return rv;
}
*aResult = result;
NS_ADDREF(*aResult);
return NS_OK;
}
NS_IMPL_ISUPPORTS2(nsDirectoryIndexStream,
nsIInputStream,
nsIBaseStream)
NS_IMETHODIMP
nsDirectoryIndexStream::Close()
{
return NS_OK;
}
NS_IMETHODIMP
nsDirectoryIndexStream::Available(PRUint32* aLength)
{
// Lie, and tell the caller that the stream is endless (until we
// actually don't have anything left).
PRBool more;
nsresult rv = mIter->HasMoreElements(&more);
if (NS_FAILED(rv)) return rv;
if (more) {
*aLength = PRUint32(-1);
return NS_OK;
}
else {
*aLength = 0;
return NS_OK;
}
}
NS_IMETHODIMP
nsDirectoryIndexStream::Read(char* aBuf, PRUint32 aCount, PRUint32* aReadCount)
{
PRUint32 nread = 0;
// If anything is enqueued (or left-over) in mBuf, then feed it to
// the reader first.
while (mOffset < mBuf.Length() && aCount != 0) {
*(aBuf++) = char(mBuf.CharAt(mOffset++));
--aCount;
++nread;
}
// Room left?
if (aCount > 0) {
mOffset = 0;
mBuf.Truncate();
// Okay, now we'll suck stuff off of our iterator into the mBuf...
while (PRUint32(mBuf.Length()) < aCount) {
PRBool more;
nsresult rv = mIter->HasMoreElements(&more);
if (NS_FAILED(rv)) return rv;
if (!more) break;
nsCOMPtr<nsISupports> cur;
rv = mIter->GetNext(getter_AddRefs(cur));
nsCOMPtr<nsIFile> current = do_QueryInterface(cur, &rv);
if (NS_FAILED(rv)) return rv;
#ifdef PR_LOGGING
if (PR_LOG_TEST(gLog, PR_LOG_DEBUG)) {
nsXPIDLCString path;
current->GetPath(getter_Copies(path));
PR_LOG(gLog, PR_LOG_DEBUG,
("nsDirectoryIndexStream[%p]: iterated %s",
this, (const char*) path));
}
#endif
// rjc: don't return hidden files/directories!
PRBool hidden;
rv = current->IsHidden(&hidden);
if (NS_FAILED(rv)) return rv;
if (hidden) {
PR_LOG(gLog, PR_LOG_DEBUG,
("nsDirectoryIndexStream[%p]: skipping hidden file/directory",
this));
continue;
}
PRInt64 fileSize;
PRInt64 fileInfoModifyTime;
rv = current->GetFileSize( &fileSize );
if (NS_FAILED(rv)) return rv;
PROffset32 fileInfoSize;
LL_L2I( fileInfoSize,fileSize );
rv = current->GetLastModificationDate( &fileInfoModifyTime );
if (NS_FAILED(rv)) return rv;
mBuf += "201: ";
// The "filename" field
{
char* leafname;
rv = current->GetLeafName(&leafname);
if (NS_FAILED(rv)) return rv;
if (leafname) {
char* escaped = nsEscape(leafname, url_Path);
if (escaped) {
mBuf += escaped;
mBuf.Append(' ');
nsCRT::free(escaped);
}
nsCRT::free(leafname);
}
}
// The "content-length" field
mBuf.Append(fileInfoSize, 10);
mBuf.Append(' ');
// The "last-modified" field
PRExplodedTime tm;
PR_ExplodeTime(fileInfoModifyTime, PR_GMTParameters, &tm);
{
char buf[64];
PR_FormatTimeUSEnglish(buf, sizeof(buf), "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm);
mBuf.Append(buf);
}
// The "file-type" field
PRBool isFile;
rv = current->IsFile(&isFile);
if (NS_FAILED(rv)) return rv;
if (isFile) {
mBuf += "FILE ";
}
else {
PRBool isDir;
rv = current->IsDirectory(&isDir);
if (NS_FAILED(rv)) return rv;
if (isDir) {
mBuf += "DIRECTORY ";
}
else {
PRBool isLink;
rv = current->IsSymlink(&isLink);
if (NS_FAILED(rv)) return rv;
if (isLink) {
mBuf += "SYMBOLIC-LINK ";
}
}
}
mBuf.Append('\n');
}
// ...and once we've either run out of directory entries, or
// filled up the buffer, then we'll push it to the reader.
while (mOffset < mBuf.Length() && aCount != 0) {
*(aBuf++) = char(mBuf.CharAt(mOffset++));
--aCount;
++nread;
}
}
*aReadCount = nread;
return NS_OK;
}

View File

@@ -0,0 +1,59 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsDirectoryIndexStream_h__
#define nsDirectoryIndexStream_h__
#include "nsIFile.h"
#include "nsString.h"
#include "nsIInputStream.h"
#include "nsCOMPtr.h"
class nsDirectoryIndexStream : public nsIInputStream
{
protected:
nsCAutoString mBuf;
PRInt32 mOffset;
nsCOMPtr<nsIFile> mDir;
nsCOMPtr<nsISimpleEnumerator> mIter;
nsDirectoryIndexStream();
nsresult Init(nsIFile* aDir);
virtual ~nsDirectoryIndexStream();
public:
static nsresult
Create(nsIFile* aDir, nsIInputStream** aStreamResult);
// nsISupportsInterface
NS_DECL_ISUPPORTS
// nsIBaseStream interface
NS_DECL_NSIBASESTREAM
// nsIInputStream interface
NS_DECL_NSIINPUTSTREAM
};
#endif // nsDirectoryIndexStream_h__

View File

@@ -0,0 +1,209 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsFileStreams.h"
#include "nsILocalFile.h"
#include "prerror.h"
////////////////////////////////////////////////////////////////////////////////
// nsFileStream
nsFileStream::nsFileStream()
: mFD(nsnull)
{
NS_INIT_REFCNT();
}
nsFileStream::~nsFileStream()
{
Close();
}
NS_IMPL_THREADSAFE_ISUPPORTS2(nsFileStream,
nsIBaseStream,
nsISeekableStream);
NS_IMETHODIMP
nsFileStream::Close()
{
if (mFD) {
PR_Close(mFD);
mFD = nsnull;
}
return NS_OK;
}
NS_IMETHODIMP
nsFileStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 cnt = PR_Seek(mFD, offset, (PRSeekWhence)whence);
if (cnt == -1) {
return NS_ErrorAccordingToNSPR();
}
return NS_OK;
}
NS_IMETHODIMP
nsFileStream::Tell(PRUint32 *result)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 cnt = PR_Seek(mFD, 0, PR_SEEK_CUR);
if (cnt == -1) {
return NS_ErrorAccordingToNSPR();
}
*result = cnt;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsFileInputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsFileInputStream,
nsFileStream,
nsIInputStream,
nsIFileInputStream);
NS_METHOD
nsFileInputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsFileInputStream* stream = new nsFileInputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsFileInputStream::Init(nsILocalFile* file)
{
NS_ASSERTION(mFD == nsnull, "already inited");
return file->OpenNSPRFileDesc(PR_RDONLY, 0, &mFD);
}
NS_IMETHODIMP
nsFileInputStream::Close()
{
return nsFileStream::Close();
}
NS_IMETHODIMP
nsFileInputStream::Available(PRUint32 *result)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 avail = PR_Available(mFD);
if (avail == -1) {
return NS_ErrorAccordingToNSPR();
}
*result = avail;
return NS_OK;
}
NS_IMETHODIMP
nsFileInputStream::Read(char * buf, PRUint32 count, PRUint32 *result)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 cnt = PR_Read(mFD, buf, count);
if (cnt == -1) {
return NS_ErrorAccordingToNSPR();
}
*result = cnt;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsFileOutputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsFileOutputStream,
nsFileStream,
nsIOutputStream,
nsIFileOutputStream);
NS_METHOD
nsFileOutputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsFileOutputStream* stream = new nsFileOutputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsFileOutputStream::Init(nsILocalFile* file, PRInt32 flags, PRInt32 mode)
{
NS_ASSERTION(mFD == nsnull, "already inited");
if (mFD != nsnull)
return NS_ERROR_FAILURE;
return file->OpenNSPRFileDesc(flags, mode, &mFD);
}
NS_IMETHODIMP
nsFileOutputStream::Close()
{
return nsFileStream::Close();
}
NS_IMETHODIMP
nsFileOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *result)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 cnt = PR_Write(mFD, buf, count);
if (cnt == -1) {
return NS_ErrorAccordingToNSPR();
}
*result = cnt;
return NS_OK;
}
NS_IMETHODIMP
nsFileOutputStream::Flush(void)
{
if (mFD == nsnull)
return NS_BASE_STREAM_CLOSED;
PRInt32 cnt = PR_Sync(mFD);
if (cnt == -1) {
return NS_ErrorAccordingToNSPR();
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,87 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsFileStreams_h__
#define nsFileStreams_h__
#include "nsIFileStreams.h"
#include "nsIFile.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsCOMPtr.h"
////////////////////////////////////////////////////////////////////////////////
class nsFileStream : public nsIBaseStream,
public nsISeekableStream
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIBASESTREAM
NS_DECL_NSISEEKABLESTREAM
nsFileStream();
virtual ~nsFileStream();
protected:
PRFileDesc* mFD;
};
////////////////////////////////////////////////////////////////////////////////
class nsFileInputStream : public nsFileStream,
public nsIFileInputStream
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIBASESTREAM
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSIFILEINPUTSTREAM
nsFileInputStream() : nsFileStream() {}
virtual ~nsFileInputStream() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
};
////////////////////////////////////////////////////////////////////////////////
class nsFileOutputStream : public nsFileStream,
public nsIFileOutputStream
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIBASESTREAM
NS_DECL_NSIOUTPUTSTREAM
NS_DECL_NSIFILEOUTPUTSTREAM
nsFileOutputStream() : nsFileStream() {}
virtual ~nsFileOutputStream() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsFileStreams_h__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,145 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsFileTransport_h__
#define nsFileTransport_h__
#include "nsIChannel.h"
#include "nsIRunnable.h"
#include "nsFileSpec.h"
#include "prlock.h"
#include "nsIEventQueueService.h"
#include "nsIPipe.h"
#include "nsILoadGroup.h"
#include "nsCOMPtr.h"
#include "nsIStreamListener.h"
#include "nsIProgressEventSink.h"
#include "nsIBufferInputStream.h"
#include "nsIBufferOutputStream.h"
#include "nsIFileSystem.h"
#include "nsIInterfaceRequestor.h"
#include "nsIFile.h"
#include "prlog.h"
class nsIInterfaceRequestor;
class nsFileTransport : public nsIChannel,
public nsIRunnable,
public nsIPipeObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSIPIPEOBSERVER
NS_DECL_NSIRUNNABLE
nsFileTransport();
// Always make the destructor virtual:
virtual ~nsFileTransport();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
nsresult Init(nsIFile* file,
PRInt32 mode,
const char* command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
nsresult Init(nsIInputStream* fromStream,
const char* contentType,
PRInt32 contentLength,
const char* command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
nsresult Init(nsIFileSystem* fsObj,
const char* command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
void Process(void);
void DoClose(void);
enum State {
CLOSED,
OPENING,
OPENED,
START_READ,
READING,
END_READ,
START_WRITE,
WRITING,
END_WRITE,
CLOSING
};
enum Command {
NONE,
INITIATE_READ,
INITIATE_WRITE
};
protected:
nsCOMPtr<nsIFile> mFile;
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIProgressEventSink> mProgress;
nsCOMPtr<nsIFileSystem> mFileObject;
char* mContentType;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
nsCOMPtr<nsIStreamObserver> mOpenObserver;
nsCOMPtr<nsISupports> mOpenContext;
nsCOMPtr<nsISupports> mContext;
State mState;
Command mCommand;
PRBool mSuspended;
PRMonitor* mMonitor;
// state variables:
nsresult mStatus;
PRUint32 mOffset;
PRInt32 mTotalAmount;
PRInt32 mTransferAmount;
// reading state varialbles:
nsCOMPtr<nsIStreamListener> mListener;
nsCOMPtr<nsIInputStream> mSource;
nsCOMPtr<nsIBufferInputStream> mBufferInputStream;
nsCOMPtr<nsIBufferOutputStream> mBufferOutputStream;
// writing state variables:
nsCOMPtr<nsIStreamObserver> mObserver;
nsCOMPtr<nsIOutputStream> mSink;
char* mBuffer;
#ifdef PR_LOGGING
char* mSpec;
#endif
};
#define NS_FILE_TRANSPORT_DEFAULT_SEGMENT_SIZE (2*1024)
#define NS_FILE_TRANSPORT_DEFAULT_BUFFER_SIZE (8*1024)
#endif // nsFileTransport_h__

View File

@@ -0,0 +1,200 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsFileTransport.h"
#include "nsFileTransportService.h"
#include "nsIURL.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIProgressEventSink.h"
#include "nsIThreadPool.h"
#include "nsISupportsArray.h"
#include "nsFileSpec.h"
#include "nsAutoLock.h"
static NS_DEFINE_CID(kStandardURLCID, NS_STANDARDURL_CID);
////////////////////////////////////////////////////////////////////////////////
nsFileTransportService::nsFileTransportService()
{
NS_INIT_REFCNT();
}
#define NS_FILE_TRANSPORT_WORKER_STACK_SIZE (64 * 1024) /* (8*1024) */
nsresult
nsFileTransportService::Init()
{
nsresult rv;
rv = NS_NewThreadPool(getter_AddRefs(mPool),
NS_FILE_TRANSPORT_WORKER_COUNT_MIN,
NS_FILE_TRANSPORT_WORKER_COUNT_MAX,
NS_FILE_TRANSPORT_WORKER_STACK_SIZE);
return rv;
}
nsFileTransportService::~nsFileTransportService()
{
mPool->Shutdown();
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsFileTransportService, nsFileTransportService);
NS_IMETHODIMP
nsFileTransportService::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsFileTransportService* ph = new nsFileTransportService();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->Init();
if (NS_SUCCEEDED(rv)) {
rv = ph->QueryInterface(aIID, aResult);
}
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsFileTransportService::CreateTransport(nsIFile* file,
PRInt32 mode,
const char* command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel** result)
{
nsresult rv;
nsFileTransport* trans = new nsFileTransport();
if (trans == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(trans);
rv = trans->Init(file, mode, command, bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(trans);
return rv;
}
*result = trans;
return NS_OK;
}
NS_IMETHODIMP
nsFileTransportService::CreateTransportFromStream(nsIInputStream *fromStream,
const char* contentType,
PRInt32 contentLength,
const char *command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel** result)
{
nsresult rv;
nsFileTransport* trans = new nsFileTransport();
if (trans == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(trans);
rv = trans->Init(fromStream, contentType, contentLength, command,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(trans);
return rv;
}
*result = trans;
return NS_OK;
}
NS_IMETHODIMP
nsFileTransportService::CreateTransportFromFileSystem(nsIFileSystem *fsObj,
const char *command,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel **result)
{
nsresult rv;
nsFileTransport* trans = new nsFileTransport();
if (trans == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(trans);
rv = trans->Init(fsObj, command, bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
NS_RELEASE(trans);
return rv;
}
*result = trans;
return NS_OK;
}
nsresult
nsFileTransportService::ProcessPendingRequests(void)
{
return mPool->ProcessPendingRequests();
}
nsresult
nsFileTransportService::Shutdown(void)
{
return mPool->Shutdown();
}
nsresult
nsFileTransportService::DispatchRequest(nsIRunnable* runnable)
{
return mPool->DispatchRequest(runnable);
}
////////////////////////////////////////////////////////////////////////////////
nsresult
nsFileTransportService::Suspend(nsIRunnable* request)
{
nsresult rv;
nsAutoCMonitor mon(this); // protect mSuspended
if (mSuspended == nsnull) {
rv = NS_NewISupportsArray(getter_AddRefs(mSuspended));
if (NS_FAILED(rv)) return rv;
}
return mSuspended->AppendElement(request) ? NS_OK : NS_ERROR_FAILURE; // XXX this method incorrectly returns a bool
}
nsresult
nsFileTransportService::Resume(nsIRunnable* request)
{
nsresult rv;
nsAutoCMonitor mon(this); // protect mSuspended
if (mSuspended == nsnull)
return NS_ERROR_FAILURE;
// XXX RemoveElement returns a bool instead of nsresult!
PRBool removed = mSuspended->RemoveElement(request);
rv = removed ? NS_OK : NS_ERROR_FAILURE;
if (NS_FAILED(rv)) return rv;
// restart the request
rv = mPool->DispatchRequest(request);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,54 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsFileTransportService_h___
#define nsFileTransportService_h___
#include "nsIFileTransportService.h"
#include "nsIThreadPool.h"
#include "nsISupportsArray.h"
#define NS_FILE_TRANSPORT_WORKER_COUNT_MIN 1
#define NS_FILE_TRANSPORT_WORKER_COUNT_MAX 16
class nsFileTransportService : public nsIFileTransportService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIFILETRANSPORTSERVICE
// nsFileTransportService methods:
nsFileTransportService();
virtual ~nsFileTransportService();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
protected:
nsCOMPtr<nsIThreadPool> mPool;
nsCOMPtr<nsISupportsArray> mOpened;
nsCOMPtr<nsISupportsArray> mSuspended;
};
#endif /* nsFileTransportService_h___ */

View File

@@ -0,0 +1,385 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsIOService.h"
#include "nsIProtocolHandler.h"
#include "nscore.h"
#include "nsString2.h"
#include "nsIServiceManager.h"
#include "nsIEventQueueService.h"
#include "nsIFileTransportService.h"
#include "nsIURI.h"
#include "nsIStreamListener.h"
#include "prprf.h"
#include "nsLoadGroup.h"
#include "nsInputStreamChannel.h"
#include "nsXPIDLString.h"
static NS_DEFINE_CID(kFileTransportService, NS_FILETRANSPORTSERVICE_CID);
static NS_DEFINE_CID(kEventQueueService, NS_EVENTQUEUESERVICE_CID);
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);
////////////////////////////////////////////////////////////////////////////////
nsIOService::nsIOService()
: mOffline(PR_FALSE)
{
NS_INIT_REFCNT();
}
nsresult
nsIOService::Init()
{
nsresult rv = NS_OK;
// We need to get references to these services so that we can shut them
// down later. If we wait until the nsIOService is being shut down,
// GetService will fail at that point.
rv = nsServiceManager::GetService(kSocketTransportServiceCID,
NS_GET_IID(nsISocketTransportService),
getter_AddRefs(mSocketTransportService));
if (NS_FAILED(rv)) return rv;
rv = nsServiceManager::GetService(kFileTransportService,
NS_GET_IID(nsIFileTransportService),
getter_AddRefs(mFileTransportService));
if (NS_FAILED(rv)) return rv;
rv = nsServiceManager::GetService(kDNSServiceCID,
NS_GET_IID(nsIDNSService),
getter_AddRefs(mDNSService));
return rv;
}
nsIOService::~nsIOService()
{
(void)SetOffline(PR_TRUE);
}
NS_METHOD
nsIOService::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsIOService* _ios = new nsIOService();
if (_ios == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(_ios);
rv = _ios->Init();
if (NS_FAILED(rv)) {
delete _ios;
return rv;
}
rv = _ios->QueryInterface(aIID, aResult);
NS_RELEASE(_ios);
return rv;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsIOService, nsIIOService);
////////////////////////////////////////////////////////////////////////////////
#define MAX_SCHEME_LENGTH 64 // XXX big enough?
#define MAX_NET_PROGID_LENGTH (MAX_SCHEME_LENGTH + NS_NETWORK_PROTOCOL_PROGID_PREFIX_LENGTH + 1)
NS_IMETHODIMP
nsIOService::GetProtocolHandler(const char* scheme, nsIProtocolHandler* *result)
{
nsresult rv;
NS_ASSERTION(NS_NETWORK_PROTOCOL_PROGID_PREFIX_LENGTH
== nsCRT::strlen(NS_NETWORK_PROTOCOL_PROGID_PREFIX),
"need to fix NS_NETWORK_PROTOCOL_PROGID_PREFIX_LENGTH");
// XXX we may want to speed this up by introducing our own protocol
// scheme -> protocol handler mapping, avoiding the string manipulation
// and service manager stuff
char buf[MAX_NET_PROGID_LENGTH];
nsCAutoString progID(NS_NETWORK_PROTOCOL_PROGID_PREFIX);
progID += scheme;
progID.ToLowerCase();
progID.ToCString(buf, MAX_NET_PROGID_LENGTH);
rv = nsServiceManager::GetService(buf, NS_GET_IID(nsIProtocolHandler), (nsISupports **)result);
if (NS_FAILED(rv))
return NS_ERROR_UNKNOWN_PROTOCOL;
return NS_OK;
}
NS_IMETHODIMP
nsIOService::ExtractScheme(const char* inURI, PRUint32 *startPos, PRUint32 *endPos,
char* *scheme)
{
// search for something up to a colon, and call it the scheme
NS_ASSERTION(inURI, "null pointer");
if (!inURI) return NS_ERROR_NULL_POINTER;
const char* uri = inURI;
// skip leading white space
while (nsString::IsSpace(*uri))
uri++;
PRUint32 start = uri - inURI;
if (startPos) {
*startPos = start;
}
PRUint32 length = 0;
char c;
while ((c = *uri++) != '\0') {
if (c == ':') {
if (endPos) {
*endPos = start + length + 1;
}
if (scheme) {
char* str = (char*)nsAllocator::Alloc(length + 1);
if (str == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsCRT::memcpy(str, &inURI[start], length);
str[length] = '\0';
*scheme = str;
}
return NS_OK;
}
else if (nsString::IsAlpha(c)) {
length++;
}
else
break;
}
return NS_ERROR_MALFORMED_URI;
}
nsresult
nsIOService::NewURI(const char* aSpec, nsIURI* aBaseURI,
nsIURI* *result, nsIProtocolHandler* *hdlrResult)
{
nsresult rv;
nsIURI* base;
char* scheme;
rv = ExtractScheme(aSpec, nsnull, nsnull, &scheme);
if (NS_SUCCEEDED(rv)) {
// then aSpec is absolute
// ignore aBaseURI in this case
base = nsnull;
}
else {
// then aSpec is relative
if (aBaseURI == nsnull)
return NS_ERROR_MALFORMED_URI;
rv = aBaseURI->GetScheme(&scheme);
if (NS_FAILED(rv)) return rv;
base = aBaseURI;
}
nsCOMPtr<nsIProtocolHandler> handler;
rv = GetProtocolHandler(scheme, getter_AddRefs(handler));
nsCRT::free(scheme);
if (NS_FAILED(rv)) return rv;
if (hdlrResult) {
*hdlrResult = handler;
NS_ADDREF(*hdlrResult);
}
return handler->NewURI(aSpec, base, result);
}
NS_IMETHODIMP
nsIOService::NewURI(const char* aSpec, nsIURI* aBaseURI,
nsIURI* *result)
{
return NewURI(aSpec, aBaseURI, result, nsnull);
}
NS_IMETHODIMP
nsIOService::NewChannelFromURI(const char* verb, nsIURI *aURI,
nsILoadGroup *aGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel **result)
{
nsresult rv;
nsXPIDLCString scheme;
rv = aURI->GetScheme(getter_Copies(scheme));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIProtocolHandler> handler;
rv = GetProtocolHandler((const char*)scheme, getter_AddRefs(handler));
if (NS_FAILED(rv)) return rv;
rv = handler->NewChannel(verb, aURI, aGroup, notificationCallbacks,
loadAttributes, originalURI,
bufferSegmentSize, bufferMaxSize, result);
return rv;
}
NS_IMETHODIMP
nsIOService::NewChannel(const char* verb, const char *aSpec,
nsIURI *aBaseURI,
nsILoadGroup *aGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel **result)
{
nsresult rv;
nsCOMPtr<nsIURI> uri;
nsCOMPtr<nsIProtocolHandler> handler;
rv = NewURI(aSpec, aBaseURI, getter_AddRefs(uri), getter_AddRefs(handler));
if (NS_FAILED(rv)) return rv;
rv = handler->NewChannel(verb, uri, aGroup, notificationCallbacks,
loadAttributes, originalURI,
bufferSegmentSize, bufferMaxSize, result);
return rv;
}
NS_IMETHODIMP
nsIOService::GetOffline(PRBool *offline)
{
*offline = mOffline;
return NS_OK;
}
NS_IMETHODIMP
nsIOService::SetOffline(PRBool offline)
{
mOffline = offline;
if (offline) {
// be sure to try and shutdown both (even if the first fails)
nsresult rv1 = NS_OK;
nsresult rv2 = NS_OK;
if (mSocketTransportService)
rv1 = mSocketTransportService->Shutdown();
if (mDNSService)
rv2 = mDNSService->Shutdown();
if (NS_FAILED(rv1)) return rv1;
if (NS_FAILED(rv2)) return rv2;
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// URL parsing utilities
NS_IMETHODIMP
nsIOService::Escape(const char *str, PRInt16 mask, char** result)
{
nsCAutoString esc_str;
nsresult rv = nsURLEscape((char*)str,mask,esc_str);
CRTFREEIF(*result);
if (NS_FAILED(rv))
return rv;
*result = esc_str.ToNewCString();
if (!*result)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsIOService::Unescape(const char *str, char **result)
{
return nsURLUnescape((char*)str,result);
}
NS_IMETHODIMP
nsIOService::ExtractPort(const char *str, PRInt32 *result)
{
PRInt32 returnValue = -1;
*result = (0 < PR_sscanf(str, "%d", &returnValue)) ? returnValue : -1;
return NS_OK;
}
NS_IMETHODIMP
nsIOService::ResolveRelativePath(const char *relativePath, const char* basePath,
char **result)
{
nsCAutoString name;
nsCAutoString path(basePath);
PRUnichar last = path.Last();
PRBool needsDelim = !(last == '/' || last == '\\' || last == '\0');
PRBool end = PR_FALSE;
char c;
while (!end) {
c = *relativePath++;
switch (c) {
case '\0':
case '#':
case ';':
case '?':
end = PR_TRUE;
// fall through...
case '/':
case '\\':
// delimiter found
if (name.Equals("..")) {
// pop path
PRInt32 pos = path.RFind("/");
if (pos > 0) {
path.Truncate(pos + 1);
path += name;
}
else {
return NS_ERROR_MALFORMED_URI;
}
}
else if (name.Equals(".") || name.Equals("")) {
// do nothing
}
else {
// append name to path
if (needsDelim)
path += "/";
path += name;
needsDelim = PR_TRUE;
}
name = "";
break;
default:
// append char to name
name += c;
}
}
// append anything left on relativePath (e.g. #..., ;..., ?...)
if (c != '\0')
path += --relativePath;
*result = path.ToNewCString();
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,60 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsIOService_h__
#define nsIOService_h__
#include "nsIIOService.h"
#include "nsString2.h"
#include "nsISocketTransportService.h"
#include "nsIFileTransportService.h"
#include "nsIDNSService.h"
#include "nsCOMPtr.h"
#include "nsURLHelper.h"
class nsIOService : public nsIIOService
{
public:
NS_DECL_ISUPPORTS
// nsIIOService methods:
NS_DECL_NSIIOSERVICE
// nsIOService methods:
nsIOService();
virtual ~nsIOService();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
nsresult NewURI(const char* aSpec, nsIURI* aBaseURI,
nsIURI* *result, nsIProtocolHandler* *hdlrResult);
protected:
PRBool mOffline;
nsCOMPtr<nsISocketTransportService> mSocketTransportService;
nsCOMPtr<nsIFileTransportService> mFileTransportService;
nsCOMPtr<nsIDNSService> mDNSService;
};
#endif // nsIOService_h__

View File

@@ -0,0 +1,381 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsInputStreamChannel.h"
#include "nsCOMPtr.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsIMIMEService.h"
#include "nsIFileTransportService.h"
#include "netCore.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
static NS_DEFINE_CID(kMIMEServiceCID, NS_MIMESERVICE_CID);
static NS_DEFINE_CID(kFileTransportServiceCID, NS_FILETRANSPORTSERVICE_CID);
////////////////////////////////////////////////////////////////////////////////
// nsInputStreamChannel methods:
nsInputStreamChannel::nsInputStreamChannel()
: mContentType(nsnull), mContentLength(-1), mLoadAttributes(LOAD_NORMAL)
{
NS_INIT_REFCNT();
}
nsInputStreamChannel::~nsInputStreamChannel()
{
if (mContentType) nsCRT::free(mContentType);
}
NS_METHOD
nsInputStreamChannel::Create(nsISupports *aOuter, REFNSIID aIID,
void **aResult)
{
nsInputStreamChannel* channel = new nsInputStreamChannel();
if (channel == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(channel);
nsresult rv = channel->QueryInterface(aIID, aResult);
NS_RELEASE(channel);
return rv;
}
NS_IMETHODIMP
nsInputStreamChannel::Init(nsIURI* uri,
const char* contentType,
PRInt32 contentLength,
nsIInputStream* in,
nsILoadGroup *aGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
nsIURI* originalURI,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize)
{
nsresult rv;
mOriginalURI = originalURI ? originalURI : uri;
mURI = uri;
mContentLength = contentLength;
mBufferSegmentSize = bufferSegmentSize;
mBufferMaxSize = bufferMaxSize;
rv = SetLoadAttributes(loadAttributes);
if (NS_FAILED(rv)) return rv;
rv = SetLoadGroup(aGroup);
if (NS_FAILED(rv)) return rv;
rv = SetNotificationCallbacks(notificationCallbacks);
if (NS_FAILED(rv)) return rv;
if (contentType) {
mContentType = nsCRT::strdup(contentType);
const char *constContentType = mContentType;
if (!constContentType) return NS_ERROR_OUT_OF_MEMORY;
char* semicolon = PL_strchr(constContentType, ';');
CBufDescriptor cbd(constContentType,
PR_TRUE,
semicolon ? (semicolon-constContentType) + 1: PL_strlen(constContentType), // capacity
semicolon ? (semicolon-constContentType) : PL_strlen(constContentType));
nsCAutoString(cbd).ToLowerCase();
}
mInputStream = in;
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS5(nsInputStreamChannel,
nsIInputStreamChannel,
nsIChannel,
nsIRequest,
nsIStreamObserver,
nsIStreamListener);
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsInputStreamChannel::IsPending(PRBool *result)
{
if (mFileTransport)
return mFileTransport->IsPending(result);
*result = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::Cancel(void)
{
if (mFileTransport)
return mFileTransport->Cancel();
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::Suspend(void)
{
if (mFileTransport)
return mFileTransport->Suspend();
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::Resume(void)
{
if (mFileTransport)
return mFileTransport->Resume();
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods:
NS_IMETHODIMP
nsInputStreamChannel::GetOriginalURI(nsIURI * *aURI)
{
*aURI = mOriginalURI;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetURI(nsIURI * *aURI)
{
*aURI = mURI;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::AsyncOpen(nsIStreamObserver *observer, nsISupports* ctxt)
{
if (mFileTransport)
return NS_ERROR_IN_PROGRESS;
nsresult rv;
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = fts->CreateTransportFromStream(mInputStream, mContentType, mContentLength,
"load", mBufferSegmentSize, mBufferMaxSize,
getter_AddRefs(mFileTransport));
if (NS_FAILED(rv)) return rv;
return mFileTransport->AsyncOpen(observer, ctxt);
}
NS_IMETHODIMP
nsInputStreamChannel::OpenInputStream(PRUint32 startPosition, PRInt32 readCount,
nsIInputStream **result)
{
// if we had seekable streams, we could seek here:
NS_ASSERTION(startPosition == 0, "Can't seek in nsInputStreamChannel");
*result = mInputStream;
NS_ADDREF(*result);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::OpenOutputStream(PRUint32 startPosition, nsIOutputStream **_retval)
{
// we don't do output
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsInputStreamChannel::AsyncRead(PRUint32 startPosition, PRInt32 readCount,
nsISupports *ctxt, nsIStreamListener *listener)
{
nsresult rv;
mRealListener = listener;
if (mLoadGroup) {
nsCOMPtr<nsILoadGroupListenerFactory> factory;
//
// Create a load group "proxy" listener...
//
rv = mLoadGroup->GetGroupListenerFactory(getter_AddRefs(factory));
if (factory) {
nsIStreamListener *newListener;
rv = factory->CreateLoadGroupListener(mRealListener, &newListener);
if (NS_SUCCEEDED(rv)) {
mRealListener = newListener;
NS_RELEASE(newListener);
}
}
rv = mLoadGroup->AddChannel(this, nsnull);
if (NS_FAILED(rv)) return rv;
}
if (mFileTransport == nsnull) {
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = fts->CreateTransportFromStream(mInputStream, mContentType, mContentLength,
"load", mBufferSegmentSize, mBufferMaxSize,
getter_AddRefs(mFileTransport));
if (NS_FAILED(rv)) return rv;
}
return mFileTransport->AsyncRead(startPosition, readCount, ctxt, this);
}
NS_IMETHODIMP
nsInputStreamChannel::AsyncWrite(nsIInputStream *fromStream, PRUint32 startPosition,
PRInt32 writeCount, nsISupports *ctxt,
nsIStreamObserver *observer)
{
// we don't do output
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsInputStreamChannel::GetLoadAttributes(nsLoadFlags *aLoadAttributes)
{
*aLoadAttributes = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::SetLoadAttributes(nsLoadFlags aLoadAttributes)
{
mLoadAttributes = aLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetContentType(char * *aContentType)
{
*aContentType = nsCRT::strdup(mContentType);
if (*aContentType == nsnull) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::SetContentType(const char *aContentType)
{
if (mContentType) {
nsCRT::free(mContentType);
}
mContentType = nsCRT::strdup(aContentType);
if (aContentType == nsnull) {
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetContentLength(PRInt32 *aContentLength)
{
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup.get();
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
mLoadGroup = aLoadGroup;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetOwner(nsISupports* *aOwner)
{
*aOwner = mOwner.get();
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsInputStreamChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIStreamListener methods:
////////////////////////////////////////////////////////////////////////////////
NS_IMETHODIMP
nsInputStreamChannel::OnStartRequest(nsIChannel* transportChannel, nsISupports* context)
{
NS_ASSERTION(mRealListener, "No listener...");
return mRealListener->OnStartRequest(this, context);
}
NS_IMETHODIMP
nsInputStreamChannel::OnStopRequest(nsIChannel* transportChannel, nsISupports* context,
nsresult aStatus, const PRUnichar* aMsg)
{
nsresult rv;
rv = mRealListener->OnStopRequest(this, context, aStatus, aMsg);
if (mLoadGroup) {
if (NS_SUCCEEDED(rv)) {
mLoadGroup->RemoveChannel(this, context, aStatus, aMsg);
}
}
// Release the reference to the consumer stream listener...
mRealListener = null_nsCOMPtr();
mFileTransport = null_nsCOMPtr();
return rv;
}
NS_IMETHODIMP
nsInputStreamChannel::OnDataAvailable(nsIChannel* transportChannel, nsISupports* context,
nsIInputStream *aIStream, PRUint32 aSourceOffset,
PRUint32 aLength)
{
return mRealListener->OnDataAvailable(this, context, aIStream,
aSourceOffset, aLength);
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,68 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsInputStreamChannel_h__
#define nsInputStreamChannel_h__
#include "nsIChannel.h"
#include "nsIInputStream.h"
#include "nsIURI.h"
#include "nsCRT.h"
#include "nsILoadGroup.h"
#include "nsIStreamListener.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
class nsInputStreamChannel : public nsIInputStreamChannel,
public nsIStreamListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSIINPUTSTREAMCHANNEL
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
nsInputStreamChannel();
virtual ~nsInputStreamChannel();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsCOMPtr<nsIURI> mURI;
char* mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCOMPtr<nsISupports> mOwner;
nsCOMPtr<nsIChannel> mFileTransport;
nsCOMPtr<nsIStreamListener> mRealListener;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRUint32 mLoadAttributes;
};
#endif // nsInputStreamChannel_h__

View File

@@ -0,0 +1,670 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsLoadGroup.h"
#include "nsIStreamObserver.h"
#include "nsIChannel.h"
#include "nsISupportsArray.h"
#include "nsEnumeratorUtils.h"
#include "nsIServiceManager.h"
#include "nsIEventQueueService.h"
#include "nsCOMPtr.h"
#include "nsIURI.h"
#include "prlog.h"
#include "nsCRT.h"
#if defined(PR_LOGGING)
//
// Log module for nsILoadGroup logging...
//
// To enable logging (see prlog.h for full details):
//
// set NSPR_LOG_MODULES=LoadGroup:5
// set NSPR_LOG_FILE=nspr.log
//
// this enables PR_LOG_DEBUG level information and places all output in
// the file nspr.log
//
PRLogModuleInfo* gLoadGroupLog = nsnull;
#endif /* PR_LOGGING */
////////////////////////////////////////////////////////////////////////////////
nsLoadGroup::nsLoadGroup(nsISupports* outer)
: mDefaultLoadAttributes(nsIChannel::LOAD_NORMAL),
mForegroundCount(0),
mChannels(nsnull)
{
NS_INIT_AGGREGATED(outer);
#if defined(PR_LOGGING)
//
// Initialize the global PRLogModule for nsILoadGroup logging
// if necessary...
//
if (nsnull == gLoadGroupLog) {
gLoadGroupLog = PR_NewLogModule("LoadGroup");
}
#endif /* PR_LOGGING */
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Created.\n", this));
}
nsLoadGroup::~nsLoadGroup()
{
nsresult rv;
rv = Cancel();
NS_ASSERTION(NS_SUCCEEDED(rv), "Cancel failed");
NS_IF_RELEASE(mChannels);
mDefaultLoadChannel = null_nsCOMPtr();
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Destroyed.\n", this));
}
nsresult nsLoadGroup::Init()
{
return NS_NewISupportsArray(&mChannels);
}
NS_METHOD
nsLoadGroup::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
NS_ENSURE_PROPER_AGGREGATION(aOuter, aIID);
nsresult rv;
nsLoadGroup* group = new nsLoadGroup(aOuter);
if (group == nsnull) {
*aResult = nsnull;
return NS_ERROR_OUT_OF_MEMORY;
}
rv = group->Init();
if (NS_SUCCEEDED(rv)) {
rv = group->AggregatedQueryInterface(aIID, aResult);
}
if (NS_FAILED(rv)) {
delete group;
}
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsISupports methods:
NS_IMPL_AGGREGATED(nsLoadGroup);
NS_IMETHODIMP
nsLoadGroup::AggregatedQueryInterface(const nsIID& aIID, void** aInstancePtr)
{
NS_ENSURE_ARG_POINTER(aInstancePtr);
if (aIID.Equals(NS_GET_IID(nsISupports)))
*aInstancePtr = GetInner();
else if (aIID.Equals(NS_GET_IID(nsILoadGroup)) ||
aIID.Equals(NS_GET_IID(nsIRequest)) ||
aIID.Equals(NS_GET_IID(nsISupports))) {
*aInstancePtr = NS_STATIC_CAST(nsILoadGroup*, this);
}
else if (aIID.Equals(NS_GET_IID(nsISupportsWeakReference))) {
*aInstancePtr = NS_STATIC_CAST(nsISupportsWeakReference*,this);
}
else {
*aInstancePtr = nsnull;
return NS_NOINTERFACE;
}
NS_ADDREF((nsISupports*)*aInstancePtr);
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsLoadGroup::IsPending(PRBool *aResult)
{
if (mForegroundCount > 0) {
*aResult = PR_TRUE;
} else {
*aResult = PR_FALSE;
}
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::Cancel()
{
nsresult rv, firstError;
PRUint32 count;
rv = mChannels->Count(&count);
if (NS_FAILED(rv)) return rv;
firstError = NS_OK;
if (count) {
nsIChannel* channel;
//
// Operate the elements from back to front so that if items get
// get removed from the list it won't affect our iteration
//
while (count > 0) {
channel = NS_STATIC_CAST(nsIChannel*, mChannels->ElementAt(--count));
NS_ASSERTION(channel, "NULL channel found in list.");
if (!channel) {
continue;
}
#if defined(PR_LOGGING)
char* uriStr;
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_SUCCEEDED(rv)) {
rv = uri->GetSpec(&uriStr);
}
if (NS_FAILED(rv)) {
uriStr = nsCRT::strdup("?");
}
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Canceling channel %x %s.\n",
this, channel, uriStr));
nsCRT::free(uriStr);
#endif /* PR_LOGGING */
//
// Remove the channel from the load group... This may cause
// the OnStopRequest notification to fire...
//
// XXX: What should the context and error message be?
//
(void)RemoveChannel(channel, nsnull, NS_BINDING_ABORTED, nsnull);
// Cancel the channel...
rv = channel->Cancel();
// Remember the first failure and return it...
if (NS_FAILED(rv) && NS_SUCCEEDED(firstError)) {
firstError = rv;
}
NS_RELEASE(channel);
}
#if defined(DEBUG)
(void)mChannels->Count(&count);
NS_ASSERTION(count == 0, "Channel list is not empty.");
NS_ASSERTION(mForegroundCount == 0, "Foreground URLs are active.");
#endif /* DEBUG */
}
return firstError;
}
NS_IMETHODIMP
nsLoadGroup::Suspend()
{
nsresult rv, firstError;
PRUint32 count;
rv = mChannels->Count(&count);
if (NS_FAILED(rv)) return rv;
firstError = NS_OK;
//
// Operate the elements from back to front so that if items get
// get removed from the list it won't affect our iteration
//
while (count > 0) {
nsIChannel* channel;
channel = NS_STATIC_CAST(nsIChannel*, mChannels->ElementAt(--count));
NS_ASSERTION(channel, "NULL channel found in list.");
if (!channel) {
continue;
}
#if defined(PR_LOGGING)
char* uriStr;
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_SUCCEEDED(rv)) {
rv = uri->GetSpec(&uriStr);
}
if (NS_FAILED(rv)) {
uriStr = nsCRT::strdup("?");
}
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Suspending channel %x %s.\n",
this, channel, uriStr));
nsCRT::free(uriStr);
#endif /* PR_LOGGING */
// Suspend the channel...
rv = channel->Suspend();
// Remember the first failure and return it...
if (NS_FAILED(rv) && NS_SUCCEEDED(firstError)) {
firstError = rv;
}
NS_RELEASE(channel);
}
return firstError;
}
NS_IMETHODIMP
nsLoadGroup::Resume()
{
nsresult rv, firstError;
PRUint32 count;
rv = mChannels->Count(&count);
if (NS_FAILED(rv)) return rv;
firstError = NS_OK;
//
// Operate the elements from back to front so that if items get
// get removed from the list it won't affect our iteration
//
while (count > 0) {
nsIChannel* channel;
channel = NS_STATIC_CAST(nsIChannel*, mChannels->ElementAt(--count));
NS_ASSERTION(channel, "NULL channel found in list.");
if (!channel) {
continue;
}
#if defined(PR_LOGGING)
char* uriStr;
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_SUCCEEDED(rv)) {
rv = uri->GetSpec(&uriStr);
}
if (NS_FAILED(rv)) {
uriStr = nsCRT::strdup("?");
}
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Resuming channel %x %s.\n",
this, channel, uriStr));
nsCRT::free(uriStr);
#endif /* PR_LOGGING */
// Resume the channel...
rv = channel->Resume();
// Remember the first failure and return it...
if (NS_FAILED(rv) && NS_SUCCEEDED(firstError)) {
firstError = rv;
}
NS_RELEASE(channel);
}
return firstError;
}
////////////////////////////////////////////////////////////////////////////////
// nsILoadGroup methods:
NS_IMETHODIMP
nsLoadGroup::Init(nsIStreamObserver *aObserver)
{
nsresult rv;
rv = SetGroupObserver(aObserver);
return rv;
}
NS_IMETHODIMP
nsLoadGroup::GetDefaultLoadAttributes(PRUint32 *aDefaultLoadAttributes)
{
*aDefaultLoadAttributes = mDefaultLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::SetDefaultLoadAttributes(PRUint32 aDefaultLoadAttributes)
{
mDefaultLoadAttributes = aDefaultLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::GetDefaultLoadChannel(nsIChannel * *aChannel)
{
*aChannel = mDefaultLoadChannel;
NS_IF_ADDREF(*aChannel);
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::SetDefaultLoadChannel(nsIChannel *aChannel)
{
mDefaultLoadChannel = aChannel;
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::AddChannel(nsIChannel *channel, nsISupports* ctxt)
{
nsresult rv;
#if defined(PR_LOGGING)
{
PRUint32 count;
char* uriStr;
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_SUCCEEDED(rv))
rv = uri->GetSpec(&uriStr);
if (NS_FAILED(rv))
uriStr = nsCRT::strdup("?");
(void)mChannels->Count(&count);
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Adding channel %x %s (count=%d).\n",
this, channel, uriStr, count));
nsCRT::free(uriStr);
}
#endif /* PR_LOGGING */
nsLoadFlags flags;
MergeLoadAttributes(channel);
rv = channel->GetLoadAttributes(&flags);
if (NS_FAILED(rv)) return rv;
//
// Add the channel to the list of active channels...
//
// XXX this method incorrectly returns a bool
//
rv = mChannels->AppendElement(channel) ? NS_OK : NS_ERROR_FAILURE;
if (NS_FAILED(rv)) return rv;
if (!(flags & nsIChannel::LOAD_BACKGROUND)) {
// Update the count of foreground URIs..
mForegroundCount += 1;
//
// Fire the OnStartRequest notification out to the observer...
//
// If the notification fails then DO NOT add the channel to
// the load group.
//
if (mObserver) {
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Firing OnStartRequest for channel %x."
"(foreground count=%d).\n",
this, channel, mForegroundCount));
rv = mObserver->OnStartRequest(channel, ctxt);
if (NS_FAILED(rv)) {
PR_LOG(gLoadGroupLog, PR_LOG_ERROR,
("LOADGROUP [%x]: OnStartRequest for channel %x FAILED.\n",
this, channel));
//
// The URI load has been canceled by the observer. Clean up
// the damage...
//
// XXX this method incorrectly returns a bool
//
rv = mChannels->RemoveElement(channel) ? NS_OK : NS_ERROR_FAILURE;
mForegroundCount -= 1;
}
}
}
return rv;
}
NS_IMETHODIMP
nsLoadGroup::RemoveChannel(nsIChannel *channel, nsISupports* ctxt,
nsresult status, const PRUnichar *errorMsg)
{
nsresult rv;
#if defined(PR_LOGGING)
{
PRUint32 count = 0;
char* uriStr;
nsCOMPtr<nsIURI> uri;
if (channel) {
rv = channel->GetURI(getter_AddRefs(uri));
}
else {
rv = NS_ERROR_NULL_POINTER;
}
if (NS_SUCCEEDED(rv))
rv = uri->GetSpec(&uriStr);
if (NS_FAILED(rv))
uriStr = nsCRT::strdup("?");
(void)mChannels->Count(&count);
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Removing channel %x %s status %x (count=%d).\n",
this, channel, uriStr, status, count-1));
nsCRT::free(uriStr);
}
#endif /* PR_LOGGING */
//
// Remove the channel from the group. If this fails, it means that
// the channel was *not* in the group so do not update the foreground
// count or it will get messed up...
//
//
// XXX this method incorrectly returns a bool
//
rv = mChannels->RemoveElement(channel) ? NS_OK : NS_ERROR_FAILURE;
if (NS_FAILED(rv)) {
PR_LOG(gLoadGroupLog, PR_LOG_ERROR,
("LOADGROUP [%x]: Unable to remove channel %x. Not in group!\n",
this, channel));
return rv;
}
nsLoadFlags flags;
rv = channel->GetLoadAttributes(&flags);
if (NS_FAILED(rv)) return rv;
if (!(flags & nsIChannel::LOAD_BACKGROUND)) {
NS_ASSERTION(mForegroundCount > 0, "ForegroundCount messed up");
mForegroundCount -= 1;
// Fire the OnStopRequest out to the observer...
if (mObserver) {
PR_LOG(gLoadGroupLog, PR_LOG_DEBUG,
("LOADGROUP [%x]: Firing OnStopRequest for channel %x."
"(foreground count=%d).\n",
this, channel, mForegroundCount));
rv = mObserver->OnStopRequest(channel, ctxt, status, errorMsg);
if (NS_FAILED(rv)) {
PR_LOG(gLoadGroupLog, PR_LOG_ERROR,
("LOADGROUP [%x]: OnStopRequest for channel %x FAILED.\n",
this, channel));
}
}
}
return rv;
}
NS_IMETHODIMP
nsLoadGroup::GetChannels(nsISimpleEnumerator * *aChannels)
{
return NS_NewArrayEnumerator(aChannels, mChannels);
}
NS_IMETHODIMP
nsLoadGroup::GetGroupListenerFactory(nsILoadGroupListenerFactory * *aFactory)
{
if (mGroupListenerFactory) {
mGroupListenerFactory->QueryReferent(NS_GET_IID(nsILoadGroupListenerFactory), (void**)aFactory);
}
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::SetGroupListenerFactory(nsILoadGroupListenerFactory *aFactory)
{
mGroupListenerFactory = getter_AddRefs(NS_GetWeakReference(aFactory));
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::SetGroupObserver(nsIStreamObserver* aObserver)
{
nsresult rv = NS_OK;
// Release the old observer (if any...)
mObserver = null_nsCOMPtr();
#if 0
if (aObserver) {
nsCOMPtr<nsIEventQueue> eventQueue;
NS_WITH_SERVICE(nsIEventQueueService, eventQService, kEventQueueService, &rv);
if (NS_FAILED(rv)) return rv;
rv = eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, getter_AddRefs(eventQueue));
if (NS_FAILED(rv)) return rv;
rv = NS_NewAsyncStreamObserver(getter_AddRefs(mObserver),
eventQueue, aObserver);
}
#else
mObserver = aObserver;
#endif
return rv;
}
NS_IMETHODIMP
nsLoadGroup::GetGroupObserver(nsIStreamObserver* *aResult)
{
*aResult = mObserver;
NS_IF_ADDREF(*aResult);
return NS_OK;
}
NS_IMETHODIMP
nsLoadGroup::GetActiveCount(PRUint32* aResult)
{
*aResult = mForegroundCount;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
nsresult nsLoadGroup::MergeLoadAttributes(nsIChannel *aChannel)
{
nsresult rv;
nsLoadFlags flags, oldFlags;
rv = aChannel->GetLoadAttributes(&flags);
if (NS_FAILED(rv)) return rv;
oldFlags = flags;
//
// Inherit the group cache validation policy (bits 12-15)
//
if ( !((nsIChannel::VALIDATE_NEVER |
nsIChannel::VALIDATE_ALWAYS |
nsIChannel::VALIDATE_ONCE_PER_SESSION |
nsIChannel::VALIDATE_HEURISTICALLY) & flags)) {
flags |= (nsIChannel::VALIDATE_NEVER |
nsIChannel::VALIDATE_ALWAYS |
nsIChannel::VALIDATE_ONCE_PER_SESSION |
nsIChannel::VALIDATE_HEURISTICALLY) & mDefaultLoadAttributes;
}
//
// Inherit the group reload policy (bits 9-10)
//
if (!(nsIChannel::FORCE_VALIDATION & flags)) {
flags |= (nsIChannel::FORCE_VALIDATION & mDefaultLoadAttributes);
}
if (!(nsIChannel::FORCE_RELOAD & flags)) {
flags |= (nsIChannel::FORCE_RELOAD & mDefaultLoadAttributes);
}
//
// Inherit the group persistent cache policy (bit 8)
//
if (!(nsIChannel::INHIBIT_PERSISTENT_CACHING & flags)) {
flags |= (nsIChannel::INHIBIT_PERSISTENT_CACHING & mDefaultLoadAttributes);
}
//
// Inherit the group loading policy (bit 0)
//
if (!(nsIChannel::LOAD_BACKGROUND & flags)) {
flags |= (nsIChannel::LOAD_BACKGROUND & mDefaultLoadAttributes);
}
if (flags != oldFlags) {
rv = aChannel->SetLoadAttributes(flags);
}
return rv;
}

View File

@@ -0,0 +1,77 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsLoadGroup_h__
#define nsLoadGroup_h__
#include "nsILoadGroup.h"
#include "nsIChannel.h"
#include "nsIStreamListener.h"
#include "nsAgg.h"
#include "nsCOMPtr.h"
#include "nsWeakPtr.h"
#include "nsWeakReference.h"
class nsISupportsArray;
class nsLoadGroup : public nsILoadGroup,
public nsSupportsWeakReference
{
public:
NS_DECL_AGGREGATED
////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_DECL_NSIREQUEST
////////////////////////////////////////////////////////////////////////////
// nsILoadGroup methods:
NS_DECL_NSILOADGROUP
////////////////////////////////////////////////////////////////////////////
// nsLoadGroup methods:
nsLoadGroup(nsISupports* outer);
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
virtual ~nsLoadGroup();
nsresult Init();
nsresult MergeLoadAttributes(nsIChannel *aChannel);
protected:
PRUint32 mDefaultLoadAttributes;
PRUint32 mForegroundCount;
nsISupportsArray* mChannels;
//// nsWeakPtr mObserver;
nsCOMPtr<nsIStreamObserver> mObserver;
nsCOMPtr<nsIChannel> mDefaultLoadChannel;
nsWeakPtr mGroupListenerFactory;
};
#endif // nsLoadGroup_h__

View File

@@ -0,0 +1,183 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsNetModRegEntry.h"
#include "plstr.h"
#include "nsIAllocator.h"
#include "nsIServiceManager.h"
#include "nsIEventQueueService.h"
#include "nsProxyObjectManager.h"
static NS_DEFINE_IID(kProxyObjectManagerCID, NS_PROXYEVENT_MANAGER_CID);
static NS_DEFINE_IID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
//////////////////////////////
//// nsISupports
//////////////////////////////
NS_IMPL_ISUPPORTS(nsNetModRegEntry, NS_GET_IID(nsINetModRegEntry));
//////////////////////////////
//// nsINetModRegEntry
//////////////////////////////
NS_IMETHODIMP
nsNetModRegEntry::GetSyncProxy(nsINetNotify **aNotify)
{
if (mSyncProxy)
{
*aNotify = mSyncProxy;
NS_ADDREF(*aNotify);
return NS_OK;
}
nsresult rv = BuildProxy(PR_TRUE);
if (NS_SUCCEEDED(rv))
{
*aNotify = mSyncProxy;
NS_ADDREF(*aNotify);
}
return rv;
}
NS_IMETHODIMP
nsNetModRegEntry::GetAsyncProxy(nsINetNotify **aNotify)
{
if (mAsyncProxy)
{
*aNotify = mAsyncProxy;
NS_ADDREF(*aNotify);
return NS_OK;
}
nsresult rv = BuildProxy(PR_FALSE);
if (NS_SUCCEEDED(rv))
{
*aNotify = mAsyncProxy;
NS_ADDREF(*aNotify);
}
return rv;
}
NS_IMETHODIMP
nsNetModRegEntry::GetTopic(char **topic)
{
if (mTopic)
{
*topic = (char *) nsAllocator::Clone(mTopic, nsCRT::strlen(mTopic) + 1);
return NS_OK;
}
return NS_ERROR_NULL_POINTER;
}
NS_IMETHODIMP
nsNetModRegEntry::Equals(nsINetModRegEntry* aEntry, PRBool *_retVal)
{
nsresult rv = NS_OK;
*_retVal = PR_FALSE;
char* topic;
rv = aEntry->GetTopic(&topic);
if (NS_FAILED(rv))
return rv;
if (topic && PL_strcmp(topic, mTopic))
{
nsCOMPtr<nsINetNotify> aSyncProxy;
rv = aEntry->GetSyncProxy(getter_AddRefs(aSyncProxy));
if(aSyncProxy == mSyncProxy)
{
*_retVal = PR_TRUE;
}
nsAllocator::Free(topic);
}
return rv;
}
//////////////////////////////
//// nsNetModRegEntry
//////////////////////////////
nsNetModRegEntry::nsNetModRegEntry(const char *aTopic,
nsINetNotify *aNotify,
nsresult *result)
{
NS_INIT_REFCNT();
mTopic = new char [PL_strlen(aTopic) + 1];
PL_strcpy(mTopic, aTopic);
mAsyncProxy = nsnull;
mSyncProxy = nsnull;
mRealNotifier = aNotify;
NS_WITH_SERVICE(nsIEventQueueService, eventQService, kEventQueueServiceCID, result);
if (NS_FAILED(*result)) return;
*result = eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, getter_AddRefs(mEventQ));
}
nsresult
nsNetModRegEntry::BuildProxy(PRBool sync)
{
if (mEventQ == nsnull)
return NS_ERROR_NULL_POINTER;
nsresult result;
NS_WITH_SERVICE( nsIProxyObjectManager, proxyManager, kProxyObjectManagerCID, &result);
if (NS_FAILED(result))
return result;
if (sync)
{
result = proxyManager->GetProxyObject( mEventQ,
NS_GET_IID(nsINetNotify),
mRealNotifier,
PROXY_SYNC | PROXY_ALWAYS,
getter_AddRefs(mSyncProxy));
}
else
{
result = proxyManager->GetProxyObject( mEventQ,
NS_GET_IID(nsINetNotify),
mRealNotifier,
PROXY_ASYNC | PROXY_ALWAYS,
getter_AddRefs(mAsyncProxy));
}
return result;
}
nsNetModRegEntry::~nsNetModRegEntry()
{
delete [] mTopic;
}

View File

@@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef ___nsNetModRegEntry_h___
#define ___nsNetModRegEntry_h___
#include "nsINetModRegEntry.h"
#include "nsIEventQueue.h"
#include "nsCOMPtr.h"
class nsNetModRegEntry : public nsINetModRegEntry {
public:
// nsISupports
NS_DECL_ISUPPORTS
// nsINetModRegEntry
NS_IMETHOD GetSyncProxy(nsINetNotify * *aSyncProxy);
NS_IMETHOD GetAsyncProxy(nsINetNotify * *aAsyncProxy);
NS_IMETHOD GetTopic(char * *aTopic);
NS_IMETHOD Equals(nsINetModRegEntry* aEntry, PRBool *_retVal);
// nsNetModRegEntry
nsNetModRegEntry(const char *aTopic, nsINetNotify *aNotify, nsresult *result);
virtual ~nsNetModRegEntry();
protected:
char *mTopic;
nsCOMPtr<nsINetNotify> mRealNotifier;
nsCOMPtr<nsINetNotify> mSyncProxy;
nsCOMPtr<nsINetNotify> mAsyncProxy;
nsCOMPtr<nsIEventQueue> mEventQ;
nsresult BuildProxy(PRBool sync);
};
#endif //___nsNetModRegEntry_h___

View File

@@ -0,0 +1,203 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsAutoLock.h"
#include "nsNetModuleMgr.h"
#include "nsNetModRegEntry.h"
#include "nsEnumeratorUtils.h" // for nsArrayEnumerator
#include "nsString2.h"
#include "nsXPIDLString.h"
#include "nsIEventQueue.h"
nsNetModuleMgr* nsNetModuleMgr::gManager;
///////////////////////////////////
//// nsISupports
///////////////////////////////////
NS_IMPL_ISUPPORTS(nsNetModuleMgr, NS_GET_IID(nsINetModuleMgr));
///////////////////////////////////
//// nsINetModuleMgr
///////////////////////////////////
NS_IMETHODIMP
nsNetModuleMgr::RegisterModule(const char *aTopic, nsINetNotify *aNotify)
{
nsresult rv;
PRUint32 cnt;
// XXX before registering an object for a particular topic
// XXX QI the nsINetNotify interface passed in for the interfaces
// XXX supported by the topic.
nsAutoLock lock(mLock);
nsNetModRegEntry *newEntry = new nsNetModRegEntry(aTopic, aNotify, &rv);
if (!newEntry)
return NS_ERROR_OUT_OF_MEMORY;
if (NS_FAILED(rv)) {
delete newEntry;
return rv;
}
nsCOMPtr<nsINetModRegEntry> newEntryI = do_QueryInterface(newEntry, &rv);
if (NS_FAILED(rv)) {
delete newEntry;
return rv;
}
// Check for a previous registration
mEntries->Count(&cnt);
for (PRUint32 i = 0; i < cnt; i++)
{
nsCOMPtr<nsINetModRegEntry> curEntry =
dont_AddRef(NS_STATIC_CAST(nsINetModRegEntry*, mEntries->ElementAt(i)));
PRBool same = PR_FALSE;
rv = newEntryI->Equals(curEntry, &same);
if (NS_FAILED(rv)) return rv;
// if we've already got this one registered, yank it, and replace it with the new one
if (same) {
mEntries->DeleteElementAt(i);
break;
}
}
rv = mEntries->AppendElement(NS_STATIC_CAST(nsISupports*, newEntryI)) ? NS_OK : NS_ERROR_FAILURE; // XXX this method incorrectly returns a bool
return rv;
}
NS_IMETHODIMP
nsNetModuleMgr::UnregisterModule(const char *aTopic, nsINetNotify *aNotify)
{
nsAutoLock lock(mLock);
nsresult rv;
nsCOMPtr<nsINetModRegEntry> tmpEntryI;
nsNetModRegEntry *tmpEntry = new nsNetModRegEntry(aTopic, aNotify, &rv);
if (!tmpEntry)
return NS_ERROR_OUT_OF_MEMORY;
if (NS_FAILED(rv)) return rv;
rv = tmpEntry->QueryInterface(NS_GET_IID(nsINetModRegEntry), getter_AddRefs(tmpEntryI));
if (NS_FAILED(rv)) return rv;
PRUint32 cnt;
mEntries->Count(&cnt);
for (PRUint32 i = 0; i < cnt; i++) {
nsCOMPtr<nsINetModRegEntry> curEntry =
dont_AddRef(NS_STATIC_CAST(nsINetModRegEntry*, mEntries->ElementAt(i)));
PRBool same = PR_FALSE;
rv = tmpEntryI->Equals(curEntry, &same);
if (NS_FAILED(rv)) return rv;
if (same) {
mEntries->DeleteElementAt(i);
break;
}
}
return NS_OK;
}
NS_IMETHODIMP
nsNetModuleMgr::EnumerateModules(const char *aTopic, nsISimpleEnumerator **aEnumerator) {
nsresult rv;
// get all the entries for this topic
nsAutoLock lock(mLock);
PRUint32 cnt;
rv = mEntries->Count(&cnt);
if (NS_FAILED(rv)) return rv;
// create the new array
nsCOMPtr<nsISupportsArray> topicEntries;
rv = NS_NewISupportsArray(getter_AddRefs(topicEntries));
if (NS_FAILED(rv)) return rv;
// run through the main entry array looking for topic matches.
for (PRUint32 i = 0; i < cnt; i++) {
nsCOMPtr<nsINetModRegEntry> entry =
dont_AddRef(NS_STATIC_CAST(nsINetModRegEntry*, mEntries->ElementAt(i)));
nsXPIDLCString topic;
rv = entry->GetTopic(getter_Copies(topic));
if (NS_FAILED(rv)) return rv;
if (0 == PL_strcmp(aTopic, topic)) {
// found a match, add it to the list
rv = topicEntries->AppendElement(NS_STATIC_CAST(nsISupports*, entry)) ? NS_OK : NS_ERROR_FAILURE; // XXX this method incorrectly returns a bool
if (NS_FAILED(rv)) return rv;
}
}
nsCOMPtr<nsISimpleEnumerator> enumerator;
rv = NS_NewArrayEnumerator(getter_AddRefs(enumerator), topicEntries);
if (NS_FAILED(rv)) return rv;
*aEnumerator = enumerator;
NS_ADDREF(*aEnumerator);
return NS_OK;
}
///////////////////////////////////
//// nsNetModuleMgr
///////////////////////////////////
nsNetModuleMgr::nsNetModuleMgr() {
NS_INIT_REFCNT();
NS_NewISupportsArray(&mEntries);
mLock = PR_NewLock();
}
nsNetModuleMgr::~nsNetModuleMgr() {
NS_IF_RELEASE(mEntries);
PR_DestroyLock(mLock);
gManager = nsnull;
}
NS_METHOD
nsNetModuleMgr::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
if (! gManager) {
gManager = new nsNetModuleMgr();
if (! gManager)
return NS_ERROR_OUT_OF_MEMORY;
}
NS_ADDREF(gManager);
nsresult rv = gManager->QueryInterface(aIID, aResult);
NS_RELEASE(gManager);
return rv;
}

View File

@@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef ___nsNetModuleMgr_h__
#define ___nsNetModuleMgr_h__
#include "nsINetModuleMgr.h"
#include "prlock.h"
#include "nspr.h"
#include "nsISupportsArray.h"
class nsNetModuleMgr : public nsINetModuleMgr {
protected:
static nsNetModuleMgr* gManager;
public:
// nsISupports
NS_DECL_ISUPPORTS
// nsINetModuleMgr
NS_DECL_NSINETMODULEMGR
// nsNetModuleMgr
nsNetModuleMgr();
virtual ~nsNetModuleMgr();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsISupportsArray *mEntries;
PRLock *mLock;
};
#endif // ___nsNetModuleMgr_h__

View File

@@ -0,0 +1,310 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Andreas Otte.
*
* Contributor(s):
*/
#include "nsNoAuthURLParser.h"
#include "nsURLHelper.h"
#include "nsCRT.h"
#include "nsString.h"
#include "prprf.h"
NS_IMPL_THREADSAFE_ISUPPORTS(nsNoAuthURLParser, NS_GET_IID(nsIURLParser))
nsNoAuthURLParser::~nsNoAuthURLParser()
{
}
NS_METHOD
nsNoAuthURLParser::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsNoAuthURLParser* p = new nsNoAuthURLParser();
if (p == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(p);
nsresult rv = p->QueryInterface(aIID, aResult);
NS_RELEASE(p);
return rv;
}
nsresult
nsNoAuthURLParser::ParseAtScheme(const char* i_Spec, char* *o_Scheme,
char* *o_Username, char* *o_Password,
char* *o_Host, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
NS_PRECONDITION( (nsnull != i_Spec), "Parse called on empty url!");
if (!i_Spec)
return NS_ERROR_MALFORMED_URI;
int len = PL_strlen(i_Spec);
if (len >= 2 && *i_Spec == '/' && *(i_Spec+1) == '/') // No Scheme
{
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host, o_Port,
o_Path);
return rv;
}
static const char delimiters[] = ":"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a path
{
rv = ParseAtPath((char*)i_Spec, o_Path);
return rv;
}
switch (*brk)
{
case ':' :
rv = ExtractString((char*)i_Spec, o_Scheme, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsNoAuthURLParser::ParseAtPreHost(const char* i_Spec, char* *o_Username,
char* *o_Password, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// Skip leading two slashes
char* fwdPtr= (char*) i_Spec;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
// There is no PreHost
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
nsresult
nsNoAuthURLParser::ParseAtHost(const char* i_Spec, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// There is no Host
rv = ParseAtPath(i_Spec, o_Path);
return rv;
}
nsresult
nsNoAuthURLParser::ParseAtPort(const char* i_Spec, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// There is no Port
rv = ParseAtPath(i_Spec, o_Path);
return NS_OK;
}
nsresult
nsNoAuthURLParser::ParseAtPath(const char* i_Spec, char* *o_Path)
{
// Just write the path and check for a starting /
nsCAutoString dir;
if ('/' != *i_Spec)
dir += "/";
dir += i_Spec;
*o_Path = dir.ToNewCString();
return (*o_Path ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
nsresult
nsNoAuthURLParser::ParseAtDirectory(const char* i_Path, char* *o_Directory,
char* *o_FileBaseName, char* *o_FileExtension,
char* *o_Param, char* *o_Query, char* *o_Ref)
{
// Cleanout
CRTFREEIF(*o_Directory);
CRTFREEIF(*o_FileBaseName);
CRTFREEIF(*o_FileExtension);
CRTFREEIF(*o_Param);
CRTFREEIF(*o_Query);
CRTFREEIF(*o_Ref);
nsresult rv = NS_OK;
// Parse the Path into its components
if (!i_Path)
{
DupString(o_Directory, "/");
return (o_Directory ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
char* dirfile = nsnull;
char* options = nsnull;
int len = PL_strlen(i_Path);
/* Factor out the optionpart with ;?# */
static const char delimiters[] = ";?#"; // for param, query and ref
char* brk = PL_strpbrk(i_Path, delimiters);
if (!brk) // Everything is just path and filename
{
DupString(&dirfile, i_Path);
}
else
{
int dirfileLen = brk - i_Path;
ExtractString((char*)i_Path, &dirfile, dirfileLen);
len -= dirfileLen;
ExtractString((char*)i_Path + dirfileLen, &options, len);
brk = options;
}
/* now that we have broken up the path treat every part differently */
/* first dir+file */
char* file;
int dlen = PL_strlen(dirfile);
if (dlen == 0)
{
DupString(o_Directory, "/");
file = dirfile;
} else {
CoaleseDirs(dirfile);
// Get length again
dlen = PL_strlen(dirfile);
// First find the last slash
file = PL_strrchr(dirfile, '/');
if (!file)
{
DupString(o_Directory, "/");
file = dirfile;
}
// If its not the same as the first slash then extract directory
if (file != dirfile)
{
ExtractString(dirfile, o_Directory, (file - dirfile)+1);
} else {
DupString(o_Directory, "/");
}
}
/* Extract FileBaseName and FileExtension */
if (dlen > 0) {
// Look again if there was a slash
char* slash = PL_strrchr(dirfile, '/');
char* e_FileName = nsnull;
if (slash) {
if (dirfile+dlen-1>slash)
ExtractString(slash+1, &e_FileName, dlen-(slash-dirfile+1));
} else {
// Use the full String as Filename
ExtractString(dirfile, &e_FileName, dlen);
}
rv = ParseFileName(e_FileName,o_FileBaseName,o_FileExtension);
CRTFREEIF(e_FileName);
}
// Now take a look at the options. "#" has precedence over "?"
// which has precedence over ";"
if (options) {
// Look for "#" first. Everything following it is in the ref
brk = PL_strchr(options, '#');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Ref, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for "?"
brk = PL_strchr(options, '?');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Query, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for ';'
brk = PL_strchr(options, ';');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Param, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
}
nsCRT::free(dirfile);
nsCRT::free(options);
return rv;
}
nsresult
nsNoAuthURLParser::ParsePreHost(const char* i_PreHost, char* *o_Username,
char* *o_Password)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult
nsNoAuthURLParser::ParseFileName(const char* i_FileName,
char* *o_FileBaseName,
char* *o_FileExtension)
{
nsresult rv = NS_OK;
if (!i_FileName) {
*o_FileBaseName = nsnull;
*o_FileExtension = nsnull;
return rv;
}
// Search for FileExtension
// Search for last .
// Ignore . at the beginning
char* brk = PL_strrchr(i_FileName+1, '.');
if (brk)
{
rv = ExtractString((char*)i_FileName, o_FileBaseName,
(brk - i_FileName));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk + 1, o_FileExtension,
(i_FileName+PL_strlen(i_FileName) - brk - 1));
} else {
rv = DupString(o_FileBaseName, i_FileName);
}
return rv;
}

View File

@@ -0,0 +1,51 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsNoAuthURLParser_h__
#define nsNoAuthURLParser_h__
#include "nsIURLParser.h"
#include "nsIURI.h"
#include "nsAgg.h"
#include "nsCRT.h"
class nsNoAuthURLParser : public nsIURLParser
{
public:
NS_DECL_ISUPPORTS
///////////////////////////////////////////////////////////////////////////
// nsNoAuthURLParser methods:
nsNoAuthURLParser() {
NS_INIT_REFCNT();
}
virtual ~nsNoAuthURLParser();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
///////////////////////////////////////////////////////////////////////////
// nsIURLParser methods:
NS_DECL_NSIURLPARSER
};
#endif // nsNoAuthURLParser_h__

View File

@@ -0,0 +1,236 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsProtocolProxyService.h"
#include "nsIServiceManager.h"
#include "nsXPIDLString.h"
static NS_DEFINE_CID(kPrefServiceCID, NS_PREF_CID);
static const char PROXY_PREFS[] = "network.proxy";
PRInt32 PR_CALLBACK ProxyPrefsCallback(const char* pref, void* instance)
{
nsProtocolProxyService* proxyServ = (nsProtocolProxyService*) instance;
NS_ASSERTION(proxyServ, "bad instance data");
if (proxyServ) proxyServ->PrefsChanged(pref);
return 0;
}
NS_IMPL_ISUPPORTS1(nsProtocolProxyService, nsIProtocolProxyService);
// nsProtocolProxyService methods
NS_IMETHODIMP
nsProtocolProxyService::Init() {
nsresult rv = NS_OK;
mPrefs = do_GetService(kPrefServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
// register for change callbacks
rv = mPrefs->RegisterCallback(PROXY_PREFS, ProxyPrefsCallback, (void*)this);
if (NS_FAILED(rv)) return rv;
PrefsChanged(nsnull);
return NS_OK;
}
NS_METHOD
nsProtocolProxyService::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) {
nsresult rv;
if (aOuter) return NS_ERROR_NO_AGGREGATION;
nsProtocolProxyService* serv = new nsProtocolProxyService();
if (!serv) return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(serv);
rv = serv->Init();
if (NS_FAILED(rv)) {
delete serv;
return rv;
}
rv = serv->QueryInterface(aIID, aResult);
NS_RELEASE(serv);
return rv;
}
void
nsProtocolProxyService::PrefsChanged(const char* pref) {
PRBool bChangeAll = (pref) ? PR_FALSE : PR_TRUE;
NS_ASSERTION(mPrefs, "No preference service available!");
if (!mPrefs) return;
nsresult rv = NS_OK;
if (bChangeAll || !PL_strcmp(pref, "network.proxy.type"))
{
PRInt32 type = -1;
rv = mPrefs->GetIntPref("network.proxy.type",&type);
if (NS_SUCCEEDED(rv))
mUseProxy = (type == 1); // type == 2 is autoconfig stuff
}
nsXPIDLCString tempString;
if (bChangeAll || !PL_strcmp(pref, "network.proxy.http"))
{
mHTTPProxyHost = "";
rv = mPrefs->CopyCharPref("network.proxy.http",
getter_Copies(tempString));
if (NS_SUCCEEDED(rv) && tempString && *tempString)
mHTTPProxyHost = nsCRT::strdup(tempString);
}
if (bChangeAll || !PL_strcmp(pref, "network.proxy.http_port"))
{
mHTTPProxyPort = -1;
PRInt32 proxyPort = -1;
rv = mPrefs->GetIntPref("network.proxy.http_port",&proxyPort);
if (NS_SUCCEEDED(rv) && proxyPort>0)
mHTTPProxyPort = proxyPort;
}
if (bChangeAll || !PL_strcmp(pref, "network.proxy.ftp"))
{
mFTPProxyHost = "";
rv = mPrefs->CopyCharPref("network.proxy.ftp",
getter_Copies(tempString));
if (NS_SUCCEEDED(rv) && tempString && *tempString)
mFTPProxyHost = nsCRT::strdup(tempString);
}
if (bChangeAll || !PL_strcmp(pref, "network.proxy.ftp_port"))
{
mFTPProxyPort = -1;
PRInt32 proxyPort = -1;
rv = mPrefs->GetIntPref("network.proxy.ftp_port",&proxyPort);
if (NS_SUCCEEDED(rv) && proxyPort>0)
mFTPProxyPort = proxyPort;
}
if (bChangeAll || !PL_strcmp(pref, "network.proxy.no_proxies_on"))
{
CRTFREEIF(mFilters);
rv = mPrefs->CopyCharPref("network.proxy.no_proxies_on",
getter_Copies(tempString));
if (NS_SUCCEEDED(rv) && tempString && *tempString)
mFilters = nsCRT::strdup(tempString);
}
}
PRBool
nsProtocolProxyService::CanUseProxy(nsIURI* aURI)
{
if (!mFilters || !*mFilters)
return PR_TRUE;
PRInt32 port;
nsXPIDLCString host;
nsresult rv = aURI->GetHost(getter_Copies(host));
if (NS_FAILED(rv) || !host || !*host)
return PR_FALSE;
rv = aURI->GetPort(&port);
if (NS_FAILED(rv)) {
return PR_FALSE;
}
// TODO this parsing should occur when mFilters is read in from the pref
// into an array of hosts/port combinations.
// so that we just compare the strings and be quicker. -Gagan
char* np= mFilters;
while (*np)
{
while (*np && (*np == ',' || nsString::IsSpace(*np)))
np++;
char* endproxy = np+1;
char* portLocation = 0;
PRInt32 nport = 0; // no proxy port
// find the end of this element.
while (*endproxy && (*endproxy != ',' &&
!nsString::IsSpace(*endproxy)))
{
if (*endproxy == ':')
portLocation=endproxy;
endproxy++;
}
if (portLocation)
nport = atoi(portLocation+1);
if (!nport || (nport == port)) // ports match...
{
int nlength = (portLocation ? portLocation : endproxy) - np;
// compare the trailing portion of the host-
if (0 == PL_strncasecmp(host+PL_strlen(host)-nlength, np, nlength))
return PR_FALSE;
}
np = endproxy;
}
return PR_TRUE;
}
// nsIProtocolProxyService
NS_IMETHODIMP
nsProtocolProxyService::ExamineForProxy(nsIURI *aURI, nsIProxy *aProxy) {
nsresult rv = NS_OK;
NS_ASSERTION(aURI && aProxy, "need a uri and proxy iface folks.");
// if proxies are enabled and this host:port combo is
// supposed to use a proxy, check for a proxy.
if (!mUseProxy || !CanUseProxy(aURI)) {
rv = aProxy->SetProxyHost(nsnull);
if (NS_FAILED(rv)) return rv;
rv = aProxy->SetProxyPort(-1);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
nsXPIDLCString scheme;
rv = aURI->GetScheme(getter_Copies(scheme));
if (NS_FAILED(rv)) return rv;
if (!PL_strcasecmp(scheme, "http")) {
rv = aProxy->SetProxyHost(mHTTPProxyHost);
if (NS_FAILED(rv)) return rv;
return aProxy->SetProxyPort(mHTTPProxyPort);
}
if (!PL_strcasecmp(scheme, "ftp")) {
rv = aProxy->SetProxyHost(mFTPProxyHost);
if (NS_FAILED(rv)) return rv;
return aProxy->SetProxyPort(mFTPProxyPort);
}
return NS_OK;
}
NS_IMETHODIMP
nsProtocolProxyService::GetProxyEnabled(PRBool* o_Enabled)
{
if (!o_Enabled)
return NS_ERROR_NULL_POINTER;
*o_Enabled = mUseProxy;
return NS_OK;
}

View File

@@ -0,0 +1,70 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef __nsprotocolproxyservice___h___
#define __nsprotocolproxyservice___h___
#include "nsString.h"
#include "nsCOMPtr.h"
#include "nsIPref.h"
#include "nsHashtable.h"
#include "nsXPIDLString.h"
#include "nsIProtocolProxyService.h"
class nsProtocolProxyService : public nsIProtocolProxyService {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLPROXYSERVICE
nsProtocolProxyService() {
NS_INIT_REFCNT();
mUseProxy = PR_FALSE;
mFilters=0;
};
virtual ~nsProtocolProxyService() {
CRTFREEIF(mFilters);
};
NS_IMETHOD Init();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
void PrefsChanged(const char* pref);
protected:
PRBool CanUseProxy(nsIURI* aURI);
nsCOMPtr<nsIPref> mPrefs;
char *mFilters;
PRBool mUseProxy;
nsXPIDLCString mHTTPProxyHost;
PRInt32 mHTTPProxyPort;
nsXPIDLCString mFTPProxyHost;
PRInt32 mFTPProxyPort;
};
#endif // __nsprotocolproxyservice___h___

View File

@@ -0,0 +1,291 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Pierre Phaneuf <pp@ludusdesign.com>
*/
#include "nsSimpleURI.h"
#include "nscore.h"
#include "nsCRT.h"
#include "nsString.h"
#include "prmem.h"
#include "prprf.h"
#include "nsURLHelper.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
static NS_DEFINE_CID(kThisSimpleURIImplementationCID,
NS_THIS_SIMPLEURI_IMPLEMENTATION_CID);
static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID);
////////////////////////////////////////////////////////////////////////////////
// nsSimpleURI methods:
nsSimpleURI::nsSimpleURI(nsISupports* outer)
: mScheme(nsnull),
mPath(nsnull)
{
NS_INIT_AGGREGATED(outer);
}
nsSimpleURI::~nsSimpleURI()
{
if (mScheme) nsCRT::free(mScheme);
if (mPath) nsCRT::free(mPath);
}
NS_IMPL_AGGREGATED(nsSimpleURI);
NS_IMETHODIMP
nsSimpleURI::AggregatedQueryInterface(const nsIID& aIID, void** aInstancePtr)
{
NS_ENSURE_ARG_POINTER(aInstancePtr);
if (aIID.Equals(kISupportsIID))
*aInstancePtr = GetInner();
else if (aIID.Equals(kThisSimpleURIImplementationCID) || // used by Equals
aIID.Equals(NS_GET_IID(nsIURI)))
*aInstancePtr = NS_STATIC_CAST(nsIURI*, this);
else {
*aInstancePtr = nsnull;
return NS_NOINTERFACE;
}
NS_ADDREF((nsISupports*)*aInstancePtr);
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIURI methods:
NS_IMETHODIMP
nsSimpleURI::GetSpec(char* *result)
{
nsAutoString string;
// NS_LOCK_INSTANCE();
string.SetString(mScheme);
string.Append(':');
string.Append(mPath);
// NS_UNLOCK_INSTANCE();
*result = string.ToNewCString();
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::SetSpec(const char* aSpec)
{
nsAutoString spec(aSpec);
PRInt32 pos = spec.Find(":");
if (pos == -1)
return NS_ERROR_FAILURE;
nsAutoString scheme;
PRInt32 n = spec.Left(scheme, pos);
NS_ASSERTION(n == pos, "Left failed");
nsAutoString path;
PRInt32 count = spec.Length() - pos - 1;
n = spec.Mid(path, pos + 1, count);
NS_ASSERTION(n == count, "Mid failed");
if (mScheme)
nsCRT::free(mScheme);
mScheme = scheme.ToNewCString();
if (mScheme == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
if (mPath)
nsCRT::free(mPath);
mPath = path.ToNewCString();
if (mPath == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::GetScheme(char* *result)
{
*result = nsCRT::strdup(mScheme);
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::SetScheme(const char* scheme)
{
if (mScheme) nsCRT::free(mScheme);
mScheme = nsCRT::strdup(scheme);
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::GetPreHost(char* *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetPreHost(const char* preHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::GetUsername(char* *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetUsername(const char* userName)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::GetPassword(char* *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetPassword(const char* password)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::GetHost(char* *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetHost(const char* host)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::GetPort(PRInt32 *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetPort(PRInt32 port)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::GetPath(char* *result)
{
*result = nsCRT::strdup(mPath);
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::SetPath(const char* path)
{
if (mPath) nsCRT::free(mPath);
mPath = nsCRT::strdup(path);
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::GetURLParser(nsIURLParser* *result)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::SetURLParser(nsIURLParser* URLParser)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::Equals(nsIURI* other, PRBool *result)
{
PRBool eq = PR_FALSE;
if (other) {
// NS_LOCK_INSTANCE();
nsSimpleURI* otherUrl;
nsresult rv =
other->QueryInterface(kThisSimpleURIImplementationCID,
(void**)&otherUrl);
if (NS_SUCCEEDED(rv)) {
eq = PRBool((0 == PL_strcmp(mScheme, otherUrl->mScheme)) &&
(0 == PL_strcmp(mPath, otherUrl->mPath)));
NS_RELEASE(otherUrl);
}
// NS_UNLOCK_INSTANCE();
}
*result = eq;
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::Clone(nsIURI* *result)
{
nsSimpleURI* url = new nsSimpleURI(nsnull); // XXX outer?
if (url == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
url->mScheme = nsCRT::strdup(mScheme);
if (url->mScheme == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
url->mPath = nsCRT::strdup(mPath);
if (url->mPath == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
*result = url;
NS_ADDREF(url);
return NS_OK;
}
NS_IMETHODIMP
nsSimpleURI::SetRelativePath(const char *i_RelativePath)
{
NS_ASSERTION(PR_FALSE, "This is meaningless in hack context!");
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsSimpleURI::Resolve(const char *relativePath, char **result)
{
return DupString(result,(char*)relativePath);
}
////////////////////////////////////////////////////////////////////////////////
NS_METHOD
nsSimpleURI::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
NS_ENSURE_PROPER_AGGREGATION(aOuter, aIID);
nsSimpleURI* url = new nsSimpleURI(aOuter);
if (url == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = url->AggregatedQueryInterface(aIID, aResult);
if (NS_FAILED(rv))
delete url;
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -0,0 +1,56 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsSimpleURI_h__
#define nsSimpleURI_h__
#include "nsIURL.h"
#include "nsAgg.h"
#define NS_THIS_SIMPLEURI_IMPLEMENTATION_CID \
{ /* 22b8f64a-2f7b-11d3-8cd0-0060b0fc14a3 */ \
0x22b8f64a, \
0x2f7b, \
0x11d3, \
{0x8c, 0xd0, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
class nsSimpleURI : public nsIURI
{
public:
NS_DECL_AGGREGATED
NS_DECL_NSIURI
// nsSimpleURI methods:
nsSimpleURI(nsISupports* outer);
virtual ~nsSimpleURI();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
char* mScheme;
char* mPath;
};
#endif // nsSimpleURI_h__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,248 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsSocketTransport_h___
#define nsSocketTransport_h___
#include "prclist.h"
#include "prio.h"
#include "prnetdb.h"
#include "prinrval.h"
#include "nsCOMPtr.h"
#include "nsISocketTransport.h"
#include "nsIChannel.h"
#include "nsIInputStream.h"
#include "nsIBufferInputStream.h"
#include "nsIBufferOutputStream.h"
#include "nsIEventQueueService.h"
#include "nsIStreamListener.h"
#include "nsIDNSListener.h"
#include "nsIPipe.h"
#include "nsIProgressEventSink.h"
#include "nsIInterfaceRequestor.h"
#define NS_SOCKET_TRANSPORT_SEGMENT_SIZE (2*1024)
#define NS_SOCKET_TRANSPORT_BUFFER_SIZE (8*1024)
//
// This is the maximum amount of data that will be read into a stream before
// another transport is processed...
//
#define MAX_IO_TRANSFER_SIZE (8*1024)
enum nsSocketState {
eSocketState_Created = 0,
eSocketState_WaitDNS = 1,
eSocketState_Closed = 2,
eSocketState_WaitConnect = 3,
eSocketState_Connected = 4,
eSocketState_WaitReadWrite = 5,
eSocketState_Done = 6,
eSocketState_Timeout = 7,
eSocketState_Error = 8,
eSocketState_Max = 9
};
enum nsSocketOperation {
eSocketOperation_None = 0,
eSocketOperation_Connect = 1,
eSocketOperation_ReadWrite = 2,
eSocketOperation_Max = 3
};
//
// The following emun provides information about the currently
// active read and/or write requests...
//
// +-------------------------------+
// | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
// +-------------------------------+
// <-----flag bits----><-type bits->
//
// Bits:
// 0-3: Type (ie. None, Async, Sync)
// 4: Done flag.
// 5: Wait flag.
// 6-7: Unused flags...
//
//
//
enum nsSocketReadWriteInfo {
eSocketRead_None = 0x0000,
eSocketRead_Async = 0x0001,
eSocketRead_Sync = 0x0002,
eSocketRead_Done = 0x0010,
eSocketRead_Wait = 0x0020,
eSocketRead_Type_Mask = 0x000F,
eSocketRead_Flag_Mask = 0x00F0,
eSocketWrite_None = 0x0000,
eSocketWrite_Async = 0x0100,
eSocketWrite_Sync = 0x0200,
eSocketWrite_Done = 0x1000,
eSocketWrite_Wait = 0x2000,
eSocketWrite_Type_Mask = 0x0F00,
eSocketWrite_Flag_Mask = 0xF000,
eSocketDNS_Wait = 0x2020
};
// Forward declarations...
class nsSocketTransportService;
class nsIInterfaceRequestor;
class nsSocketTransport : public nsISocketTransport,
public nsIChannel,
public nsIDNSListener,
public nsIPipeObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISOCKETTRANSPORT
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSIPIPEOBSERVER
NS_DECL_NSIDNSLISTENER
// nsSocketTransport methods:
nsSocketTransport();
virtual ~nsSocketTransport();
nsresult Init(nsSocketTransportService* aService,
const char* aHost,
PRInt32 aPort,
const char* aSocketType,
const char* aPrintHost, // This host is used for status mesg
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize);
nsresult Process(PRInt16 aSelectFlags);
nsresult CheckForTimeout(PRIntervalTime aCurrentTime);
// Close this socket either right away or once done with the transaction.
nsresult CloseConnection(PRBool bNow=PR_TRUE);
// Access methods used by the socket transport service...
PRFileDesc* GetSocket(void) { return mSocketFD; }
PRInt16 GetSelectFlags(void) { return mSelectFlags; }
PRCList* GetListNode(void) { return &mListLink; }
static nsSocketTransport* GetInstance(PRCList* qp) { return (nsSocketTransport*)((char*)qp - offsetof(nsSocketTransport, mListLink)); }
static void SetSocketTimeout(PRIntervalTime aTimeoutInterval);
PRBool CanBeReused(void) { return
(mCurrentState != eSocketState_Error) && !mCloseConnectionOnceDone;}
protected:
nsresult doConnection(PRInt16 aSelectFlags);
nsresult doResolveHost(void);
nsresult doRead(PRInt16 aSelectFlags);
nsresult doWrite(PRInt16 aSelectFlags);
nsresult doWriteFromBuffer(PRUint32 *aCount);
nsresult doWriteFromStream(PRUint32 *aCount);
nsresult fireStatus(PRUint32 aCode);
nsresult GetSocketErrorString(PRUint32 iCode, PRUnichar** oString) const;
private:
// Access methods for manipulating the ReadWriteInfo...
inline void SetReadType(nsSocketReadWriteInfo aType) {
mReadWriteState = (mReadWriteState & ~eSocketRead_Type_Mask) | aType;
}
inline PRUint32 GetReadType(void) {
return mReadWriteState & eSocketRead_Type_Mask;
}
inline void SetWriteType(nsSocketReadWriteInfo aType) {
mReadWriteState = (mReadWriteState & ~eSocketWrite_Type_Mask) | aType;
}
inline PRUint32 GetWriteType(void) {
return mReadWriteState & eSocketWrite_Type_Mask;
}
inline void SetFlag(nsSocketReadWriteInfo aFlag) {
mReadWriteState |= aFlag;
}
inline PRUint32 GetFlag(nsSocketReadWriteInfo aFlag) {
return mReadWriteState & aFlag;
}
inline void ClearFlag(nsSocketReadWriteInfo aFlag) {
mReadWriteState &= ~aFlag;
}
protected:
PRBool mCancelOperation;
PRBool mCloseConnectionOnceDone;
nsSocketState mCurrentState;
nsCOMPtr<nsIRequest> mDNSRequest;
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIProgressEventSink> mEventSink;
char* mHostName;
PRIntervalTime mLastActiveTime;
PRCList mListLink;
PRUint32 mLoadAttributes;
PRLock* mLock;
PRNetAddr mNetAddress;
nsCOMPtr<nsISupports> mOpenContext;
nsCOMPtr<nsIStreamObserver> mOpenObserver;
nsSocketOperation mOperation;
nsCOMPtr<nsISupports> mOwner;
PRInt32 mPort;
char* mPrintHost; // not the proxy
nsCOMPtr<nsISupports> mReadContext;
nsCOMPtr<nsIStreamListener> mReadListener;
nsCOMPtr<nsIBufferInputStream> mReadPipeIn;
nsCOMPtr<nsIBufferOutputStream> mReadPipeOut;
PRUint32 mReadWriteState;
PRInt16 mSelectFlags;
nsSocketTransportService* mService;
PRFileDesc* mSocketFD;
char* mSocketType;
PRUint32 mReadOffset;
PRUint32 mWriteOffset;
nsresult mStatus;
PRInt32 mSuspendCount;
PRInt32 mWriteCount;
nsCOMPtr<nsISupports> mWriteContext;
PRInt32 mBytesAllowed;
// The following four members are used when AsyncWrite(...) is called
// with an nsIInputStream which does not also support the
// nsIBufferedInputStream interface...
//
nsCOMPtr<nsIInputStream> mWriteFromStream;
char * mWriteBuffer;
PRUint32 mWriteBufferIndex;
PRUint32 mWriteBufferLength;
nsCOMPtr<nsIStreamObserver> mWriteObserver;
nsCOMPtr<nsIBufferInputStream> mWritePipeIn;
nsCOMPtr<nsIBufferOutputStream> mWritePipeOut;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
};
#endif /* nsSocketTransport_h___ */

View File

@@ -0,0 +1,640 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsILoadGroup.h"
#include "netCore.h"
#include "nsSocketTransportService.h"
#include "nsSocketTransport.h"
#include "nsAutoLock.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
nsSocketTransportService::nsSocketTransportService()
{
NS_INIT_REFCNT();
PR_INIT_CLIST(&mWorkQ);
mThread = nsnull;
#ifdef USE_POLLABLE_EVENT
mThreadEvent = nsnull;
#endif /* USE_POLLABLE_EVENT */
mThreadLock = nsnull;
mSelectFDSet = nsnull;
mSelectFDSetCount = 0;
mActiveTransportList = nsnull;
mThreadRunning = PR_FALSE;
SetSocketTimeoutInterval(PR_MillisecondsToInterval(DEFAULT_SOCKET_TIMEOUT_IN_MS));
}
nsSocketTransportService::~nsSocketTransportService()
{
//
// It is impossible for the nsSocketTransportService to be deleted while
// the transport thread is running because it holds a reference to the
// nsIRunnable (ie. the nsSocketTransportService instance)...
//
NS_ASSERTION(!mThread && !mThreadRunning,
"The socket transport thread is still running...");
if (mSelectFDSet) {
PR_Free(mSelectFDSet);
mSelectFDSet = nsnull;
}
if (mActiveTransportList) {
PR_Free(mActiveTransportList);
mActiveTransportList = nsnull;
}
#ifdef USE_POLLABLE_EVENT
if (mThreadEvent) {
PR_DestroyPollableEvent(mThreadEvent);
mThreadEvent = nsnull;
}
#endif /* USE_POLLABLE_EVENT */
if (mThreadLock) {
PR_DestroyLock(mThreadLock);
mThreadLock = nsnull;
}
}
NS_METHOD
nsSocketTransportService::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsSocketTransportService* trans = new nsSocketTransportService();
if (trans == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(trans);
rv = trans->Init();
if (NS_SUCCEEDED(rv)) {
rv = trans->QueryInterface(aIID, aResult);
}
NS_RELEASE(trans);
return rv;
}
nsresult nsSocketTransportService::Init(void)
{
nsresult rv = NS_OK;
NS_ASSERTION(!mThread, "Socket transport thread has already been created!.");
//
// Create FDSET list used by PR_Poll(...)
//
if (!mSelectFDSet) {
mSelectFDSet = (PRPollDesc*)PR_Malloc(sizeof(PRPollDesc)*MAX_OPEN_CONNECTIONS);
if (mSelectFDSet) {
memset(mSelectFDSet, 0, sizeof(PRPollDesc)*MAX_OPEN_CONNECTIONS);
} else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
//
// Create the list of Active transport objects... This list contains the
// nsSocketTransport corresponding to each PRFileDesc* in the mSelectFDSet
//
if (NS_SUCCEEDED(rv) && !mActiveTransportList) {
mActiveTransportList = (nsSocketTransport**)PR_Malloc(sizeof(nsSocketTransport*)*MAX_OPEN_CONNECTIONS);
if (mActiveTransportList) {
memset(mActiveTransportList, 0, sizeof(nsSocketTransport*)*MAX_OPEN_CONNECTIONS);
} else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
#ifdef USE_POLLABLE_EVENT
//
// Create the pollable event used to immediately wake up the transport
// thread when it is blocked in PR_Poll(...)
//
if (NS_SUCCEEDED(rv) && !mThreadEvent) {
mThreadEvent = PR_NewPollableEvent();
if (!mThreadEvent) {
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
#endif /* USE_POLLABLE_EVENT */
//
// Create the synchronization lock for the transport thread...
//
if (NS_SUCCEEDED(rv) && !mThreadLock) {
mThreadLock = PR_NewLock();
if (!mThreadLock) {
rv = NS_ERROR_OUT_OF_MEMORY;
}
}
//
// Create the transport thread...
//
if (NS_SUCCEEDED(rv) && !mThread) {
mThreadRunning = PR_TRUE;
rv = NS_NewThread(&mThread, this, 0, PR_JOINABLE_THREAD);
}
return rv;
}
nsresult nsSocketTransportService::AddToWorkQ(nsSocketTransport* aTransport)
{
PRStatus status = PR_SUCCESS;
PRBool bFireEvent = PR_FALSE;
nsresult rv = NS_OK;
PRCList* qp;
{
nsAutoLock lock(mThreadLock);
//
// Only add the transport if it is *not* already on the list...
//
qp = aTransport->GetListNode();
if (PR_CLIST_IS_EMPTY(qp)) {
NS_ADDREF(aTransport);
bFireEvent = PR_CLIST_IS_EMPTY(&mWorkQ);
PR_APPEND_LINK(qp, &mWorkQ);
}
}
//
// Only fire an event if this is the first entry in the workQ. Otherwise,
// the event has already been fired and the transport thread will process
// all of the entries at once...
//
if (bFireEvent) {
#ifdef USE_POLLABLE_EVENT
status = PR_SetPollableEvent(mThreadEvent);
#else
//
// Need to break the socket transport thread out of the call to PR_Poll(...)
// since a new transport needs to be processed...
//
#endif /* USE_POLLABLE_EVENT */
if (PR_FAILURE == status) {
rv = NS_ERROR_FAILURE;
}
}
return rv;
}
nsresult nsSocketTransportService::ProcessWorkQ(void)
{
nsresult rv = NS_OK;
PRCList* qp;
//
// Only process pending operations while there is space available in the
// select list...
//
// XXX: Need a way to restart the ProcessWorkQ(...) when space becomes
// available in the select set...
//
PR_Lock(mThreadLock);
while (!PR_CLIST_IS_EMPTY(&mWorkQ) &&
(MAX_OPEN_CONNECTIONS > mSelectFDSetCount)) {
nsSocketTransport* transport;
// Get the next item off of the workQ...
qp = PR_LIST_HEAD(&mWorkQ);
transport = nsSocketTransport::GetInstance(qp);
PR_REMOVE_AND_INIT_LINK(qp);
//
// Make sure that the transport is not already on the select list.
// It will be added (if necessary) after Process() is called...
//
RemoveFromSelectList(transport);
// Try to perform the operation...
//
// Do not process the transport while holding the transport service
// lock... A deadlock could occur if another thread is holding the
// transport lock and tries to add the transport to the service's WorkQ...
//
// Do not pass any select flags...
PR_Unlock(mThreadLock);
rv = transport->Process(0);
PR_Lock(mThreadLock);
//
// If the operation would block, then add it to the select list for
// later processing when the data arrives...
//
if (NS_BASE_STREAM_WOULD_BLOCK == rv) {
rv = AddToSelectList(transport);
}
// Release the transport object (since it is no longer on the WorkQ).
NS_RELEASE(transport);
}
PR_Unlock(mThreadLock);
return rv;
}
nsresult nsSocketTransportService::AddToSelectList(nsSocketTransport* aTransport)
{
nsresult rv = NS_OK;
if (aTransport && (MAX_OPEN_CONNECTIONS > mSelectFDSetCount) ) {
PRPollDesc* pfd;
int i;
//
// Check to see if the transport is already in the list...
//
// If the first FD is the Pollable Event, it will be ignored since
// its corresponding entry in the ActiveTransportList is nsnull.
//
for (i=0; i<mSelectFDSetCount; i++) {
if (mActiveTransportList[i] == aTransport) {
break;
}
}
// Initialize/update the info in the entry...
pfd = &mSelectFDSet[i];
pfd->fd = aTransport->GetSocket();;
pfd->in_flags = aTransport->GetSelectFlags();
pfd->out_flags = 0;
// Add the FileDesc to the PRPollDesc list...
if (i == mSelectFDSetCount) {
// Add the transport instance to the corresponding active transport list...
NS_ADDREF(aTransport);
mActiveTransportList[mSelectFDSetCount] = aTransport;
mSelectFDSetCount += 1;
}
}
return rv;
}
nsresult nsSocketTransportService::RemoveFromSelectList(nsSocketTransport* aTransport)
{
int i;
nsresult rv = NS_ERROR_FAILURE;
if (!aTransport) return rv;
//
// Remove the transport from SelectFDSet and ActiveTransportList...
//
// If the first FD is the Pollable Event, it will be ignored since
// its corresponding entry in the ActiveTransportList is nsnull.
//
for (i=0; i<mSelectFDSetCount; i++) {
if (mActiveTransportList[i] == aTransport) {
int last = mSelectFDSetCount-1;
NS_RELEASE(mActiveTransportList[i]);
// Move the last element in the array into the new empty slot...
if (i != last) {
memcpy(&mSelectFDSet[i], &mSelectFDSet[last], sizeof(mSelectFDSet[0]));
mSelectFDSet[last].fd = nsnull;
mActiveTransportList[i] = mActiveTransportList[last];
mActiveTransportList[last] = nsnull;
} else {
mSelectFDSet[i].fd = nsnull;
mActiveTransportList[i] = nsnull;
}
mSelectFDSetCount -= 1;
rv = NS_OK;
break;
}
}
return rv;
}
nsresult
nsSocketTransportService::GetSocketTimeoutInterval(PRIntervalTime* aResult)
{
*aResult = mSocketTimeoutInterval;
return NS_OK;
}
nsresult
nsSocketTransportService::SetSocketTimeoutInterval(PRIntervalTime aTime)
{
mSocketTimeoutInterval = aTime;
// Update the timeout value in the socket transport...
nsSocketTransport::SetSocketTimeout(aTime);
return NS_OK;
}
//
// --------------------------------------------------------------------------
// nsISupports implementation...
// --------------------------------------------------------------------------
//
NS_IMPL_THREADSAFE_ISUPPORTS2(nsSocketTransportService,
nsISocketTransportService,
nsIRunnable)
//
// --------------------------------------------------------------------------
// nsIRunnable implementation...
// --------------------------------------------------------------------------
//
NS_IMETHODIMP
nsSocketTransportService::Run(void)
{
PRIntervalTime pollTimeout;
#ifdef USE_POLLABLE_EVENT
//
// Initialize the FDSET used by PR_Poll(...). The first item in the FDSet
// is *always* the pollable event (ie. mThreadEvent).
//
mSelectFDSet[0].fd = mThreadEvent;
mSelectFDSet[0].in_flags = PR_POLL_READ;
mSelectFDSetCount = 1;
pollTimeout = mSocketTimeoutInterval;
#else
//
// For now, rather than breaking out of the call to PR_Poll(...) just set
// the time out small enough...
//
// This means that new transports will only be processed once a timeout
// occurs...
//
mSelectFDSetCount = 0;
pollTimeout = PR_MillisecondsToInterval(5);
#endif /* USE_POLLABLE_EVENT */
while (mThreadRunning) {
nsresult rv;
PRInt32 count;
PRIntervalTime intervalNow;
nsSocketTransport* transport;
int i;
count = PR_Poll(mSelectFDSet, mSelectFDSetCount, pollTimeout);
if (-1 == count) {
// XXX: PR_Poll failed... What should happen?
}
intervalNow = PR_IntervalNow();
//
// See if any sockets have data...
//
// Walk the list of active transports backwards to avoid missing
// elements when a transport is removed...
//
for (i=mSelectFDSetCount-1; i>=0; i--) {
PRPollDesc* pfd;
PRInt16 out_flags;
transport = mActiveTransportList[i];
pfd = &mSelectFDSet[i];
/* Process any sockets with data first... */
//
// XXX: PR_Poll(...) has the unpleasent behavior of ONLY setting the
// out_flags if one or more FDs are ready. So, DO NOT look at
// the out_flags unless count > 0.
//
if ((count > 0) && pfd->out_flags) {
// Clear the out_flags for next time...
out_flags = pfd->out_flags;
pfd->out_flags = 0;
if (transport) {
rv = transport->Process(out_flags);
if (NS_BASE_STREAM_WOULD_BLOCK == rv) {
// Update the select flags...
pfd->in_flags = transport->GetSelectFlags();
}
//
// If the operation completed, then remove the entry from the
// select list...
//
else {
rv = RemoveFromSelectList(transport);
}
}
else {
#ifdef USE_POLLABLE_EVENT
/* Process any pending operations on the mWorkQ... */
NS_ASSERTION(0 == i, "Null transport in active list...");
if (0 == i) {
//
// Clear the pollable event... This call should *never* block since
// PR_Poll(...) said that it had been fired...
//
NS_ASSERTION(!(mSelectFDSet[0].out_flags & PR_POLL_EXCEPT),
"Exception on Pollable event.");
PR_WaitForPollableEvent(mThreadEvent);
rv = ProcessWorkQ();
}
#else
//
// The pollable event should be the *only* null transport
// in the active transport list.
//
NS_ASSERTION(transport, "Null transport in active list...");
#endif /* USE_POLLABLE_EVENT */
}
//
// Check to see if the transport has timed out...
//
} else {
if (transport) {
rv = transport->CheckForTimeout(intervalNow);
if (NS_ERROR_NET_TIMEOUT == rv) {
// Process the timeout...
rv = transport->Process(0);
//
// The operation has completed. Remove the entry from the
// select list///
//
rv = RemoveFromSelectList(transport);
}
}
}
} // end-for
#ifndef USE_POLLABLE_EVENT
/* Process any pending operations on the mWorkQ... */
rv = ProcessWorkQ();
#endif /* !USE_POLLABLE_EVENT */
}
return NS_OK;
}
//
// --------------------------------------------------------------------------
// nsISocketTransportService implementation...
// --------------------------------------------------------------------------
//
NS_IMETHODIMP
nsSocketTransportService::CreateTransport(const char* aHost,
PRInt32 aPort,
const char* aPrintHost,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel** aResult)
{
return CreateTransportOfType(nsnull, aHost, aPort, aPrintHost,
bufferSegmentSize, bufferMaxSize, aResult);
}
NS_IMETHODIMP
nsSocketTransportService::CreateTransportOfType(const char* aSocketType,
const char* aHost,
PRInt32 aPort,
const char* aPrintHost,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize,
nsIChannel** aResult)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsIIOService, ios, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
PRBool offline;
rv = ios->GetOffline(&offline);
if (NS_FAILED(rv)) return rv;
if (offline) return NS_ERROR_OFFLINE;
nsSocketTransport* transport = nsnull;
// Parameter validation...
NS_ASSERTION(aResult, "aResult == nsnull.");
if (!aResult) {
return NS_ERROR_NULL_POINTER;
}
// Create and initialize a new connection object...
NS_NEWXPCOM(transport, nsSocketTransport);
if (transport) {
rv = transport->Init(this, aHost, aPort, aSocketType, aPrintHost,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) {
delete transport;
transport = nsnull;
}
}
else {
rv = NS_ERROR_OUT_OF_MEMORY;
}
// Set the reference count to one...
if (NS_SUCCEEDED(rv)) {
NS_ADDREF(transport);
}
*aResult = transport;
return rv;
}
NS_IMETHODIMP
nsSocketTransportService::ReuseTransport(nsIChannel* i_Transport,
PRBool * o_Reuse)
{
nsresult rv = NS_ERROR_FAILURE;
if (!i_Transport)
return NS_ERROR_NULL_POINTER;
nsSocketTransport* trans = NS_STATIC_CAST(nsSocketTransport*,
i_Transport);
if (!trans) return rv;
*o_Reuse = trans->CanBeReused();
return NS_OK;
}
/**
* wakeup the transport from PR_Poll ()
*/
NS_IMETHODIMP
nsSocketTransportService::Wakeup (nsIChannel* i_Transport)
{
nsSocketTransport *transport = NS_STATIC_CAST (nsSocketTransport *, i_Transport);
if (transport == NULL)
return NS_ERROR_NULL_POINTER;
AddToWorkQ (transport);
#ifdef USE_POLLABLE_EVENT
PR_SetPollableEvent (mThreadEvent);
#else
// XXX/ruslan: normally we would call PR_Interrupt (), but since it did work
// wait till NSPR fixes it one day
#endif
return NS_OK;
}
NS_IMETHODIMP
nsSocketTransportService::Shutdown(void)
{
PRStatus status;
nsresult rv = NS_OK;
if (mThread) {
//
// Clear the running flag and wake up the transport thread...
//
mThreadRunning = PR_FALSE;
#ifdef USE_POLLABLE_EVENT
status = PR_SetPollableEvent(mThreadEvent);
// XXX: what should happen if this fails?
NS_ASSERTION(PR_SUCCESS == status, "Unable to wake up the transport thread.");
#else
status = PR_SUCCESS;
#endif /* USE_POLLABLE_EVENT */
// Wait for the transport thread to exit nsIRunnable::Run()
if (PR_SUCCESS == status) {
mThread->Join();
}
NS_RELEASE(mThread);
} else {
rv = NS_ERROR_FAILURE;
}
return rv;
}

View File

@@ -0,0 +1,106 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsSocketTransportService_h___
#define nsSocketTransportService_h___
#include "nspr.h"
#include "nsIRunnable.h"
#include "nsIThread.h"
#include "nsISocketTransportService.h"
#include "nsIInputStream.h"
#if defined(XP_PC) || defined(XP_UNIX) || defined(XP_BEOS)
//
// Both Windows and Unix support PR_PollableEvents which are used to break
// the socket transport thread out of calls to PR_Poll(...) when new
// file descriptors must be added to the poll list...
//
#define USE_POLLABLE_EVENT
#endif
//
// This is the default timeout value (in milliseconds) for sockets which have
// no activity...
//
#define DEFAULT_SOCKET_TIMEOUT_IN_MS 35*1000
//
// This is the Maximum number of Socket Transport instances that can be active
// at once...
//
#define MAX_OPEN_CONNECTIONS 50
// Forward declarations...
class nsSocketTransport;
class nsSocketTransportService : public nsISocketTransportService,
public nsIRunnable
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISOCKETTRANSPORTSERVICE
NS_DECL_NSIRUNNABLE
// nsSocketTransportService methods:
nsSocketTransportService();
virtual ~nsSocketTransportService();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init(void);
nsresult AddToWorkQ(nsSocketTransport* aTransport);
// XXX: Should these use intervals or Milliseconds?
nsresult GetSocketTimeoutInterval(PRIntervalTime* aResult);
nsresult SetSocketTimeoutInterval(PRIntervalTime aTime);
// The following methods are called by the transport thread...
nsresult ProcessWorkQ(void);
nsresult AddToSelectList(nsSocketTransport* aTransport);
nsresult RemoveFromSelectList(nsSocketTransport* aTransport);
protected:
nsIThread* mThread;
#ifdef USE_POLLABLE_EVENT
PRFileDesc* mThreadEvent;
#endif /* USE_POLLABLE_EVENT */
PRLock* mThreadLock;
PRBool mThreadRunning;
PRIntervalTime mSocketTimeoutInterval;
PRCList mWorkQ;
PRInt32 mSelectFDSetCount;
PRPollDesc* mSelectFDSet;
nsSocketTransport** mActiveTransportList;
};
#endif /* nsSocketTransportService_h___ */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,218 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsStdURL_h__
#define nsStdURL_h__
#include "nsIURL.h"
#include "nsIURLParser.h"
#include "nsURLHelper.h"
#include "nsAgg.h"
#include "nsCRT.h"
#include "nsString.h" // REMOVE Later!!
#include "nsCOMPtr.h"
#include "nsIFile.h"
#define NS_THIS_STANDARDURL_IMPLEMENTATION_CID \
{ /* e3939dc8-29ab-11d3-8cce-0060b0fc14a3 */ \
0xe3939dc8, \
0x29ab, \
0x11d3, \
{0x8c, 0xce, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
class nsStdURL : public nsIFileURL
{
public:
///////////////////////////////////////////////////////////////////////////
// nsStdURL methods:
nsStdURL();
nsStdURL(const char* i_Spec, nsISupports* outer=nsnull);
nsStdURL(const nsStdURL& i_URL);
virtual ~nsStdURL();
nsStdURL& operator =(const nsStdURL& otherURL);
PRBool operator ==(const nsStdURL& otherURL) const;
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
NS_DECL_AGGREGATED
NS_DECL_NSIURI
NS_DECL_NSIURL
NS_DECL_NSIFILEURL
protected:
enum Format { ESCAPED, UNESCAPED };
nsresult Parse(const char* i_Spec);
nsresult AppendString(nsCString& buffer, char* fromUnescapedStr,
Format toFormat, PRInt16 mask);
nsresult GetString(char** result, char* fromEscapedStr,
Format toFormat);
nsresult AppendPreHost(nsCString& buffer, char* i_Username,
char* i_Password, Format toFormat);
nsresult AppendFileName(nsCString& buffer, char* i_FileBaseName,
char* i_FileExtension, Format toFormat);
protected:
char* mScheme;
char* mUsername;
char* mPassword;
char* mHost;
PRInt32 mPort;
char* mDirectory;
char* mFileBaseName;
char* mFileExtension;
char* mParam;
char* mQuery;
char* mRef;
nsCOMPtr<nsIURLParser> mURLParser;
// If a file was given to SetFile, then this instance variable holds it.
// If GetFile is called, we synthesize one and cache it here.
nsCOMPtr<nsIFile> mFile;
};
inline NS_METHOD
nsStdURL::GetScheme(char* *o_Scheme)
{
return GetString(o_Scheme, mScheme, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetUsername(char* *o_Username)
{
return GetString(o_Username, mUsername, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetPassword(char* *o_Password)
{
return GetString(o_Password, mPassword, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetHost(char* *o_Host)
{
return GetString(o_Host, mHost, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetPort(PRInt32 *aPort)
{
if (aPort)
{
*aPort = mPort;
return NS_OK;
}
return NS_ERROR_NULL_POINTER;
}
inline NS_METHOD
nsStdURL::GetFileBaseName(char* *o_FileBaseName)
{
return GetString(o_FileBaseName, mFileBaseName, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetFileExtension(char* *o_FileExtension)
{
return GetString(o_FileExtension, mFileExtension, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetParam(char **o_Param)
{
return GetString(o_Param, mParam, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetQuery(char* *o_Query)
{
return GetString(o_Query, mQuery, UNESCAPED);
}
inline NS_METHOD
nsStdURL::GetRef(char* *o_Ref)
{
return GetString(o_Ref, mRef, UNESCAPED);
}
inline NS_METHOD
nsStdURL::SetScheme(const char* i_Scheme)
{
CRTFREEIF(mScheme);
nsresult rv = DupString(&mScheme, i_Scheme);
ToLowerCase(mScheme);
return rv;
}
inline NS_METHOD
nsStdURL::SetUsername(const char* i_Username)
{
CRTFREEIF(mUsername);
return DupString(&mUsername, i_Username);
}
inline NS_METHOD
nsStdURL::SetPassword(const char* i_Password)
{
CRTFREEIF(mPassword);
return DupString(&mPassword, i_Password);
}
inline NS_METHOD
nsStdURL::SetHost(const char* i_Host)
{
CRTFREEIF(mHost);
nsresult rv = DupString(&mHost, i_Host);
ToLowerCase(mHost);
return rv;
}
inline NS_METHOD
nsStdURL::SetPort(PRInt32 aPort)
{
mPort = aPort;
return NS_OK;
}
inline NS_METHOD
nsStdURL::SetFileBaseName(const char* i_FileBaseName)
{
CRTFREEIF(mFileBaseName);
return DupString(&mFileBaseName, i_FileBaseName);
}
inline NS_METHOD
nsStdURL::SetFileExtension(const char* i_FileExtension)
{
CRTFREEIF(mFileExtension);
return DupString(&mFileExtension, i_FileExtension);
}
#endif // nsStdURL_h__

View File

@@ -0,0 +1,524 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Andreas Otte.
*
* Contributor(s):
*/
#include "nsStdURLParser.h"
#include "nsURLHelper.h"
#include "nsCRT.h"
#include "nsString.h"
#include "prprf.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsStdURLParser, nsIURLParser)
nsStdURLParser::~nsStdURLParser()
{
}
NS_METHOD
nsStdURLParser::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsStdURLParser* p = new nsStdURLParser();
if (p == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(p);
nsresult rv = p->QueryInterface(aIID, aResult);
NS_RELEASE(p);
return rv;
}
nsresult
nsStdURLParser::ParseAtScheme(const char* i_Spec, char* *o_Scheme,
char* *o_Username,
char* *o_Password,
char* *o_Host, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
NS_PRECONDITION( (nsnull != i_Spec), "Parse called on empty url!");
if (!i_Spec)
return NS_ERROR_MALFORMED_URI;
int len = PL_strlen(i_Spec);
if (len >= 2 && *i_Spec == '/' && *(i_Spec+1) == '/') // No Scheme
{
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host, o_Port,
o_Path);
return rv;
}
static const char delimiters[] = "/:@?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
ToLowerCase(*o_Host);
return rv;
} else
len = PL_strlen(brk);
switch (*brk)
{
case '/' :
case '?' :
// If the URL starts with a slash then everything is a path
if (brk == i_Spec)
{
rv = ParseAtPath(brk, o_Path);
return rv;
}
else // The first part is host, so its host/path
{
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
}
break;
case ':' :
if (len >= 2 && *(brk+1) == '/' && *(brk+2) == '/') {
// Standard http://...
rv = ExtractString((char*)i_Spec, o_Scheme, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
if (rv == NS_ERROR_MALFORMED_URI) {
// or not ? Try something else
CRTFREEIF(*o_Username);
CRTFREEIF(*o_Password);
CRTFREEIF(*o_Host);
*o_Port = -1;
rv = ParseAtPath(brk+3, o_Path);
}
return rv;
} else {
if ( len >= 2 && *(brk+1) == '/' && *(brk+2) != '/') {
// May be it is file:/....
rv = ExtractString((char*)i_Spec, o_Scheme, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPath(brk+1, o_Path);
return rv;
} else {
// Could be host:port, so try conversion to number
PRInt32 port = ExtractPortFrom(brk+1);
if (port <= 0)
{
// No, try normal procedure
rv = ExtractString((char*)i_Spec, o_Scheme,
(brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
if (rv == NS_ERROR_MALFORMED_URI) {
// Try something else
CRTFREEIF(*o_Username);
CRTFREEIF(*o_Password);
CRTFREEIF(*o_Host);
*o_Port = -1;
rv = ParseAtPath(brk+1, o_Path);
}
return rv;
} else {
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
}
}
}
break;
case '@' :
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsStdURLParser::ParseAtPreHost(const char* i_Spec, char* *o_Username,
char* *o_Password, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// Skip leading two slashes
char* fwdPtr= (char*) i_Spec;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
static const char delimiters[] = "/:@?";
char* brk = PL_strpbrk(fwdPtr, delimiters);
char* brk2 = nsnull;
if (!brk)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
char* e_PreHost = nsnull;
switch (*brk)
{
case ':' :
// this maybe the : of host:port or username:password
// look if the next special char is @
brk2 = PL_strpbrk(brk+1, delimiters);
if (!brk2)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
switch (*brk2)
{
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk2 - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk2+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
break;
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
}
return rv;
}
nsresult
nsStdURLParser::ParseAtHost(const char* i_Spec, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
int len = PL_strlen(i_Spec);
static const char delimiters[] = ":/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
ToLowerCase(*o_Host);
return rv;
}
switch (*brk)
{
case '/' :
case '?' :
// Get the Host, the rest is Path
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
break;
case ':' :
// Get the Host
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsStdURLParser::ParseAtPort(const char* i_Spec, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
static const char delimiters[] = "/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a Port
{
*o_Port = ExtractPortFrom(i_Spec);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
else
return NS_OK;
}
switch (*brk)
{
case '/' :
case '?' :
// Get the Port, the rest is Path
*o_Port = ExtractPortFrom(i_Spec);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
rv = ParseAtPath(brk, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsStdURLParser::ParseAtPath(const char* i_Spec, char* *o_Path)
{
// Just write the path and check for a starting /
nsCAutoString dir;
if ('/' != *i_Spec)
dir += "/";
dir += i_Spec;
*o_Path = dir.ToNewCString();
return (*o_Path ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
nsresult
nsStdURLParser::ParseAtDirectory(const char* i_Path, char* *o_Directory,
char* *o_FileBaseName, char* *o_FileExtension,
char* *o_Param, char* *o_Query, char* *o_Ref)
{
// Cleanout
CRTFREEIF(*o_Directory);
CRTFREEIF(*o_FileBaseName);
CRTFREEIF(*o_FileExtension);
CRTFREEIF(*o_Param);
CRTFREEIF(*o_Query);
CRTFREEIF(*o_Ref);
nsresult rv = NS_OK;
// Parse the Path into its components
if (!i_Path)
{
DupString(o_Directory, "/");
return (o_Directory ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
char* dirfile = nsnull;
char* options = nsnull;
int len = PL_strlen(i_Path);
/* Factor out the optionpart with ;?# */
static const char delimiters[] = ";?#"; // for param, query and ref
char* brk = PL_strpbrk(i_Path, delimiters);
if (!brk) // Everything is just path and filename
{
DupString(&dirfile, i_Path);
}
else
{
int dirfileLen = brk - i_Path;
ExtractString((char*)i_Path, &dirfile, dirfileLen);
len -= dirfileLen;
ExtractString((char*)i_Path + dirfileLen, &options, len);
brk = options;
}
/* now that we have broken up the path treat every part differently */
/* first dir+file */
char* file= nsnull;
int dlen = PL_strlen(dirfile);
if (dlen == 0)
{
DupString(o_Directory, "/");
file = dirfile;
} else {
CoaleseDirs(dirfile);
// Get length again
dlen = PL_strlen(dirfile);
// First find the last slash
file = PL_strrchr(dirfile, '/');
if (!file)
{
DupString(o_Directory, "/");
file = dirfile;
}
// If its not the same as the first slash then extract directory
if (file != dirfile)
{
ExtractString(dirfile, o_Directory, (file - dirfile)+1);
} else {
DupString(o_Directory, "/");
}
}
/* Extract FileBaseName and FileExtension */
if (dlen > 0) {
// Look again if there was a slash
char* slash = PL_strrchr(dirfile, '/');
char* e_FileName = nsnull;
if (slash) {
if (dirfile+dlen-1>slash)
ExtractString(slash+1, &e_FileName, dlen-(slash-dirfile+1));
} else {
// Use the full String as Filename
ExtractString(dirfile, &e_FileName, dlen);
}
rv = ParseFileName(e_FileName,o_FileBaseName,o_FileExtension);
CRTFREEIF(e_FileName);
}
// Now take a look at the options. "#" has precedence over "?"
// which has precedence over ";"
if (options) {
// Look for "#" first. Everything following it is in the ref
brk = PL_strchr(options, '#');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Ref, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for "?"
brk = PL_strchr(options, '?');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Query, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for ';'
brk = PL_strchr(options, ';');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Param, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
}
CRTFREEIF(dirfile);
CRTFREEIF(options);
return rv;
}
nsresult
nsStdURLParser::ParsePreHost(const char* i_PreHost, char* *o_Username,
char* *o_Password)
{
nsresult rv = NS_OK;
if (!i_PreHost) {
*o_Username = nsnull;
*o_Password = nsnull;
return rv;
}
// Search for :
static const char delimiters[] = ":";
char* brk = PL_strpbrk(i_PreHost, delimiters);
if (brk)
{
rv = ExtractString((char*)i_PreHost, o_Username, (brk - i_PreHost));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk+1, o_Password,
(i_PreHost+PL_strlen(i_PreHost) - brk - 1));
} else {
CRTFREEIF(*o_Password);
rv = DupString(o_Username, i_PreHost);
}
return rv;
}
nsresult
nsStdURLParser::ParseFileName(const char* i_FileName, char* *o_FileBaseName,
char* *o_FileExtension)
{
nsresult rv = NS_OK;
if (!i_FileName) {
*o_FileBaseName = nsnull;
*o_FileExtension = nsnull;
return rv;
}
// Search for FileExtension
// Search for last .
// Ignore . at the beginning
char* brk = PL_strrchr(i_FileName+1, '.');
if (brk)
{
rv = ExtractString((char*)i_FileName, o_FileBaseName,
(brk - i_FileName));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk + 1, o_FileExtension,
(i_FileName+PL_strlen(i_FileName) - brk - 1));
} else {
rv = DupString(o_FileBaseName, i_FileName);
}
return rv;
}

View File

@@ -0,0 +1,51 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsStdURLParser_h__
#define nsStdURLParser_h__
#include "nsIURLParser.h"
#include "nsIURI.h"
#include "nsAgg.h"
#include "nsCRT.h"
class nsStdURLParser : public nsIURLParser
{
public:
NS_DECL_ISUPPORTS
///////////////////////////////////////////////////////////////////////////
// nsStdURLParser methods:
nsStdURLParser() {
NS_INIT_REFCNT();
}
virtual ~nsStdURLParser();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
///////////////////////////////////////////////////////////////////////////
// nsIURLParser methods:
NS_DECL_NSIURLPARSER
};
#endif // nsStdURLParser_h__

View File

@@ -0,0 +1,146 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#include "nsStreamLoader.h"
#include "nsIInputStream.h"
#include "nsIURL.h"
#include "nsNetUtil.h"
#include "nsIChannel.h"
#include "nsIServiceManager.h"
#include "nsIIOService.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
NS_IMETHODIMP
nsStreamLoader::Init(nsIURI* aURL,
nsIStreamLoaderObserver* observer,
nsISupports* context,
nsILoadGroup* aGroup,
nsIInterfaceRequestor* notificationCallbacks,
nsLoadFlags loadAttributes,
PRUint32 bufferSegmentSize,
PRUint32 bufferMaxSize)
{
nsresult rv = NS_OK;
mObserver = observer;
mContext = context;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = serv->NewChannelFromURI("load", aURL, aGroup, notificationCallbacks,
loadAttributes, nsnull,
bufferSegmentSize, bufferMaxSize, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->AsyncRead(0, -1, nsnull, this);
if (NS_FAILED(rv) && mObserver) {
nsresult rv2 = mObserver->OnStreamComplete(this, mContext, rv,
mData.Length(),
mData.GetBuffer());
if (NS_FAILED(rv2))
rv = rv2; // take the user's error instead
}
return rv;
}
NS_METHOD
nsStreamLoader::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter) return NS_ERROR_NO_AGGREGATION;
nsStreamLoader* it = new nsStreamLoader();
if (it == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(it);
nsresult rv = it->QueryInterface(aIID, aResult);
NS_RELEASE(it);
return rv;
}
NS_IMPL_ISUPPORTS3(nsStreamLoader, nsIStreamLoader,
nsIStreamObserver, nsIStreamListener)
NS_IMETHODIMP
nsStreamLoader::GetNumBytesRead(PRUint32* aNumBytes)
{
if (!mData.IsEmpty()) {
*aNumBytes = mData.Length();
}
else {
*aNumBytes = 0;
}
return NS_OK;
}
NS_IMETHODIMP
nsStreamLoader::OnStartRequest(nsIChannel* channel, nsISupports *ctxt)
{
return NS_OK;
}
NS_IMETHODIMP
nsStreamLoader::OnStopRequest(nsIChannel* channel, nsISupports *ctxt,
nsresult status, const PRUnichar *errorMsg)
{
nsresult rv = mObserver->OnStreamComplete(this, mContext, status,
mData.Length(),
mData.GetBuffer());
return rv;
}
#define BUF_SIZE 1024
NS_IMETHODIMP
nsStreamLoader::OnDataAvailable(nsIChannel* channel, nsISupports *ctxt,
nsIInputStream *inStr,
PRUint32 sourceOffset, PRUint32 count)
{
nsresult rv = NS_OK;
char buffer[BUF_SIZE];
PRUint32 len, lenRead;
inStr->Available(&len);
while (len > 0) {
if (len < BUF_SIZE) {
lenRead = len;
}
else {
lenRead = BUF_SIZE;
}
rv = inStr->Read(buffer, lenRead, &lenRead);
if (NS_FAILED(rv) || lenRead == 0) {
return rv;
}
mData.Append(buffer, lenRead);
len -= lenRead;
}
return rv;
}

View File

@@ -0,0 +1,53 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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 Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*/
#ifndef nsStreamLoader_h__
#define nsStreamLoader_h__
#include "nsIStreamLoader.h"
#include "nsIStreamListener.h"
#include "nsCOMPtr.h"
#include "nsString.h"
class nsStreamLoader : public nsIStreamLoader,
public nsIStreamListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMLOADER
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
nsStreamLoader() { NS_INIT_REFCNT();} ;
virtual ~nsStreamLoader() {};
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
nsCOMPtr<nsIStreamLoaderObserver> mObserver;
nsCOMPtr<nsISupports> mContext; // the observer's context
nsCString mData;
/// nsCOMPtr<nsILoadGroup> mLoadGroup;
};
#endif // nsStreamLoader_h__

Some files were not shown because too many files have changed in this diff Show More