Compare commits

..

31 Commits

Author SHA1 Message Date
gordon%netscape.com
f06d4f2264 The files have been replaced by nsDiskCacheBinding.*
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95453 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 23:02:39 +00:00
gordon%netscape.com
168ba7fac5 Use approximation of last fetch time for eviction rank.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95437 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 22:26:38 +00:00
gordon%netscape.com
544dab6d92 Change mGeneration to PRUint8.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95411 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 20:57:40 +00:00
darin%netscape.com
3e4ab67de4 changes resulting from review
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95405 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 20:12:31 +00:00
gordon%netscape.com
1d221aa7dd Fixed accounting bugs for total size and entry count.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95386 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 08:02:18 +00:00
darin%netscape.com
344240b9f6 removed unnecessary stuff
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95368 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 04:42:51 +00:00
darin%netscape.com
643bedea5c fixed byte ordering for little endian
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95349 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 00:46:15 +00:00
gordon%netscape.com
ab1f74bc51 Minor fix.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95344 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 00:24:50 +00:00
gordon%netscape.com
0c75de57d4 Minor fixes.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95343 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 00:22:29 +00:00
gordon%netscape.com
7f31a3499d Fixed more bugs.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95341 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-18 00:08:32 +00:00
darin%netscape.com
75f4a226fa make it compile on windows
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95302 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-17 20:50:05 +00:00
gordon%netscape.com
c4f4404360 Update for tip.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95279 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-17 18:50:55 +00:00
gordon%netscape.com
1307eaca6a Implement clear disk cache, and fix bugs.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95278 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-17 18:48:27 +00:00
darin%netscape.com
79730cfa63 make it build on windows
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95179 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-17 01:19:36 +00:00
gordon%netscape.com
f3628c7bd5 Updating for linux.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95149 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-16 22:29:41 +00:00
gordon%netscape.com
e87d348d54 Change for new files in DISKCACHE2_BRANCH.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95148 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-16 22:29:07 +00:00
gordon%netscape.com
606cb60b1f Level 2 nearly done. Eviction still needs to be hooked back up.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@95099 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-16 04:06:21 +00:00
gordon%netscape.com
e6669e5d3a Sync with tip.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94898 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 21:31:47 +00:00
gordon%netscape.com
8e855ab4ed Back out non-essential change.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94897 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 21:29:11 +00:00
gordon%netscape.com
184791f5ea Add nsDiskCacheBindData.cpp and nsDiskCacheBlockFile.cpp to build.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94896 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 21:14:03 +00:00
gordon%netscape.com
fdd7e77c2d Joining change from tip.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94895 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 21:12:13 +00:00
gordon%netscape.com
f8cf79b055 Fixes for a few bugs caught by linux.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94894 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 20:23:17 +00:00
gordon%netscape.com
8a22ddce2f Additional refactoring of disk cache.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94893 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-14 20:04:53 +00:00
gordon%netscape.com
826ed51db3 Renaming nsDiskCacheEntry -> nsDiskCacheBindInfo, and reorganize files.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94555 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-11 01:38:03 +00:00
gordon%netscape.com
cc6d193bae updating branch for recent trunk changes
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94413 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-09 22:46:14 +00:00
(no author)
9e5b5201e6 This commit was manufactured by cvs2svn to create branch
'DISKCACHE2_BRANCH'.

git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@94030 18797224-902f-48f8-a5cc-f745e15eee43
2001-05-05 05:33:39 +00:00
gordon%netscape.com
ce35aa80bc updating from trunk.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@93323 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-27 23:23:53 +00:00
gordon%netscape.com
908e3bc997 Begin refactoring for nsDiskCacheBlockFile integration. (flat files for metadata).
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@92513 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-17 04:10:54 +00:00
gordon%netscape.com
0ee6b398ae Implement deviceID attribute for nsICacheEntryInfo. Implement nsCacheSession::EvictEntries().
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@92057 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-12 02:44:10 +00:00
gordon%netscape.com
ccc56f1b74 Added attribute to nsICacheEntryInfo to get deviceID for entry.
git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@92056 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-12 02:42:26 +00:00
(no author)
0893647797 This commit was manufactured by cvs2svn to create branch
'DISKCACHE2_BRANCH'.

git-svn-id: svn://10.0.0.236/branches/DISKCACHE2_BRANCH@91529 18797224-902f-48f8-a5cc-f745e15eee43
2001-04-06 00:33:20 +00:00
90 changed files with 11181 additions and 5119 deletions

View File

@@ -1,70 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsISupports.idl"
interface nsIDOMWindow;
/**
* This interface provides support for registering Mozilla as the default
* Mail Client. This interface can also be used to get/set the user preference
* for the default Mail Client.
*
*/
[scriptable, uuid(c5be14ba-4e0a-4eec-a1b8-04363761d63c)]
interface nsIMapiRegistry: nsISupports {
/** This is set to TRUE if Mozilla is the default Application
*/
attribute boolean isDefaultMailClient;
/** This is set TRUE only once per session.
*/
readonly attribute boolean showDialog;
/** This will bring the dialog asking the user if he/she wants to set
* Mozilla as default Mail Client.
* Call this only if Mozilla is not the default Mail client
*/
void showMailIntegrationDialog(in nsIDOMWindow parentWindow);
};
%{C++
#define NS_IMAPIREGISTRY_CONTRACTID "@mozilla.org/mapiregistry;1"
#define NS_IMAPIREGISTRY_CLASSNAME "Mozilla MAPI Registry"
%}

View File

@@ -1,27 +0,0 @@
#!nmake
#
# 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): Srilatha Moturi <srilatha@netscape.com>
# Krishna Mohan Khandrika <kkhandrika@netscape.com>
DEPTH=..\..
DIRS=mapihook resources mapiDll
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,54 +0,0 @@
; ***** BEGIN LICENSE BLOCK *****
; Version: MPL 1.1/GPL 2.0/LGPL 2.1
;
; The contents of this file are subject to the Mozilla 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/MPL/
;
; 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.
;
; The Initial Developer of the Original Code is
; Netscape Communications Corp.
; Portions created by the Initial Developer are Copyright (C) 2001
; the Initial Developer. All Rights Reserved.
;
; Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
;
; Alternatively, the contents of this file may be used under the terms of
; either the GNU General Public License Version 2 or later (the "GPL"), or
; the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
; in which case the provisions of the GPL or the LGPL are applicable instead
; of those above. If you wish to allow use of your version of this file only
; under the terms of either the GPL or the LGPL, and not to allow others to
; use your version of this file under the terms of the MPL, indicate your
; decision by deleting the provisions above and replace them with the notice
; and other provisions required by the GPL or the LGPL. If you do not delete
; the provisions above, a recipient may use your version of this file under
; the terms of any one of the MPL, the GPL or the LGPL.
;
; ***** END LICENSE BLOCK *****
LIBRARY mozMapi32.dll
DESCRIPTION 'Mozilla Simple MAPI Support'
EXPORTS
MAPILogon
MAPILogoff
MAPISendMail
MAPISendDocuments
MAPIFindNext
MAPIReadMail
MAPISaveMail
MAPIDeleteMail
MAPIAddress
MAPIDetails
MAPIResolveName
MAPIFreeBuffer
GetMapiDllVersion

View File

@@ -1,346 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
* Contributor(s): Rajiv Dayal (rdayal@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <windows.h>
#include <tchar.h>
#include <mapidefs.h>
#include <mapi.h>
#include "msgMapi.h"
#include "msgMapiMain.h"
#define MAX_RECIPS 100
#define MAX_FILES 100
const CLSID CLSID_CMapiImp = {0x29f458be, 0x8866, 0x11d5,
{0xa3, 0xdd, 0x0, 0xb0, 0xd0, 0xf3, 0xba, 0xa7}};
const IID IID_nsIMapi = {0x6EDCD38E,0x8861,0x11d5,
{0xA3,0xDD,0x00,0xB0,0xD0,0xF3,0xBA,0xA7}};
DWORD tId = 0;
BOOL WINAPI DllMain(HINSTANCE aInstance, DWORD aReason, LPVOID aReserved)
{
switch (aReason)
{
case DLL_PROCESS_ATTACH : tId = TlsAlloc();
if (tId == 0xFFFFFFFF)
return FALSE;
break;
case DLL_PROCESS_DETACH : TlsFree(tId);
break;
}
return TRUE;
}
BOOL InitMozillaReference(nsIMapi **aRetValue)
{
// Check wehther this thread has a valid Interface
// by looking into thread-specific-data variable
*aRetValue = (nsIMapi *)TlsGetValue(tId);
// Check whether the pointer actually resolves to
// a valid method call; otherwise mozilla is not running
if ((*aRetValue) && (*aRetValue)->IsValid() == S_OK)
return TRUE;
HRESULT hRes = ::CoInitialize(nsnull) ;
hRes = ::CoCreateInstance(CLSID_CMapiImp, NULL, CLSCTX_LOCAL_SERVER,
IID_nsIMapi, (LPVOID *)aRetValue);
if (hRes == S_OK && (*aRetValue)->Initialize() == S_OK)
if (TlsSetValue(tId, (LPVOID)(*aRetValue)))
return TRUE;
// Either CoCreate or TlsSetValue failed; so return FALSE
if ((*aRetValue))
(*aRetValue)->Release();
::CoUninitialize();
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////////////
// The MAPILogon function begins a Simple MAPI session, loading the default message ////
// store and address book providers ////
////////////////////////////////////////////////////////////////////////////////////////
ULONG FAR PASCAL MAPILogon(ULONG aUIParam, LPTSTR aProfileName,
LPTSTR aPassword, FLAGS aFlags,
ULONG aReserved, LPLHANDLE aSession)
{
HRESULT hr = 0;
ULONG nSessionId = 0;
nsIMapi *pNsMapi = NULL;
if (!InitMozillaReference(&pNsMapi))
return MAPI_E_FAILURE;
if (!(aFlags & MAPI_UNICODE))
{
// Need to convert the parameters to Unicode.
char *pUserName = (char *) aProfileName;
char *pPassWord = (char *) aPassword;
TCHAR ProfileName[MAX_NAME_LEN] = {0};
TCHAR PassWord[MAX_PW_LEN] = {0};
if (pUserName != NULL)
{
if (!MultiByteToWideChar(CP_ACP, 0, pUserName, -1, ProfileName,
MAX_NAME_LEN))
return MAPI_E_FAILURE;
}
if (pPassWord != NULL)
{
if (!MultiByteToWideChar(CP_ACP, 0, pPassWord, -1, PassWord,
MAX_NAME_LEN))
return MAPI_E_FAILURE;
}
hr = pNsMapi->Login(aUIParam, ProfileName, PassWord, aFlags,
&nSessionId);
}
else
hr = pNsMapi->Login(aUIParam, aProfileName, aPassword,
aFlags, &nSessionId);
if (hr == S_OK)
(*aSession) = (LHANDLE) nSessionId;
else
return nSessionId;
return SUCCESS_SUCCESS;
}
ULONG FAR PASCAL MAPILogoff (LHANDLE aSession, ULONG aUIParam,
FLAGS aFlags, ULONG aReserved)
{
nsIMapi *pNsMapi = (nsIMapi *)TlsGetValue(tId);
if (pNsMapi != NULL)
{
if (pNsMapi->Logoff((ULONG) aSession) == S_OK)
pNsMapi->Release();
pNsMapi = NULL;
}
TlsSetValue(tId, NULL);
::CoUninitialize();
return SUCCESS_SUCCESS;
}
ULONG FAR PASCAL MAPISendMail (LHANDLE lhSession, ULONG ulUIParam, lpnsMapiMessage lpMessage,
FLAGS flFlags, ULONG ulReserved )
{
HRESULT hr = 0;
BOOL bTempSession = FALSE ;
nsIMapi *pNsMapi = NULL;
if (!InitMozillaReference(&pNsMapi))
return MAPI_E_FAILURE;
if (lpMessage->nRecipCount > MAX_RECIPS)
return MAPI_E_TOO_MANY_RECIPIENTS ;
if (lpMessage->nFileCount > MAX_FILES)
return MAPI_E_TOO_MANY_FILES ;
if ( (!(flFlags & MAPI_DIALOG)) && (lpMessage->lpRecips == NULL) )
return MAPI_E_UNKNOWN_RECIPIENT ;
if (!lhSession || pNsMapi->IsValidSession(lhSession) != S_OK)
{
FLAGS LoginFlag ;
if ( (flFlags & MAPI_LOGON_UI) && (flFlags & MAPI_NEW_SESSION) )
LoginFlag = MAPI_LOGON_UI | MAPI_NEW_SESSION ;
else if (flFlags & MAPI_LOGON_UI)
LoginFlag = MAPI_LOGON_UI ;
hr = MAPILogon (ulUIParam, (LPTSTR) NULL, (LPTSTR) NULL, LoginFlag, 0, &lhSession) ;
if (hr != SUCCESS_SUCCESS)
return MAPI_E_LOGIN_FAILURE ;
bTempSession = TRUE ;
}
// we need to deal with null data passed in by MAPI clients, specially when MAPI_DIALOG is set.
// The MS COM type lib code generated by MIDL for the MS COM interfaces checks for these parameters
// to be non null, although null is a valid value for them here.
nsMapiRecipDesc * lpRecips ;
nsMapiFileDesc * lpFiles ;
nsMapiMessage Message ;
memset (&Message, 0, sizeof (nsMapiMessage) ) ;
nsMapiRecipDesc Recipient ;
memset (&Recipient, 0, sizeof (nsMapiRecipDesc) );
nsMapiFileDesc Files ;
memset (&Files, 0, sizeof (nsMapiFileDesc) ) ;
if(!lpMessage)
{
lpMessage = &Message ;
}
if(!lpMessage->lpRecips)
{
lpRecips = &Recipient ;
}
else
lpRecips = lpMessage->lpRecips ;
if(!lpMessage->lpFiles)
{
lpFiles = &Files ;
}
else
lpFiles = lpMessage->lpFiles ;
HANDLE hEvent = CreateEvent (NULL, FALSE, FALSE, (LPCTSTR) MAPI_SENDCOMPLETE_EVENT) ;
hr = pNsMapi->SendMail (lhSession, lpMessage,
(short) lpMessage->nRecipCount, lpRecips,
(short) lpMessage->nFileCount, lpFiles,
flFlags, ulReserved);
// we are seeing a problem when using Word, although we return success from the MAPI support
// MS COM interface in mozilla, we are getting this error here. This is a temporary hack !!
if (hr == 0x800703e6)
hr = SUCCESS_SUCCESS;
if (hr == SUCCESS_SUCCESS)
WaitForSingleObject (hEvent, INFINITE) ;
CloseHandle (hEvent) ;
if (bTempSession)
MAPILogoff (lhSession, ulUIParam, 0,0) ;
return hr ;
}
ULONG FAR PASCAL MAPISendDocuments(ULONG ulUIParam, LPTSTR lpszDelimChar, LPTSTR lpszFilePaths,
LPTSTR lpszFileNames, ULONG ulReserved)
{
LHANDLE lhSession ;
nsIMapi *pNsMapi = NULL;
if (!InitMozillaReference(&pNsMapi))
return MAPI_E_FAILURE;
unsigned long result = MAPILogon (ulUIParam, (LPTSTR) NULL, (LPTSTR) NULL, MAPI_LOGON_UI, 0, &lhSession) ;
if (result != SUCCESS_SUCCESS)
return MAPI_E_LOGIN_FAILURE ;
HRESULT hr;
HANDLE hEvent = CreateEvent (NULL, FALSE, FALSE, (LPCTSTR) MAPI_SENDCOMPLETE_EVENT) ;
hr = pNsMapi->SendDocuments(lhSession, (LPTSTR) lpszDelimChar, (LPTSTR) lpszFilePaths,
(LPTSTR) lpszFileNames, ulReserved) ;
if (hr == SUCCESS_SUCCESS)
WaitForSingleObject (hEvent, INFINITE) ;
CloseHandle (hEvent) ;
MAPILogoff (lhSession, ulUIParam, 0,0) ;
return hr ;
}
ULONG FAR PASCAL MAPIFindNext(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageType,
LPTSTR lpszSeedMessageID, FLAGS flFlags, ULONG ulReserved,
LPTSTR lpszMessageID)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIReadMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
FLAGS flFlags, ULONG ulReserved, lpMapiMessage FAR *lppMessage)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPISaveMail(LHANDLE lhSession, ULONG ulUIParam, lpMapiMessage lpMessage,
FLAGS flFlags, ULONG ulReserved, LPTSTR lpszMessageID)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIDeleteMail(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszMessageID,
FLAGS flFlags, ULONG ulReserved)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIAddress(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszCaption,
ULONG nEditFields, LPTSTR lpszLabels, ULONG nRecips,
lpMapiRecipDesc lpRecips, FLAGS flFlags,
ULONG ulReserved, LPULONG lpnNewRecips,
lpMapiRecipDesc FAR *lppNewRecips)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIDetails(LHANDLE lhSession, ULONG ulUIParam, lpMapiRecipDesc lpRecip,
FLAGS flFlags, ULONG ulReserved)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIResolveName(LHANDLE lhSession, ULONG ulUIParam, LPTSTR lpszName,
FLAGS flFlags, ULONG ulReserved, lpMapiRecipDesc FAR *lppRecip)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL MAPIFreeBuffer(LPVOID pv)
{
return MAPI_E_FAILURE;
}
ULONG FAR PASCAL GetMapiDllVersion()
{
return 94;
}

View File

@@ -1,62 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corp.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH=..\..\..
MODULE = mozMapi32
EXPORT_LIBRARY = $(MODULE)
LIBRARY_NAME = $(MODULE)
DEFFILE = Mapi32.def
REQUIRES = MapiProxy \
msgMapi \
xpcom \
string \
$(NULL)
include <$(DEPTH)\config\config.mak>
###############################################################
LCFLAGS=-DUNICODE -D_UNICODE
OBJS= .\$(OBJDIR)\MapiDll.obj \
$(NULL)
WIN_LIBS= ole32.lib \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,47 +0,0 @@
; ***** BEGIN LICENSE BLOCK *****
; Version: MPL 1.1/GPL 2.0/LGPL 2.1
;
; The contents of this file are subject to the Mozilla 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/MPL/
;
; 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.
;
; The Initial Developer of the Original Code is
; Netscape Communications Corp.
; Portions created by the Initial Developer are Copyright (C) 2001
; the Initial Developer. All Rights Reserved.
;
; Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
;
; Alternatively, the contents of this file may be used under the terms of
; either the GNU General Public License Version 2 or later (the "GPL"), or
; the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
; in which case the provisions of the GPL or the LGPL are applicable instead
; of those above. If you wish to allow use of your version of this file only
; under the terms of either the GPL or the LGPL, and not to allow others to
; use your version of this file under the terms of the MPL, indicate your
; decision by deleting the provisions above and replace them with the notice
; and other provisions required by the GPL or the LGPL. If you do not delete
; the provisions above, a recipient may use your version of this file under
; the terms of any one of the MPL, the GPL or the LGPL.
;
; ***** END LICENSE BLOCK *****
LIBRARY MapiProxy.dll
DESCRIPTION 'Proxy/Stub DLL'
EXPORTS
DllGetClassObject @1 PRIVATE
DllCanUnloadNow @2 PRIVATE
GetProxyDllInfo @3 PRIVATE
DllRegisterServer @4 PRIVATE
DllUnregisterServer @5 PRIVATE

View File

@@ -1,68 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corp.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH=..\..\..\..
MODULE = MapiProxy
EXPORT_LIBRARY = $(MODULE)
LIBRARY_NAME = $(MODULE)
DEFFILE = MapiProxy.def
include <$(DEPTH)\config\config.mak>
##################################################################
LCFLAGS=-DREGISTER_PROXY_DLL -DUNICODE -D_UNICODE
OBJS= .\$(OBJDIR)\dlldata.obj \
.\$(OBJDIR)\msgMapi_p.obj \
.\$(OBJDIR)\msgMapi_i.obj \
$(NULL)
WIN_LIBS= rpcrt4.lib
EXPORTS= msgMapi.h \
$(NULL)
include <$(DEPTH)\config\rules.mak>
msgMapi.h msgMapi_p.c msgMapi_i.c dlldata.c : msgMapi.idl
midl $(UNICODE_FLAGS) msgMapi.idl
clobber::
rm -f dlldata.c msgMapi_i.c msgMapi_p.c msgMapi.h

View File

@@ -1,114 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
* Contributor(s): Rajiv Dayal (rdayal@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This idl will be compiled by MIDL. MS-COM is used
// as brdige between MAPI clients and the Mozilla.
import "unknwn.idl";
typedef wchar_t LOGIN_PW_TYPE[256];
typedef struct
{
unsigned long ulReserved;
unsigned long flFlags; /* Flags */
unsigned long nPosition_NotUsed; /* character in text to be replaced by attachment */
LPTSTR lpszPathName; /* Full path name including file name */
LPTSTR lpszFileName; /* Real (original) file name */
unsigned char * lpFileType_NotUsed ;
} nsMapiFileDesc, * lpnsMapiFileDesc;
typedef struct
{
unsigned long ulReserved;
unsigned long ulRecipClass; /* MAPI_TO, MAPI_CC, MAPI_BCC, MAPI_ORIG */
LPTSTR lpszName; /* Recipient name to display */
LPTSTR lpszAddress; /* Recipient email address */
unsigned long ulEIDSize_NotUsed;
unsigned char * lpEntryID_NotUsed ;
} nsMapiRecipDesc, * lpnsMapiRecipDesc;
typedef struct
{
unsigned long ulReserved;
LPTSTR lpszSubject; /* Message Subject */
LPTSTR lpszNoteText; /* Message Text */
LPTSTR lpszMessageType_NotUsed;
LPTSTR lpszDateReceived_notUsed; /* in YYYY/MM/DD HH:MM format */
LPTSTR lpszConversationID_NotUsed; /* conversation thread ID */
unsigned long flFlags; /* unread,return receipt */
lpnsMapiRecipDesc lpOriginator; /* Originator descriptor */
unsigned long nRecipCount; /* Number of recipients */
lpnsMapiRecipDesc lpRecips; /* Recipient descriptors */
unsigned long nFileCount; /* # of file attachments */
lpnsMapiFileDesc lpFiles; /* Attachment descriptors */
} nsMapiMessage, * lpnsMapiMessage;
[
object,
uuid(6EDCD38E-8861-11d5-A3DD-00B0D0F3BAA7),
helpstring("nsIMapi Inteface"),
pointer_default(unique)
]
interface nsIMapi : IUnknown
{
HRESULT Login(unsigned long aUIArg, LOGIN_PW_TYPE aLogin,
LOGIN_PW_TYPE aPassWord, unsigned long aFlags,
[out] unsigned long *aSessionId);
HRESULT Initialize();
HRESULT IsValid();
HRESULT IsValidSession([in] unsigned long aSession);
HRESULT SendMail([in] unsigned long aSession, [in] lpnsMapiMessage aMessage,
[in] short aRecipCount, [in, size_is(aRecipCount)] lpnsMapiRecipDesc aRecips,
[in] short aFileCount, [in, size_is(aFileCount)] lpnsMapiFileDesc aFiles,
[in] unsigned long aFlags, [in] unsigned long aReserved) ;
HRESULT SendDocuments( [in] unsigned long aSession,
[in] LPTSTR aDelimChar, [in] LPTSTR aFilePaths,
[in] LPTSTR aFileNames, [in] ULONG aFlags ) ;
HRESULT Logoff (unsigned long aSession);
HRESULT CleanUp();
};

View File

@@ -1,41 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corp.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s): Srilatha Moturi (srilatha@netscape.com)
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH=..\..\..
DIRS= build public src
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,49 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH=..\..\..\..
MODULE=msgMapi
XPIDL_MODULE=mapihook
XPIDLSRCS = \
.\nsIMapiRegistry.idl \
.\nsIMapiSupport.idl \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,70 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsISupports.idl"
interface nsIDOMWindow;
/**
* This interface provides support for registering Mozilla as the default
* Mail Client. This interface can also be used to get/set the user preference
* for the default Mail Client.
*
*/
[scriptable, uuid(c5be14ba-4e0a-4eec-a1b8-04363761d63c)]
interface nsIMapiRegistry: nsISupports {
/** This is set to TRUE if Mozilla is the default Application
*/
attribute boolean isDefaultMailClient;
/** This is set TRUE only once per session.
*/
readonly attribute boolean showDialog;
/** This will bring the dialog asking the user if he/she wants to set
* Mozilla as default Mail Client.
* Call this only if Mozilla is not the default Mail client
*/
void showMailIntegrationDialog(in nsIDOMWindow parentWindow);
};
%{C++
#define NS_IMAPIREGISTRY_CONTRACTID "@mozilla.org/mapiregistry;1"
#define NS_IMAPIREGISTRY_CLASSNAME "Mozilla MAPI Registry"
%}

View File

@@ -1,64 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsISupports.idl"
/**
* This interface provides support for registering Mozilla as a COM component
* for extending the use of Mail/News through Simple MAPI.
*
*/
[noscript, uuid(8967fed2-c8bb-11d5-a3e9-00b0d0f3baa7)]
interface nsIMapiSupport : nsISupports {
/** Initiates MAPI support
*/
void initializeMAPISupport();
/** Shuts down the MAPI support
*/
void shutdownMAPISupport();
};
%{C++
#define NS_IMAPISUPPORT_CONTRACTID "@mozilla.org/mapisupport;1"
#define NS_IMAPISUPPORT_CLASSNAME "Mozilla MAPI Support"
%}

View File

@@ -1,323 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika <kkhandrika@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#undef _UNICODE
#undef UNICODE
#include <objbase.h>
#include "nsString.h"
#include "Registry.h"
#define MAPI_PROXY_DLL_NAME "MapiProxy.dll"
#define MAPI_STARTUP_ARG " /MAPIStartUp"
#define MAX_SIZE 2048
// Size of a CLSID as a string
const int CLSID_STRING_SIZE = 39;
// Proxy/Stub Dll Routines
typedef HRESULT (__stdcall ProxyServer)();
// Convert a CLSID to a char string.
BOOL CLSIDtochar(const CLSID& clsid, char* szCLSID,
int length)
{
LPOLESTR wszCLSID = NULL;
// Get CLSID
HRESULT hr = StringFromCLSID(clsid, &wszCLSID);
if (FAILED(hr))
return FALSE;
// Covert from wide characters to non-wide.
wcstombs(szCLSID, wszCLSID, length);
// Free memory.
CoTaskMemFree(wszCLSID);
return TRUE;
}
// Create a key and set its value.
BOOL setKeyAndValue(nsCAutoString keyName, const char* subKey,
const char* theValue)
{
HKEY hKey;
BOOL retValue = TRUE;
nsCAutoString theKey(keyName);
if (subKey != NULL)
{
theKey += "\\";
theKey += subKey;
}
// Create and open key and subkey.
long lResult = RegCreateKeyEx(HKEY_CLASSES_ROOT, theKey.get(),
0, NULL, REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, NULL, &hKey, NULL);
if (lResult != ERROR_SUCCESS)
return FALSE ;
// Set the Value.
if (theValue != NULL)
{
lResult = RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *)theValue,
strlen(theValue)+1);
if (lResult != ERROR_SUCCESS)
retValue = FALSE;
}
RegCloseKey(hKey);
return TRUE;
}
// Delete a key and all of its descendents.
LONG recursiveDeleteKey(HKEY hKeyParent, // Parent of key to delete
const char* lpszKeyChild) // Key to delete
{
// Open the child.
HKEY hKeyChild ;
LONG lRes = RegOpenKeyEx(hKeyParent, lpszKeyChild, 0,
KEY_ALL_ACCESS, &hKeyChild) ;
if (lRes != ERROR_SUCCESS)
{
return lRes ;
}
// Enumerate all of the decendents of this child.
FILETIME time ;
char szBuffer[MAX_SIZE] ;
DWORD dwSize = MAX_SIZE ;
while (RegEnumKeyEx(hKeyChild, 0, szBuffer, &dwSize, NULL,
NULL, NULL, &time) == S_OK)
{
// Delete the decendents of this child.
lRes = recursiveDeleteKey(hKeyChild, szBuffer) ;
if (lRes != ERROR_SUCCESS)
{
// Cleanup before exiting.
RegCloseKey(hKeyChild) ;
return lRes;
}
dwSize = MAX_SIZE;
}
// Close the child.
RegCloseKey(hKeyChild) ;
// Delete this child.
return RegDeleteKey(hKeyParent, lpszKeyChild) ;
}
void RegisterProxy()
{
HINSTANCE h = NULL;
ProxyServer *RegisterFunc = NULL;
char szModule[MAX_SIZE];
char *pTemp = NULL;
HMODULE hModule = GetModuleHandle(NULL);
DWORD dwResult = ::GetModuleFileName(hModule, szModule,
sizeof(szModule)/sizeof(char));
if (dwResult == 0)
return;
pTemp = strrchr(szModule, '\\');
if (pTemp == NULL)
return;
*pTemp = '\0';
nsCAutoString proxyPath(szModule);
proxyPath += "\\";
proxyPath += MAPI_PROXY_DLL_NAME;
h = LoadLibrary(proxyPath.get());
if (h == NULL)
return;
RegisterFunc = (ProxyServer *) GetProcAddress(h, "DllRegisterServer");
if (RegisterFunc)
RegisterFunc();
FreeLibrary(h);
}
void UnRegisterProxy()
{
HINSTANCE h = NULL;
ProxyServer *UnRegisterFunc = NULL;
char szModule[MAX_SIZE];
char *pTemp = NULL;
HMODULE hModule = GetModuleHandle(NULL);
DWORD dwResult = ::GetModuleFileName(hModule, szModule,
sizeof(szModule)/sizeof(char));
if (dwResult == 0)
return;
pTemp = strrchr(szModule, '\\');
if (pTemp == NULL)
return;
*pTemp = '\0';
nsCAutoString proxyPath(szModule);
proxyPath += "\\";
proxyPath += MAPI_PROXY_DLL_NAME;
h = LoadLibrary(proxyPath.get());
if (h == NULL)
return;
UnRegisterFunc = (ProxyServer *) GetProcAddress(h, "DllUnregisterServer");
if (UnRegisterFunc)
UnRegisterFunc();
FreeLibrary(h);
}
// Register the component in the registry.
HRESULT RegisterServer(const CLSID& clsid, // Class ID
const char* szFriendlyName, // Friendly Name
const char* szVerIndProgID, // Programmatic
const char* szProgID) // IDs
{
HMODULE hModule = GetModuleHandle(NULL);
char szModuleName[MAX_SIZE];
char szCLSID[CLSID_STRING_SIZE];
nsCAutoString independentProgId(szVerIndProgID);
nsCAutoString progId(szProgID);
DWORD dwResult = ::GetModuleFileName(hModule, szModuleName,
sizeof(szModuleName)/sizeof(char));
if (dwResult == 0)
return S_FALSE;
nsCAutoString moduleName(szModuleName);
nsCAutoString registryKey("CLSID\\");
moduleName += MAPI_STARTUP_ARG;
// Convert the CLSID into a char.
if (!CLSIDtochar(clsid, szCLSID, sizeof(szCLSID)))
return S_FALSE;
registryKey += szCLSID;
// Add the CLSID to the registry.
if (!setKeyAndValue(registryKey, NULL, szFriendlyName))
return S_FALSE;
if (!setKeyAndValue(registryKey, "LocalServer32", moduleName.get()))
return S_FALSE;
// Add the ProgID subkey under the CLSID key.
if (!setKeyAndValue(registryKey, "ProgID", szProgID))
return S_FALSE;
// Add the version-independent ProgID subkey under CLSID key.
if (!setKeyAndValue(registryKey, "VersionIndependentProgID", szVerIndProgID))
return S_FALSE;
// Add the version-independent ProgID subkey under HKEY_CLASSES_ROOT.
if (!setKeyAndValue(independentProgId, NULL, szFriendlyName))
return S_FALSE;
if (!setKeyAndValue(independentProgId, "CLSID", szCLSID))
return S_FALSE;
if (!setKeyAndValue(independentProgId, "CurVer", szProgID))
return S_FALSE;
// Add the versioned ProgID subkey under HKEY_CLASSES_ROOT.
if (!setKeyAndValue(progId, NULL, szFriendlyName))
return S_FALSE;
if (!setKeyAndValue(progId, "CLSID", szCLSID))
return S_FALSE;
RegisterProxy();
return S_OK;
}
LONG UnregisterServer(const CLSID& clsid, // Class ID
const char* szVerIndProgID, // Programmatic
const char* szProgID) // IDs
{
LONG lResult = S_OK;
// Convert the CLSID into a char.
char szCLSID[CLSID_STRING_SIZE];
if (!CLSIDtochar(clsid, szCLSID, sizeof(szCLSID)))
return S_FALSE;
UnRegisterProxy();
nsCAutoString registryKey("CLSID\\");
registryKey += szCLSID;
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, registryKey.get());
if (lResult == ERROR_SUCCESS || lResult == ERROR_FILE_NOT_FOUND)
return lResult;
registryKey += "\\LocalServer32";
// Delete only the path for this server.
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, registryKey.get());
if (lResult != ERROR_SUCCESS && lResult != ERROR_FILE_NOT_FOUND)
return lResult;
// Delete the version-independent ProgID Key.
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, szVerIndProgID);
if (lResult != ERROR_SUCCESS && lResult != ERROR_FILE_NOT_FOUND)
return lResult;
lResult = recursiveDeleteKey(HKEY_CLASSES_ROOT, szProgID);
return lResult;
}

View File

@@ -1,56 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Krishna Mohan Khandrika <kkhandrika@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef _REGISTRY_H_
#define _REGISTRY_H_
#include <objbase.h>
// This function will register a component in the Registry.
HRESULT RegisterServer(const CLSID& clsid,
const char* szFriendlyName,
const char* szVerIndProgID,
const char* szProgID) ;
// This function will unregister a component.
HRESULT UnregisterServer(const CLSID& clsid,
const char* szVerIndProgID,
const char* szProgID) ;
#endif

View File

@@ -1,107 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH=..\..\..\..
MODULE = msgMapi
MAKE_OBJ_TYPE = DLL
LIBRARY_NAME=$(MODULE)
MODULE_NAME = $(MODULE)
REQUIRES = xpcom \
string \
MapiProxy \
appshell \
windowwatcher \
dom \
profile \
msgbase \
pref \
msgbaseutil \
msgcompo \
mailnews \
necko \
intl \
editor \
msgdb \
uriloader \
appstartup \
$(NULL)
include <$(DEPTH)\config\config.mak>
############################################################################
LCFLAGS=-DUNICODE -D_UNICODE
OBJS= \
..\build\$(OBJDIR)\msgMapi_i.obj \
.\$(OBJDIR)\msgMapiFactory.obj \
.\$(OBJDIR)\msgMapiHook.obj \
.\$(OBJDIR)\msgMapiImp.obj \
.\$(OBJDIR)\msgMapiMain.obj \
.\$(OBJDIR)\msgMapiSupport.obj \
.\$(OBJDIR)\nsMapiRegistry.obj \
.\$(OBJDIR)\nsMapiRegistryUtils.obj \
.\$(OBJDIR)\Registry.obj \
$(NULL)
LLIBS= \
$(DIST)\lib\xpcom.lib \
$(DIST)\lib\msgbsutl.lib \
$(LIBNSPR) \
$(NULL)
WIN_LIBS= \
ole32.lib \
$(NULL)
EXPORTS= \
msgMapiFactory.h \
msgMapiHook.h \
msgMapiImp.h \
msgMapiMain.h \
msgMapiSupport.h \
nsMapiRegistry.h \
nsMapiRegistryUtils.h \
Registry.h \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,118 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#undef UNICODE
#undef _UNICODE
#include "msgMapiFactory.h"
#include "msgMapiImp.h"
#include "msgMapi.h"
CMapiFactory ::CMapiFactory()
: m_cRef(1)
{
}
CMapiFactory::~CMapiFactory()
{
}
STDMETHODIMP CMapiFactory::QueryInterface(const IID& aIid, void** aPpv)
{
if ((aIid == IID_IUnknown) || (aIid == IID_IClassFactory))
{
*aPpv = static_cast<IClassFactory*>(this);
}
else
{
*aPpv = nsnull;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(*aPpv)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) CMapiFactory::AddRef()
{
return (PR_AtomicIncrement(&m_cRef));
}
STDMETHODIMP_(ULONG) CMapiFactory::Release()
{
PRInt32 temp;
temp = PR_AtomicDecrement(&m_cRef);
if (m_cRef == 0)
{
delete this;
return 0;
}
return temp;
}
STDMETHODIMP CMapiFactory::CreateInstance(IUnknown* aUnknownOuter,
const IID& aIid,
void** aPpv)
{
// Cannot aggregate.
if (aUnknownOuter != nsnull)
{
return CLASS_E_NOAGGREGATION ;
}
// Create component.
CMapiImp* pImp = new CMapiImp();
if (pImp == nsnull)
{
return E_OUTOFMEMORY ;
}
// Get the requested interface.
HRESULT hr = pImp->QueryInterface(aIid, aPpv);
// Release the IUnknown pointer.
// (If QueryInterface failed, component will delete itself.)
pImp->Release();
return hr;
}
STDMETHODIMP CMapiFactory::LockServer(PRBool aLock)
{
return S_OK ;
}

View File

@@ -1,69 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MSG_MAPI_FACTORY_H
#define MSG_MAPI_FACTORY_H
#include <windows.h>
#include <objbase.h>
#include "nspr.h"
class CMapiFactory : public IClassFactory
{
public :
// IUnknown
STDMETHODIMP QueryInterface (REFIID aIid, void** aPpv);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IClassFactory
STDMETHODIMP CreateInstance (LPUNKNOWN aUnkOuter, REFIID aIid, void **aPpv);
STDMETHODIMP LockServer (BOOL aLock);
CMapiFactory ();
~CMapiFactory ();
private :
PRInt32 m_cRef;
};
#endif // MSG_MAPI_FACTORY_H

View File

@@ -1,777 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
* Contributor(s): Srilatha Moturi (srilatha@netscape.com)
* Contributor(s): Rajiv Dayal (rdayal@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#define MAPI_STARTUP_ARG "/MAPIStartUp"
#define MAPI_STARTUP_ARG "/MAPIStartUp"
#include <mapidefs.h>
#include <mapi.h>
#include <tchar.h>
#include "nsCOMPtr.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsISupports.h"
#include "nsIPromptService.h"
#include "nsAppShellCIDs.h"
#include "nsIDOMWindowInternal.h"
#include "nsIAppShellService.h"
#include "nsINativeAppSupport.h"
#include "nsICmdLineService.h"
#include "nsIProfileInternal.h"
#include "nsIMsgAccountManager.h"
#include "nsIDOMWindowInternal.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "nsMsgBaseCID.h"
#include "nsIStringBundle.h"
#include "nsIPref.h"
#include "nsString.h"
#include "nsIMsgAttachment.h"
#include "nsIMsgCompFields.h"
#include "nsIMsgComposeParams.h"
#include "nsIMsgCompose.h"
#include "nsMsgCompCID.h"
#include "nsIMsgSend.h"
#include "nsIProxyObjectManager.h"
#include "nsIMsgComposeService.h"
#include "nsProxiedService.h"
#include "nsSpecialSystemDirectory.h"
#include "nsMsgI18N.h"
#include "msgMapi.h"
#include "msgMapiHook.h"
#include "msgMapiSupport.h"
#include "msgMapiMain.h"
#include "nsNetUtil.h"
static NS_DEFINE_CID(kCmdLineServiceCID, NS_COMMANDLINE_SERVICE_CID);
class nsMAPISendListener : public nsIMsgSendListener
{
public:
virtual ~nsMAPISendListener() { }
// nsISupports interface
NS_DECL_ISUPPORTS
/* void OnStartSending (in string aMsgID, in PRUint32 aMsgSize); */
NS_IMETHOD OnStartSending(const char *aMsgID, PRUint32 aMsgSize) { return NS_OK; }
/* void OnProgress (in string aMsgID, in PRUint32 aProgress, in PRUint32 aProgressMax); */
NS_IMETHOD OnProgress(const char *aMsgID, PRUint32 aProgress, PRUint32 aProgressMax) { return NS_OK;}
/* void OnStatus (in string aMsgID, in wstring aMsg); */
NS_IMETHOD OnStatus(const char *aMsgID, const PRUnichar *aMsg) { return NS_OK;}
/* void OnStopSending (in string aMsgID, in nsresult aStatus, in wstring aMsg, in nsIFileSpec returnFileSpec); */
NS_IMETHOD OnStopSending(const char *aMsgID, nsresult aStatus, const PRUnichar *aMsg,
nsIFileSpec *returnFileSpec) {
m_done = PR_TRUE;
HANDLE hEvent = CreateEvent (NULL, FALSE, FALSE, (LPCTSTR) MAPI_SENDCOMPLETE_EVENT) ;
SetEvent (hEvent) ;
CloseHandle (hEvent) ;
return NS_OK ;
}
/* void OnSendNotPerformed */
NS_IMETHOD OnSendNotPerformed(const char *aMsgID, nsresult aStatus)
{
return OnStopSending(aMsgID, aStatus, nsnull, nsnull) ;
}
/* void OnGetDraftFolderURI (); */
NS_IMETHOD OnGetDraftFolderURI(const char *aFolderURI) {return NS_OK;}
static nsresult CreateMAPISendListener( nsIMsgSendListener **ppListener);
PRBool IsDone() { return m_done ; }
protected :
nsMAPISendListener() {
NS_INIT_REFCNT();
m_done = PR_FALSE;
}
PRBool m_done;
};
NS_IMPL_THREADSAFE_ISUPPORTS1(nsMAPISendListener, nsIMsgSendListener)
nsresult nsMAPISendListener::CreateMAPISendListener( nsIMsgSendListener **ppListener)
{
NS_ENSURE_ARG_POINTER(ppListener) ;
*ppListener = new nsMAPISendListener();
if (! *ppListener)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(*ppListener);
return NS_OK;
}
PRBool nsMapiHook::isMapiService = PR_FALSE;
PRBool nsMapiHook::Initialize()
{
nsresult rv;
nsCOMPtr<nsINativeAppSupport> native;
nsCOMPtr<nsICmdLineService> cmdLineArgs(do_GetService(kCmdLineServiceCID, &rv));
if (NS_FAILED(rv)) return PR_FALSE;
nsCOMPtr<nsIAppShellService> appShell (do_GetService( "@mozilla.org/appshell/appShellService;1", &rv));
if (NS_FAILED(rv)) return PR_FALSE;
rv = appShell->GetNativeAppSupport( getter_AddRefs( native ));
if (NS_FAILED(rv)) return PR_FALSE;
rv = native->EnsureProfile(cmdLineArgs);
if (NS_FAILED(rv)) return PR_FALSE;
return PR_TRUE;
}
void nsMapiHook::CleanUp()
{
// This routine will be fully implemented in future
// to cleanup mapi related stuff inside mozilla code.
}
PRBool nsMapiHook::DisplayLoginDialog(PRBool aLogin, PRUnichar **aUsername, \
PRUnichar **aPassword)
{
nsresult rv;
PRBool btnResult = PR_FALSE;
nsCOMPtr<nsIAppShellService> appShell(do_GetService( "@mozilla.org/appshell/appShellService;1", &rv));
if (NS_FAILED(rv) || !appShell) return PR_FALSE;
nsCOMPtr<nsIPromptService> dlgService(do_GetService("@mozilla.org/embedcomp/prompt-service;1", &rv));
if (NS_SUCCEEDED(rv) && dlgService)
{
nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv));
if (NS_FAILED(rv) || !bundleService) return PR_FALSE;
nsCOMPtr<nsIStringBundle> bundle;
rv = bundleService->CreateBundle(MAPI_PROPERTIES_CHROME, getter_AddRefs(bundle));
if (NS_FAILED(rv) || !bundle) return PR_FALSE;
nsCOMPtr<nsIStringBundle> brandBundle;
rv = bundleService->CreateBundle(
"chrome://global/locale/brand.properties",
getter_AddRefs(brandBundle));
if (NS_FAILED(rv)) return PR_FALSE;
nsXPIDLString brandName;
rv = brandBundle->GetStringFromName(
NS_LITERAL_STRING("brandShortName").get(),
getter_Copies(brandName));
if (NS_FAILED(rv)) return PR_FALSE;
nsXPIDLString loginTitle;
const PRUnichar *brandStrings[] = { brandName.get() };
NS_NAMED_LITERAL_STRING(loginTitlePropertyTag, "loginTitle");
const PRUnichar *dTitlePropertyTag = loginTitlePropertyTag.get();
rv = bundle->FormatStringFromName(dTitlePropertyTag, brandStrings, 1,
getter_Copies(loginTitle));
if (NS_FAILED(rv)) return PR_FALSE;
if (aLogin)
{
nsXPIDLString loginText;
rv = bundle->GetStringFromName(NS_LITERAL_STRING("loginTextwithName").get(),
getter_Copies(loginText));
if (NS_FAILED(rv) || !loginText) return PR_FALSE;
rv = dlgService->PromptUsernameAndPassword(nsnull, loginTitle,
loginText, aUsername, aPassword,
nsnull, PR_FALSE, &btnResult);
}
else
{
//nsString loginString;
nsXPIDLString loginText;
const PRUnichar *userNameStrings[] = { *aUsername };
NS_NAMED_LITERAL_STRING(loginTextPropertyTag, "loginText");
const PRUnichar *dpropertyTag = loginTextPropertyTag.get();
rv = bundle->FormatStringFromName(dpropertyTag, userNameStrings, 1,
getter_Copies(loginText));
if (NS_FAILED(rv)) return PR_FALSE;
rv = dlgService->PromptPassword(nsnull, loginTitle, loginText,
aPassword, nsnull, PR_FALSE, &btnResult);
}
}
return btnResult;
}
PRBool nsMapiHook::VerifyUserName(const PRUnichar *aUsername, char **aIdKey)
{
nsresult rv;
if (aUsername == nsnull)
return PR_FALSE;
nsCOMPtr<nsIMsgAccountManager> accountManager(do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv));
if (NS_FAILED(rv)) return PR_FALSE;
nsCOMPtr<nsISupportsArray> identities;
rv = accountManager->GetAllIdentities(getter_AddRefs(identities));
if (NS_FAILED(rv)) return PR_FALSE;
PRUint32 numIndentities;
identities->Count(&numIndentities);
for (PRUint32 i = 0; i < numIndentities; i++)
{
// convert supports->Identity
nsCOMPtr<nsISupports> thisSupports;
rv = identities->GetElementAt(i, getter_AddRefs(thisSupports));
if (NS_FAILED(rv)) continue;
nsCOMPtr<nsIMsgIdentity> thisIdentity(do_QueryInterface(thisSupports, &rv));
if (NS_SUCCEEDED(rv) && thisIdentity)
{
nsXPIDLCString email;
rv = thisIdentity->GetEmail(getter_Copies(email));
if (NS_FAILED(rv)) continue;
// get the username from the email and compare with the username
nsCAutoString aEmail(email.get());
PRInt32 index = aEmail.FindChar('@');
if (index != -1)
aEmail.Truncate(index);
if (nsDependentString(aUsername) == NS_ConvertASCIItoUCS2(aEmail)) // == overloaded
return NS_SUCCEEDED(thisIdentity->GetKey(aIdKey));
}
}
return PR_FALSE;
}
PRBool
nsMapiHook::IsBlindSendAllowed()
{
PRBool enabled = PR_FALSE;
PRBool warn = PR_TRUE;
nsCOMPtr<nsIPref> prefs = do_GetService(NS_PREF_CONTRACTID);
if (prefs) {
prefs->GetBoolPref(PREF_MAPI_WARN_PRIOR_TO_BLIND_SEND,&warn);
prefs->GetBoolPref(PREF_MAPI_BLIND_SEND_ENABLED,&enabled);
}
if (!enabled)
return PR_FALSE;
if (!warn)
return PR_TRUE; // Everything is okay.
nsresult rv;
nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv));
if (NS_FAILED(rv) || !bundleService) return PR_FALSE;
nsCOMPtr<nsIStringBundle> bundle;
rv = bundleService->CreateBundle(MAPI_PROPERTIES_CHROME, getter_AddRefs(bundle));
if (NS_FAILED(rv) || !bundle) return PR_FALSE;
nsXPIDLString warningMsg;
rv = bundle->GetStringFromName(NS_LITERAL_STRING("mapiBlindSendWarning").get(),
getter_Copies(warningMsg));
if (NS_FAILED(rv)) return PR_FALSE;
nsXPIDLString dontShowAgainMessage;
rv = bundle->GetStringFromName(NS_LITERAL_STRING("mapiBlindSendDontShowAgain").get(),
getter_Copies(dontShowAgainMessage));
if (NS_FAILED(rv)) return PR_FALSE;
nsCOMPtr<nsIPromptService> dlgService(do_GetService("@mozilla.org/embedcomp/prompt-service;1", &rv));
if (NS_FAILED(rv) || !dlgService) return PR_FALSE;
PRBool continueToWarn = PR_TRUE;
PRBool okayToContinue = PR_FALSE;
dlgService->ConfirmCheck(nsnull, nsnull, warningMsg, dontShowAgainMessage, &continueToWarn, &okayToContinue);
if (!continueToWarn && okayToContinue && prefs)
prefs->SetBoolPref(PREF_MAPI_WARN_PRIOR_TO_BLIND_SEND,PR_FALSE);
return okayToContinue;
}
// this is used for Send without UI
nsresult nsMapiHook::BlindSendMail (unsigned long aSession, nsIMsgCompFields * aCompFields)
{
nsresult rv = NS_OK ;
if (!IsBlindSendAllowed())
return NS_ERROR_FAILURE;
/** create nsIMsgComposeParams obj and other fields to populate it **/
// get parent window
nsCOMPtr<nsIAppShellService> appService = do_GetService( "@mozilla.org/appshell/appShellService;1", &rv);
if (NS_FAILED(rv)|| (!appService) ) return rv ;
nsCOMPtr<nsIDOMWindowInternal> hiddenWindow;
rv = appService->GetHiddenDOMWindow(getter_AddRefs(hiddenWindow));
if ( NS_FAILED(rv) ) return rv ;
// smtp password and Logged in used IdKey from MapiConfig (session obj)
nsMAPIConfiguration * pMapiConfig = nsMAPIConfiguration::GetMAPIConfiguration() ;
if (!pMapiConfig) return NS_ERROR_FAILURE ; // get the singelton obj
PRUnichar * password = pMapiConfig->GetPassword(aSession) ;
// password
nsCAutoString smtpPassword ;
smtpPassword.AssignWithConversion (password) ;
// Id key
char * MsgIdKey = pMapiConfig->GetIdKey(aSession) ;
// get the MsgIdentity for the above key using AccountManager
nsCOMPtr <nsIMsgAccountManager> accountManager = do_GetService (NS_MSGACCOUNTMANAGER_CONTRACTID) ;
if (NS_FAILED(rv) || (!accountManager) ) return rv ;
nsCOMPtr <nsIMsgIdentity> pMsgId ;
rv = accountManager->GetIdentity (MsgIdKey, getter_AddRefs(pMsgId)) ;
if (NS_FAILED(rv) ) return rv ;
// create a send listener to get back the send status
nsCOMPtr <nsIMsgSendListener> sendListener ;
rv = nsMAPISendListener::CreateMAPISendListener(getter_AddRefs(sendListener)) ;
if (NS_FAILED(rv) || (!sendListener) ) return rv;
// create the compose params object
nsCOMPtr<nsIMsgComposeParams> pMsgComposeParams (do_CreateInstance(NS_MSGCOMPOSEPARAMS_CONTRACTID, &rv));
if (NS_FAILED(rv) || (!pMsgComposeParams) ) return rv ;
// populate the compose params
pMsgComposeParams->SetType(nsIMsgCompType::New);
pMsgComposeParams->SetFormat(nsIMsgCompFormat::Default);
pMsgComposeParams->SetIdentity(pMsgId);
pMsgComposeParams->SetComposeFields(aCompFields);
pMsgComposeParams->SetSendListener(sendListener) ;
pMsgComposeParams->SetSmtpPassword(smtpPassword.get());
// create the nsIMsgCompose object to send the object
nsCOMPtr<nsIMsgCompose> pMsgCompose (do_CreateInstance(NS_MSGCOMPOSE_CONTRACTID, &rv));
if (NS_FAILED(rv) || (!pMsgCompose) ) return rv ;
/** initialize nsIMsgCompose, Send the message, wait for send completion response **/
rv = pMsgCompose->Initialize(hiddenWindow, pMsgComposeParams) ;
if (NS_FAILED(rv)) return rv ;
pMsgCompose->SendMsg(nsIMsgSend::nsMsgDeliverNow, pMsgId, nsnull) ;
if (NS_FAILED(rv)) return rv ;
// assign to interface pointer from nsCOMPtr to facilitate typecast below
nsIMsgSendListener * pSendListener = sendListener ;
// we need to wait here to make sure that we return only after send is completed
// so we will have a event loop here which will process the events till the Send IsDone.
nsCOMPtr<nsIEventQueueService> pEventQService = do_GetService(NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
nsCOMPtr<nsIEventQueue> eventQueue;
pEventQService->GetThreadEventQueue(NS_CURRENT_THREAD,getter_AddRefs(eventQueue));
while ( !((nsMAPISendListener *) pSendListener)->IsDone() )
eventQueue->ProcessPendingEvents();
return rv ;
}
// this is used to populate comp fields with Unicode data
nsresult nsMapiHook::PopulateCompFields(lpnsMapiMessage aMessage,
nsIMsgCompFields * aCompFields)
{
nsresult rv = NS_OK ;
if (aMessage->lpOriginator)
{
PRUnichar * From = aMessage->lpOriginator->lpszAddress ;
aCompFields->SetFrom (From) ;
}
nsAutoString To ;
nsAutoString Cc ;
nsAutoString Bcc ;
nsAutoString Comma ;
Comma.AssignWithConversion(",");
if (aMessage->lpRecips)
{
for (int i=0 ; i < (int) aMessage->nRecipCount ; i++)
{
if (aMessage->lpRecips[i].lpszAddress)
{
switch (aMessage->lpRecips[i].ulRecipClass)
{
case MAPI_TO :
if (To.Length() > 0)
To += Comma ;
To += (PRUnichar *) aMessage->lpRecips[i].lpszAddress ;
break ;
case MAPI_CC :
if (Cc.Length() > 0)
Cc += Comma ;
Cc += (PRUnichar *) aMessage->lpRecips[i].lpszAddress ;
break ;
case MAPI_BCC :
if (Bcc.Length() > 0)
Bcc += Comma ;
Bcc += (PRUnichar *) aMessage->lpRecips[i].lpszAddress ;
break ;
}
}
}
}
// set To, Cc, Bcc
aCompFields->SetTo (To.get()) ;
aCompFields->SetCc (Cc.get()) ;
aCompFields->SetBcc (Bcc.get()) ;
// set subject
if (aMessage->lpszSubject)
{
PRUnichar * Subject = aMessage->lpszSubject ;
aCompFields->SetSubject(Subject) ;
}
// handle attachments as File URL
rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, PR_TRUE) ;
if (NS_FAILED(rv)) return rv ;
// set body
if (aMessage->lpszNoteText)
{
PRUnichar * Body = aMessage->lpszNoteText ;
rv = aCompFields->SetBody(Body) ;
}
#ifdef RAJIV_DEBUG
// testing what all was set in CompFields
printf ("To : %S \n", To.get()) ;
printf ("CC : %S \n", Cc.get() ) ;
printf ("BCC : %S \n", Bcc.get() ) ;
#endif
return rv ;
}
nsresult nsMapiHook::HandleAttachments (nsIMsgCompFields * aCompFields, PRInt32 aFileCount,
lpnsMapiFileDesc aFiles, BOOL aIsUnicode)
{
nsresult rv = NS_OK ;
nsCAutoString Attachments ;
nsCAutoString TempFiles ;
nsCOMPtr <nsILocalFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
if (NS_FAILED(rv) || (!pFile) ) return rv ;
for (int i=0 ; i < aFileCount ; i++)
{
if (aFiles[i].lpszPathName)
{
// check if attachment exists
if (aIsUnicode)
pFile->InitWithUnicodePath (aFiles[i].lpszPathName) ;
else
pFile->InitWithPath ((char *) aFiles[i].lpszPathName) ;
PRBool bExist ;
rv = pFile->Exists(&bExist) ;
if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;
// create Msg attachment object
nsCOMPtr<nsIMsgAttachment> attachment = do_CreateInstance(NS_MSGATTACHMENT_CONTRACTID, &rv);
if (NS_FAILED(rv) || (!attachment) ) return rv ;
// set url
nsXPIDLCString pURL ;
NS_GetURLSpecFromFile(pFile, getter_Copies(pURL));
attachment->SetUrl(pURL) ;
if (aFiles[i].lpszFileName)
{
if (! aIsUnicode)
{
nsAutoString realFileName ;
realFileName.AssignWithConversion ((char *) aFiles[i].lpszFileName) ;
attachment->SetName(realFileName.get()) ;
// attachment->SetName( (nsDependentString(aFiles[i].lpszFileName)).get() );
}
else
attachment->SetName(aFiles[i].lpszFileName) ;
}
attachment->SetTemporary(PR_FALSE) ;
rv = aCompFields->AddAttachment (attachment);
}
}
return rv ;
}
// this is used to convert non Unicode data and then populate comp fields
nsresult nsMapiHook::PopulateCompFieldsWithConversion(lpnsMapiMessage aMessage,
nsIMsgCompFields * aCompFields)
{
nsresult rv = NS_OK ;
if (aMessage->lpOriginator)
{
nsAutoString From ;
From.AssignWithConversion((char *) aMessage->lpOriginator->lpszAddress);
aCompFields->SetFrom (From.get()) ;
}
nsAutoString To ;
nsAutoString Cc ;
nsAutoString Bcc ;
nsAutoString Comma ;
Comma.AssignWithConversion(",");
if (aMessage->lpRecips)
{
for (int i=0 ; i < (int) aMessage->nRecipCount ; i++)
{
if (aMessage->lpRecips[i].lpszAddress)
{
switch (aMessage->lpRecips[i].ulRecipClass)
{
case MAPI_TO :
if (To.Length() > 0)
To += Comma ;
To.AppendWithConversion ((char *) aMessage->lpRecips[i].lpszAddress);
break ;
case MAPI_CC :
if (Cc.Length() > 0)
Cc += Comma ;
Cc.AppendWithConversion ((char *) aMessage->lpRecips[i].lpszAddress);
break ;
case MAPI_BCC :
if (Bcc.Length() > 0)
Bcc += Comma ;
Bcc.AppendWithConversion ((char *) aMessage->lpRecips[i].lpszAddress) ;
break ;
}
}
}
}
// set To, Cc, Bcc
aCompFields->SetTo (To.get()) ;
aCompFields->SetCc (Cc.get()) ;
aCompFields->SetBcc (Bcc.get()) ;
nsCAutoString platformCharSet;
// set subject
if (aMessage->lpszSubject)
{
nsAutoString Subject ;
if (platformCharSet.IsEmpty())
platformCharSet.Assign(nsMsgI18NFileSystemCharset());
rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszSubject, Subject);
if (NS_FAILED(rv)) return rv ;
aCompFields->SetSubject(Subject.get()) ;
}
// handle attachments as File URL
rv = HandleAttachments (aCompFields, aMessage->nFileCount, aMessage->lpFiles, PR_FALSE) ;
if (NS_FAILED(rv)) return rv ;
// set body
if (aMessage->lpszNoteText)
{
nsAutoString Body ;
if (platformCharSet.IsEmpty())
platformCharSet.Assign(nsMsgI18NFileSystemCharset());
rv = ConvertToUnicode(platformCharSet.get(), (char *) aMessage->lpszNoteText, Body);
if (NS_FAILED(rv)) return rv ;
rv = aCompFields->SetBody(Body.get()) ;
}
#ifdef RAJIV_DEBUG
// testing what all was set in CompFields
printf ("To : %S \n", To.get()) ;
printf ("CC : %S \n", Cc.get() ) ;
printf ("BCC : %S \n", Bcc.get() ) ;
#endif
return rv ;
}
// this is used to populate the docs as attachments in the Comp fields for Send Documents
nsresult nsMapiHook::PopulateCompFieldsForSendDocs(nsIMsgCompFields * aCompFields, ULONG aFlags,
PRUnichar * aDelimChar, PRUnichar * aFilePaths)
{
nsAutoString strDelimChars ;
nsString strFilePaths;
nsresult rv = NS_OK ;
if (aFlags & MAPI_UNICODE)
{
if (aDelimChar)
strDelimChars.Assign (aDelimChar) ;
if (aFilePaths)
strFilePaths.Assign (aFilePaths) ;
}
else
{
if (aDelimChar)
strDelimChars.AssignWithConversion ((char*) aDelimChar) ;
if (aFilePaths)
strFilePaths.AssignWithConversion ((char *) aFilePaths) ;
}
// check for comma in filename
if (strDelimChars.Find (",") == kNotFound) // if comma is not in the delimiter specified by user
{
if (strFilePaths.Find(",") != kNotFound) // if comma found in filenames return error
return NS_ERROR_FILE_INVALID_PATH ;
}
nsCString Attachments ;
// only 1 file is to be sent, no delim specified
if ((!strDelimChars.Length()) && (strFilePaths.Length()>0))
{
nsCOMPtr <nsILocalFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
if (NS_FAILED(rv) || (!pFile) ) return rv ;
pFile->InitWithUnicodePath (strFilePaths.get()) ;
PRBool bExist ;
rv = pFile->Exists(&bExist) ;
if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;
nsXPIDLCString pURL ;
NS_GetURLSpecFromFile(pFile, getter_Copies(pURL));
if (pURL)
Attachments.Assign(pURL) ;
// set attachments for comp field and return
rv = aCompFields->SetAttachments (Attachments.get());
return rv ;
}
// multiple files to be sent, delim specified
nsCOMPtr <nsILocalFile> pFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv) ;
if (NS_FAILED(rv) || (!pFile) ) return rv ;
PRInt32 offset = 0 ;
PRInt32 FilePathsLen = strFilePaths.Length() ;
if (FilePathsLen)
{
PRUnichar * newFilePaths = (PRUnichar *) strFilePaths.get() ;
while (offset != kNotFound)
{
nsString RemainingPaths ;
RemainingPaths.Assign(newFilePaths) ;
offset = RemainingPaths.Find (strDelimChars) ;
if (offset != kNotFound)
{
RemainingPaths.SetLength (offset) ;
if ((offset + strDelimChars.Length()) < FilePathsLen)
newFilePaths += offset + strDelimChars.Length() ;
}
pFile->InitWithUnicodePath (RemainingPaths.get()) ;
#ifdef RAJIV_DEBUG
printf ("File : %S \n", RemainingPaths.get()) ;
#endif
PRBool bExist ;
rv = pFile->Exists(&bExist) ;
if (NS_FAILED(rv) || (!bExist) ) return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ;
nsXPIDLCString pURL ;
NS_GetURLSpecFromFile(pFile, getter_Copies(pURL));
if (pURL)
{
if (Attachments.Length() > 0)
Attachments.Append(",") ;
Attachments.Append(pURL) ;
}
}
rv = aCompFields->SetAttachments (Attachments.get());
}
return rv ;
}
// this used for Send with UI
nsresult nsMapiHook::ShowComposerWindow (unsigned long aSession, nsIMsgCompFields * aCompFields)
{
nsresult rv = NS_OK ;
// create a send listener to get back the send status
nsCOMPtr <nsIMsgSendListener> sendListener ;
rv = nsMAPISendListener::CreateMAPISendListener(getter_AddRefs(sendListener)) ;
if (NS_FAILED(rv) || (!sendListener) ) return rv ;
// create the compose params object
nsCOMPtr<nsIMsgComposeParams> pMsgComposeParams (do_CreateInstance(NS_MSGCOMPOSEPARAMS_CONTRACTID, &rv));
if (NS_FAILED(rv) || (!pMsgComposeParams) ) return rv ;
// populate the compose params
pMsgComposeParams->SetType(nsIMsgCompType::New);
pMsgComposeParams->SetFormat(nsIMsgCompFormat::Default);
pMsgComposeParams->SetComposeFields(aCompFields);
pMsgComposeParams->SetSendListener(sendListener) ;
/** get the nsIMsgComposeService object to open the compose window **/
nsCOMPtr <nsIMsgComposeService> compService = do_GetService (NS_MSGCOMPOSESERVICE_CONTRACTID) ;
if (NS_FAILED(rv)|| (!compService) ) return rv ;
rv = compService->OpenComposeWindowWithParams(nsnull, pMsgComposeParams) ;
if (NS_FAILED(rv)) return rv ;
return rv ;
}

View File

@@ -1,66 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MSG_MAPI_HOOK_H_
#define MSG_MAPI_HOOK_H_
#include "prtypes.h"
class nsMapiHook
{
public :
static PRBool Initialize();
static PRBool DisplayLoginDialog(PRBool aLogin, PRUnichar **aUsername,
PRUnichar **aPassword);
static PRBool VerifyUserName(const PRUnichar *aUsername, char **aIdKey);
static PRBool IsBlindSendAllowed () ;
static nsresult BlindSendMail (unsigned long aSession, nsIMsgCompFields * aCompFields) ;
static nsresult ShowComposerWindow (unsigned long aSession, nsIMsgCompFields * aCompFields) ;
static nsresult PopulateCompFields(lpnsMapiMessage aMessage, nsIMsgCompFields * aCompFields) ;
static nsresult PopulateCompFieldsWithConversion(lpnsMapiMessage aMessage,
nsIMsgCompFields * aCompFields) ;
static nsresult PopulateCompFieldsForSendDocs(nsIMsgCompFields * aCompFields,
ULONG aFlags, LPTSTR aDelimChar, LPTSTR aFilePaths) ;
static nsresult HandleAttachments (nsIMsgCompFields * aCompFields, PRInt32 aFileCount,
lpnsMapiFileDesc aFiles, BOOL aIsUnicode) ;
static void CleanUp();
static PRBool isMapiService;
};
#endif // MSG_MAPI_HOOK_H_

View File

@@ -1,266 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
* Contributor(s): Rajiv Dayal (rdayal@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <mapidefs.h>
#include <mapi.h>
#include "msgMapi.h"
#include "msgMapiImp.h"
#include "msgMapiFactory.h"
#include "msgMapiMain.h"
#include "nsMsgCompFields.h"
#include "msgMapiHook.h"
#include "nsString.h"
#include "nsCOMPtr.h"
#include "nsISupports.h"
#include "nsMsgCompCID.h"
CMapiImp::CMapiImp()
: m_cRef(1)
{
m_Lock = PR_NewLock();
}
CMapiImp::~CMapiImp()
{
if (m_Lock)
PR_DestroyLock(m_Lock);
}
STDMETHODIMP CMapiImp::QueryInterface(const IID& aIid, void** aPpv)
{
if (aIid == IID_IUnknown)
{
*aPpv = static_cast<nsIMapi*>(this);
}
else if (aIid == IID_nsIMapi)
{
*aPpv = static_cast<nsIMapi*>(this);
}
else
{
*aPpv = nsnull;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>(*aPpv)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) CMapiImp::AddRef()
{
return PR_AtomicIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG) CMapiImp::Release()
{
PRInt32 temp;
temp = PR_AtomicDecrement(&m_cRef);
if (m_cRef == 0)
{
delete this;
return 0;
}
return temp;
}
STDMETHODIMP CMapiImp::IsValid()
{
return S_OK;
}
STDMETHODIMP CMapiImp::IsValidSession(unsigned long aSession)
{
nsMAPIConfiguration *pConfig = nsMAPIConfiguration::GetMAPIConfiguration();
if (pConfig && pConfig->IsSessionValid(aSession))
return S_OK;
return E_FAIL;
}
STDMETHODIMP CMapiImp::Initialize()
{
HRESULT hr = E_FAIL;
if (!m_Lock)
return E_FAIL;
PR_Lock(m_Lock);
// Initialize MAPI Configuration
nsMAPIConfiguration *pConfig = nsMAPIConfiguration::GetMAPIConfiguration();
if (pConfig != nsnull)
if (nsMapiHook::Initialize())
hr = S_OK;
PR_Unlock(m_Lock);
return hr;
}
STDMETHODIMP CMapiImp::Login(unsigned long aUIArg, LOGIN_PW_TYPE aLogin, LOGIN_PW_TYPE aPassWord,
unsigned long aFlags, unsigned long *aSessionId)
{
HRESULT hr = E_FAIL;
PRBool bNewSession = PR_FALSE;
char *id_key = nsnull;
if (aFlags & MAPI_NEW_SESSION)
bNewSession = PR_TRUE;
// Check For Profile Name
if (aLogin != nsnull && aLogin[0] != '\0')
{
if (nsMapiHook::VerifyUserName(aLogin, &id_key) == PR_FALSE)
{
*aSessionId = MAPI_E_LOGIN_FAILURE;
return hr;
}
}
// finally register(create) the session.
PRUint32 nSession_Id;
PRInt16 nResult = 0;
nsMAPIConfiguration *pConfig = nsMAPIConfiguration::GetMAPIConfiguration();
if (pConfig != nsnull)
nResult = pConfig->RegisterSession(aUIArg, aLogin, aPassWord,
(aFlags & MAPI_FORCE_DOWNLOAD), bNewSession,
&nSession_Id, id_key);
switch (nResult)
{
case -1 :
{
*aSessionId = MAPI_E_TOO_MANY_SESSIONS;
return hr;
}
case 0 :
{
*aSessionId = MAPI_E_INSUFFICIENT_MEMORY;
return hr;
}
default :
{
*aSessionId = nSession_Id;
break;
}
}
return S_OK;
}
STDMETHODIMP CMapiImp::SendMail( unsigned long aSession, lpnsMapiMessage aMessage,
short aRecipCount, lpnsMapiRecipDesc aRecips , short aFileCount, lpnsMapiFileDesc aFiles ,
unsigned long aFlags, unsigned long aReserved)
{
nsresult rv = NS_OK ;
// Assign the pointers in the aMessage struct to the array of Recips and Files
// recieved here from MS COM. These are used in BlindSendMail and ShowCompWin fns
aMessage->lpRecips = aRecips ;
aMessage->lpFiles = aFiles ;
/** create nsIMsgCompFields obj and populate it **/
nsCOMPtr<nsIMsgCompFields> pCompFields = do_CreateInstance(NS_MSGCOMPFIELDS_CONTRACTID, &rv) ;
if (NS_FAILED(rv) || (!pCompFields) ) return MAPI_E_INSUFFICIENT_MEMORY ;
if (aFlags & MAPI_UNICODE)
rv = nsMapiHook::PopulateCompFields(aMessage, pCompFields) ;
else
rv = nsMapiHook::PopulateCompFieldsWithConversion(aMessage, pCompFields) ;
if (NS_SUCCEEDED (rv))
{
// see flag to see if UI needs to be brought up
if (!(aFlags & MAPI_DIALOG))
{
rv = nsMapiHook::BlindSendMail(aSession, pCompFields);
}
else
{
rv = nsMapiHook::ShowComposerWindow(aSession, pCompFields);
}
}
return nsMAPIConfiguration::GetMAPIErrorFromNSError (rv) ;
}
STDMETHODIMP CMapiImp::SendDocuments( unsigned long aSession, LPTSTR aDelimChar,
LPTSTR aFilePaths, LPTSTR aFileNames, ULONG aFlags)
{
nsresult rv = NS_OK ;
/** create nsIMsgCompFields obj and populate it **/
nsCOMPtr<nsIMsgCompFields> pCompFields = do_CreateInstance(NS_MSGCOMPFIELDS_CONTRACTID, &rv) ;
if (NS_FAILED(rv) || (!pCompFields) ) return MAPI_E_INSUFFICIENT_MEMORY ;
if (aFilePaths)
{
rv = nsMapiHook::PopulateCompFieldsForSendDocs(pCompFields, aFlags, aDelimChar, aFilePaths) ;
}
if (NS_SUCCEEDED (rv))
rv = nsMapiHook::ShowComposerWindow(aSession, pCompFields);
return nsMAPIConfiguration::GetMAPIErrorFromNSError (rv) ;
}
STDMETHODIMP CMapiImp::Logoff (unsigned long aSession)
{
nsMAPIConfiguration *pConfig = nsMAPIConfiguration::GetMAPIConfiguration();
if (pConfig->UnRegisterSession((PRUint32)aSession))
return S_OK;
return E_FAIL;
}
STDMETHODIMP CMapiImp::CleanUp()
{
nsMapiHook::CleanUp();
return S_OK;
}

View File

@@ -1,92 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MSG_MAPI_IMP_H
#define MSG_MAPI_IMP_H
#include <windows.h>
#include <mapi.h>
#include "msgMapi.h"
#include "nsXPIDLString.h"
#include "nspr.h"
const CLSID CLSID_CMapiImp = {0x29f458be, 0x8866, 0x11d5, {0xa3, 0xdd, 0x0, 0xb0, 0xd0, 0xf3, 0xba, 0xa7}};
// this class implements the MS COM interface nsIMapi that provides the methods
// called by mapi32.dll to perform the mail operations as specified by MAPI.
// These class methods in turn use the Mozilla Mail XPCOM interfaces to do so.
class CMapiImp : public nsIMapi
{
public :
// IUnknown
STDMETHODIMP QueryInterface(const IID& aIid, void** aPpv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
// Interface INsMapi
STDMETHODIMP Login(unsigned long aUIArg, LOGIN_PW_TYPE aLogin,
LOGIN_PW_TYPE aPassWord, unsigned long aFlags,
unsigned long *aSessionId);
STDMETHODIMP SendMail( unsigned long aSession, lpnsMapiMessage aMessage,
short aRecipCount, lpnsMapiRecipDesc aRecips ,
short aFileCount, lpnsMapiFileDesc aFiles ,
unsigned long aFlags, unsigned long aReserved) ;
STDMETHODIMP SendDocuments( unsigned long aSession, LPTSTR aDelimChar,
LPTSTR aFilePaths, LPTSTR aFileNames, ULONG aFlags);
STDMETHODIMP Initialize();
STDMETHODIMP IsValid();
STDMETHODIMP IsValidSession(unsigned long aSession);
STDMETHODIMP Logoff (unsigned long aSession);
STDMETHODIMP CleanUp();
CMapiImp();
~CMapiImp();
private :
PRLock *m_Lock;
PRInt32 m_cRef;
};
#endif // MSG_MAPI_IMP_H

View File

@@ -1,376 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <mapidefs.h>
#include <mapi.h>
#include "msgCore.h"
#include "nsMsgComposeStringBundle.h"
#include "msgMapiMain.h"
#include "nsIServiceManager.h"
#include "nsCOMPtr.h"
// move to xpcom bug 81956.
class nsPRUintKey : public nsHashKey {
protected:
PRUint32 mKey;
public:
nsPRUintKey(PRUint32 key) : mKey(key) {}
PRUint32 HashCode(void) const {
return mKey;
}
PRBool Equals(const nsHashKey *aKey) const {
return mKey == ((const nsPRUintKey *) aKey)->mKey;
}
nsHashKey *Clone() const {
return new nsPRUintKey(mKey);
}
PRUint32 GetValue() { return mKey; }
};
//
nsMAPIConfiguration *nsMAPIConfiguration::m_pSelfRef = nsnull;
PRUint32 nsMAPIConfiguration::session_generator = 0;
PRUint32 nsMAPIConfiguration::sessionCount = 0;
nsMAPIConfiguration *nsMAPIConfiguration::GetMAPIConfiguration()
{
if (m_pSelfRef == nsnull)
m_pSelfRef = new nsMAPIConfiguration();
return m_pSelfRef;
}
nsMAPIConfiguration::nsMAPIConfiguration()
: m_nMaxSessions(MAX_SESSIONS)
{
m_Lock = PR_NewLock();
}
static PRBool
FreeSessionMapEntries(nsHashKey *aKey, void *aData, void* aClosure)
{
nsMAPISession *pTemp = (nsMAPISession*) aData;
if (pTemp)
{
delete pTemp;
pTemp = nsnull;
}
return PR_TRUE;
}
static PRBool
FreeProfileMapEntries(nsHashKey *aKey, void *aData, void* aClosure)
{
return PR_TRUE;
}
nsMAPIConfiguration::~nsMAPIConfiguration()
{
if (m_Lock)
PR_DestroyLock(m_Lock);
m_SessionMap.Reset(FreeSessionMapEntries);
m_ProfileMap.Reset(FreeProfileMapEntries);
}
void nsMAPIConfiguration::OpenConfiguration()
{
// No. of max. sessions is set to MAX_SESSIONS. In future
// if it is decided to have configuration (registry)
// parameter, this function can be used to set the
// max sessions;
return;
}
PRInt16 nsMAPIConfiguration::RegisterSession(PRUint32 aHwnd,
const PRUnichar *aUserName, const PRUnichar *aPassword,
PRBool aForceDownLoad, PRBool aNewSession,
PRUint32 *aSession, char *aIdKey)
{
PRInt16 nResult = 0;
PRUint32 n_SessionId = 0;
PR_Lock(m_Lock);
// Check whether max sessions is exceeded
if (sessionCount >= m_nMaxSessions)
{
PR_Unlock(m_Lock);
return -1;
}
if (aUserName != nsnull && aUserName[0] != '\0')
{
nsStringKey usernameKey(aUserName);
n_SessionId = (PRUint32) m_ProfileMap.Get(&usernameKey);
}
// try to share a session; if not create a session
if (n_SessionId > 0)
{
nsPRUintKey sessionKey(n_SessionId);
nsMAPISession *pTemp = (nsMAPISession *)m_SessionMap.Get(&sessionKey);
if (pTemp != nsnull)
{
pTemp->IncrementSession();
*aSession = n_SessionId;
nResult = 1;
}
}
else if (aNewSession || n_SessionId == 0) // checking for n_SessionId is a concession
{
// create a new session ; if new session is specified OR there is no session
nsMAPISession *pTemp = nsnull;
pTemp = new nsMAPISession(aHwnd, aUserName,
aPassword, aForceDownLoad, aIdKey);
if (pTemp != nsnull)
{
session_generator++;
// I don't think there will be (2 power 32) sessions alive
// in a cycle. This is an assumption
if (session_generator == 0)
session_generator++;
nsPRUintKey sessionKey(session_generator);
m_SessionMap.Put(&sessionKey, pTemp);
if (aUserName != nsnull && aUserName[0] != '\0')
{
nsStringKey usernameKey(aUserName);
m_ProfileMap.Put(&usernameKey, (void*)session_generator);
}
*aSession = session_generator;
sessionCount++;
nResult = 1;
}
}
PR_Unlock(m_Lock);
return nResult;
}
PRBool nsMAPIConfiguration::UnRegisterSession(PRUint32 aSessionID)
{
PRBool bResult = PR_FALSE;
PR_Lock(m_Lock);
if (aSessionID != 0)
{
nsPRUintKey sessionKey(aSessionID);
nsMAPISession *pTemp = (nsMAPISession *)m_SessionMap.Get(&sessionKey);
if (pTemp != nsnull)
{
if (pTemp->DecrementSession() == 0)
{
if (pTemp->m_pProfileName.get() != nsnull)
{
nsStringKey stringKey(pTemp->m_pProfileName.get());
m_ProfileMap.Remove(&stringKey);
}
m_SessionMap.Remove(&sessionKey);
sessionCount--;
bResult = PR_TRUE;
}
}
}
PR_Unlock(m_Lock);
return bResult;
}
PRBool nsMAPIConfiguration::IsSessionValid(PRUint32 aSessionID)
{
if (aSessionID == 0)
return PR_FALSE;
PRBool retValue = PR_FALSE;
nsPRUintKey sessionKey(aSessionID);
PR_Lock(m_Lock);
retValue = m_SessionMap.Exists(&sessionKey);
PR_Unlock(m_Lock);
return retValue;
}
PRUnichar *nsMAPIConfiguration::GetPassword(PRUint32 aSessionID)
{
PRUnichar *pResult = nsnull;
PR_Lock(m_Lock);
if (aSessionID != 0)
{
nsPRUintKey sessionKey(aSessionID);
nsMAPISession *pTemp = (nsMAPISession *)m_SessionMap.Get(&sessionKey);
if (pTemp)
{
pResult = pTemp->GetPassword();
}
}
PR_Unlock(m_Lock);
return pResult;
}
char *nsMAPIConfiguration::GetIdKey(PRUint32 aSessionID)
{
char *pResult = nsnull;
PR_Lock(m_Lock);
if (aSessionID != 0)
{
nsPRUintKey sessionKey(aSessionID);
nsMAPISession *pTemp = (nsMAPISession *)m_SessionMap.Get(&sessionKey);
if (pTemp)
{
pResult = pTemp->GetIdKey();
}
}
PR_Unlock(m_Lock);
return pResult;
}
// util func
HRESULT nsMAPIConfiguration::GetMAPIErrorFromNSError (nsresult res)
{
HRESULT hr = SUCCESS_SUCCESS ;
if (NS_SUCCEEDED (hr)) return hr ;
// if failure return the related MAPI failure code
switch (res)
{
case NS_MSG_NO_RECIPIENTS :
hr = MAPI_E_BAD_RECIPTYPE ;
break ;
case NS_ERROR_COULD_NOT_GET_USERS_MAIL_ADDRESS :
hr = MAPI_E_INVALID_RECIPS ;
break ;
case NS_ERROR_COULD_NOT_LOGIN_TO_SMTP_SERVER :
hr = MAPI_E_LOGIN_FAILURE ;
break ;
case NS_MSG_UNABLE_TO_OPEN_FILE :
case NS_MSG_UNABLE_TO_OPEN_TMP_FILE :
case NS_MSG_COULDNT_OPEN_FCC_FOLDER :
case NS_ERROR_FILE_INVALID_PATH :
hr = MAPI_E_ATTACHMENT_OPEN_FAILURE ;
break ;
case NS_ERROR_FILE_TARGET_DOES_NOT_EXIST :
hr = MAPI_E_ATTACHMENT_NOT_FOUND ;
break ;
case NS_MSG_CANCELLING :
hr = MAPI_E_USER_ABORT ;
break ;
case NS_MSG_ERROR_WRITING_FILE :
case NS_MSG_UNABLE_TO_SAVE_TEMPLATE :
case NS_MSG_UNABLE_TO_SAVE_DRAFT :
hr = MAPI_E_ATTACHMENT_WRITE_FAILURE ;
break ;
default :
hr = MAPI_E_FAILURE ;
break ;
}
return hr ;
}
nsMAPISession::nsMAPISession(PRUint32 aHwnd, const PRUnichar *aUserName,\
const PRUnichar *aPassword, \
PRBool aForceDownLoad, char *aKey)
: m_bIsForcedDownLoad(aForceDownLoad),
m_hAppHandle(aHwnd),
m_nShared(1),
m_pIdKey(aKey)
{
m_pProfileName.Assign(aUserName);
m_pPassword.Assign(aPassword);
}
nsMAPISession::~nsMAPISession()
{
if (m_pIdKey != nsnull)
{
delete [] m_pIdKey;
m_pIdKey = nsnull;
}
}
PRUint32 nsMAPISession::IncrementSession()
{
return ++m_nShared;
}
PRUint32 nsMAPISession::DecrementSession()
{
return --m_nShared;
}
PRUint32 nsMAPISession::GetSessionCount()
{
return m_nShared;
}
PRUnichar *nsMAPISession::GetPassword()
{
return (PRUnichar *)m_pPassword.get();
}
char *nsMAPISession::GetIdKey()
{
return m_pIdKey;
}

View File

@@ -1,112 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MSG_MAPI_MAIN_H_
#define NSG_MAPI_MAIN_H_
#define MAX_NAME_LEN 256
#define MAX_PW_LEN 256
#define MAX_SESSIONS 50
#define MAPI_SENDCOMPLETE_EVENT "SendCompletionEvent"
#define MAPI_PROPERTIES_CHROME "chrome://messenger-mapi/locale/mapi.properties"
#define PREF_MAPI_WARN_PRIOR_TO_BLIND_SEND "mapi.blind-send.warn"
#define PREF_MAPI_BLIND_SEND_ENABLED "mapi.blind-send.enabled"
#include "nsXPIDLString.h"
#include "nspr.h"
#include "nsString.h"
#include "nsHashtable.h"
class nsMAPIConfiguration
{
private :
static PRUint32 session_generator;
static PRUint32 sessionCount;
static nsMAPIConfiguration *m_pSelfRef;
PRLock *m_Lock;
PRUint32 m_nMaxSessions;
nsHashtable m_ProfileMap;
nsHashtable m_SessionMap;
nsMAPIConfiguration();
public :
static nsMAPIConfiguration *GetMAPIConfiguration();
void OpenConfiguration();
PRInt16 RegisterSession(PRUint32 aHwnd, const PRUnichar *aUserName, \
const PRUnichar *aPassword, PRBool aForceDownLoad, \
PRBool aNewSession, PRUint32 *aSession, char *aIdKey);
PRBool IsSessionValid(PRUint32 aSessionID);
PRBool UnRegisterSession(PRUint32 aSessionID);
PRUnichar *GetPassword(PRUint32 aSessionID);
char *GetIdKey(PRUint32 aSessionID);
~nsMAPIConfiguration();
// a util func
static HRESULT GetMAPIErrorFromNSError (nsresult res) ;
};
class nsMAPISession
{
friend class nsMAPIConfiguration;
private :
PRBool m_bIsForcedDownLoad;
PRBool m_bApp_or_Service;
PRUint32 m_hAppHandle;
PRUint32 m_nShared;
char *m_pIdKey;
nsString m_pProfileName;
nsString m_pPassword;
public :
nsMAPISession(PRUint32 aHwnd, const PRUnichar *aUserName, \
const PRUnichar *aPassword, \
PRBool aForceDownLoad, char *aKey);
PRUint32 IncrementSession();
PRUint32 DecrementSession();
PRUint32 GetSessionCount();
PRUnichar *nsMAPISession::GetPassword();
char *nsMAPISession::GetIdKey();
~nsMAPISession();
};
#endif // MSG_MAPI_MAIN_H_

View File

@@ -1,209 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
* Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsCOMPtr.h"
#include "objbase.h"
#include "nsISupports.h"
#include "nsIGenericFactory.h"
#include "nsIObserverService.h"
#include "nsIAppStartupNotifier.h"
#include "nsIServiceManager.h"
#include "nsIComponentManager.h"
#include "nsICategoryManager.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefBranchInternal.h"
#include "msgMapiSupport.h"
#include "nsMapiRegistryUtils.h"
#include "nsMapiRegistry.h"
#include "msgMapiImp.h"
/** Implementation of the nsIMapiSupport interface.
* Use standard implementation of nsISupports stuff.
*/
NS_IMPL_THREADSAFE_ISUPPORTS2(nsMapiSupport, nsIMapiSupport, nsIObserver);
static NS_METHOD nsMapiRegistrationProc(nsIComponentManager *aCompMgr,
nsIFile *aPath, const char *registryLocation, const char *componentType,
const nsModuleComponentInfo *info)
{
nsresult rv;
nsCOMPtr<nsICategoryManager> categoryManager(do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv));
if (NS_SUCCEEDED(rv))
rv = categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "Mapi Support",
"service," NS_IMAPISUPPORT_CONTRACTID, PR_TRUE, PR_TRUE, nsnull);
return rv ;
}
NS_IMETHODIMP
nsMapiSupport::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
nsresult rv = NS_OK ;
if (!nsCRT::strcmp(aTopic, "profile-after-change"))
return InitializeMAPISupport();
if (!nsCRT::strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID))
return ShutdownMAPISupport();
if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID))
{
nsCOMPtr<nsIPrefBranch> prefs = do_QueryInterface(aSubject, &rv);
if (NS_FAILED(rv)) return rv;
// which preference changed?
if (!nsCRT::strcmp(MAILNEWS_ALLOW_DEFAULT_MAIL_CLIENT, NS_ConvertUCS2toUTF8(aData).get()))
{
PRBool bIsDefault = PR_FALSE ;
rv = prefs->GetBoolPref(MAILNEWS_ALLOW_DEFAULT_MAIL_CLIENT, &bIsDefault);
if (NS_FAILED(rv)) return rv;
nsCOMPtr <nsIMapiRegistry> mapiRegistry = do_CreateInstance(NS_IMAPIREGISTRY_CONTRACTID, &rv) ;
if (NS_FAILED(rv)) return rv;
return mapiRegistry->SetIsDefaultMailClient(bIsDefault) ;
}
return rv ;
}
nsCOMPtr<nsIObserverService> observerService(do_GetService("@mozilla.org/observer-service;1", &rv));
if (NS_FAILED(rv)) return rv;
rv = observerService->AddObserver(this,"profile-after-change", PR_FALSE);
if (NS_FAILED(rv)) return rv;
rv = observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_FALSE);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIPrefService> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIPrefBranchInternal> prefInternal = do_QueryInterface(prefs, &rv);
if (NS_FAILED(rv)) return rv;
rv = prefInternal->AddObserver(MAILNEWS_ALLOW_DEFAULT_MAIL_CLIENT, this, PR_FALSE);
if (NS_FAILED(rv)) return rv;
return rv;
}
nsMapiSupport::nsMapiSupport()
: m_dwRegister(0),
m_nsMapiFactory(nsnull)
{
NS_INIT_ISUPPORTS();
}
nsMapiSupport::~nsMapiSupport()
{
}
NS_IMETHODIMP
nsMapiSupport::InitializeMAPISupport()
{
::CoInitialize(nsnull) ;
if (m_nsMapiFactory == nsnull) // No Registering if already done. Sanity Check!!
{
m_nsMapiFactory = new CMapiFactory();
if (m_nsMapiFactory != nsnull)
{
HRESULT hr = ::CoRegisterClassObject(CLSID_CMapiImp, \
m_nsMapiFactory, \
CLSCTX_LOCAL_SERVER, \
REGCLS_MULTIPLEUSE, \
&m_dwRegister);
if (FAILED(hr))
{
m_nsMapiFactory->Release() ;
m_nsMapiFactory = nsnull;
return NS_ERROR_FAILURE;
}
}
}
return NS_OK;
}
NS_IMETHODIMP
nsMapiSupport::ShutdownMAPISupport()
{
if (m_dwRegister != 0)
::CoRevokeClassObject(m_dwRegister);
if (m_nsMapiFactory != nsnull)
{
m_nsMapiFactory->Release();
m_nsMapiFactory = nsnull;
}
::CoUninitialize();
return NS_OK ;
}
NS_GENERIC_FACTORY_CONSTRUCTOR(nsMapiRegistry);
NS_GENERIC_FACTORY_CONSTRUCTOR(nsMapiSupport);
// The list of components we register
static nsModuleComponentInfo components[] =
{
{
NS_IMAPIREGISTRY_CLASSNAME,
NS_IMAPIREGISTRY_CID,
NS_IMAPIREGISTRY_CONTRACTID,
nsMapiRegistryConstructor
},
{
NS_IMAPISUPPORT_CLASSNAME,
NS_IMAPISUPPORT_CID,
NS_IMAPISUPPORT_CONTRACTID,
nsMapiSupportConstructor,
nsMapiRegistrationProc,
nsnull
}
};
NS_IMPL_NSGETMODULE(msgMapiModule, components);

View File

@@ -1,66 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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
*
* The Initial Developer of the Original Code is
# Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Krishna Mohan Khandrika (kkhandrika@netscape.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef MSG_MAPI_SUPPORT_H_
#define MSG_MAPI_SUPPORT_H_
#include "nsIObserver.h"
#include "nsIMapiSupport.h"
#include "msgMapiFactory.h"
#define NS_IMAPISUPPORT_CID \
{0x8967fed2, 0xc8bb, 0x11d5, \
{ 0xa3, 0xe9, 0x00, 0xb0, 0xd0, 0xf3, 0xba, 0xa7 }}
class nsMapiSupport : public nsIMapiSupport,
public nsIObserver
{
public :
nsMapiSupport();
~nsMapiSupport();
// Declare all interface methods we must implement.
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
NS_DECL_NSIMAPISUPPORT
private :
DWORD m_dwRegister;
CMapiFactory *m_nsMapiFactory;
};
#endif // MSG_MAPI_SUPPORT_H_

View File

@@ -1,167 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsIServiceManager.h"
#include "nsXPIDLString.h"
#include "nsIPromptService.h"
#include "nsIProxyObjectManager.h"
#include "nsProxiedService.h"
#include "nsMapiRegistryUtils.h"
#include "nsMapiRegistry.h"
static NS_DEFINE_CID(kStringBundleServiceCID, NS_STRINGBUNDLESERVICE_CID);
/** Implementation of the nsIMapiRegistry interface.
* Use standard implementation of nsISupports stuff.
*/
NS_IMPL_ISUPPORTS1(nsMapiRegistry, nsIMapiRegistry);
nsMapiRegistry::nsMapiRegistry() {
NS_INIT_ISUPPORTS();
m_ShowDialog = ! m_registryUtils.verifyRestrictedAccess();
m_DefaultMailClient = m_registryUtils.IsDefaultMailClient();
}
nsMapiRegistry::~nsMapiRegistry() {
}
NS_IMETHODIMP
nsMapiRegistry::GetIsDefaultMailClient(PRBool * retval) {
// we need to get the value from registry everytime
// because the registry settings can be changed from
// other mail applications.
*retval = m_registryUtils.IsDefaultMailClient();
return NS_OK;
}
NS_IMETHODIMP
nsMapiRegistry::GetShowDialog(PRBool * retval) {
*retval = m_ShowDialog;
return NS_OK;
}
NS_IMETHODIMP
nsMapiRegistry::SetIsDefaultMailClient(PRBool aIsDefaultMailClient)
{
nsresult rv = NS_OK ;
if (aIsDefaultMailClient)
{
rv = m_registryUtils.setDefaultMailClient();
if (NS_SUCCEEDED(rv))
m_DefaultMailClient = PR_TRUE;
else
m_registryUtils.ShowMapiErrorDialog();
}
else
{
rv = m_registryUtils.unsetDefaultMailClient();
if (NS_SUCCEEDED(rv))
m_DefaultMailClient = PR_FALSE;
else
m_registryUtils.ShowMapiErrorDialog();
}
return rv ;
}
/** This will bring up the dialog box only once per session and
* only if the current app is not default Mail Client.
* This also checks the registry if the registry key
* showMapiDialog is set
*/
NS_IMETHODIMP
nsMapiRegistry::ShowMailIntegrationDialog(nsIDOMWindow *aParentWindow) {
nsresult rv;
if (!m_ShowDialog || !m_registryUtils.getShowDialog()) return NS_OK;
nsCOMPtr<nsIPromptService> promptService(do_GetService(
"@mozilla.org/embedcomp/prompt-service;1", &rv));
if (NS_SUCCEEDED(rv) && promptService)
{
nsCOMPtr<nsIStringBundle> bundle;
rv = m_registryUtils.MakeMapiStringBundle (getter_AddRefs (bundle)) ;
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString dialogTitle;
const PRUnichar *brandStrings[] = { m_registryUtils.brandName() };
NS_NAMED_LITERAL_STRING(dialogTitlePropertyTag, "dialogTitle");
rv = bundle->FormatStringFromName(dialogTitlePropertyTag.get(),
brandStrings, 1,
getter_Copies(dialogTitle));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString dialogText;
NS_NAMED_LITERAL_STRING(dialogTextPropertyTag, "dialogText");
rv = bundle->FormatStringFromName(dialogTextPropertyTag.get(),
brandStrings, 1,
getter_Copies(dialogText));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString checkboxText;
rv = bundle->GetStringFromName(
NS_LITERAL_STRING("checkboxText").get(),
getter_Copies(checkboxText));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
PRBool checkValue = PR_FALSE;
PRInt32 buttonPressed = 0;
rv = promptService->ConfirmEx(aParentWindow,
dialogTitle,
dialogText.get(),
(nsIPromptService::BUTTON_TITLE_YES *
nsIPromptService::BUTTON_POS_0) +
(nsIPromptService::BUTTON_TITLE_NO *
nsIPromptService::BUTTON_POS_1),
nsnull,
nsnull,
nsnull,
checkboxText,
&checkValue,
&buttonPressed);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = m_registryUtils.SetRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Mozilla\\Desktop",
"showMapiDialog", (checkValue) ? "0" : "1");
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
m_ShowDialog = PR_FALSE;
if (!buttonPressed)
rv = SetIsDefaultMailClient(PR_TRUE) ; // SetDefaultMailClient();
}
return rv;
}

View File

@@ -1,76 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsmapiregistry_h____
#define nsmapiregistry_h____
#include "nsIMapiRegistry.h"
#ifndef MAX_BUF
#define MAX_BUF 4096
#endif
/* c5be14ba-4e0a-4eec-a1b8-04363761d63c */
#define NS_IMAPIREGISTRY_CID \
{ 0xc5be14ba, 0x4e0a, 0x4eec, {0xa1, 0xb8, 0x04, 0x36, 0x37, 0x61, 0xd6, 0x3c} }
#define NS_IMAPIREGISTRY_CONTRACTID "@mozilla.org/mapiregistry;1"
#define NS_IMAPIREGISTRY_CLASSNAME "Mozilla MAPI Registry"
#define MAILNEWS_ALLOW_DEFAULT_MAIL_CLIENT "mailnews.default_mail_client"
class nsMapiRegistry : public nsIMapiRegistry {
public:
// ctor/dtor
nsMapiRegistry();
virtual ~nsMapiRegistry();
// Declare all interface methods we must implement.
NS_DECL_ISUPPORTS
NS_DECL_NSIMAPIREGISTRY
protected:
PRBool m_DefaultMailClient;
PRBool m_ShowDialog;
nsMapiRegistryUtils m_registryUtils ;
private:
// Special member to handle initialization.
PRBool mHaveBeenSet;
}; // nsMapiRegistry
#endif // nsmapiregistry_h____

View File

@@ -1,743 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#undef UNICODE
#undef _UNICODE
#include "nsIServiceManager.h"
#include "msgMapiImp.h"
#include "msgMapiMain.h"
#include "nsMapiRegistryUtils.h"
#include "nsString.h"
#include "nsIStringBundle.h"
#include "nsIPromptService.h"
#include "nsXPIDLString.h"
#include "nsSpecialSystemDirectory.h"
#include "nsDirectoryService.h"
#include "nsDirectoryServiceDefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsIPref.h"
static NS_DEFINE_CID(kStringBundleServiceCID, NS_STRINGBUNDLESERVICE_CID);
#define EXE_EXTENSION ".exe"
#define USERAGENT_VERSION_PREF "general.useragent.misc"
#define USERAGENT_VERSION_NS_PREF "general.useragent.vendorSub"
#define USERAGENT_PREF_PREFIX "rv:"
nsMapiRegistryUtils::nsMapiRegistryUtils()
{
m_mapiStringBundle = nsnull ;
}
const char * nsMapiRegistryUtils::thisApplication()
{
if (m_thisApp.IsEmpty()) {
char buffer[MAX_PATH] = {0};
DWORD len = ::GetModuleFileName(NULL, buffer, MAX_PATH);
if (!len) return nsnull ;
char shortPathBuf[MAX_PATH] = {0};
len = ::GetShortPathName(buffer, shortPathBuf, MAX_PATH);
if (!len) return nsnull ;
m_thisApp = buffer;
m_thisApp.ToUpperCase();
}
return m_thisApp.get() ;
}
const PRUnichar * nsMapiRegistryUtils::brandName()
{
nsresult rv;
if (m_brand.IsEmpty()) {
nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(
kStringBundleServiceCID, &rv));
if (NS_SUCCEEDED(rv) && bundleService) {
nsCOMPtr<nsIStringBundle> brandBundle;
rv = bundleService->CreateBundle(
"chrome://global/locale/brand.properties",
getter_AddRefs(brandBundle));
if (NS_SUCCEEDED(rv)) {
nsXPIDLString brandName;
rv = brandBundle->GetStringFromName(
NS_LITERAL_STRING("brandShortName").get(),
getter_Copies(brandName));
if (NS_SUCCEEDED(rv)) {
m_brand = brandName ;
}
}
}
}
return m_brand.get() ;
}
const PRUnichar * nsMapiRegistryUtils::versionNo()
{
if (!m_versionNo.IsEmpty())
return m_versionNo.get() ;
nsCOMPtr<nsIPref> prefs = do_GetService(NS_PREF_CONTRACTID);
if (prefs) {
nsXPIDLCString versionStr ;
nsresult rv = prefs->GetCharPref(USERAGENT_VERSION_NS_PREF, getter_Copies(versionStr));
if (NS_SUCCEEDED(rv) && versionStr)
m_versionNo.AssignWithConversion (versionStr.get()) ;
else {
rv = prefs->GetCharPref(USERAGENT_VERSION_PREF, getter_Copies(versionStr));
if (NS_SUCCEEDED(rv) && versionStr) {
m_versionNo.AssignWithConversion (versionStr.get()) ;
m_versionNo.StripChars (USERAGENT_PREF_PREFIX) ;
}
}
}
return m_versionNo.get() ;
}
PRBool nsMapiRegistryUtils::verifyRestrictedAccess() {
char subKey[] = "Software\\Mozilla - Test Key";
PRBool result = PR_FALSE;
DWORD dwDisp = 0;
HKEY key;
// Try to create/open a subkey under HKLM.
DWORD rc = ::RegCreateKeyEx(HKEY_LOCAL_MACHINE,
subKey,
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
NULL,
&key,
&dwDisp);
if (rc == ERROR_SUCCESS) {
// Key was opened; first close it.
::RegCloseKey(key);
// Delete it if we just created it.
switch(dwDisp) {
case REG_CREATED_NEW_KEY:
::RegDeleteKey(HKEY_LOCAL_MACHINE, subKey);
break;
case REG_OPENED_EXISTING_KEY:
break;
}
} else {
// Can't create/open it; we don't have access.
result = PR_TRUE;
}
return result;
}
nsresult nsMapiRegistryUtils::SetRegistryKey(HKEY baseKey, const char * keyName,
const char * valueName, char * value)
{
nsresult result = NS_ERROR_FAILURE;
HKEY key;
LONG rc = ::RegCreateKey(baseKey, keyName, &key);
if (rc == ERROR_SUCCESS) {
rc = ::RegSetValueEx(key, valueName, NULL, REG_SZ,
(LPBYTE)(const char*)value, strlen(value));
if (rc == ERROR_SUCCESS) {
result = NS_OK;
}
::RegCloseKey(key);
}
return result;
}
nsresult nsMapiRegistryUtils::DeleteRegistryValue(HKEY baseKey, const char * keyName,
const char * valueName)
{
nsresult result = NS_ERROR_FAILURE;
HKEY key;
LONG rc = ::RegOpenKey(baseKey, keyName, &key);
if (rc == ERROR_SUCCESS) {
rc = ::RegDeleteValue(key, valueName);
if (rc == ERROR_SUCCESS)
result = NS_OK;
::RegCloseKey(key);
}
return result;
}
void nsMapiRegistryUtils::GetRegistryKey(HKEY baseKey, const char * keyName,
const char * valueName, nsCAutoString & value)
{
HKEY key;
LONG rc = ::RegOpenKey(baseKey, keyName, &key);
if (rc == ERROR_SUCCESS) {
char buffer[MAX_PATH] = {0};
DWORD len = sizeof buffer;
rc = ::RegQueryValueEx(key, valueName, NULL, NULL,
(LPBYTE)buffer, &len);
if (rc == ERROR_SUCCESS) {
if (len)
value = buffer;
}
::RegCloseKey(key);
}
}
PRBool nsMapiRegistryUtils::IsDefaultMailClient()
{
if (!isSmartDll() && !isMozDll())
return PR_FALSE;
nsCAutoString name;
GetRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Clients\\Mail", "", name);
if (!name.IsEmpty()) {
nsCAutoString keyName("Software\\Clients\\Mail\\");
keyName += name.get();
keyName += "\\protocols\\mailto\\shell\\open\\command";
nsCAutoString result;
GetRegistryKey(HKEY_LOCAL_MACHINE, keyName.get(), "", result);
if (!result.IsEmpty()) {
nsCAutoString strExtension;
strExtension.Assign(EXE_EXTENSION);
result.ToUpperCase();
strExtension.ToUpperCase();
PRInt32 index = result.RFind(strExtension.get());
if (index != kNotFound) {
result.Truncate(index + strExtension.Length());
}
nsCAutoString thisApp (thisApplication()) ;
return (result == thisApp);
}
}
return PR_FALSE;
}
nsresult nsMapiRegistryUtils::saveDefaultMailClient()
{
nsresult rv;
nsCAutoString name ;
GetRegistryKey(HKEY_LOCAL_MACHINE,"Software\\Clients\\Mail", "", name);
if (!name.IsEmpty()) {
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"HKEY_LOCAL_MACHINE\\Software\\Clients\\Mail",
(char *)name.get());
if (NS_SUCCEEDED(rv)) {
nsCAutoString keyName("Software\\Clients\\Mail\\");
keyName += name.get();
keyName += "\\protocols\\mailto\\shell\\open\\command";
nsCAutoString appPath ;
GetRegistryKey(HKEY_LOCAL_MACHINE, keyName.get(), "", appPath);
if (!appPath.IsEmpty()) {
nsCAutoString stringName("HKEY_LOCAL_MACHINE\\");
stringName += keyName.get();
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
stringName.get(), (char *)appPath.get());
}
}
}
else
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"HKEY_LOCAL_MACHINE\\Software\\Clients\\Mail",
"");
return rv;
}
nsresult nsMapiRegistryUtils::saveUserDefaultMailClient()
{
nsresult rv;
nsCAutoString name ;
GetRegistryKey(HKEY_CURRENT_USER,"Software\\Clients\\Mail", "", name);
if (!name.IsEmpty()) {
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"HKEY_CURRENT_USER\\Software\\Clients\\Mail",
(char *)name.get());
}
else {
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"HKEY_CURRENT_USER\\Software\\Clients\\Mail",
"");
}
return rv;
}
/**
* Check whether it is a smart dll or not. Smart dll is the one installed by
* IE5 or Outlook Express which forwards the MAPI calls to the dll based on the
* registry key setttings.
* Returns TRUE if is a smart dll.
*/
typedef HRESULT (FAR PASCAL GetOutlookVersionFunc)();
PRBool nsMapiRegistryUtils::isSmartDll()
{
char buffer[MAX_PATH] = {0};
if (GetSystemDirectory(buffer, sizeof(buffer)) == 0)
return PR_FALSE;
PL_strcatn(buffer, sizeof(buffer), "\\Mapi32.dll");
HINSTANCE hInst;
GetOutlookVersionFunc *doesExist = nsnull;
hInst = LoadLibrary(buffer);
if (hInst == nsnull)
return PR_FALSE;
doesExist = (GetOutlookVersionFunc *) GetProcAddress (hInst, "GetOutlookVersion");
FreeLibrary(hInst);
return (doesExist != nsnull);
}
typedef HRESULT (FAR PASCAL GetMapiDllVersion)();
/**
* Checks whether mapi32.dll is installed by this app.
* Returns TRUE if it is.
*/
PRBool nsMapiRegistryUtils::isMozDll()
{
char buffer[MAX_PATH] = {0};
if (GetSystemDirectory(buffer, sizeof(buffer)) == 0)
return PR_FALSE;
PL_strcatn(buffer, sizeof(buffer), "\\Mapi32.dll");
HINSTANCE hInst;
GetMapiDllVersion *doesExist = nsnull;
hInst = LoadLibrary(buffer);
if (hInst == nsnull)
return PR_FALSE;
doesExist = (GetMapiDllVersion *) GetProcAddress (hInst, "GetMapiDllVersion");
FreeLibrary(hInst);
return (doesExist != nsnull);
}
/** Renames Mapi32.dl in system directory to Mapi32_moz_bak.dll
* copies the mozMapi32.dll from bin directory to the system directory
*/
nsresult nsMapiRegistryUtils::CopyMozMapiToWinSysDir()
{
nsresult rv;
char buffer[MAX_PATH] = {0};
if (GetSystemDirectory(buffer, sizeof(buffer)) == 0)
return NS_ERROR_FAILURE;
nsCAutoString filePath(buffer);
filePath.Append("\\Mapi32_moz_bak.dll");
nsCOMPtr<nsILocalFile> pCurrentMapiFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv);
if (NS_FAILED(rv) || !pCurrentMapiFile) return rv;
pCurrentMapiFile->InitWithPath(filePath.get());
nsCOMPtr<nsIFile> pMozMapiFile;
nsCOMPtr<nsIProperties> directoryService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
if (!directoryService) return NS_ERROR_FAILURE;
rv = directoryService->Get(NS_OS_CURRENT_PROCESS_DIR,
NS_GET_IID(nsIFile),
getter_AddRefs(pMozMapiFile));
if (NS_FAILED(rv)) return rv;
pMozMapiFile->Append("mozMapi32.dll");
PRBool bExist;
rv = pMozMapiFile->Exists(&bExist);
if (NS_FAILED(rv) || !bExist) return rv;
rv = pCurrentMapiFile->Exists(&bExist);
if (NS_SUCCEEDED(rv) && bExist)
{
rv = pCurrentMapiFile->Remove(PR_FALSE);
}
if (NS_FAILED(rv)) return rv;
filePath.Assign(buffer);
filePath.Append("\\Mapi32.dll");
pCurrentMapiFile->InitWithPath(filePath.get());
rv = pCurrentMapiFile->Exists(&bExist);
if (NS_SUCCEEDED(rv) && bExist)
{
rv = pCurrentMapiFile->MoveTo(nsnull, "Mapi32_moz_bak.dll");
if (NS_FAILED(rv)) return rv;
nsCAutoString fullFilePath(buffer);
fullFilePath.Append("\\Mapi32_moz_bak.dll");
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"Mapi_backup_dll",
(char *)fullFilePath.get());
if (NS_FAILED(rv)) {
RestoreBackedUpMapiDll();
return rv;
}
}
NS_NAMED_LITERAL_STRING(fileName, "Mapi32.dll");
filePath.Assign(buffer);
pCurrentMapiFile->InitWithPath(filePath.get());
rv = pMozMapiFile->CopyToUnicode(pCurrentMapiFile, fileName.get());
if (NS_FAILED(rv))
RestoreBackedUpMapiDll();
return rv;
}
/** deletes the Mapi32.dll in system directory and renames Mapi32_moz_bak.dll
* to Mapi32.dll
*/
nsresult nsMapiRegistryUtils::RestoreBackedUpMapiDll()
{
nsresult rv;
char buffer[MAX_PATH] = {0};
if (GetSystemDirectory(buffer, sizeof(buffer)) == 0)
return NS_ERROR_FAILURE;
nsCAutoString filePath(buffer);
nsCAutoString previousFileName(buffer);
filePath.Append("\\Mapi32.dll");
previousFileName.Append("\\Mapi32_moz_bak.dll");
nsCOMPtr <nsILocalFile> pCurrentMapiFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
if (NS_FAILED(rv) || !pCurrentMapiFile) return NS_ERROR_FAILURE;
pCurrentMapiFile->InitWithPath(filePath.get());
nsCOMPtr<nsILocalFile> pPreviousMapiFile = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID, &rv);
if (NS_FAILED(rv) || !pPreviousMapiFile) return NS_ERROR_FAILURE;
pPreviousMapiFile->InitWithPath(previousFileName.get());
PRBool bExist;
rv = pCurrentMapiFile->Exists(&bExist);
if (NS_SUCCEEDED(rv) && bExist) {
rv = pCurrentMapiFile->Remove(PR_FALSE);
if (NS_FAILED(rv)) return rv;
}
rv = pPreviousMapiFile->Exists(&bExist);
if (NS_SUCCEEDED(rv) && bExist)
rv = pPreviousMapiFile->MoveTo(nsnull, "Mapi32.dll");
if (NS_SUCCEEDED(rv))
DeleteRegistryValue(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"Mapi_backup_dll");
return rv;
}
/** Sets Mozilla as default Mail Client
*/
nsresult nsMapiRegistryUtils::setDefaultMailClient()
{
nsresult rv;
nsresult mailKeySet=NS_ERROR_FAILURE;
if (verifyRestrictedAccess()) return NS_ERROR_FAILURE;
if (!isSmartDll()) {
if (NS_FAILED(CopyMozMapiToWinSysDir())) return NS_ERROR_FAILURE;
}
rv = saveDefaultMailClient();
if (NS_FAILED(saveUserDefaultMailClient()) ||
NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsCAutoString keyName("Software\\Clients\\Mail\\");
nsCAutoString appName (NS_ConvertUCS2toUTF8(brandName()).get());
if (!appName.IsEmpty()) {
keyName.Append(appName.get());
nsCOMPtr<nsIStringBundle> bundle;
rv = MakeMapiStringBundle (getter_AddRefs (bundle)) ;
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString defaultMailTitle;
const PRUnichar *keyValuePrefixStr[] = { brandName(), versionNo() };
NS_NAMED_LITERAL_STRING(defaultMailTitleTag, "defaultMailDisplayTitle");
rv = bundle->FormatStringFromName(defaultMailTitleTag.get(),
keyValuePrefixStr, 2,
getter_Copies(defaultMailTitle));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(),
"", NS_CONST_CAST(char *, NS_ConvertUCS2toUTF8(defaultMailTitle).get()) ) ;
}
else
rv = NS_ERROR_FAILURE;
if (NS_SUCCEEDED(rv)) {
nsCAutoString thisApp (thisApplication()) ;
if (NS_FAILED(rv)) return rv ;
nsCAutoString dllPath (thisApp) ;
PRInt32 index = dllPath.RFind("\\");
if (index != kNotFound)
dllPath.Truncate(index + 1);
dllPath += "mozMapi32.dll";
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(), "DLLPath",
(char *)dllPath.get());
if (NS_SUCCEEDED(rv)) {
keyName.Append("\\protocols\\mailto");
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(),
"", "URL:MailTo Protocol");
if (NS_SUCCEEDED(rv)) {
nsCAutoString appPath (thisApp);
appPath += " \"%1\"";
keyName.Append("\\shell\\open\\command");
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(),
"", (char *)appPath.get());
if (NS_SUCCEEDED(rv)) {
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Clients\\Mail",
"", (char *)appName.get());
}
if (NS_SUCCEEDED(rv)) {
nsCAutoString mailAppPath(thisApp);
mailAppPath += " -mail";
nsCAutoString appKeyName ("Software\\Clients\\Mail\\");
appKeyName.Append(appName.get());
appKeyName.Append("\\shell\\open\\command");
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
appKeyName.get(),
"", (char *)mailAppPath.get());
}
if (NS_SUCCEEDED(rv)) {
nsCAutoString iconPath(thisApp);
iconPath += ",0";
nsCAutoString iconKeyName ("Software\\Clients\\Mail\\");
iconKeyName.Append(appName.get());
iconKeyName.Append("\\DefaultIcon");
mailKeySet = SetRegistryKey(HKEY_LOCAL_MACHINE,
iconKeyName.get(),
"", (char *)iconPath.get());
}
}
}
}
if (NS_SUCCEEDED(mailKeySet)) {
nsresult desktopKeySet = SetRegistryKey(HKEY_CURRENT_USER,
"Software\\Clients\\Mail",
"", (char *)appName.get());
if (NS_SUCCEEDED(desktopKeySet)) {
desktopKeySet = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"defaultMailHasBeenSet", "1");
}
::SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM)"Software\\Clients\\Mail");
RegisterServer(CLSID_CMapiImp, "Mozilla MAPI", "mozMapi", "mozMapi.1");
return desktopKeySet;
}
return mailKeySet;
}
/** Removes Mozilla as the default Mail client and restores the previous setting
*/
nsresult nsMapiRegistryUtils::unsetDefaultMailClient() {
nsresult result = NS_OK;
nsresult mailKeySet = NS_ERROR_FAILURE;
if (verifyRestrictedAccess()) return NS_ERROR_FAILURE;
if (!isSmartDll()) {
if (NS_FAILED(RestoreBackedUpMapiDll())) return NS_ERROR_FAILURE;
}
nsCAutoString name ;
GetRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Mozilla\\Desktop",
"HKEY_LOCAL_MACHINE\\Software\\Clients\\Mail", name);
nsCAutoString appName (NS_ConvertUCS2toUTF8(brandName()).get());
if (!name.IsEmpty() && !appName.IsEmpty() && name.Equals(appName)) {
nsCAutoString keyName("HKEY_LOCAL_MACHINE\\Software\\Clients\\Mail\\");
keyName.Append(appName.get());
keyName.Append("\\protocols\\mailto\\shell\\open\\command");
nsCAutoString appPath ;
GetRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Mozilla\\Desktop",
keyName.get(), appPath);
if (!appPath.IsEmpty()) {
keyName.Assign("Software\\Clients\\Mail\\");
keyName.Append(appName.get());
keyName.Append("\\protocols\\mailto\\shell\\open\\command");
result = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(),
"", (char *)appPath.get());
if (NS_SUCCEEDED(result)) {
PRInt32 index = appPath.RFind("\\");
if (index != kNotFound)
appPath.Truncate(index + 1);
appPath += "mozMapi32.dll";
keyName.Assign("Software\\Clients\\Mail\\");
keyName.Append(appName.get());
result = SetRegistryKey(HKEY_LOCAL_MACHINE,
keyName.get(),
"DLLPath", (char *) appPath.get());
}
}
}
if (!name.IsEmpty()) {
if (NS_SUCCEEDED(result)) {
mailKeySet = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Clients\\Mail",
"", (char *)name.get());
}
}
else
mailKeySet = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Clients\\Mail",
"", "");
if (NS_SUCCEEDED(mailKeySet)) {
nsCAutoString userAppName ;
GetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"HKEY_CURRENT_USER\\Software\\Clients\\Mail", userAppName);
nsresult desktopKeySet = NS_OK;
if (!userAppName.IsEmpty()) {
desktopKeySet = SetRegistryKey(HKEY_CURRENT_USER,
"Software\\Clients\\Mail",
"", (char *)userAppName.get());
}
else {
DeleteRegistryValue(HKEY_CURRENT_USER, "Software\\Clients\\Mail", "");
}
if (NS_SUCCEEDED(desktopKeySet)) {
desktopKeySet = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"defaultMailHasBeenSet", "0");
}
::SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM)"Software\\Clients\\Mail");
UnregisterServer(CLSID_CMapiImp, "mozMapi", "mozMapi.1");
return desktopKeySet;
}
return mailKeySet;
}
/** Returns FALSE if showMapiDialog is set to 0.
* Returns TRUE otherwise
* Also returns TRUE if the Mozilla has been set as the default mail client
* and some other application has changed that setting.
* This function gets called only if the current app is not the default mail
* client
*/
PRBool nsMapiRegistryUtils::getShowDialog() {
PRBool rv = PR_FALSE;
nsCAutoString showDialog ;
GetRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Mozilla\\Desktop",
"showMapiDialog", showDialog);
// if the user has not selected the checkbox, show dialog
if (showDialog.IsEmpty() || showDialog.Equals("1"))
rv = PR_TRUE;
if (!rv) {
// even if the user has selected the checkbox
// show it if some other application has changed the
// default setting.
nsCAutoString setMailDefault ;
GetRegistryKey(HKEY_LOCAL_MACHINE,"Software\\Mozilla\\Desktop",
"defaultMailHasBeenSet", setMailDefault);
if (setMailDefault.Equals("1")) {
// need to reset the defaultMailHasBeenSet to "0"
// so that after the dialog is displayed once,
// we do not keep displaying this dialog after the user has
// selected the checkbox
rv = SetRegistryKey(HKEY_LOCAL_MACHINE,
"Software\\Mozilla\\Desktop",
"defaultMailHasBeenSet", "0");
rv = PR_TRUE;
}
}
return rv;
}
nsresult nsMapiRegistryUtils::MakeMapiStringBundle(nsIStringBundle ** aMapiStringBundle)
{
nsresult rv = NS_OK ;
if (m_mapiStringBundle)
{
*aMapiStringBundle = m_mapiStringBundle ;
NS_ADDREF(*aMapiStringBundle);
return rv ;
}
nsCOMPtr<nsIStringBundleService> bundleService(do_GetService(
kStringBundleServiceCID, &rv));
if (NS_FAILED(rv) || !bundleService) return NS_ERROR_FAILURE;
rv = bundleService->CreateBundle(
MAPI_PROPERTIES_CHROME,
getter_AddRefs(m_mapiStringBundle));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
NS_ADDREF(*aMapiStringBundle = m_mapiStringBundle) ;
return rv ;
}
nsresult nsMapiRegistryUtils::ShowMapiErrorDialog()
{
nsresult rv;
nsCOMPtr<nsIPromptService> promptService(do_GetService(
"@mozilla.org/embedcomp/prompt-service;1", &rv));
if (NS_SUCCEEDED(rv) && promptService)
{
nsCOMPtr<nsIStringBundle> bundle;
rv = MakeMapiStringBundle (getter_AddRefs (bundle)) ;
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString dialogTitle;
const PRUnichar *brandStrings[] = { brandName() };
NS_NAMED_LITERAL_STRING(dialogTitlePropertyTag, "errorMessageTitle");
rv = bundle->FormatStringFromName(dialogTitlePropertyTag.get(),
brandStrings, 1,
getter_Copies(dialogTitle));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsXPIDLString dialogText;
NS_NAMED_LITERAL_STRING(dialogTextPropertyTag, "errorMessage");
rv = bundle->FormatStringFromName(dialogTextPropertyTag.get(),
brandStrings, 1,
getter_Copies(dialogText));
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = promptService->Alert(nsnull, dialogTitle,
dialogText);
}
return rv;
}

View File

@@ -1,112 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsmapiregistryutils_h____
#define nsmapiregistryutils_h____
#include <windows.h>
#include <string.h>
#include <winreg.h>
#include "Registry.h"
#include "nsString.h"
#include "nsIStringBundle.h"
class nsMapiRegistryUtils
{
private :
nsCAutoString m_thisApp ;
nsAutoString m_brand ;
nsAutoString m_versionNo ;
nsCOMPtr<nsIStringBundle> m_mapiStringBundle ;
public :
nsMapiRegistryUtils() ;
// returns TRUE if the Mapi32.dll is smart dll.
PRBool isSmartDll();
// returns TRUE if the Mapi32.dll is a Mozilla dll.
PRBool isMozDll();
// Returns the (fully-qualified) name of this executable.
const char * thisApplication() ;
// This returns the brand name for this application
const PRUnichar * brandName() ;
// This returns the version no for this application
const PRUnichar * versionNo() ;
// verifyRestrictedAccess - Returns PR_TRUE if this user only has restricted access
// to the registry keys we need to modify.
PRBool verifyRestrictedAccess() ;
// set the Windows registry key
nsresult SetRegistryKey(HKEY baseKey, const char * keyName,
const char * valueName, char * value);
// delete a registry key
nsresult DeleteRegistryValue(HKEY baseKey, const char * keyName,
const char * valueName);
// get a Windows registry key
void GetRegistryKey(HKEY baseKey, const char * keyName,
const char * valueName, nsCAutoString & value) ;
// Returns TRUE if the current application is default mail client.
PRBool IsDefaultMailClient();
// Sets Mozilla as default Mail Client
nsresult setDefaultMailClient() ;
// Removes Mozilla as the default Mail client and restores the previous setting
nsresult unsetDefaultMailClient() ;
// Saves the current setting of the default Mail Client in
// HKEY_LOCAL_MACHINE\\Software\\Mozilla\\Desktop
nsresult saveDefaultMailClient();
// Saves the current user setting of the default Mail Client in
// HKEY_LOCAL_MACHINE\\Software\\Mozilla\\Desktop
nsresult saveUserDefaultMailClient();
nsresult CopyMozMapiToWinSysDir();
nsresult RestoreBackedUpMapiDll();
// Returns FALSE if showMapiDialog is set to 0.
PRBool getShowDialog() ;
// create a string bundle for MAPI messages
nsresult MakeMapiStringBundle(nsIStringBundle ** aMapiStringBundle) ;
// display an error dialog for MAPI messages
nsresult ShowMapiErrorDialog() ;
} ;
#endif

View File

@@ -1,30 +0,0 @@
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:chrome="http://www.mozilla.org/rdf/chrome#">
<!-- list all the packages being supplied by this jar -->
<RDF:Seq about="urn:mozilla:package:root">
<RDF:li resource="urn:mozilla:package:messenger-mapi"/>
</RDF:Seq>
<!-- package information -->
<RDF:Description about="urn:mozilla:package:messenger-mapi"
chrome:displayName="Messenger"
chrome:author="mozilla.org"
chrome:name="messenger-mapi"
chrome:localeVersion="0.9.7"
chrome:skinVersion="0.9.4">
</RDF:Description>
<!-- overlay information -->
<RDF:Seq about="urn:mozilla:overlays">
<RDF:li resource="chrome://messenger/content/pref-mailnews.xul"/>
</RDF:Seq>
<!-- mapi items for Mail And Newsgroups preferences pane -->
<RDF:Seq about="chrome://messenger/content/pref-mailnews.xul">
<RDF:li>chrome://messenger-mapi/content/pref-mailnewsOverlay.xul</RDF:li>
</RDF:Seq>
</RDF:RDF>

View File

@@ -1,3 +0,0 @@
messenger.jar:
content/messenger-mapi/pref-mailnewsOverlay.xul
content/messenger-mapi/contents.rdf

View File

@@ -1,29 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
DEPTH=..\..\..\..
include <$(DEPTH)\config\rules.mak>
chrome::
$(REGCHROME) content messenger-mapi messenger.jar

View File

@@ -1,14 +0,0 @@
<?xml version="1.0"?>
<RDF:RDF xmlns:chrome="http://www.mozilla.org/rdf/chrome#"
xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<!-- mapi items for mailnews preferences -->
<RDF:Seq about="urn:mozilla:overlays">
<RDF:li resource="chrome://messenger/content/pref-mailnews.xul"/>
</RDF:Seq>
<RDF:Seq about="chrome://messenger/content/pref-mailnews.xul">
<RDF:li>chrome://messenger/content/pref-mailnewsOverlay.xul</RDF:li>
</RDF:Seq>
</RDF:RDF>

View File

@@ -1,104 +0,0 @@
/*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Srilatha Moturi <srilatha@netscape.com>
*/
function mailnewsOverlayStartup() {
mailnewsOverlayInit();
parent.hPrefWindow.registerOKCallbackFunc(onOK);
if (!("mapiPref" in parent)) {
parent.mapiPref = new Object;
parent.mapiPref.isDefaultMailClient =
document.getElementById("mailnewsEnableMapi").checked;
}
else {
// when we switch between different panes
// set the checkbox based on the saved state
var mailnewsEnableMapi = document.getElementById("mailnewsEnableMapi");
if (parent.mapiPref.isDefaultMailClient)
mailnewsEnableMapi.setAttribute("checked", "true");
else
mailnewsEnableMapi.setAttribute("checked", "false");
}
}
function mailnewsOverlayInit() {
try {
var mapiRegistry = Components.classes[ "@mozilla.org/mapiregistry;1" ].
getService( Components.interfaces.nsIMapiRegistry );
}
catch(ex){
mapiRegistry = null;
}
const prefbase = "system.windows.lock_ui.";
var mailnewsEnableMapi = document.getElementById("mailnewsEnableMapi");
if (mapiRegistry) {
// initialise preference component.
// While the data is coming from the system registry, we use a set
// of parallel preferences to indicate if the ui should be locked.
try {
var prefService = Components.classes["@mozilla.org/preferences-service;1"]
.getService()
.QueryInterface(Components.interfaces.nsIPrefService);
var prefBranch = prefService.getBranch(prefbase);
if (prefBranch && prefBranch.prefIsLocked("default_mail_client")) {
if (prefBranch.getBoolPref("default_mail_client"))
mapiRegistry.setDefaultMailClient();
else
mapiRegistry.unsetDefaultMailClient();
mailnewsEnableMapi.setAttribute("disabled", "true");
}
}
catch(ex) {}
if (mapiRegistry.isDefaultMailClient)
mailnewsEnableMapi.setAttribute("checked", "true");
else
mailnewsEnableMapi.setAttribute("checked", "false");
}
else
mailnewsEnableMapi.setAttribute("disabled", "true");
}
function onEnableMapi() {
// save the state of the checkbox
if ("mapiPref" in parent)
parent.mapiPref.isDefaultMailClient =
document.getElementById("mailnewsEnableMapi").checked;
}
function onOK()
{
try {
var mapiRegistry = Components.classes[ "@mozilla.org/mapiregistry;1" ].
getService( Components.interfaces.nsIMapiRegistry );
}
catch(ex){
mapiRegistry = null;
}
if (mapiRegistry &&
("mapiPref" in parent) &&
(mapiRegistry.isDefaultMailClient != parent.mapiPref.isDefaultMailClient)) {
if (parent.mapiPref.isDefaultMailClient)
mapiRegistry.setDefaultMailClient();
else
mapiRegistry.unsetDefaultMailClient();
}
}

View File

@@ -1,44 +0,0 @@
<?xml version="1.0"?>
<!--
The contents of this file are subject to the Mozilla 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/MPL/
oftware 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) 2001 Netscape Communications Corporation. All
Rights Reserved.
Contributor(s):
Srilatha Moturi <srilatha@netscape.com>
-->
<!DOCTYPE window [
<!ENTITY % brandDTD SYSTEM "chrome://global/locale/brand.dtd" >
%brandDTD;
<!ENTITY % prefMailnewsOverlayDTD SYSTEM "chrome://messenger-mapi/locale/pref-mailnewsOverlay.dtd" >
%prefMailnewsOverlayDTD;
]>
<overlay id="prefMailnewsOverlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript">
<![CDATA[
_elementIDs.push("mailnewsEnableMapi");
]]>
</script>
<script type="application/x-javascript" src="chrome://messenger-mapi/content/pref-mailnewsOverlay.js"/>
<hbox autostretch="never" id="mapi">
<checkbox id="mailnewsEnableMapi" label="&enableMapi.label;"
accesskey="&enableMapi.accesskey;"
preftype="bool" prefstring="mailnews.default_mail_client" prefattribute="checked"/>
</hbox>
</overlay>

View File

@@ -1,23 +0,0 @@
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:chrome="http://www.mozilla.org/rdf/chrome#">
<!-- list all the skins being supplied by this package -->
<RDF:Seq about="urn:mozilla:locale:root">
<RDF:li resource="urn:mozilla:locale:en-US"/>
</RDF:Seq>
<!-- locale information -->
<RDF:Description about="urn:mozilla:locale:en-US">
<chrome:packages>
<RDF:Seq about="urn:mozilla:locale:en-US:packages">
<RDF:li resource="urn:mozilla:locale:en-US:messenger-mapi"/>
</RDF:Seq>
</chrome:packages>
</RDF:Description>
<!-- Version Information. State that we work only with major version of this
package. -->
<RDF:Description about="urn:mozilla:locale:en-US:messenger-mapi"
chrome:localeVersion="0.9.7"/>
</RDF:RDF>

View File

@@ -1,4 +0,0 @@
en-US.jar:
locale/en-US/messenger-mapi/pref-mailnewsOverlay.dtd
locale/en-US/messenger-mapi/mapi.properties
locale/en-US/messenger-mapi/contents.rdf

View File

@@ -1,40 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
DEPTH=..\..\..\..\..
CHROME_DIR=locales\en-US
CHROME_L10N_DIR=messenger\locale
CHROME_L10N = \
.\pref-mailnewsOverlay.dtd \
.\mapi.properties \
.\contents.rdf \
$(NULL)
include <$(DEPTH)\config\rules.mak>
chrome::
$(REGCHROME) locale en-US/messenger-mapi en-US.jar

View File

@@ -1,23 +0,0 @@
# Mail Integration Dialog
dialogTitle=%S Mail
dialogText=Do you want to use %S as the default mail application?
checkboxText=Do not display this dialog again
# MAPI Messages
loginText=Please enter your password for %S:
loginTextwithName=Please enter your username and password
loginTitle=%S Mail
PasswordTitle=%S Mail
# MAPI Error Messages
errorMessage=%S Mail could not be set as the default mail application because a registry key could not be updated. Verify with your system administrator that you have write access to your system registry, and then try again.
errorMessageTitle=%S Mail
# MAPI Security Messages
mapiBlindSendWarning=Another application is attempting to send mail using your user profile. Are you sure you want to send mail?
mapiBlindSendDontShowAgain=Warn me whenever other applications try to send mail from me
#Default Mail Display String
# localization note, $1%S is the app name, $2%S is the version
defaultMailDisplayTitle=%S %S Mail

View File

@@ -1,3 +0,0 @@
<!ENTITY enableMapiTitle.label "When sending mail from other applications">
<!ENTITY enableMapi.label "Use &vendorShortName; Mail as the default mail application.">
<!ENTITY enableMapi.accesskey "u">

View File

@@ -1,28 +0,0 @@
#!nmake
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
DEPTH=..\..\..\..
DIRS=en-US
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,27 +0,0 @@
#
# The contents of this file are subject to the Mozilla 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/MPL/
#
# 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) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
# Srilatha Moturi <srilatha@netscape.com>
#
DEPTH=..\..\..
DIRS=content locale
include <$(DEPTH)\config\rules.mak>

6
mozilla/netwerk/cache/public/MANIFEST vendored Normal file
View File

@@ -0,0 +1,6 @@
nsICachedNetData.idl
nsINetDataCache.idl
nsINetDataCacheManager.idl
nsINetDataCacheRecord.idl
nsINetDataDiskCache.idl
nsIStreamAsFile.idl

View File

@@ -0,0 +1,60 @@
#
# 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@
MODULE = nkcache
XPIDL_MODULE = necko_cache
include $(DEPTH)/config/autoconf.mk
XPIDLSRCS = $(NULL)
ifdef OLD_CACHE
XPIDLSRCS += \
nsICachedNetData.idl \
nsINetDataCacheManager.idl \
nsINetDataCache.idl \
nsINetDataCacheRecord.idl \
nsINetDataDiskCache.idl \
nsIStreamAsFile.idl \
$(NULL)
endif
ifdef MOZ_NEW_CACHE
XPIDLSRCS += \
nsICache.idl \
nsICacheEntryDescriptor.idl \
nsICacheListener.idl \
nsICacheService.idl \
nsICacheSession.idl \
nsICacheVisitor.idl \
$(NULL)
endif
EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS))
include $(topsrcdir)/config/rules.mk

53
mozilla/netwerk/cache/public/Makefile.win vendored Executable file
View File

@@ -0,0 +1,53 @@
#!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
XPIDL_MODULE = necko_cache
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
EXPORTS = \
$(NULL)
XPIDLSRCS = \
!ifdef MOZ_OLD_CACHE
.\nsICachedNetData.idl \
.\nsINetDataCacheManager.idl \
.\nsINetDataCache.idl \
.\nsINetDataCacheRecord.idl \
.\nsINetDataDiskCache.idl \
.\nsIStreamAsFile.idl \
!endif
!ifdef MOZ_NEW_CACHE
.\nsICache.idl \
.\nsICacheEntryDescriptor.idl \
.\nsICacheListener.idl \
.\nsICacheService.idl \
.\nsICacheSession.idl \
.\nsICacheVisitor.idl \
!endif
$(NULL)
include <$(DEPTH)/config/rules.mak>

View File

@@ -0,0 +1,170 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsICache.idl, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsISupports.idl"
typedef long nsCacheStoragePolicy;
typedef long nsCacheAccessMode;
/**
* nsICache is a namespace for various cache constants. It does not represent
* an actual object.
*/
[scriptable, uuid(ec1c0063-197d-44bb-84ba-7525d50fc937)]
interface nsICache
{
/**
* Access Modes
*
*
* Mode Requested | Not Cached | Cached
* ------------------------------------------------------------------------
* READ | KEY_NOT_FOUND | NS_OK
* | Mode = NONE | Mode = READ
* | No Descriptor | Descriptor
* ------------------------------------------------------------------------
* WRITE | NS_OK | NS_OK (Cache service
* | Mode = WRITE | Mode = WRITE dooms existing
* | Descriptor | Descriptor cache entry)
* ------------------------------------------------------------------------
* READ_WRITE | NS_OK | NS_OK
* (1st req.) | Mode = WRITE | Mode = READ_WRITE
* | Descriptor | Descriptor
* ------------------------------------------------------------------------
* READ_WRITE | N/A | NS_OK
* (Nth req.) | | Mode = READ
* | | Descriptor
* ------------------------------------------------------------------------
*
*
* Access Requested:
*
* READ - I only want to READ, if there isn't an entry just fail
* WRITE - I have something new I want to write into the cache, make
* me a new entry and doom the old one, if any.
* READ_WRITE - I want to READ, but I'm willing to update an existing
* entry if necessary, or create a new one if none exists.
*
*
* Access Granted:
*
* NONE - No descriptor is provided. You get zilch. Nada. Nothing.
* READ - You can READ from this descriptor.
* WRITE - You must WRITE to this descriptor because the cache entry
* was just created for you.
* READ_WRITE - You can READ the descriptor to determine if it's valid,
* you may WRITE if it needs updating.
*
*
* Comments:
*
* If you think that you might need to modify cached data or meta data,
* then you must open a cache entry requesting WRITE access. Only one
* cache entry descriptor, per cache entry, will be granted WRITE access.
*
* Usually, you will request READ_WRITE access in order to first test the
* meta data and informational fields to determine if a write (ie. going
* to the net) may actually be necessary. If you determine that it is
* not, then you would mark the cache entry as valid (using MarkValid) and
* then simply read the data from the cache.
*
* A descriptor granted WRITE access has exclusive access to the cache
* entry up to the point at which it marks it as valid. Once the cache
* entry has been "validated", other descriptors with READ access may be
* opened to the cache entry.
*
* If you make a request for READ_WRITE access to a cache entry, the cache
* service will downgrade your access to READ if there is already a
* cache entry descriptor open with WRITE access.
*
* If you make a request for only WRITE access to a cache entry and another
* descriptor with WRITE access is currently open, then the existing cache
* entry will be 'doomed', and you will be given a descriptor (with WRITE
* access only) to a new cache entry.
*
*/
const nsCacheAccessMode ACCESS_NONE = 0;
const nsCacheAccessMode ACCESS_READ = 1;
const nsCacheAccessMode ACCESS_WRITE = 2;
const nsCacheAccessMode ACCESS_READ_WRITE = 3;
/**
* Storage Policy
*
* The storage policy of a cache entry determines the device(s) to which
* it belongs. See nsICacheSession and nsICacheEntryDescriptor for more
* details.
*
* STORE_ANYWHERE - Allows the cache entry to be stored in any device.
* The cache service decides which cache device to use
* based on "some resource management calculation."
* STORE_IN_MEMORY - Requires the cache entry to reside in non-persistent
* storage (ie. typically in system RAM).
* STORE_ON_DISK - Requires the cache entry to reside in persistent
* storage (ie. typically on a system's hard disk).
* STORE_ON_DISK_AS_DISK - Requires the cache entry to reside in persistent
* storage, and in a specific file.
*/
const nsCacheStoragePolicy STORE_ANYWHERE = 0;
const nsCacheStoragePolicy STORE_IN_MEMORY = 1;
const nsCacheStoragePolicy STORE_ON_DISK = 2;
const nsCacheStoragePolicy STORE_ON_DISK_AS_FILE = 3;
/**
* All entries for a cache session are stored as streams of data or
* as objects. These constant my be used to specify the type of entries
* when calling nsICacheService::CreateSession().
*/
const long NOT_STREAM_BASED = 0;
const long STREAM_BASED = 1;
/**
* The synchronous OpenCacheEntry() may be blocking or non-blocking. If a cache entry is
* waiting to be validated by another cache descriptor (so no new cache descriptors for that
* key can be created, OpenCacheEntry() will return NS_ERROR_CACHE_WAIT_FOR_VALIDATION in
* non-blocking mode. In blocking mode, it will wait until the cache entry for the key has
* been validated or doomed. If the cache entry is validated, then a descriptor for that
* entry will be created and returned. If the cache entry was doomed, then a descriptor
* will be created for a new cache entry for the key.
*/
const long NON_BLOCKING = 0;
const long BLOCKING = 1;
};
%{C++
/**
* Cache specific nsresult error codes
*/
#define NS_ERROR_CACHE_KEY_NOT_FOUND NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 61)
#define NS_ERROR_CACHE_DATA_IS_STREAM NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 62)
#define NS_ERROR_CACHE_DATA_IS_NOT_STREAM NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 63)
#define NS_ERROR_CACHE_WAIT_FOR_VALIDATION NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 64)
#define NS_ERROR_CACHE_ENTRY_DOOMED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 65)
#define NS_ERROR_CACHE_READ_ACCESS_DENIED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 66)
#define NS_ERROR_CACHE_WRITE_ACCESS_DENIED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 67)
%}

View File

@@ -0,0 +1,137 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsICacheEntryDescriptor.idl, released
* February 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsICacheVisitor.idl"
#include "nsICache.idl"
interface nsISimpleEnumerator;
interface nsICacheListener;
interface nsITransport;
interface nsIFile;
interface nsICacheMetaDataVisitor;
[scriptable, uuid(49c1a11d-f5d2-4f09-8262-551e64908ada)]
interface nsICacheEntryDescriptor : nsICacheEntryInfo
{
/**
* Set the time at which the cache entry should be considered invalid (in
* seconds since the Epoch).
*/
void setExpirationTime(in PRUint32 expirationTime);
/**
* Set the cache entry data size. This will fail if the cache entry
* IS stream based.
*/
void setDataSize(in unsigned long size);
/**
* Get a transport to the cache data. This will fail if the cache entry
* IS NOT stream based.
*/
readonly attribute nsITransport transport;
/**
* Get/set the cache data element. This will fail if the cache entry
* IS stream based. The cache entry holds a strong reference to this
* object. The object will be released when the cache entry is destroyed.
*/
attribute nsISupports cacheElement;
/**
* Get the access granted to this descriptor. See nsICache.idl for the
* definitions of the access modes and a thorough description of their
* corresponding meanings.
*/
readonly attribute nsCacheAccessMode accessGranted;
/**
* Get/set the storage policy of the cache entry. See nsICache.idl for
* the definitions of the storage policies.
*/
attribute nsCacheStoragePolicy storagePolicy;
/**
* Get the disk file associated with the cache entry.
*/
readonly attribute nsIFile file;
/**
* Get/set security info on the cache entry for this descriptor. This fails
* if the storage policy is not STORE_IN_MEMORY.
*/
attribute nsISupports securityInfo;
/**
* Doom the cache entry this descriptor references in order to slate it for
* removal. Once doomed a cache entry cannot be undoomed.
*
* A descriptor with WRITE access can doom the cache entry and choose to
* fail pending requests. This means that pending requests will not get
* a cache descriptor. This is meant as a tool for clients that wish to
* instruct pending requests to skip the cache.
*/
void doom();
void doomAndFailPendingRequests(in nsresult status);
/**
* A writer must validate this cache object before any readers are given
* a descriptor to the object.
*/
void markValid();
/**
* Explicitly close the descriptor (optional).
*/
void close();
/**
* Methods for accessing meta data. Meta data is a table of key/value
* string pairs. The strings do not have to conform to any particular
* charset, but they must be null terminated.
*/
string getMetaDataElement(in string key);
void setMetaDataElement(in string key, in string value);
/**
* Visitor will be called with key/value pair for each meta data element.
*/
void visitMetaData(in nsICacheMetaDataVisitor visitor);
};
[scriptable, uuid(22f9a49c-3cf8-4c23-8006-54efb11ac562)]
interface nsICacheMetaDataVisitor : nsISupports
{
/**
* Called for each key/value pair in the meta data for a cache entry
*/
boolean visitMetaDataElement(in string key,
in string value);
};

View File

@@ -0,0 +1,44 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsICacheListener.idl, released January 19, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsISupports.idl"
#include "nsICache.idl"
interface nsICacheEntryDescriptor;
[scriptable, uuid(638c3848-778b-4851-8ff3-9400f65b8773)]
interface nsICacheListener : nsISupports
{
/**
* Called when the requested access (or appropriate subset) is
* acquired. The status parameter equals NS_OK on success.
* See nsICacheService.idl for accessGranted values.
*/
void onCacheEntryAvailable(in nsICacheEntryDescriptor descriptor,
in nsCacheAccessMode accessGranted,
in nsresult status);
};

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 Mozilla 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/MPL/
*
* 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 nsICacheService.idl, released February 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsISupports.idl"
#include "nsICache.idl"
interface nsISimpleEnumerator;
interface nsICacheListener;
interface nsICacheSession;
interface nsICacheVisitor;
[scriptable, uuid(0ebec4c7-742f-4f27-8e7b-7c8a0cc76348)]
interface nsICacheService : nsISupports
{
/**
* Initialize the cache service.
*/
void init();
/**
* Shutdown the cache service.
*/
void shutdown();
/**
* Create a cache session
*
* A cache session represents a client's access into the cache. The cache
* session is not "owned" by the cache service. Hence, it is possible to
* create duplicate cache sessions. Entries created by a cache session
* are invisible to other cache sessions, unless the cache sessions are
* equivalent.
*
* @param clientID - Specifies the name of the client using the cache.
* @param storagePolicy - Limits the storage policy for all entries
* accessed via the returned session. As a result, devices excluded
* by the storage policy will not be searched when opening entries
* from the returned session.
* @param streamBased - Indicates whether or not the data being cached
* can be represented as a stream. The storagePolicy must be
* consistent with the value of this field. For example, a non-stream-
* based cache entry can only have a storage policy of STORE_IN_MEMORY.
* @return new cache session.
*/
nsICacheSession createSession(in string clientID,
in nsCacheStoragePolicy storagePolicy,
in boolean streamBased);
/**
* Visit entries stored in the cache. Used to implement about:cache.
*/
void visitEntries(in nsICacheVisitor visitor);
/**
* Evicts all entries in all devices implied by the storage policy.
*/
void evictEntries(in nsCacheStoragePolicy storagePolicy);
};

View File

@@ -0,0 +1,72 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsICacheSession.idl, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsISupports.idl"
#include "nsICache.idl"
interface nsICacheEntryDescriptor;
interface nsICacheListener;
[scriptable, uuid(b4b419ad-28b7-4d25-9988-20fa98505a19)]
interface nsICacheSession : nsISupports
{
/**
* Expired entries will be doomed or evicted if this attribute is set to
* true. If false, expired entries will be returned (useful for offline-
* mode and clients, such as HTTP, that can update the valid lifetime of
* cached content). This attribute defaults to true.
*/
attribute PRBool doomEntriesIfExpired;
/**
* A cache session can only give out one descriptor with WRITE access
* to a given cache entry at a time. Until the client calls MarkValid on
* its descriptor, other attempts to open the same cache entry will block.
*/
/**
* Synchronous cache access. This returns a unique descriptor each
* time it is called, even if the same key is specified. When
* called by multiple threads for write access, only one writable
* descriptor will be granted. If 'blocking' is set to false,
*/
nsICacheEntryDescriptor openCacheEntry(in string key,
in nsCacheAccessMode accessRequested,
in boolean blockingMode);
/**
* Asynchronous cache access. Does not block the calling thread.
* Instead, the listener will be notified when the descriptor is
* available.
*/
void asyncOpenCacheEntry(in string key,
in nsCacheAccessMode accessRequested,
in nsICacheListener listener);
/**
* Evict all entries for this session's clientID according to its storagePolicy.
*/
void evictEntries();
};

View File

@@ -0,0 +1,142 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsICacheVisitor.idl, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsISupports.idl"
/* XXX we should define device and entry info as well (stats, etc) */
interface nsICacheDeviceInfo;
interface nsICacheEntryInfo;
[scriptable, uuid(f8c08c4b-d778-49d1-a59b-866fdc500d95)]
interface nsICacheVisitor : nsISupports
{
/**
* Called to provide information about a cache device.
*
* @param deviceID - specifies the device being visited.
* @param deviceInfo - specifies information about this device.
*
* @return true to start visiting all entries for this device.
* @return false to advance to the next device.
*/
boolean visitDevice(in string deviceID,
in nsICacheDeviceInfo deviceInfo);
/**
* Called to provide information about a cache entry.
*
* @param deviceID - specifies the device being visited.
* @param entryInfo - specifies information about this entry.
*
* @return true to visit the next entry on the current device, or if the
* end of the device has been reached, advance to the next device.
* @return false to advance to the next device.
*/
boolean visitEntry(in string deviceID,
in nsICacheEntryInfo entryInfo);
};
[scriptable, uuid(31d1c294-1dd2-11b2-be3a-c79230dca297)]
interface nsICacheDeviceInfo : nsISupports
{
/**
* Get a human readable description of the cache device.
*/
readonly attribute string description;
/**
* Get a usage report, statistics, miscellaneous data about
* the cache device.
*/
readonly attribute string usageReport;
/**
* Get the number of stored cache entries.
*/
readonly attribute unsigned long entryCount;
/**
* Get the total size of the stored cache entries.
*/
readonly attribute unsigned long totalSize;
/**
* Get the upper limit of the size of the data the cache can store.
*/
readonly attribute unsigned long maximumSize;
};
[scriptable, uuid(72c64022-1dd2-11b2-b3a5-b8b859e0a1b2)]
interface nsICacheEntryInfo : nsISupports
{
/**
* Get the client id associated with this cache entry.
*/
readonly attribute string clientID;
/**
* Get the id for the device that stores this cache entry.
*/
readonly attribute string deviceID;
/**
* Get the key identifying the cache entry.
*/
readonly attribute string key;
/**
* Get the number of times the cache entry has been opened.
*/
readonly attribute long fetchCount;
/**
* Get the last time the cache entry was opened (in seconds since the Epoch).
*/
readonly attribute PRUint32 lastFetched;
/**
* Get the last time the cache entry was modified (in seconds since the Epoch).
*/
readonly attribute PRUint32 lastModified;
/**
* Get the expiration time of the cache entry (in seconds since the Epoch).
*/
readonly attribute PRUint32 expirationTime;
/**
* Get the cache entry data size.
*/
readonly attribute unsigned long dataSize;
/**
* Find out whether or not the cache entry is stream based.
*/
boolean isStreamBased();
};

View File

@@ -0,0 +1,240 @@
/* -*- 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 "nsrootidl.idl"
#include "nsISupports.idl"
interface nsIURI;
interface nsIObserver;
interface nsIChannel;
interface nsINetDataCache;
interface nsINetDataCacheRecord;
interface nsILoadGroup;
interface nsIStreamListener;
/**
* The nsICachedNetData interface represents a single entry in a database that
* caches data retrieved from the network. This interface is implemented by the
* cache manager on top of the low-level nsINetDataCacheRecord and
* nsINetDataCache interfaces that are implemented by the database.
*
* Each cache record may contain both content and metadata. The content may
* be, for example, GIF image data or HTML, and it is accessed through
* nsIChannel's streaming API. The opaque metadata, which may contain HTTP
* headers among other things, is stored as a byte array. Each entry in the
* cache is indexed by two different keys: a record id number and a key created
* by combining the URI with a "secondary key", e.g. HTTP post data.
*
* @See nsINetDataCacheRecord
* @See nsINetDataCache
* @See nsINetDataDiskCache
* @See nsINetDataCacheManager
*/
[scriptable, uuid(6aeb2a40-6d43-11d3-90c8-000064657374)]
interface nsICachedNetData : nsISupports
{
/**
* String form of the URI provided as an argument to the call to
* nsINetDataCacheManager::GetCachedNetData() that created this record.
*/
readonly attribute string uriSpec;
/**
* Getter for the opaque secondary database key provided as an argument to
* the call to nsINetDataCacheManager::GetCachedNetData() that created this
* record.
*/
void getSecondaryKey(out unsigned long length,
[retval, size_is(length)] out string secondaryKey);
/**
* This flag may be set by a protocol handler to indicate that it supports
* partial fetching of data. In that case, the cache manager is permitted
* to truncate the entry's content to accommodate incoming data for other
* cache entries rather than deleting it wholesale.
*/
attribute boolean allowPartial;
/**
* This flag indicates that the write stream supplying content data for the
* cache did not complete normally and, therefore, the content may be
* truncated.
*/
readonly attribute boolean partialFlag;
/**
* This flag can be set and cleared by a protocol handler as a form of
* self-notification, so as to avoid race conditions in which a protocol
* handler issues two identical network requests to fill the same cache
* entry. The cache manager itself largely ignores this flag.
*/
attribute boolean updateInProgress;
/**
* inUse is set if any existing channels are associated with this cache
* entry or if the updateInProgess flag is set. This can be used to
* prevent writing to a cache entry by a protocol handler if it's being
* read or written elsewhere.
*/
readonly attribute boolean inUse;
/**
* Date/time that the document was last stored on the origin server, as
* supplied by the protocol handler. This value is used as input to the
* cache replacement policy, i.e. it is not used for validation. If the
* protocol can't supply a last-modified time, this attribute should remain
* unset. When unset, the value of this attribute is zero.
*
* FIXME: Should use nsIDateTime interface, once it's created
* instead of PRTime, for improved scriptability ?
*/
attribute PRTime lastModifiedTime;
/**
* Supplied by the protocol handler, the expirationTime attribute specifies
* the time until which the document is guaranteed fresh, i.e. the document
* does not have to be validated with the server and, therefore, any data
* in cache is definitely usable. The value of this attribute serves as a
* hint to the cache replacement policy. Only one of either staleTime or
* expirationTime may be set for a single cache record. When unset, the
* value of this attribute is zero.
*/
attribute PRTime expirationTime;
/**
* Date/time supplied by the protocol handler, at which point the content
* is *likely* to be stale, i.e. the data in the cache may be out-of-date
* with respect to the data on the server. This heuristic date does not
* necessarily correspond to the HTTP Expires header, as it does not
* determine when cached network data must be validated with the origin
* server, but only serves as a hint to the cache replacement policy. Only
* one of either staleTime or expirationTime may be set for a single cache
* record. When unset, the value of this attribute is zero.
*/
attribute PRTime staleTime;
/**
* Date/time of last access of the data in this cache record, as determined
* by the cache manager.
*/
readonly attribute PRTime lastAccessTime;
readonly attribute PRTime lastUpdateTime;
/**
* Number of times this record has been accessed since it was first stored.
*/
readonly attribute PRUint16 numberAccesses;
/**
* Accessor methods for opaque meta-data which can be read and updated
* independently of the content data.
*
* The aTag argument can be used to accommodate multiple clients of the
* cache API, each of which wants to store its own private meta-data into
* the cache. For example, there could be a "headers" tag that the HTTP
* protocol handler uses to store http response headers and a "image size"
* tag used to store the image dimensions of a GIF file. The aData
* argument refers to an opaque blob of arbitrary bytes.
*
* IMPORTANT: If aData does not contain byte-oriented data, i.e. it's not a
* string, the contents of aData must be byte-swapped by the,
* caller, so as to make the cache files endian-independent.
*/
void getAnnotation(in string aTag,
out PRUint32 aLength, [size_is(aLength), retval] out string aData);
void setAnnotation(in string aTag,
in PRUint32 aLength, [size_is(aLength)] in string aData);
/**
* As a getter, return the number of content bytes stored in the cache,
* i.e. via the nsIChannel streaming APIs. This may be less than the
* complete content length if a partial cache fill occurred. The cached
* content can be truncated by setting the value of this attribute. The
* value of the attribute represents a logical, not a physical, length. If
* compression has been used, the content may consume less storage than
* indicated by this attribute.
*
* When this attribute is set to zero the associated cache disk file, if
* any, should be deleted.
*/
attribute PRUint32 storedContentLength;
/**
* Length of stored content, which may be less than storage consumed if
* compression is used
*/
readonly attribute PRUint32 logicalLength;
/**
* Opaque security info associated with the cache entry; it can't be serialized
* to disk, so it'll only make sense with memory cache
*/
attribute nsISupports securityInfo;
/**
* Notify any observers associated with this cache entry of the deletion
* request. If all observers drop their reference to the cache entry,
* proceed to delete the underlying cache database record and associated
* content storage.
*/
void delete();
/**
* Flush any changes in this entry's data to the cache database. This
* method will automatically be called when the last reference to the cache
* is dropped, but it can also be called explicitly for a synchronous
* effect.
*/
void commit();
/**
* Parent container cache for this entry.
*/
readonly attribute nsINetDataCache cache;
/**
* Create a channel for reading or writing a stream of content into the
* entry. It is expected that many of the nsIChannel methods return
* NS_NOT_IMPLEMENTED, including:
*
* + GetURI()
* + GetContentType()
* + GetContentLength()
*
* Though nsIChannel provides for both async and synchronous I/O APIs, both
* may not be implemented. Only AsyncRead() and OpenOutputStream() is
* required.
*/
nsIChannel newChannel(in nsILoadGroup aLoadGroup);
/**
* This method can be used by a caching protocol handler to store data in
* the cache by forking an asynchronous read stream so that it is
* simultaneously sent to a requester and written into the cache. This
* method implicitly sets the updateInProgress flag, if it has not already
* been set.
*/
nsIStreamListener interceptAsyncRead(in nsIStreamListener aOriginalListener,
in PRUint32 aStartOffset);
};

View File

@@ -0,0 +1,142 @@
/* -*- 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 "nsISupports.idl"
interface nsIURI;
interface nsINetDataCacheRecord;
interface nsISimpleEnumerator;
/**
* The nsINetDataCache defines the low-level API for a network-data
* cache, used to cache the responses to network retrieval commands.
* This interface, along with nsINetDataCacheRecord, is implemented by
* the memory cache, the file cache and, optionally, by some extension
* caches. This interface is essentially a pseudo-private API for the
* cache manager. Other clients should never use this interface.
*
* Each cache entry may contain both content, e.g. GIF image data, and
* associated metadata, e.g. HTTP headers. Each entry is indexed by two
* different keys: a record id number and a key created by combining the URI
* with a "secondary key", e.g. HTTP post data.
*
* The nsINetDataCache interface is agnostic as to where the data is
* stored and whether the storage is volatile or persistent. The
* memory cache, any disk caches and any extension caches must all
* implement this interface.
*
*/
[scriptable, uuid(ccfc58c0-6dde-11d3-90c8-000064657374)]
interface nsINetDataCache : nsISupports
{
/**
* Human-readable description of the cache module, e.g. "Disk Cache"
*/
readonly attribute wstring description;
/**
* Returns true if cached data is available for the given opaque key,
* even if only partial data is stored.
*/
boolean contains([size_is(length)] in string key, in PRUint32 length);
/**
* Fetch the cache entry record for the given opaque key. If one does not
* exist, create a new, empty record.
*/
nsINetDataCacheRecord getCachedNetData([size_is(length)] in string key,
in PRUint32 length);
/**
* Fetch the cache entry record for the given URI using the record ID as a key.
*/
nsINetDataCacheRecord getCachedNetDataByID(in PRInt32 RecordID);
/**
* False indicates that this cache is entirely bypassed.
*/
attribute boolean enabled;
/**
* Constants for flags attribute, below
*/
// Used for extension caches, e.g. a CD-ROM cache
const long READ_ONLY = 1 << 0;
// One of these bits must be set
const long MEMORY_CACHE = 1 << 1;
const long FLAT_FILE_CACHE = 1 << 2;
const long FILE_PER_URL_CACHE = 1 << 3;
/**
* See constants defined above.
*/
readonly attribute PRUint32 flags;
/**
* Total number of URI entries stored in the cache.
*/
readonly attribute PRUint32 numEntries;
/**
* Maximum number of URI entries that may be stored in the cache.
*/
readonly attribute PRUint32 maxEntries;
/**
* Enumerate the URI entries stored in the cache.
*/
nsISimpleEnumerator newCacheEntryIterator();
/**
* Contains a reference to the next cache in search order. For the memory
* cache, this attribute always references the disk cache. For the disk
* cache, it contains a reference to the first extension cache.
*/
attribute nsINetDataCache nextCache;
/**
* An estimate of the amount of storage occupied by the cache, in kB.
* Actual use may be slightly higher than reported due to cache overhead
* and heap fragmentation (in the memory cache) or block quantization (in
* the disk cache).
*/
readonly attribute PRUint32 storageInUse;
/**
* Remove all entries from a writable cache. This could be used, for
* example, after a guest ends a browser session. This is equivalent to
* setting the cache's Capacity to zero, except that all cache entries,
* even those in active use, will be deleted. Also, any global cache
* database files will be deleted.
*/
void removeAll();
};
%{ C++
// ContractID prefix for Components that implement this interface
#define NS_NETWORK_CACHE_CONTRACTID "@mozilla.org/network/cache;1"
#define NS_NETWORK_MEMORY_CACHE_CONTRACTID NS_NETWORK_CACHE_CONTRACTID "?name=memory-cache"
#define NS_NETWORK_FLAT_CACHE_CONTRACTID NS_NETWORK_CACHE_CONTRACTID "?name=flat-cache"
#define NS_NETWORK_FILE_CACHE_CONTRACTID NS_NETWORK_CACHE_CONTRACTID "?name=file-cache"
%}

View File

@@ -0,0 +1,169 @@
/* -*- 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 "nsISupports.idl"
#include "nsINetDataCache.idl"
interface nsISimpleEnumerator;
interface nsICachedNetData;
interface nsINetDataDiskCache;
interface nsIURI;
/**
* The network-response cache manager is partly responsible for the caching of
* content and associated metadata that has been retrieved via the network.
* (The remaining responsibility for caching lies with individual network
* protocol handlers.)
*
* The cache manager supervises the actions of individual cache components,
* such as the memory cache, the disk cache and any extension caches, e.g. a
* read-only CD-ROM cache.
*
* @See nsINetDataCache
* @See nsICachedNetData
*/
[scriptable, uuid(71c8ab00-6d5c-11d3-90c8-000064657374)]
interface nsINetDataCacheManager : nsISupports
{
/**
* Flag for the GetCachedNetData() method: If set, the memory cache is
* neither searched nor will any data be stored into it. This might be
* appropriate, for example, with images, because they have their own
* cache for storing *decoded* images.
*/
const unsigned long BYPASS_MEMORY_CACHE = 1 << 0;
/**
* Flag for the GetCachedNetData() method: If set, the disk cache
* is neither searched nor will any be data stored into it.
* However, read-only extension caches may be searched. This
* might be used to avoid leaving persistent records of secure
* data.
*/
const unsigned long BYPASS_PERSISTENT_CACHE = 1 << 1;
/**
* Flag for the GetCachedNetData() method: If set, any stream
* content is stored in the cache as a single disk file. Content
* will not be cached in the memory cache nor is it cached in 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 bowser plugin API.
*/
const unsigned long CACHE_AS_FILE = 1 << 2;
/**
These enum's are used for the ClearCache calls.
*/
const unsigned long ALL_CACHES = 1;
const unsigned long MEM_CACHE = 1<<1;
const unsigned long FILE_CACHE = 1<<2;
const unsigned long FLAT_CACHE = 1<<3;
/**
* Fetch the cache entry record for the given URI. If one does not exist,
* create a new, empty record. The normal search order for caches is:
* + Memory cache
* + Disk cache
* + File cache (stream-as-file cache)
* + All extension caches
*
* When writing, data is typically stored in both the memory cache and the
* disk cache. Both the search order and this write policy can be modified by
* setting one or more of the flag argument bits, as defined above.
*
* The optionally-NULL secondaryKey argument can be used, e.g. for form
* post data or for HTTP headers in the case of HTTP.
*/
nsICachedNetData getCachedNetData(in string uri,
[size_is(secondaryKeyLength)] in string secondaryKey,
in PRUint32 secondaryKeyLength,
in PRUint32 flags);
/**
* Returns true if cached content is available for the given URI, even if
* only partial data is stored. The flags argument behaves the same as for
* the GetCachedNetData() method, above.
*/
boolean contains(in string uri,
[size_is(secondaryKeyLength)] in string secondaryKey,
in PRUint32 secondaryKeyLength,
in PRUint32 flags);
/**
* Total number of unexpired URI entries stored in all caches. This number
* does not take into account duplicate URIs, e.g. because the memory cache
* and the disk cache might each contain an entry for the same URI.
*/
readonly attribute PRUint32 numEntries;
/**
* Enumerate the unexpired URI entries stored in all caches. Some URIs may
* be enumerated more than once, e.g. because the the memory cache and the
* disk cache might each contain an entry for the same URI.
*/
nsISimpleEnumerator newCacheEntryIterator();
/*
* Enumerate all the loaded nsINetDataCache-implementing cache modules.
* The first module enumerated will be the memory cache, the second will be
* the disk cache, then the file cache, followed by all the extension
* caches, in search order.
*/
nsISimpleEnumerator newCacheModuleIterator();
/**
* Remove all entries from all writable caches. This could be used, for
* example, after a guest ends a browser session. This is equivalent to
* setting the DiskCacheCapacity to zero, except that all cache entries,
* even those in active use, will be deleted. Also, any global cache
* database files will be deleted.
*/
void removeAll();
/**
* Clears the specified cache
*/
void clear( in PRUint32 aCacheToClear );
/**
* The disk cache is made up of the file cache (for stream-as-file
* requests) and a (possibly independent) persistent cache that handles all
* other cache requests. This attribute sets/gets the combined capacity of
* these caches, measured in KBytes. Setting the capacity lower than the
* current amount of space currently in use may cause cache entries to be
* evicted from the cache to accomodate the requested capacity.
*/
attribute PRUint32 diskCacheCapacity;
/**
* This attribute sets/gets the capacity of the memory cache, measured in
* KBytes. Setting the capacity lower than the current amount of space
* currently in use may cause cache entries to be evicted from the cache to
* accomodate the requested capacity.
*/
attribute PRUint32 memCacheCapacity;
};
%{ C++
// ContractID prefix for Components that implement this interface
#define NS_NETWORK_CACHE_MANAGER_CONTRACTID NS_NETWORK_CACHE_CONTRACTID "?name=manager"
%}

View File

@@ -0,0 +1,131 @@
/* -*- 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 "nsISupports.idl"
#include "nsrootidl.idl"
interface nsIFile;
interface nsIChannel;
interface nsINetDataCache;
/**
* The nsINetDataCacheRecord represents a single entry in a database that
* caches data retrieved from the network. On top of this low-level interface
* to the raw record data, the cache manager implements a higher-level record
* interface, nsICachedNetData. Each instance of nsINetDataCacheRecord is
* (internally) associated with a parent database, an instance of the
* nsINetDataCache interface. This interface is essentially a pseudo-private
* API for the cache manager. Other clients should never use this interface.
*
* Each cache record may contain both content and metadata. The content may
* be, for example, GIF image data or HTML, and it is accessed through
* nsIChannel's streaming API. The opaque metadata, which may contain HTTP
* headers among other things, is accessed as a contiguous byte array. Each
* entry in the cache is indexed by two different keys: a unique record id
* number, generated by the cache, and an opaque string. The latter contains
* the URI and other secondary key information, e.g. HTTP form post key/value
* pairs.
*
* The nsINetDataCacheRecord interface is agnostic as to where the data is
* stored and whether the storage is volatile or persistent. The memory cache,
* the disk cache, a flat-file cache and any read-only extension caches must
* all implement this interface.
*
* @See nsICachedNetData
* @See nsINetDataCache
* @See nsINetDataDiskCache
* @See nsINetDataCacheManager
*/
interface nsILoadGroup;
[scriptable, uuid(fdcdd6a0-7461-11d3-90ca-0040056a906e)]
interface nsINetDataCacheRecord : nsISupports
{
/**
* As far as the nsINetDataCacheRecord implementation is concerned, the
* cache entry database key is an opaque blob, but it's intended to contain
* both the URI and any secondary keys, such as HTTP post data.
*/
void getKey(out unsigned long length, [size_is(length), retval] out string key);
/**
* A persistent record number assigned by the cache which must be unique
* among all entries stored within the same cache. The record ID serves as
* an alternate key to the cache record. Providing that they satisfy the
* afforementioned uniqueness requirement, record IDs can be assigned any
* value by the database except that they may never be zero.
*/
readonly attribute PRInt32 recordID;
/**
* Opaque data which can be updated for each cache entry independently of
* the content data. This data is a combination of protocol-independent
* data provided by the cache manager and protocol-specific meta-data,
* e.g. HTTP headers.
*/
void getMetaData(out PRUint32 length, [size_is(length), retval] out string metaData);
void setMetaData(in PRUint32 length, [size_is(length)] in string data);
/**
* Number of content bytes stored in the cache, i.e. via the nsIChannel
* streaming APIs. This may be less than the complete content length if a
* partial cache fill occurred. Additionally, the cached content can be
* truncated by reducing the value of this attribute. When this attribute
* is set to zero the associated cache disk file, if any, should be
* deleted.
*/
attribute PRUint32 storedContentLength;
/**
* Opaque security info associated with the cache entry; it can't be serialized
* to disk, so it'll only make sense with memory cache
*/
attribute nsISupports securityInfo;
/**
* Delete this cache entry and its associated content.
*/
void delete();
/**
* Create a channel for reading or writing a stream of content into the
* entry. However, many of the nsIChannel methods may return
* NS_NOT_IMPLEMENTED, including:
*
* + GetURI()
* + GetContentType()
* + GetContentLength()
*/
nsIChannel newChannel(in nsILoadGroup loadGroup);
/**
* If a cache is implemented such that it stores each URI's content in an
* individual disk file, this method will identify the file corresponding
* to this record. This may be used to implement the "stream-as-file"
* semantics required by some plugins and by the 'jar:' protocol handler.
* However, not all cache implementations are *required* to store the data
* from each URI in an individual file, so it is acceptable for an
* implementation of this method to signal NS_NOT_IMPLEMENTED.
*/
readonly attribute nsIFile file;
};

View File

@@ -0,0 +1,41 @@
/* -*- 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 "nsINetDataCache.idl"
interface nsIFile;
/**
* A network-data disk cache is used to persistently cache the responses to
* network retrieval commands. Each cache entry may contain both content,
* e.g. GIF image data, and associated metadata, e.g. HTTP headers.
*/
[scriptable, uuid(6408e390-6f13-11d3-90c8-000064657374)]
interface nsINetDataDiskCache : nsINetDataCache
{
/**
* This attribute must be set before calling any other methods of this
* interface.
*/
attribute nsIFile diskCacheFolder;
};

View File

@@ -0,0 +1,106 @@
/* -*- 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 Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Scott Furman, fur@netscape.com
*/
#include "nsrootidl.idl"
#include "nsISupports.idl"
interface nsIFile;
interface nsIStreamAsFileObserver;
/**
* In addition to enhancing effective network response time via caching, the
* cache manager serves a second purpose by providing the stream-as-file
* service required by traditional browser plugins and the jar: protocol
* handler. The interface below provides a means for a client to determine the
* filename associated with a stream and to detect modification/deletion of
* that file.
*/
[scriptable, uuid(0eedbbf0-92d9-11d3-90d3-0040056a906e)]
interface nsIStreamAsFile : nsISupports
{
/**
* Filename containing stream-as-file
*/
readonly attribute nsIFile file;
/**
* Add an observer for this cache record. When the cache wants to delete
* or truncate a record, so as to make space for another cache entry's
* content data, it will call <code>aObserver</code>'s Observe() method,
* passing the nsIStreamAsFile instance as the <code>aSubject</code>
* argument and an appropriate message. If the observer does not wish to
* inhibit deletion/truncation, it should Release() any references it has to the
* cache record.
*
* @See nsIStreamAsFileObserver
*/
void addObserver(in nsIStreamAsFileObserver aObserver);
/**
* Delete an observer that was added by the AddObserver() method.
*/
void removeObserver(in nsIStreamAsFileObserver aObserver);
};
/**
* This interface can be implemented by a client to receive notifications of
* either modification or deletion of a file created by the cache manager using
* the stream-as-file semantics.
*/
[scriptable, uuid(a26e27c0-92da-11d3-90d3-0040056a906e)]
interface nsIStreamAsFileObserver : nsISupports
{
/**
* Flag bits for argument to observeStreamAsFile() method.
*/
const long NOTIFY_AVAILABLE = 1 << 0; // Stream-as-file now available for reading
const long NOTIFY_ERROR = 1 << 1; // Error while loading stream / creating file
const long REQUEST_DELETION = 1 << 2; // Cache manager wishes to delete/truncate file
const long INVALIDATE = 1 << 3; // File is out-of-date
// Convenience value
const long MAKE_UNAVAILABLE = REQUEST_DELETION | INVALIDATE;
/**
* Receive either a notification or a request concerning a file that has
* been opened using stream-as-file. The aMessage and aError arguments
* have varying values depending on the nature of the notification.
* aMessage is set to NOTIFY_AVAILABLE when a complete stream has been read
* and stored on disk in a file. At that point, and no sooner, may the
* filename attribute of the associated nsIStreamAsFile be accessed via the
* associated nsIStreamAsFile interface. If the aMessage argument is
* NOTIFY_ERROR, the aError argument contains the relevant error code. If
* the aMessage argument is either REQUEST_DELETION or REQUEST_TRUNCATION,
* the callee should immediately Release() all references to the
* nsIStreamAsFile (and any references to its associated nsICachedNetData
* instances), unless it wishes to inhibit the requested file modification.
* If the aMessage argument is INVALIDATE, the cache manager is replacing
* the file with a more recent version. If a client wants to continue
* using the (now out-of-date) file, it must delete it when it has finished,
* as the cache manager will effectively relinquished ownership of the
* file.
*/
void observeStreamAsFile(in nsIStreamAsFile aStreamAsFile,
in PRUint32 aMessage,
in nsresult aError);
};

68
mozilla/netwerk/cache/src/Makefile.in vendored Normal file
View File

@@ -0,0 +1,68 @@
#
# 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) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = nkcache
LIBRARY_NAME = nkcache
EXPORT_LIBRARY = 1
IS_COMPONENT = 1
REQUIRES = xpcom string necko pref
EXPORTS = \
nsCacheService.h \
$(NULL)
CPPSRCS = \
nsCache.cpp \
nsCacheEntry.cpp \
nsCacheEntryDescriptor.cpp \
nsCacheMetaData.cpp \
nsCacheModule.cpp \
nsCacheService.cpp \
nsCacheSession.cpp \
nsDiskCacheBinding.cpp \
nsDiskCacheBlockFile.cpp \
nsDiskCacheDevice.cpp \
nsDiskCacheEntry.cpp \
nsDiskCacheMap.cpp \
nsMemoryCacheDevice.cpp \
$(NULL)
include $(topsrcdir)/config/config.mk
EXTRA_DSO_LDOPTS = $(MOZ_COMPONENT_LIBS)
#EXTRA_LIBS = $(NSPR_LIBS)
# 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

69
mozilla/netwerk/cache/src/makefile.win vendored Executable file
View File

@@ -0,0 +1,69 @@
#
# 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 = ..\..\..
include <$(DEPTH)/config/config.mak>
MODULE = nkcache
DLLNAME=nkcache
DLL=.\$(OBJDIR)\$(DLLNAME).dll
MAKE_OBJ_TYPE=DLL
LCFLAGS = -DWIN32_LEAN_AND_MEAN -D_IMPL_NS_NET
EXPORTS = \
nsCacheService.h \
$(NULL)
CPP_OBJS = \
.\$(OBJDIR)\nsCache.obj \
.\$(OBJDIR)\nsCacheEntry.obj \
.\$(OBJDIR)\nsCacheEntryDescriptor.obj \
.\$(OBJDIR)\nsCacheMetaData.obj \
.\$(OBJDIR)\nsCacheModule.obj \
.\$(OBJDIR)\nsCacheService.obj \
.\$(OBJDIR)\nsCacheSession.obj \
.\$(OBJDIR)\nsDiskCacheBinding.obj \
.\$(OBJDIR)\nsDiskCacheBlockFile.obj \
.\$(OBJDIR)\nsDiskCacheDevice.obj \
.\$(OBJDIR)\nsDiskCacheEntry.obj \
.\$(OBJDIR)\nsDiskCacheMap.obj \
.\$(OBJDIR)\nsMemoryCacheDevice.obj \
$(NULL)
LLIBS = \
$(LIBNSPR) \
$(DIST)\lib\xpcom.lib \
$(NULL)
include <$(DEPTH)/config/rules.mak>
install:: $(DLL)
$(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).dll $(DIST)\bin\components
$(MAKE_INSTALL) .\$(OBJDIR)\$(DLLNAME).lib $(DIST)\lib
clobber::
$(RM) $(DIST)\bin\components\$(DLLNAME).dll
$(RM) $(DIST)\lib\$(DLLNAME).lib

View File

@@ -0,0 +1,388 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsANSIFileStreams.cpp, released March 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
*/
#include "nsANSIFileStreams.h"
NS_IMPL_ISUPPORTS2(nsANSIInputStream, nsIInputStream, nsISeekableStream);
nsANSIInputStream::nsANSIInputStream() : mFile(nsnull), mSize(0)
{
NS_INIT_ISUPPORTS();
}
nsANSIInputStream::~nsANSIInputStream()
{
Close();
}
nsresult nsANSIInputStream::Open(nsILocalFile* file)
{
nsresult rv;
rv = file->OpenANSIFileDesc("rb", &mFile);
if (NS_FAILED(rv)) return rv;
if (::fseek(mFile, 0, SEEK_END) != 0) return NS_ERROR_FAILURE;
mSize = ::ftell(mFile);
::fseek(mFile, 0, SEEK_SET);
rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
NS_IMETHODIMP nsANSIInputStream::Close()
{
if (mFile) {
::fclose(mFile);
mFile = nsnull;
return NS_OK;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIInputStream::Available(PRUint32 * result)
{
if (mFile) {
*result = (mSize - ::ftell(mFile));
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIInputStream::Read(char * buf, PRUint32 count, PRUint32 *result)
{
if (mFile) {
*result = ::fread(buf, 1, count, mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIInputStream::ReadSegments(nsWriteSegmentFun writer, void * closure, PRUint32 count, PRUint32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIInputStream::GetNonBlocking(PRBool *aNonBlocking)
{
*aNonBlocking = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP nsANSIInputStream::GetObserver(nsIInputStreamObserver * *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIInputStream::SetObserver(nsIInputStreamObserver * aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIInputStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mFile) {
::fseek(mFile, offset, whence);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIInputStream::Tell(PRUint32 * result)
{
if (mFile) {
*result = ::ftell(mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMPL_ISUPPORTS2(nsANSIOutputStream, nsIOutputStream, nsISeekableStream);
nsANSIOutputStream::nsANSIOutputStream() : mFile(nsnull)
{
NS_INIT_ISUPPORTS();
}
nsANSIOutputStream::~nsANSIOutputStream()
{
Close();
}
nsresult nsANSIOutputStream::Open(nsILocalFile* file)
{
nsresult rv = file->OpenANSIFileDesc("wb", &mFile);
return rv;
}
NS_IMETHODIMP nsANSIOutputStream::Close()
{
if (mFile) {
::fclose(mFile);
mFile = nsnull;
return NS_OK;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIOutputStream::Flush()
{
if (mFile) {
::fflush(mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIOutputStream::Write(const char *buffer, PRUint32 count, PRUint32 *result)
{
if (mFile) {
*result = ::fwrite(buffer, 1, count, mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIOutputStream::WriteFrom(nsIInputStream *input, PRUint32 count, PRUint32 *actualCount)
{
nsresult rv;
char buffer[BUFSIZ];
PRUint32 totalCount = count;
*actualCount = 0;
while (totalCount > 0) {
count = (totalCount < BUFSIZ ? totalCount : BUFSIZ);
rv = input->Read(buffer, count, &count);
if (NS_FAILED(rv)) break;
rv = Write(buffer, count, &count);
if (NS_FAILED(rv)) break;
totalCount -= count;
*actualCount += count;
}
return rv;
}
NS_IMETHODIMP nsANSIOutputStream::WriteSegments(nsReadSegmentFun reader, void * closure, PRUint32 count, PRUint32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIOutputStream::GetNonBlocking(PRBool *aNonBlocking)
{
*aNonBlocking = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP nsANSIOutputStream::SetNonBlocking(PRBool aNonBlocking)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIOutputStream::GetObserver(nsIOutputStreamObserver * *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIOutputStream::SetObserver(nsIOutputStreamObserver * aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIOutputStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mFile) {
::fseek(mFile, offset, whence);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIOutputStream::Tell(PRUint32 * result)
{
if (mFile) {
*result = ::ftell(mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
///////
NS_IMPL_ISUPPORTS3(nsANSIFileStream, nsIInputStream, nsIOutputStream, nsISeekableStream);
nsANSIFileStream::nsANSIFileStream() : mFile(nsnull), mSize(0)
{
NS_INIT_ISUPPORTS();
}
nsANSIFileStream::~nsANSIFileStream()
{
Close();
}
NS_IMETHODIMP nsANSIFileStream::Open(nsILocalFile* file)
{
nsresult rv;
rv = file->OpenANSIFileDesc("rb+", &mFile);
if (NS_FAILED(rv)) {
rv = rv = file->OpenANSIFileDesc("wb+", &mFile);
if (NS_FAILED(rv)) return rv;
}
// compute size of file.
if (::fseek(mFile, 0, SEEK_END) != 0) return NS_ERROR_FAILURE;
mSize = ::ftell(mFile);
::fseek(mFile, 0, SEEK_SET);
rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
NS_IMETHODIMP nsANSIFileStream::Close()
{
if (mFile) {
::fclose(mFile);
mFile = nsnull;
return NS_OK;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::Available(PRUint32 * result)
{
if (mFile) {
*result = (mSize - ::ftell(mFile));
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::Read(char * buf, PRUint32 count, PRUint32 *result)
{
if (mFile) {
*result = ::fread(buf, 1, count, mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::ReadSegments(nsWriteSegmentFun writer, void * closure, PRUint32 count, PRUint32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::GetNonBlocking(PRBool *aNonBlocking)
{
*aNonBlocking = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP nsANSIFileStream::GetObserver(nsIInputStreamObserver * *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::SetObserver(nsIInputStreamObserver * aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::Flush()
{
if (mFile) {
::fflush(mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::Write(const char *buffer, PRUint32 count, PRUint32 *result)
{
if (mFile) {
*result = ::fwrite(buffer, 1, count, mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::WriteFrom(nsIInputStream *input, PRUint32 count, PRUint32 *actualCount)
{
char buffer[BUFSIZ];
PRUint32 totalCount = count;
*actualCount = 0;
while (totalCount > 0) {
count = (totalCount < BUFSIZ ? totalCount : BUFSIZ);
nsresult rv = input->Read(buffer, count, &count);
if (NS_FAILED(rv)) return rv;
rv = Write(buffer, count, &count);
totalCount -= count;
*actualCount += count;
}
return NS_OK;
}
NS_IMETHODIMP nsANSIFileStream::WriteSegments(nsReadSegmentFun reader, void * closure, PRUint32 count, PRUint32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::SetNonBlocking(PRBool aNonBlocking)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::GetObserver(nsIOutputStreamObserver * *aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::SetObserver(nsIOutputStreamObserver * aObserver)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsANSIFileStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mFile) {
::fseek(mFile, offset, whence);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}
NS_IMETHODIMP nsANSIFileStream::Tell(PRUint32 * result)
{
if (mFile) {
*result = ::ftell(mFile);
nsresult rv = (ferror(mFile) ? NS_ERROR_FAILURE : NS_OK);
return rv;
}
return NS_BASE_STREAM_CLOSED;
}

View File

@@ -0,0 +1,80 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsANSIFileStreams.h, released March 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
*/
#ifndef _nsANSIFileStreams_h_
#define _nsANSIFileStreams_h_
#include <stdio.h>
#include "nsIFileStreams.h"
class nsANSIInputStream : public nsIInputStream, public nsISeekableStream {
FILE* mFile;
PRUint32 mSize;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
nsANSIInputStream();
virtual ~nsANSIInputStream();
nsresult Open(nsILocalFile* file);
};
class nsANSIOutputStream : public nsIOutputStream, public nsISeekableStream {
FILE* mFile;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOUTPUTSTREAM
NS_DECL_NSISEEKABLESTREAM
nsANSIOutputStream();
virtual ~nsANSIOutputStream();
nsresult Open(nsILocalFile* file);
};
class nsANSIFileStream : public nsIInputStream, public nsIOutputStream, public nsISeekableStream {
FILE* mFile;
PRUint32 mSize;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIINPUTSTREAM
// NS_DECL_NSIOUTPUTSTREAM
// XXX must only declare additional methods introduced by nsIOutputStream.
NS_IMETHOD Flush(void);
NS_IMETHOD Write(const char *buf, PRUint32 count, PRUint32 *_retval);
NS_IMETHOD WriteFrom(nsIInputStream *inStr, PRUint32 count, PRUint32 *_retval);
NS_IMETHOD WriteSegments(nsReadSegmentFun reader, void * closure, PRUint32 count, PRUint32 *_retval);
NS_IMETHOD SetNonBlocking(PRBool aNonBlocking);
NS_IMETHOD GetObserver(nsIOutputStreamObserver * *aObserver);
NS_IMETHOD SetObserver(nsIOutputStreamObserver * aObserver);
NS_DECL_NSISEEKABLESTREAM
NS_EXPORT nsANSIFileStream();
virtual ~nsANSIFileStream();
NS_IMETHOD Open(nsILocalFile* file);
};
#endif // _nsANSIFileStreams_h_

119
mozilla/netwerk/cache/src/nsCache.cpp vendored Normal file
View File

@@ -0,0 +1,119 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCache.cpp, released March 18, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsCache.h"
#include "nsReadableUtils.h"
/**
* Cache Service Utility Functions
*/
#if defined(PR_LOGGING)
PRLogModuleInfo * gCacheLog = nsnull;
void
CacheLogInit()
{
if (gCacheLog) return;
gCacheLog = PR_NewLogModule("cache");
NS_ASSERTION(gCacheLog, "\n### failed to allocate cache log.\n");
}
#endif
PRUint32
SecondsFromPRTime(PRTime prTime)
{
PRInt64 microSecondsPerSecond, intermediateResult;
PRUint32 seconds;
LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
LL_DIV(intermediateResult, prTime, microSecondsPerSecond);
LL_L2UI(seconds, intermediateResult);
return seconds;
}
PRTime
PRTimeFromSeconds(PRUint32 seconds)
{
PRInt64 microSecondsPerSecond, intermediateResult;
PRTime prTime;
LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
LL_UI2L(intermediateResult, seconds);
LL_MUL(prTime, intermediateResult, microSecondsPerSecond);
return prTime;
}
nsresult
ClientIDFromCacheKey(const nsAReadableCString& key, char ** result)
{
nsresult rv = NS_OK;
*result = nsnull;
nsReadingIterator<char> colon;
key.BeginReading(colon);
nsReadingIterator<char> start;
key.BeginReading(start);
nsReadingIterator<char> end;
key.EndReading(end);
if (FindCharInReadable(':', colon, end)) {
*result = ToNewCString( Substring(start, colon));
if (!*result) rv = NS_ERROR_OUT_OF_MEMORY;
} else {
NS_ASSERTION(PR_FALSE, "FindCharInRead failed to find ':'");
rv = NS_ERROR_UNEXPECTED;
}
return rv;
}
nsresult
ClientKeyFromCacheKey(const nsAReadableCString& key, char ** result)
{
nsresult rv = NS_OK;
*result = nsnull;
nsReadingIterator<char> start;
key.BeginReading(start);
nsReadingIterator<char> end;
key.EndReading(end);
if (FindCharInReadable(':', start, end)) {
++start; // advance past clientID ':' delimiter
*result = ToNewCString( Substring(start, end));
if (!*result) rv = NS_ERROR_OUT_OF_MEMORY;
} else {
NS_ASSERTION(PR_FALSE, "FindCharInRead failed to find ':'");
rv = NS_ERROR_UNEXPECTED;
}
return rv;
}

63
mozilla/netwerk/cache/src/nsCache.h vendored Normal file
View File

@@ -0,0 +1,63 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCache.h, released March 18, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
/**
* Cache Service Utility Functions
*/
#ifndef _nsCache_h_
#define _nsCache_h_
#include "nsAReadableString.h"
#include "prtime.h"
#include "nsError.h"
#include "prlog.h"
// PR_LOG args = "format string", arg, arg, ...
#if defined(PR_LOGGING)
extern PRLogModuleInfo * gCacheLog;
void CacheLogInit();
#define CACHE_LOG_INIT() CacheLogInit()
#define CACHE_LOG_ALWAYS(args) PR_LOG(gCacheLog, PR_LOG_ALWAYS, args)
#define CACHE_LOG_ERROR(args) PR_LOG(gCacheLog, PR_LOG_ERROR, args)
#define CACHE_LOG_WARNING(args) PR_LOG(gCacheLog, PR_LOG_WARNING, args)
#define CACHE_LOG_DEBUG(args) PR_LOG(gCacheLog, PR_LOG_DEBUG, args)
#else
#define CACHE_LOG_INIT() {}
#define CACHE_LOG_ALWAYS(args) {}
#define CACHE_LOG_ERROR(args) {}
#define CACHE_LOG_WARNING(args) {}
#define CACHE_LOG_DEBUG(args) {}
#endif
extern PRUint32 SecondsFromPRTime(PRTime prTime);
extern PRTime PRTimeFromSeconds(PRUint32 seconds);
extern nsresult ClientIDFromCacheKey(const nsAReadableCString& key, char ** result);
extern nsresult ClientKeyFromCacheKey(const nsAReadableCString& key, char ** result);
#endif // _nsCache_h

View File

@@ -0,0 +1,72 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheDevice.h, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#ifndef _nsCacheDevice_h_
#define _nsCacheDevice_h_
#include "nspr.h"
#include "nsError.h"
#include "nsICache.h"
class nsIFile;
class nsCString;
class nsCacheEntry;
class nsICacheVisitor;
class nsITransport;
/******************************************************************************
* nsCacheDevice
*******************************************************************************/
class nsCacheDevice {
public:
virtual ~nsCacheDevice() {}
virtual nsresult Init() = 0;
virtual nsresult Shutdown() = 0;
virtual const char * GetDeviceID(void) = 0;
virtual nsCacheEntry * FindEntry( nsCString * key ) = 0;
virtual nsresult DeactivateEntry( nsCacheEntry * entry ) = 0;
virtual nsresult BindEntry( nsCacheEntry * entry ) = 0;
virtual void DoomEntry( nsCacheEntry * entry ) = 0;
virtual nsresult GetTransportForEntry( nsCacheEntry * entry,
nsCacheAccessMode mode,
nsITransport **result ) = 0;
virtual nsresult GetFileForEntry( nsCacheEntry * entry,
nsIFile ** result ) = 0;
virtual nsresult OnDataSizeChange( nsCacheEntry * entry, PRInt32 deltaSize ) = 0;
virtual nsresult Visit(nsICacheVisitor * visitor) = 0;
/**
* Device must evict entries associated with clientID. If clientID == nsnull, all
* entries must be evicted. Active entries must be doomed, rather than evicted.
*/
virtual nsresult EvictEntries(const char * clientID) = 0;
};
#endif // _nsCacheDevice_h_

View File

@@ -0,0 +1,663 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheEntry.cpp, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#include "nspr.h"
#include "nsCacheEntry.h"
#include "nsCacheEntryDescriptor.h"
#include "nsCacheMetaData.h"
#include "nsCacheRequest.h"
#include "nsError.h"
#include "nsICacheService.h"
#include "nsCache.h"
#include "nsCacheDevice.h"
nsCacheEntry::nsCacheEntry(nsCString * key,
PRBool streamBased,
nsCacheStoragePolicy storagePolicy)
: mKey(key),
mFetchCount(0),
mLastFetched(0),
mExpirationTime(0),
mFlags(0),
mDataSize(0),
mMetaSize(0),
mCacheDevice(nsnull),
mData(nsnull),
mMetaData(nsnull)
{
PR_INIT_CLIST(this);
PR_INIT_CLIST(&mRequestQ);
PR_INIT_CLIST(&mDescriptorQ);
if (streamBased) MarkStreamBased();
SetStoragePolicy(storagePolicy);
}
static void* PR_CALLBACK
CacheElementReleaseEventHandler(PLEvent *self)
{
nsISupports * element = (nsISupports *)PL_GetEventOwner(self);
NS_RELEASE(element);
return 0;
}
static void PR_CALLBACK
CacheElementReleaseDestroyHandler(PLEvent *self)
{
delete self;
}
nsCacheEntry::~nsCacheEntry()
{
delete mKey;
delete mMetaData;
if (IsStreamData()) return;
// proxy release of of memory cache nsISupports objects
if (!mData) {
NS_ASSERTION(!mEventQ, "### ~nsCacheEntry: mEventQ but no mData");
return;
}
if (!mEventQ) {
NS_ASSERTION(!mData, "### ~nsCacheEntry: mData, but no eventQ");
return;
}
PLEvent * event = new PLEvent;
if (!event) {
// XXX warning
return;
}
nsISupports * data = mData;
NS_ADDREF(data); // this reference will be owned by the event
mData = nsnull; // release our reference before switching threads
PL_InitEvent(event,
data,
CacheElementReleaseEventHandler,
CacheElementReleaseDestroyHandler);
mEventQ->PostEvent(event);
}
nsresult
nsCacheEntry::Create( const char * key,
PRBool streamBased,
nsCacheStoragePolicy storagePolicy,
nsCacheDevice * device,
nsCacheEntry ** result)
{
nsCString* newKey = new nsCString(key);
if (!newKey) return NS_ERROR_OUT_OF_MEMORY;
nsCacheEntry* entry = new nsCacheEntry(newKey, streamBased, storagePolicy);
if (!entry) { delete newKey; return NS_ERROR_OUT_OF_MEMORY; }
entry->SetCacheDevice(device);
*result = entry;
return NS_OK;
}
void
nsCacheEntry::Fetched()
{
mLastFetched = SecondsFromPRTime(PR_Now());
++mFetchCount;
MarkEntryDirty();
}
const char *
nsCacheEntry::GetDeviceID()
{
if (mCacheDevice) return mCacheDevice->GetDeviceID();
return nsnull;
}
nsresult
nsCacheEntry::GetData(nsISupports **result)
{
NS_ENSURE_ARG_POINTER(result);
NS_IF_ADDREF(*result = mData);
return NS_OK;
}
void
nsCacheEntry::TouchData()
{
mLastModified = SecondsFromPRTime(PR_Now());
MarkDataDirty();
}
nsresult
nsCacheEntry::GetMetaDataElement( const nsAReadableCString& key,
nsAReadableCString ** value)
{
*value = mMetaData ? mMetaData->GetElement(&key) : nsnull;
return NS_OK;
}
nsresult
nsCacheEntry::SetMetaDataElement( const nsAReadableCString& key,
const nsAReadableCString& value)
{
if (!mMetaData) {
mMetaData = nsCacheMetaData::Create();
if (!mMetaData)
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv = mMetaData->SetElement(key, value);
if (NS_FAILED(rv))
return rv;
mMetaSize = mMetaData->Size(); // calc new meta data size
return rv;
}
nsresult
nsCacheEntry::VisitMetaDataElements( nsICacheMetaDataVisitor * visitor)
{
NS_ENSURE_ARG_POINTER(visitor);
if (mMetaData)
mMetaData->VisitElements(visitor);
return NS_OK;
}
nsresult
nsCacheEntry::FlattenMetaData(char ** data, PRUint32 * size)
{
NS_ENSURE_ARG_POINTER(size);
if (mMetaData)
return mMetaData->FlattenMetaData(data, size);
if (data) *data = nsnull;
*size = 0;
return NS_OK;
}
nsresult
nsCacheEntry::UnflattenMetaData(char * data, PRUint32 size)
{
delete mMetaData;
mMetaData = nsCacheMetaData::Create();
if (!mMetaData)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = mMetaData->UnflattenMetaData(data, size);
if (NS_SUCCEEDED(rv))
mMetaSize = mMetaData->Size();
return rv;
}
void
nsCacheEntry::TouchMetaData()
{
mLastModified = SecondsFromPRTime(PR_Now());
MarkMetaDataDirty();
}
#if 0
nsresult
nsCacheEntry::GetKeyValueArray(nsCacheMetaDataKeyValuePair ** array,
PRUint32 * count)
{
if (!array || !count) return NS_ERROR_NULL_POINTER;
if (!mMetaData) {
*array = nsnull;
*count = 0;
return NS_OK;
}
return mMetaData->GetKeyValueArray(array, count);
}
#endif
nsresult
nsCacheEntry::GetSecurityInfo( nsISupports ** result)
{
NS_ENSURE_ARG_POINTER(result);
NS_IF_ADDREF(*result = mSecurityInfo);
return NS_OK;
}
/**
* cache entry states
* 0 descriptors (new entry)
* 0 descriptors (existing, bound entry)
* n descriptors (existing, bound entry) valid
* n descriptors (existing, bound entry) not valid (wait until valid or doomed)
*/
nsresult
nsCacheEntry::RequestAccess(nsCacheRequest * request, nsCacheAccessMode *accessGranted)
{
nsresult rv = NS_OK;
if (!IsInitialized()) {
// brand new, unbound entry
request->mKey = nsnull; // steal ownership of the key string
if (request->IsStreamBased()) MarkStreamBased();
MarkInitialized();
*accessGranted = request->AccessRequested() & nsICache::ACCESS_WRITE;
NS_ASSERTION(*accessGranted, "new cache entry for READ-ONLY request");
PR_APPEND_LINK(request, &mRequestQ);
return rv;
}
if (IsDoomed()) return NS_ERROR_CACHE_ENTRY_DOOMED;
if (IsStreamData() != request->IsStreamBased()) {
*accessGranted = nsICache::ACCESS_NONE;
return request->IsStreamBased() ?
NS_ERROR_CACHE_DATA_IS_NOT_STREAM : NS_ERROR_CACHE_DATA_IS_STREAM;
}
if (PR_CLIST_IS_EMPTY(&mDescriptorQ)) {
// 1st descriptor for existing bound entry
*accessGranted = request->AccessRequested();
if (*accessGranted & nsICache::ACCESS_WRITE) {
MarkInvalid();
} else {
MarkValid();
}
} else {
// nth request for existing, bound entry
*accessGranted = request->AccessRequested() & ~nsICache::ACCESS_WRITE;
if (!IsValid())
rv = NS_ERROR_CACHE_WAIT_FOR_VALIDATION;
}
PR_APPEND_LINK(request,&mRequestQ);
return rv;
}
nsresult
nsCacheEntry::CreateDescriptor(nsCacheRequest * request,
nsCacheAccessMode accessGranted,
nsICacheEntryDescriptor ** result)
{
NS_ENSURE_ARG_POINTER(request && result);
nsCacheEntryDescriptor * descriptor =
new nsCacheEntryDescriptor(this, accessGranted);
// XXX check request is on q
PR_REMOVE_AND_INIT_LINK(request); // remove request regardless of success
if (descriptor == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
PR_APPEND_LINK(descriptor, &mDescriptorQ);
NS_ADDREF(*result = descriptor);
return NS_OK;
}
PRBool
nsCacheEntry::RemoveRequest(nsCacheRequest * request)
{
// XXX if debug: verify this request belongs to this entry
PR_REMOVE_AND_INIT_LINK(request);
// return true if this entry should stay active
return !((PR_CLIST_IS_EMPTY(&mRequestQ)) &&
(PR_CLIST_IS_EMPTY(&mDescriptorQ)));
}
PRBool
nsCacheEntry::RemoveDescriptor(nsCacheEntryDescriptor * descriptor)
{
// XXX if debug: verify this descriptor belongs to this entry
PR_REMOVE_AND_INIT_LINK(descriptor);
if (!PR_CLIST_IS_EMPTY(&mDescriptorQ))
return PR_TRUE; // stay active if we still have open descriptors
if (PR_CLIST_IS_EMPTY(&mRequestQ))
return PR_FALSE; // no descriptors or requests, we can deactivate
return PR_TRUE; // find next best request to give a descriptor to
}
void
nsCacheEntry::DetachDescriptors(void)
{
nsCacheEntryDescriptor * descriptor =
(nsCacheEntryDescriptor *)PR_LIST_HEAD(&mDescriptorQ);
while (descriptor != &mDescriptorQ) {
nsCacheEntryDescriptor * nextDescriptor =
(nsCacheEntryDescriptor *)PR_NEXT_LINK(descriptor);
descriptor->ClearCacheEntry();
PR_REMOVE_AND_INIT_LINK(descriptor);
descriptor = nextDescriptor;
}
}
/******************************************************************************
* nsCacheEntryInfo - for implementing about:cache
*****************************************************************************/
NS_IMPL_ISUPPORTS1(nsCacheEntryInfo, nsICacheEntryInfo);
NS_IMETHODIMP
nsCacheEntryInfo::GetClientID(char ** clientID)
{
NS_ENSURE_ARG_POINTER(clientID);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return ClientIDFromCacheKey(*mCacheEntry->Key(), clientID);
}
NS_IMETHODIMP
nsCacheEntryInfo::GetDeviceID(char ** deviceID)
{
NS_ENSURE_ARG_POINTER(deviceID);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*deviceID = nsCRT::strdup(mCacheEntry->GetDeviceID());
return *deviceID ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsCacheEntryInfo::GetKey(char ** key)
{
NS_ENSURE_ARG_POINTER(key);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return ClientKeyFromCacheKey(*mCacheEntry->Key(), key);
}
NS_IMETHODIMP
nsCacheEntryInfo::GetFetchCount(PRInt32 * fetchCount)
{
NS_ENSURE_ARG_POINTER(fetchCount);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*fetchCount = mCacheEntry->FetchCount();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryInfo::GetLastFetched(PRUint32 * lastFetched)
{
NS_ENSURE_ARG_POINTER(lastFetched);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*lastFetched = mCacheEntry->LastFetched();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryInfo::GetLastModified(PRUint32 * lastModified)
{
NS_ENSURE_ARG_POINTER(lastModified);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*lastModified = mCacheEntry->LastModified();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryInfo::GetExpirationTime(PRUint32 * expirationTime)
{
NS_ENSURE_ARG_POINTER(expirationTime);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*expirationTime = mCacheEntry->ExpirationTime();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryInfo::GetDataSize(PRUint32 * dataSize)
{
NS_ENSURE_ARG_POINTER(dataSize);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*dataSize = mCacheEntry->DataSize();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryInfo::IsStreamBased(PRBool * result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->IsStreamData();
return NS_OK;
}
/******************************************************************************
* nsCacheEntryHashTable
*****************************************************************************/
PLDHashTableOps
nsCacheEntryHashTable::ops =
{
PL_DHashAllocTable,
PL_DHashFreeTable,
GetKey,
HashKey,
MatchEntry,
MoveEntry,
ClearEntry,
PL_DHashFinalizeStub
};
nsCacheEntryHashTable::nsCacheEntryHashTable()
: initialized(PR_FALSE)
{
}
nsCacheEntryHashTable::~nsCacheEntryHashTable()
{
if (initialized)
Shutdown();
}
nsresult
nsCacheEntryHashTable::Init()
{
nsresult rv = NS_OK;
initialized = PL_DHashTableInit(&table, &ops, nsnull,
sizeof(nsCacheEntryHashTableEntry), 512);
if (!initialized) rv = NS_ERROR_OUT_OF_MEMORY;
return rv;
}
void
nsCacheEntryHashTable::Shutdown()
{
if (initialized) {
PL_DHashTableFinish(&table);
initialized = PR_FALSE;
}
}
nsCacheEntry *
nsCacheEntryHashTable::GetEntry( const nsCString * key)
{
PLDHashEntryHdr *hashEntry;
nsCacheEntry *result = nsnull;
NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized");
if (!initialized) return nsnull;
hashEntry = PL_DHashTableOperate(&table, key, PL_DHASH_LOOKUP);
if (PL_DHASH_ENTRY_IS_BUSY(hashEntry)) {
result = ((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry;
}
return result;
}
nsresult
nsCacheEntryHashTable::AddEntry( nsCacheEntry *cacheEntry)
{
PLDHashEntryHdr *hashEntry;
NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized");
if (!initialized) return NS_ERROR_NOT_INITIALIZED;
if (!cacheEntry) return NS_ERROR_NULL_POINTER;
hashEntry = PL_DHashTableOperate(&table, cacheEntry->mKey, PL_DHASH_ADD);
#ifndef DEBUG_dougt
NS_ASSERTION(((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry == 0,
"### nsCacheEntryHashTable::AddEntry - entry already used");
#endif
((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry = cacheEntry;
return NS_OK;
}
void
nsCacheEntryHashTable::RemoveEntry( nsCacheEntry *cacheEntry)
{
NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized");
NS_ASSERTION(cacheEntry, "### cacheEntry == nsnull");
if (!initialized) return; // NS_ERROR_NOT_INITIALIZED
#if DEBUG
// XXX debug code to make sure we have the entry we're trying to remove
nsCacheEntry *check = GetEntry(cacheEntry->mKey);
NS_ASSERTION(check == cacheEntry, "### Attempting to remove unknown cache entry!!!");
#endif
(void) PL_DHashTableOperate(&table, cacheEntry->mKey, PL_DHASH_REMOVE);
}
void
nsCacheEntryHashTable::VisitEntries( nsCacheEntryHashTable::Visitor *visitor)
{
NS_ASSERTION(initialized, "nsCacheEntryHashTable not initialized");
if (!initialized) return; // NS_ERROR_NOT_INITIALIZED
PL_DHashTableEnumerate(&table, VisitEntry, visitor);
}
PLDHashOperator PR_CALLBACK
nsCacheEntryHashTable::VisitEntry(PLDHashTable *table,
PLDHashEntryHdr *hashEntry,
PRUint32 number,
void *arg)
{
nsCacheEntry *cacheEntry = ((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry;
nsCacheEntryHashTable::Visitor *visitor = (nsCacheEntryHashTable::Visitor*) arg;
return (visitor->VisitEntry(cacheEntry) ? PL_DHASH_NEXT : PL_DHASH_STOP);
}
/**
* hash table operation callback functions
*/
const void * PR_CALLBACK
nsCacheEntryHashTable::GetKey( PLDHashTable * /*table*/, PLDHashEntryHdr *hashEntry)
{
nsCacheEntry *cacheEntry = ((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry;
return cacheEntry->mKey;
}
PLDHashNumber PR_CALLBACK
nsCacheEntryHashTable::HashKey( PLDHashTable *table, const void *key)
{
return PL_DHashStringKey(table,((nsCString *)key)->get());
}
PRBool PR_CALLBACK
nsCacheEntryHashTable::MatchEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr * hashEntry,
const void * key)
{
NS_ASSERTION(key != nsnull, "### nsCacheEntryHashTable::MatchEntry : null key");
nsCacheEntry *cacheEntry = ((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry;
return nsStr::StrCompare(*cacheEntry->mKey, *(nsCString *)key, -1, PR_FALSE) == 0;
}
void PR_CALLBACK
nsCacheEntryHashTable::MoveEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to)
{
((nsCacheEntryHashTableEntry *)to)->cacheEntry =
((nsCacheEntryHashTableEntry *)from)->cacheEntry;
}
void PR_CALLBACK
nsCacheEntryHashTable::ClearEntry(PLDHashTable * /* table */,
PLDHashEntryHdr * hashEntry)
{
((nsCacheEntryHashTableEntry *)hashEntry)->cacheEntry = 0;
}

330
mozilla/netwerk/cache/src/nsCacheEntry.h vendored Normal file
View File

@@ -0,0 +1,330 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheEntry.h, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#ifndef _nsCacheEntry_h_
#define _nsCacheEntry_h_
#include "nsICache.h"
#include "nsICacheEntryDescriptor.h"
#include "nsCacheMetaData.h"
#include "nspr.h"
#include "pldhash.h"
#include "nscore.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsAReadableString.h"
#include "nsIEventQueue.h"
class nsCacheDevice;
class nsCacheMetaData;
class nsCacheRequest;
class nsCacheEntryDescriptor;
/******************************************************************************
* nsCacheEntry
*******************************************************************************/
class nsCacheEntry : public PRCList
{
public:
nsCacheEntry(nsCString * key,
PRBool streamBased,
nsCacheStoragePolicy storagePolicy);
~nsCacheEntry();
static nsresult Create( const char * key,
PRBool streamBased,
nsCacheStoragePolicy storagePolicy,
nsCacheDevice * device,
nsCacheEntry ** result);
nsCString * Key() { return mKey; }
PRInt32 FetchCount() { return mFetchCount;}
void SetFetchCount( PRInt32 count) { mFetchCount = count;}
void Fetched();
PRUint32 LastFetched() { return mLastFetched;}
void SetLastFetched( PRUint32 lastFetched) { mLastFetched = lastFetched;}
PRUint32 LastModified() { return mLastModified;}
void SetLastModified( PRUint32 lastModified) { mLastModified = lastModified;}
PRUint32 ExpirationTime() { return mExpirationTime;}
void SetExpirationTime( PRUint32 expires) { mExpirationTime = expires;}
PRUint32 Size() { return mDataSize + mMetaSize; }
nsCacheDevice * CacheDevice() { return mCacheDevice;}
void SetCacheDevice( nsCacheDevice * device) { mCacheDevice = device;}
const char * GetDeviceID();
/**
* Data accessors
*/
nsresult GetData( nsISupports ** result);
void SetData( nsISupports * data) { mData = data;}
PRUint32 DataSize() { return mDataSize;}
void SetDataSize( PRUint32 size) { mDataSize = size;}
void TouchData();
nsIEventQueue * GetEventQ() { return mEventQ;}
void SetEventQ(nsIEventQueue * eventQ) { mEventQ = dont_AddRef(eventQ);}
/**
* Meta data accessors
*/
nsresult GetMetaDataElement( const nsAReadableCString& key,
nsAReadableCString ** value);
nsresult SetMetaDataElement( const nsAReadableCString& key,
const nsAReadableCString& value);
nsresult VisitMetaDataElements( nsICacheMetaDataVisitor * visitor);
nsresult FlattenMetaData( char ** data, PRUint32 * size);
nsresult UnflattenMetaData( char * data, PRUint32 size);
PRUint32 MetaDataSize() { return mMetaSize;}
void TouchMetaData();
/**
* Security Info accessors
*/
nsresult GetSecurityInfo( nsISupports ** result);
void SetSecurityInfo( nsISupports * info) { mSecurityInfo = info; }
// XXX enumerate MetaData method
enum CacheEntryFlags {
eStoragePolicyMask = 0x000000FF,
eDoomedMask = 0x00000100,
eEntryDirtyMask = 0x00000200,
eDataDirtyMask = 0x00000400,
eMetaDataDirtyMask = 0x00000800,
eStreamDataMask = 0x00001000,
eActiveMask = 0x00002000,
eInitializedMask = 0x00004000,
eValidMask = 0x00008000,
eBindingMask = 0x00010000
};
void MarkBinding() { mFlags |= eBindingMask; }
void ClearBinding() { mFlags &= ~eBindingMask; }
PRBool IsBinding() { return (mFlags & eBindingMask) != 0; }
void MarkEntryDirty() { mFlags |= eEntryDirtyMask; }
void MarkEntryClean() { mFlags &= ~eEntryDirtyMask; }
void MarkDataDirty() { mFlags |= eDataDirtyMask; }
void MarkDataClean() { mFlags &= ~eDataDirtyMask; }
void MarkMetaDataDirty() { mFlags |= eMetaDataDirtyMask; }
void MarkMetaDataClean() { mFlags &= ~eMetaDataDirtyMask; }
void MarkStreamData() { mFlags |= eStreamDataMask; }
void MarkValid() { mFlags |= eValidMask; }
void MarkInvalid() { mFlags &= ~eValidMask; }
// void MarkAllowedInMemory() { mFlags |= eAllowedInMemoryMask; }
// void MarkAllowedOnDisk() { mFlags |= eAllowedOnDiskMask; }
PRBool IsDoomed() { return (mFlags & eDoomedMask) != 0; }
PRBool IsEntryDirty() { return (mFlags & eEntryDirtyMask) != 0; }
PRBool IsDataDirty() { return (mFlags & eDataDirtyMask) != 0; }
PRBool IsMetaDataDirty() { return (mFlags & eMetaDataDirtyMask) != 0; }
PRBool IsStreamData() { return (mFlags & eStreamDataMask) != 0; }
PRBool IsActive() { return (mFlags & eActiveMask) != 0; }
PRBool IsInitialized() { return (mFlags & eInitializedMask) != 0; }
PRBool IsValid() { return (mFlags & eValidMask) != 0; }
PRBool IsInvalid() { return (mFlags & eValidMask) == 0; }
PRBool IsInUse() { return !(PR_CLIST_IS_EMPTY(&mRequestQ) &&
PR_CLIST_IS_EMPTY(&mDescriptorQ)); }
PRBool IsNotInUse() { return (PR_CLIST_IS_EMPTY(&mRequestQ) &&
PR_CLIST_IS_EMPTY(&mDescriptorQ)); }
PRBool IsAllowedInMemory()
{
return (StoragePolicy() == nsICache::STORE_ANYWHERE) ||
(StoragePolicy() == nsICache::STORE_IN_MEMORY);
}
PRBool IsAllowedOnDisk()
{
return (StoragePolicy() == nsICache::STORE_ANYWHERE) ||
(StoragePolicy() == nsICache::STORE_ON_DISK) ||
(StoragePolicy() == nsICache::STORE_ON_DISK_AS_FILE);
}
nsCacheStoragePolicy StoragePolicy()
{
return (nsCacheStoragePolicy)(mFlags & eStoragePolicyMask);
}
void SetStoragePolicy(nsCacheStoragePolicy policy)
{
NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy");
mFlags &= ~eStoragePolicyMask; // clear storage policy bits
mFlags |= policy;
}
// methods for nsCacheService
nsresult RequestAccess( nsCacheRequest * request, nsCacheAccessMode *accessGranted);
nsresult CreateDescriptor( nsCacheRequest * request,
nsCacheAccessMode accessGranted,
nsICacheEntryDescriptor ** result);
// nsresult Open(nsCacheRequest *request, nsICacheEntryDescriptor ** result);
// nsresult AsyncOpen(nsCacheRequest *request);
PRBool RemoveRequest( nsCacheRequest * request);
PRBool RemoveDescriptor( nsCacheEntryDescriptor * descriptor);
private:
friend class nsCacheEntryHashTable;
friend class nsCacheService;
void DetachDescriptors(void);
// internal methods
void MarkDoomed() { mFlags |= eDoomedMask; }
void MarkStreamBased() { mFlags |= eStreamDataMask; }
void MarkInitialized() { mFlags |= eInitializedMask; }
void MarkActive() { mFlags |= eActiveMask; }
void MarkInactive() { mFlags &= ~eActiveMask; }
nsCString * mKey; // 4 // XXX ask scc about const'ness
PRUint32 mFetchCount; // 4
PRUint32 mLastFetched; // 4
PRUint32 mLastModified; // 4
PRUint32 mLastValidated; // 4
PRUint32 mExpirationTime; // 4
PRUint32 mFlags; // 4
PRUint32 mDataSize; // 4
PRUint32 mMetaSize; // 4
nsCacheDevice * mCacheDevice; // 4
nsCOMPtr<nsISupports> mSecurityInfo; //
nsCOMPtr<nsISupports> mData; //
nsCOMPtr<nsIEventQueue> mEventQ; // event queue for mData (for mem object cache)
nsCacheMetaData * mMetaData; // 4
PRCList mRequestQ; // 8
PRCList mDescriptorQ; // 8
};
/******************************************************************************
* nsCacheEntryInfo
*******************************************************************************/
class nsCacheEntryInfo : public nsICacheEntryInfo {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHEENTRYINFO
nsCacheEntryInfo(nsCacheEntry* entry)
: mCacheEntry(entry)
{
NS_INIT_ISUPPORTS();
}
virtual ~nsCacheEntryInfo() {}
void DetachEntry() { mCacheEntry = nsnull; }
private:
nsCacheEntry * mCacheEntry;
};
/******************************************************************************
* nsCacheEntryHashTable
*******************************************************************************/
typedef struct {
PLDHashNumber keyHash;
nsCacheEntry *cacheEntry;
} nsCacheEntryHashTableEntry;
class nsCacheEntryHashTable
{
public:
nsCacheEntryHashTable();
~nsCacheEntryHashTable();
nsresult Init();
void Shutdown();
nsCacheEntry *GetEntry( const nsCString * key);
nsresult AddEntry( nsCacheEntry *entry);
void RemoveEntry( nsCacheEntry *entry);
// XXX enumerate entries?
class Visitor {
public:
virtual PRBool VisitEntry( nsCacheEntry *entry) = 0;
};
void VisitEntries( Visitor *visitor);
private:
friend class nsCacheService; // XXX redefine interface so this isn't necessary
// PLDHashTable operation callbacks
static const void * PR_CALLBACK GetKey( PLDHashTable *table, PLDHashEntryHdr *entry);
static PLDHashNumber PR_CALLBACK HashKey( PLDHashTable *table, const void *key);
static PRBool PR_CALLBACK MatchEntry( PLDHashTable * table,
const PLDHashEntryHdr * entry,
const void * key);
static void PR_CALLBACK MoveEntry( PLDHashTable *table,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to);
static void PR_CALLBACK ClearEntry( PLDHashTable *table, PLDHashEntryHdr *entry);
static void PR_CALLBACK Finalize( PLDHashTable *table);
static
PLDHashOperator PR_CALLBACK FreeCacheEntries(PLDHashTable * table,
PLDHashEntryHdr * hdr,
PRUint32 number,
void * arg);
static
PLDHashOperator PR_CALLBACK VisitEntry(PLDHashTable * table,
PLDHashEntryHdr * hdr,
PRUint32 number,
void * arg);
// member variables
static PLDHashTableOps ops;
PLDHashTable table;
PRBool initialized;
};
#endif // _nsCacheEntry_h_

View File

@@ -0,0 +1,647 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheEntryDescriptor.cpp, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#include "nsICache.h"
#include "nsCache.h"
#include "nsCacheService.h"
#include "nsCacheEntryDescriptor.h"
#include "nsCacheEntry.h"
#include "nsReadableUtils.h"
#include "nsIOutputStream.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsCacheEntryDescriptor, nsICacheEntryDescriptor)
nsCacheEntryDescriptor::nsCacheEntryDescriptor(nsCacheEntry * entry,
nsCacheAccessMode accessGranted)
: mCacheEntry(entry),
mAccessGranted(accessGranted)
{
NS_INIT_ISUPPORTS();
PR_INIT_CLIST(this);
}
nsCacheEntryDescriptor::~nsCacheEntryDescriptor()
{
if (mCacheEntry)
Close();
}
nsresult
nsCacheEntryDescriptor::Create(nsCacheEntry * entry, nsCacheAccessMode accessGranted,
nsICacheEntryDescriptor ** result)
{
NS_ENSURE_ARG_POINTER(result);
nsresult rv = nsnull;
nsCacheEntryDescriptor * descriptor =
new nsCacheEntryDescriptor(entry, accessGranted);
if (descriptor == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(descriptor);
rv = descriptor->QueryInterface(NS_GET_IID(nsICacheEntryDescriptor), (void**)result);
NS_RELEASE(descriptor);
return rv;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetClientID(char ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return ClientIDFromCacheKey(*(mCacheEntry->Key()), result);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetDeviceID(char ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = nsCRT::strdup(mCacheEntry->GetDeviceID());
return *result ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetKey(char ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return ClientKeyFromCacheKey(*(mCacheEntry->Key()), result);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetFetchCount(PRInt32 *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->FetchCount();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetLastFetched(PRUint32 *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->LastFetched();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetLastModified(PRUint32 *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->LastModified();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetExpirationTime(PRUint32 *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->ExpirationTime();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetExpirationTime(PRUint32 expirationTime)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
mCacheEntry->SetExpirationTime(expirationTime);
mCacheEntry->MarkEntryDirty();
return NS_OK;
}
NS_IMETHODIMP nsCacheEntryDescriptor::IsStreamBased(PRBool *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->IsStreamData(); // XXX which name is better?
return NS_OK;
}
NS_IMETHODIMP nsCacheEntryDescriptor::GetDataSize(PRUint32 *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
*result = mCacheEntry->DataSize();
return NS_OK;
}
nsresult
nsCacheEntryDescriptor::RequestDataSizeChange(PRInt32 deltaSize)
{
nsresult rv;
rv = nsCacheService::GlobalInstance()->OnDataSizeChange(mCacheEntry, deltaSize);
if (NS_SUCCEEDED(rv)) {
// XXX review for signed/unsigned math errors
PRUint32 newDataSize = mCacheEntry->DataSize() + deltaSize;
mCacheEntry->SetDataSize(newDataSize);
mCacheEntry->TouchData();
}
return rv;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetDataSize(PRUint32 dataSize)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
// XXX review for signed/unsigned math errors
PRInt32 deltaSize = dataSize - mCacheEntry->DataSize();
// this had better be NS_OK, this call instance is advisory
nsresult rv = RequestDataSizeChange(deltaSize);
NS_ASSERTION(NS_SUCCEEDED(rv), "failed SetDataSize() on memory cache object!");
return rv;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetTransport(nsITransport ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (!mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_NOT_STREAM;
NS_ADDREF(*result = &mTransportWrapper);
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetCacheElement(nsISupports ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_STREAM;
return mCacheEntry->GetData(result);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetCacheElement(nsISupports * cacheElement)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (mCacheEntry->IsStreamData()) return NS_ERROR_CACHE_DATA_IS_STREAM;
mCacheEntry->SetData(cacheElement);
mCacheEntry->TouchData();
return nsCacheService::GlobalInstance()->SetCacheElement(mCacheEntry, cacheElement);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetAccessGranted(nsCacheAccessMode *result)
{
NS_ENSURE_ARG_POINTER(result);
*result = mAccessGranted;
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetStoragePolicy(nsCacheStoragePolicy *result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return mCacheEntry->StoragePolicy();
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetStoragePolicy(nsCacheStoragePolicy policy)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
// XXX validate policy against session?
mCacheEntry->SetStoragePolicy(policy);
mCacheEntry->MarkEntryDirty();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetFile(nsIFile ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return nsCacheService::GlobalInstance()->GetFileForEntry(mCacheEntry, result);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetSecurityInfo(nsISupports ** result)
{
NS_ENSURE_ARG_POINTER(result);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return mCacheEntry->GetSecurityInfo(result);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetSecurityInfo(nsISupports * securityInfo)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
mCacheEntry->SetSecurityInfo(securityInfo);
mCacheEntry->MarkEntryDirty();
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::Doom()
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return nsCacheService::GlobalInstance()->DoomEntry(mCacheEntry);
}
NS_IMETHODIMP
nsCacheEntryDescriptor::DoomAndFailPendingRequests(nsresult status)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::MarkValid()
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
nsresult rv;
rv = nsCacheService::GlobalInstance()->ValidateEntry(mCacheEntry);
return rv;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::Close()
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
// tell nsCacheService we're going away
nsCacheService::GlobalInstance()->CloseDescriptor(this);
mCacheEntry = nsnull;
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::GetMetaDataElement(const char *key, char ** result)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (!key | !result) return NS_ERROR_NULL_POINTER;
nsAReadableCString *value;
*result = nsnull;
// XXX not thread safe
nsresult rv = mCacheEntry->GetMetaDataElement(nsLiteralCString(key), &value);
if (NS_FAILED(rv)) return rv;
if (!value) return NS_ERROR_NOT_AVAILABLE;
*result = ToNewCString(*value);
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::SetMetaDataElement(const char *key, const char *value)
{
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (!key) return NS_ERROR_NULL_POINTER;
// XXX not thread safe
// XXX allow null value, for clearing key?
nsresult rv = mCacheEntry->SetMetaDataElement(nsLiteralCString(key),
nsLiteralCString(value));
if (NS_SUCCEEDED(rv))
mCacheEntry->TouchMetaData();
return rv;
}
NS_IMETHODIMP
nsCacheEntryDescriptor::VisitMetaData(nsICacheMetaDataVisitor * visitor)
{
NS_ENSURE_ARG_POINTER(visitor);
if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return mCacheEntry->VisitMetaDataElements(visitor);
}
/******************************************************************************
* nsCacheTransportWrapper
******************************************************************************/
// XXX NS_IMPL_ISUPPORTS1(nsCacheEntryDescriptor::nsTransportWrapper, nsITransport);
NS_IMPL_QUERY_INTERFACE1(nsCacheEntryDescriptor::nsTransportWrapper, nsITransport)
// special AddRef and Release, because we are part of the descriptor
#define GET_DESCRIPTOR_FROM_TRANSPORT_WRAPPER(_this) \
((nsCacheEntryDescriptor*)((char*)(_this) - \
offsetof(nsCacheEntryDescriptor, mTransportWrapper)))
NS_IMETHODIMP_(nsrefcnt) nsCacheEntryDescriptor::
nsTransportWrapper::AddRef(void)
{
return GET_DESCRIPTOR_FROM_TRANSPORT_WRAPPER(this)->AddRef();
}
NS_IMETHODIMP_(nsrefcnt) nsCacheEntryDescriptor::
nsTransportWrapper::Release(void)
{
return GET_DESCRIPTOR_FROM_TRANSPORT_WRAPPER(this)->Release();
}
nsresult nsCacheEntryDescriptor::
nsTransportWrapper::EnsureTransportWithAccess(nsCacheAccessMode mode)
{
nsresult rv = NS_OK;
nsCacheEntryDescriptor * descriptor = GET_DESCRIPTOR_FROM_TRANSPORT_WRAPPER(this);
if (!descriptor->mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
if (!descriptor->mAccessGranted & mode) {
rv = (mode == nsICache::ACCESS_READ) ?
NS_ERROR_CACHE_READ_ACCESS_DENIED : NS_ERROR_CACHE_WRITE_ACCESS_DENIED;
return rv;
}
if (!mTransport) {
rv = nsCacheService::GlobalInstance()->
GetTransportForEntry(descriptor->mCacheEntry,
descriptor->mAccessGranted,
getter_AddRefs(mTransport));
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
nsresult
nsCacheEntryDescriptor::NewOutputStreamWrapper(nsIOutputStream ** result,
nsCacheEntryDescriptor * descriptor,
nsIOutputStream * output)
{
nsOutputStreamWrapper* cacheOutput =
new nsOutputStreamWrapper(descriptor, output);
if (!cacheOutput) return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsISupports> ref(cacheOutput);
nsresult rv = cacheOutput->Init();
if (NS_FAILED(rv)) return rv;
NS_ADDREF(*result = cacheOutput);
return NS_OK;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::GetSecurityInfo(nsISupports ** securityInfo)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::GetNotificationCallbacks(nsIInterfaceRequestor ** result)
{
NS_ENSURE_ARG_POINTER(result);
// if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::SetNotificationCallbacks(nsIInterfaceRequestor * requestor,
PRUint32 flags)
{
// if (!mCacheEntry) return NS_ERROR_NOT_AVAILABLE;
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::OpenInputStream(PRUint32 offset,
PRUint32 count,
PRUint32 flags,
nsIInputStream ** result)
{
NS_ENSURE_ARG_POINTER(result);
nsresult rv = EnsureTransportWithAccess(nsICache::ACCESS_READ);
if (NS_FAILED(rv)) return rv;
return mTransport->OpenInputStream(offset, count, flags, result);
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::OpenOutputStream(PRUint32 offset,
PRUint32 count,
PRUint32 flags,
nsIOutputStream ** result)
{
NS_ENSURE_ARG_POINTER(result);
nsresult rv = EnsureTransportWithAccess(nsICache::ACCESS_WRITE);
if (NS_FAILED(rv)) return rv;
// XXX allow more than one output stream at a time on a descriptor? Why?
// Create the underlying output stream using the wrapped transport.
nsCOMPtr<nsIOutputStream> output;
rv = mTransport->OpenOutputStream(offset, count, flags, getter_AddRefs(output));
if (NS_FAILED(rv)) return rv;
// Wrap this output stream with a stream that monitors how much data gets written,
// maintains the cache entry's size, and informs the cache device.
// This mechanism provides a way for the cache device to enforce space limits,
// and to drive cache entry eviction.
nsCacheEntryDescriptor * descriptor = GET_DESCRIPTOR_FROM_TRANSPORT_WRAPPER(this);
// reset datasize of entry based on offset so OnWrite calculates delta changes correctly.
rv = descriptor->SetDataSize(offset);
if (NS_FAILED(rv)) return rv;
return NewOutputStreamWrapper(result, descriptor, output);
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::AsyncRead(nsIStreamListener * listener,
nsISupports * ctxt,
PRUint32 offset,
PRUint32 count,
PRUint32 flags,
nsIRequest ** result)
{
NS_ENSURE_ARG_POINTER(result);
nsresult rv = EnsureTransportWithAccess(nsICache::ACCESS_READ);
if (NS_FAILED(rv)) return rv;
return mTransport->AsyncRead(listener, ctxt, offset, count, flags, result);
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsTransportWrapper::AsyncWrite(nsIStreamProvider * provider,
nsISupports * ctxt,
PRUint32 offset,
PRUint32 count,
PRUint32 flags,
nsIRequest ** result)
{
// we're not planning on implementing this
return NS_ERROR_NOT_IMPLEMENTED;
#if 0
NS_ENSURE_ARG_POINTER(result);
nsresult rv = EnsureTransportWithAccess(nsICache::ACCESS_WRITE);
if (NS_FAILED(rv)) return rv;
return mTransport->AsyncWrite(provider, ctxt, offset, count, flags, result);
#endif
}
/******************************************************************************
* nsCacheOutputStream - a wrapper for nsIOutputstream to track the amount of
* data written to a cache entry.
******************************************************************************/
NS_IMPL_ISUPPORTS1(nsCacheEntryDescriptor::nsOutputStreamWrapper, nsIOutputStream);
nsresult nsCacheEntryDescriptor::
nsOutputStreamWrapper::Init()
{
nsCacheAccessMode mode;
nsresult rv = mDescriptor->GetAccessGranted(&mode);
if (NS_FAILED(rv)) return rv;
if (mode == nsICache::ACCESS_WRITE) {
nsCacheEntry* cacheEntry = mDescriptor->CacheEntry();
if (!cacheEntry) return NS_ERROR_NOT_AVAILABLE;
nsCacheDevice* device = cacheEntry->CacheDevice();
if (!device) return NS_ERROR_NOT_AVAILABLE;
// the entry has been truncated to zero bytes, inform the device.
PRInt32 delta = -cacheEntry->DataSize();
rv = device->OnDataSizeChange(cacheEntry, delta);
cacheEntry->SetDataSize(0);
}
return rv;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsOutputStreamWrapper::Write(const char * buf,
PRUint32 count,
PRUint32 * result)
{
nsresult rv = OnWrite(count);
if (NS_FAILED(rv)) return rv;
return mOutput->Write(buf, count, result);
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsOutputStreamWrapper::WriteFrom(nsIInputStream * inStr,
PRUint32 count,
PRUint32 * result)
{
nsresult rv = OnWrite(count);
if (NS_FAILED(rv)) return rv;
return mOutput->WriteFrom(inStr, count, result);
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsOutputStreamWrapper::WriteSegments(nsReadSegmentFun reader,
void * closure,
PRUint32 count,
PRUint32 * result)
{
nsresult rv = OnWrite(count);
if (NS_FAILED(rv)) return rv;
return mOutput->WriteSegments(reader, closure, count, result);
}
nsresult nsCacheEntryDescriptor::
nsOutputStreamWrapper::OnWrite(PRUint32 count)
{
// XXX if count > 2^31 error_write_too_big
return mDescriptor->RequestDataSizeChange((PRInt32)count);
}

View File

@@ -0,0 +1,167 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheEntryDescriptor.h, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#ifndef _nsCacheEntryDescriptor_h_
#define _nsCacheEntryDescriptor_h_
#include "nsICacheEntryDescriptor.h"
#include "nsCacheEntry.h"
#include "nsIOutputStream.h"
#include "nsITransport.h"
/******************************************************************************
* nsCacheEntryDescriptor
*******************************************************************************/
class nsCacheEntryDescriptor :
public PRCList,
public nsICacheEntryDescriptor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHEENTRYDESCRIPTOR
NS_DECL_NSICACHEENTRYINFO
nsCacheEntryDescriptor(nsCacheEntry * entry, nsCacheAccessMode mode);
virtual ~nsCacheEntryDescriptor();
static nsresult Create(nsCacheEntry * entry, nsCacheAccessMode accessGranted,
nsICacheEntryDescriptor ** result);
/**
* utility method to attempt changing data size of associated entry
*/
nsresult RequestDataSizeChange(PRInt32 deltaSize);
/**
* methods callbacks for nsCacheService
*/
nsCacheEntry * CacheEntry(void) { return mCacheEntry; }
void ClearCacheEntry(void) { mCacheEntry = nsnull; }
private:
/*************************************************************************
* transport wrapper class -
*
* we want the transport wrapper to have the same lifetime as the
* descriptor, but since they each need to reference the other, we have the
* descriptor include the transport wrapper as a member, rather than just
* pointing to it, which avoids circular AddRefs.
*************************************************************************/
class nsTransportWrapper : public nsITransport
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSITRANSPORT
nsTransportWrapper() : mTransport(nsnull) {}
virtual ~nsTransportWrapper() {}
nsresult EnsureTransportWithAccess(nsCacheAccessMode mode);
nsCOMPtr<nsITransport> mTransport;
}; // end of class nsTransportWrapper
friend class nsTransportWrapper;
/*************************************************************************
* output stream wrapper class -
*
* The output stream wrapper references the descriptor, but the descriptor
* doesn't need any references to the stream wrapper, so we don't need the
* same kind of tricks that we're using for the transport wrapper.
*************************************************************************/
class nsOutputStreamWrapper : public nsIOutputStream {
private:
nsCacheEntryDescriptor * mDescriptor;
nsCOMPtr<nsIOutputStream> mOutput;
public:
NS_DECL_ISUPPORTS
// NS_DECL_NSIOUTPUTSTREAM
NS_IMETHOD Close(void) { return mOutput->Close(); }
NS_IMETHOD Flush(void) { return mOutput->Flush(); }
NS_IMETHOD Write(const char * buf,
PRUint32 count,
PRUint32 * result);
NS_IMETHOD WriteFrom(nsIInputStream * inStr,
PRUint32 count,
PRUint32 * result);
NS_IMETHOD WriteSegments(nsReadSegmentFun reader,
void * closure,
PRUint32 count,
PRUint32 * result);
NS_IMETHOD GetNonBlocking(PRBool * nonBlocking)
{ return mOutput->GetNonBlocking(nonBlocking); }
NS_IMETHOD SetNonBlocking(PRBool nonBlocking)
{ return mOutput->SetNonBlocking(nonBlocking); }
NS_IMETHOD GetObserver(nsIOutputStreamObserver ** observer)
{ return mOutput->GetObserver(observer); }
NS_IMETHOD SetObserver(nsIOutputStreamObserver * observer)
{ return mOutput->SetObserver(observer); }
nsOutputStreamWrapper(nsCacheEntryDescriptor * descriptor,
nsIOutputStream * output)
: mDescriptor(nsnull), mOutput(output)
{
NS_INIT_ISUPPORTS();
NS_ADDREF(mDescriptor = descriptor);
}
virtual ~nsOutputStreamWrapper()
{
NS_RELEASE(mDescriptor);
}
nsresult Init();
private:
nsresult OnWrite(PRUint32 count);
}; // end of class nsOutputStreamWrapper
friend class nsOutputStreamWrapper;
static nsresult NewOutputStreamWrapper(nsIOutputStream ** result,
nsCacheEntryDescriptor * descriptor,
nsIOutputStream * output);
private:
/**
* nsCacheEntryDescriptor data members
*/
nsCacheEntry * mCacheEntry; // we are a child of the entry
nsCacheAccessMode mAccessGranted;
nsTransportWrapper mTransportWrapper;
};
#endif // _nsCacheEntryDescriptor_h_

View File

@@ -0,0 +1,327 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheMetaData.cpp, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#include "nsCacheMetaData.h"
#include "nsString.h"
#include "nsICacheEntryDescriptor.h"
/*
* nsCacheClientHashTable
*/
PLDHashTableOps
nsCacheMetaData::ops =
{
PL_DHashAllocTable,
PL_DHashFreeTable,
GetKey,
HashKey,
MatchEntry,
MoveEntry,
ClearEntry,
Finalize
};
nsCacheMetaData::nsCacheMetaData()
: initialized(PR_FALSE)
{
}
nsCacheMetaData::~nsCacheMetaData()
{
if (initialized)
PL_DHashTableFinish(&table);
}
nsresult
nsCacheMetaData::Init()
{
nsresult rv = NS_OK;
initialized = PL_DHashTableInit(&table, &ops, nsnull,
sizeof(nsCacheMetaDataHashTableEntry), 16);
if (!initialized) rv = NS_ERROR_OUT_OF_MEMORY;
return rv;
}
nsCacheMetaData *
nsCacheMetaData::Create()
{
nsCacheMetaData * metaData = new nsCacheMetaData();
if (!metaData)
return nsnull;
nsresult rv = metaData->Init();
if (NS_FAILED(rv)) {
delete metaData;
return nsnull;
}
return metaData;
}
nsAReadableCString *
nsCacheMetaData::GetElement(const nsAReadableCString * key)
{
PLDHashEntryHdr * hashEntry;
nsCString * result = nsnull;
// XXX need to copy string until we have scc's new flat string abstract class
// XXX see nsCacheMetaData::HashKey below (bug 70075)
nsCString * tempKey = new nsCString(*key);
if (!tempKey) return result;
NS_ASSERTION(initialized, "nsCacheMetaDataHashTable not initialized");
hashEntry = PL_DHashTableOperate(&table, tempKey, PL_DHASH_LOOKUP);
if (PL_DHASH_ENTRY_IS_BUSY(hashEntry)) {
result = ((nsCacheMetaDataHashTableEntry *)hashEntry)->value;
}
delete tempKey;
return result;
}
nsresult
nsCacheMetaData::SetElement(const nsAReadableCString& key,
const nsAReadableCString& value)
{
nsCacheMetaDataHashTableEntry * metaEntry;
nsresult rv = NS_ERROR_OUT_OF_MEMORY; // presume the worst
NS_ASSERTION(initialized, "nsCacheMetaDataHashTable not initialized");
// XXX need to copy string until we have scc's new flat string abstract class
// XXX see nsCacheMetaData::HashKey below (bug 70075)
nsCString * tempKey = new nsCString(key);
if (!tempKey) return rv;
// XXX should empty value remove the key?
metaEntry = (nsCacheMetaDataHashTableEntry *)
PL_DHashTableOperate(&table, tempKey, PL_DHASH_ADD);
if (!metaEntry) goto error_exit;
if (metaEntry->key == nsnull) {
metaEntry->key = new nsCString(key);
if (metaEntry->key == nsnull) {
goto error_exit;
}
}
if (metaEntry->value != nsnull)
delete metaEntry->value; // clear the old value
metaEntry->value = new nsCString(value);
if (metaEntry->value == nsnull) {
// XXX remove key?
goto error_exit;
}
rv = NS_OK;
error_exit:
delete tempKey;
return rv;
}
PRUint32
nsCacheMetaData::Size(void)
{
PRUint32 size = 0;
(void) PL_DHashTableEnumerate(&table, CalculateSize, &size);
return size;
}
nsresult
nsCacheMetaData::FlattenMetaData(char ** data, PRUint32 * size)
{
*size = 0;
if (PL_DHashTableEnumerate(&table, CalculateSize, size) != 0 && data) {
*data = new char[*size];
if (*data == nsnull) return NS_ERROR_OUT_OF_MEMORY;
char* state = *data;
PL_DHashTableEnumerate(&table, AccumulateElement, &state);
}
return NS_OK;
}
nsresult
nsCacheMetaData::UnflattenMetaData(char * data, PRUint32 size)
{
nsresult rv = NS_ERROR_UNEXPECTED;
char* limit = data + size;
while (data < limit) {
const char* name = data;
PRUint32 nameSize = nsCRT::strlen(name);
data += 1 + nameSize;
if (data < limit) {
const char* value = data;
PRUint32 valueSize = nsCRT::strlen(value);
data += 1 + valueSize;
rv = SetElement(nsLocalCString(name, nameSize),
nsLocalCString(value, valueSize));
if (NS_FAILED(rv)) break;
}
}
return rv;
}
nsresult
nsCacheMetaData::VisitElements(nsICacheMetaDataVisitor * visitor)
{
(void) PL_DHashTableEnumerate(&table, VisitElement, visitor);
return NS_OK;
}
/*
* hash table operation callback functions
*/
const void * PR_CALLBACK
nsCacheMetaData::GetKey( PLDHashTable * /* table */, PLDHashEntryHdr *hashEntry)
{
return ((nsCacheMetaDataHashTableEntry *)hashEntry)->key;
}
PLDHashNumber PR_CALLBACK
nsCacheMetaData::HashKey( PLDHashTable * table, const void *key)
{
// XXX need scc's new flat string abstract class here (bug 70075)
return PL_DHashStringKey(table, ((nsCString *)key)->get());
}
PRBool PR_CALLBACK
nsCacheMetaData::MatchEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr * hashEntry,
const void * key)
{
NS_ASSERTION(key != nsnull, "### nsCacheMetaDataHashTable::MatchEntry : null key");
nsCString * entryKey = ((nsCacheMetaDataHashTableEntry *)hashEntry)->key;
NS_ASSERTION(entryKey, "### hashEntry->key == nsnull");
return entryKey->Equals(*NS_STATIC_CAST(const nsAReadableCString*,key));
}
void PR_CALLBACK
nsCacheMetaData::MoveEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to)
{
((nsCacheMetaDataHashTableEntry *)to)->key =
((nsCacheMetaDataHashTableEntry *)from)->key;
((nsCacheMetaDataHashTableEntry *)to)->value =
((nsCacheMetaDataHashTableEntry *)from)->value;
}
void PR_CALLBACK
nsCacheMetaData::ClearEntry(PLDHashTable * /* table */,
PLDHashEntryHdr * hashEntry)
{
((nsCacheMetaDataHashTableEntry *)hashEntry)->key = 0;
((nsCacheMetaDataHashTableEntry *)hashEntry)->value = 0;
}
void PR_CALLBACK
nsCacheMetaData::Finalize(PLDHashTable * table)
{
(void) PL_DHashTableEnumerate(table, FreeElement, nsnull);
}
/**
* hash table enumeration callback functions
*/
PLDHashOperator PR_CALLBACK
nsCacheMetaData::CalculateSize(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg)
{
nsCacheMetaDataHashTableEntry* hashEntry = (nsCacheMetaDataHashTableEntry *)hdr;
*(PRUint32*)arg += (2 + hashEntry->key->Length() + hashEntry->value->Length());
return PL_DHASH_NEXT;
}
PLDHashOperator PR_CALLBACK
nsCacheMetaData::AccumulateElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg)
{
char** bufferPtr = (char**) arg;
nsCacheMetaDataHashTableEntry* hashEntry = (nsCacheMetaDataHashTableEntry *)hdr;
PRUint32 size = 1 + hashEntry->key->Length();
nsCRT::memcpy(*bufferPtr, hashEntry->key->get(), size);
*bufferPtr += size;
size = 1 + hashEntry->value->Length();
nsCRT::memcpy(*bufferPtr, hashEntry->value->get(), size);
*bufferPtr += size;
return PL_DHASH_NEXT;
}
PLDHashOperator PR_CALLBACK
nsCacheMetaData::FreeElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg)
{
nsCacheMetaDataHashTableEntry *entry = (nsCacheMetaDataHashTableEntry *)hdr;
delete entry->key;
delete entry->value;
return PL_DHASH_NEXT;
}
PLDHashOperator PR_CALLBACK
nsCacheMetaData::VisitElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg)
{
nsCacheMetaDataHashTableEntry *entry = (nsCacheMetaDataHashTableEntry *)hdr;
nsICacheMetaDataVisitor *visitor = (nsICacheMetaDataVisitor *)arg;
const char * key = entry->key ? entry->key->get() : nsnull;
const char * value = entry->value ? entry->value->get() : nsnull;
PRBool keepGoing;
nsresult rv = visitor->VisitMetaDataElement(key, value, &keepGoing);
return NS_SUCCEEDED(rv) && keepGoing ? PL_DHASH_NEXT : PL_DHASH_STOP;
}

View File

@@ -0,0 +1,119 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheMetaData.h, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#ifndef _nsCacheMetaData_h_
#define _nsCacheMetaData_h_
#include "nspr.h"
#include "pldhash.h"
#include "nscore.h"
// #include "nsCOMPtr.h"
#include "nsString.h"
// #include "nsAReadableString.h"
class nsICacheMetaDataVisitor;
typedef struct {
nsCString * key;
nsCString * value;
} nsCacheMetaDataKeyValuePair;
typedef struct {
PLDHashNumber keyHash;
nsCString * key;
nsCString * value;
} nsCacheMetaDataHashTableEntry;
class nsCacheMetaData {
public:
nsCacheMetaData();
~nsCacheMetaData();
static
nsCacheMetaData * Create(void);
nsresult Init(void);
nsAReadableCString * GetElement(const nsAReadableCString * key);
nsresult SetElement(const nsAReadableCString& key,
const nsAReadableCString& value);
PRUint32 Size(void);
nsresult FlattenMetaData(char ** data, PRUint32 * size);
nsresult UnflattenMetaData(char * data, PRUint32 size);
nsresult VisitElements(nsICacheMetaDataVisitor * visitor);
private:
// PLDHashTable operation callbacks
static const void * PR_CALLBACK GetKey( PLDHashTable *table, PLDHashEntryHdr *entry);
static PLDHashNumber PR_CALLBACK HashKey( PLDHashTable *table, const void *key);
static PRBool PR_CALLBACK MatchEntry( PLDHashTable * table,
const PLDHashEntryHdr * entry,
const void * key);
static void PR_CALLBACK MoveEntry( PLDHashTable *table,
const PLDHashEntryHdr *from,
PLDHashEntryHdr *to);
static void PR_CALLBACK ClearEntry( PLDHashTable *table, PLDHashEntryHdr *entry);
static void PR_CALLBACK Finalize( PLDHashTable *table);
static
PLDHashOperator PR_CALLBACK CalculateSize(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg);
static
PLDHashOperator PR_CALLBACK AccumulateElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg);
static
PLDHashOperator PR_CALLBACK FreeElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg);
static
PLDHashOperator PR_CALLBACK VisitElement(PLDHashTable *table,
PLDHashEntryHdr *hdr,
PRUint32 number,
void *arg);
// member variables
static PLDHashTableOps ops;
PLDHashTable table;
PRBool initialized;
};
#endif // _nsCacheMetaData_h

View File

@@ -0,0 +1,41 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheModule.cpp, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
* Gordon Sheridan <gordon@netscape.com>
*/
#include "nsIGenericFactory.h"
#include "nsCacheService.h"
#include "nsNetCID.h"
// nsCacheService
//
static nsModuleComponentInfo gResComponents[] = {
{
NS_CACHESERVICE_CLASSNAME,
NS_CACHESERVICE_CID,
NS_CACHESERVICE_CONTRACTID,
nsCacheService::Create
}
};
NS_IMPL_NSGETMODULE(cacheservice, gResComponents)

View File

@@ -0,0 +1,178 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheRequest.h, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 22-February-2001
*/
#ifndef _nsCacheRequest_h_
#define _nsCacheRequest_h_
#include "nspr.h"
#include "nsCOMPtr.h"
#include "nsICache.h"
#include "nsICacheListener.h"
#include "nsIEventQueue.h"
#include "nsCacheSession.h"
class nsCacheRequest : public PRCList
{
private:
friend class nsCacheService;
friend class nsCacheEntry;
nsCacheRequest( nsCString * key,
nsICacheListener * listener,
nsCacheAccessMode accessRequested,
PRBool blockingMode,
nsCacheSession * session)
: mKey(key),
mInfo(0),
mListener(listener),
mEventQ(nsnull),
mLock(nsnull),
mCondVar(nsnull)
{
PR_INIT_CLIST(this);
SetAccessRequested(accessRequested);
SetStoragePolicy(session->StoragePolicy());
if (session->IsStreamBased()) MarkStreamBased();
if (session->WillDoomEntriesIfExpired()) MarkDoomEntriesIfExpired();
if (blockingMode == nsICache::BLOCKING) MarkBlockingMode();
MarkWaitingForValidation();
}
~nsCacheRequest()
{
delete mKey;
if (mLock) PR_DestroyLock(mLock);
if (mCondVar) PR_DestroyCondVar(mCondVar);
NS_ASSERTION(PR_CLIST_IS_EMPTY(this), "request still on a list");
}
/**
* Simple Accessors
*/
enum CacheRequestInfo {
eStoragePolicyMask = 0x000000FF,
eStreamBasedMask = 0x00000100,
eDoomEntriesIfExpiredMask = 0x00001000,
eBlockingModeMask = 0x00010000,
eWaitingForValidationMask = 0x00100000,
eAccessRequestedMask = 0xFF000000
};
void SetAccessRequested(nsCacheAccessMode mode)
{
NS_ASSERTION(mode <= 0xFF, "too many bits in nsCacheAccessMode");
mInfo &= ~eAccessRequestedMask;
mInfo |= mode << 24;
}
nsCacheAccessMode AccessRequested()
{
return (nsCacheAccessMode)((mInfo >> 24) & 0xFF);
}
void MarkStreamBased() { mInfo |= eStreamBasedMask; }
PRBool IsStreamBased() { return (mInfo & eStreamBasedMask) != 0; }
void MarkDoomEntriesIfExpired() { mInfo |= eDoomEntriesIfExpiredMask; }
PRBool WillDoomEntriesIfExpired() { return (mInfo & eDoomEntriesIfExpiredMask); }
void MarkBlockingMode() { mInfo |= eBlockingModeMask; }
PRBool IsBlocking() { return (mInfo & eBlockingModeMask); }
PRBool IsNonBlocking() { return !(mInfo & eBlockingModeMask); }
void SetStoragePolicy(nsCacheStoragePolicy policy)
{
NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy");
mInfo &= ~eStoragePolicyMask; // clear storage policy bits
mInfo |= policy; // or in new bits
}
nsCacheStoragePolicy StoragePolicy()
{
return (nsCacheStoragePolicy)(mInfo & 0xFF);
}
void MarkWaitingForValidation() { mInfo |= eWaitingForValidationMask; }
void DoneWaitingForValidation() { mInfo &= ~eWaitingForValidationMask; }
PRBool WaitingForValidation()
{
return (mInfo & eWaitingForValidationMask) != 0;
}
nsresult
WaitForValidation(void)
{
if (!WaitingForValidation()) { // flag already cleared
MarkWaitingForValidation(); // set up for next time
return NS_OK; // early exit;
}
if (!mLock) {
mLock = PR_NewLock();
if (!mLock) return NS_ERROR_OUT_OF_MEMORY;
NS_ASSERTION(!mCondVar,"we have mCondVar, but didn't have mLock?");
mCondVar = PR_NewCondVar(mLock);
if (!mCondVar) {
PR_DestroyLock(mLock);
return NS_ERROR_OUT_OF_MEMORY;
}
}
PRStatus status = PR_SUCCESS;
PR_Lock(mLock);
while (WaitingForValidation() && (status == PR_SUCCESS) ) {
status = PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT);
}
MarkWaitingForValidation(); // set up for next time
PR_Unlock(mLock);
NS_ASSERTION(status == PR_SUCCESS, "PR_WaitCondVar() returned PR_FAILURE?");
if (status == PR_FAILURE)
return NS_ERROR_UNEXPECTED;
return NS_OK;
}
void WakeUp(void) {
DoneWaitingForValidation();
if (mLock) {
PR_Lock(mLock);
PR_NotifyCondVar(mCondVar);
PR_Unlock(mLock);
}
}
/**
* Data members
*/
nsCString * mKey;
PRUint32 mInfo;
nsCOMPtr<nsICacheListener> mListener;
nsCOMPtr<nsIEventQueue> mEventQ;
PRLock * mLock;
PRCondVar * mCondVar;
};
#endif // _nsCacheRequest_h_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,194 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheService.h, released February 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#ifndef _nsCacheService_h_
#define _nsCacheService_h_
#include "nsICacheService.h"
#include "nsCacheSession.h"
#include "nsCacheDevice.h"
#include "nsCacheEntry.h"
#include "nspr.h"
#include "nsIObserver.h"
#include "nsString.h"
#include "nsIEventQueueService.h"
#include "nsProxiedService.h"
class nsCacheRequest;
/******************************************************************************
* nsCacheService
******************************************************************************/
class nsCacheService : public nsICacheService, public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHESERVICE
NS_DECL_NSIOBSERVER
nsCacheService();
virtual ~nsCacheService();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* outer, const nsIID& iid, void* *result);
/**
* Methods called by nsCacheSession
*/
nsresult OpenCacheEntry(nsCacheSession * session,
const char * key,
nsCacheAccessMode accessRequested,
PRBool blockingMode,
nsICacheListener * listener,
nsICacheEntryDescriptor ** result);
nsresult EvictEntriesForSession(nsCacheSession * session);
nsresult EvictEntriesForClient(const char * clientID,
nsCacheStoragePolicy storagePolicy);
/**
* Methods called by nsCacheEntryDescriptor
*/
nsresult SetCacheElement(nsCacheEntry * entry, nsISupports * element);
nsresult OnDataSizeChange(nsCacheEntry * entry, PRInt32 deltaSize);
nsresult ValidateEntry(nsCacheEntry * entry);
nsresult GetTransportForEntry(nsCacheEntry * entry,
nsCacheAccessMode mode,
nsITransport ** result);
void CloseDescriptor(nsCacheEntryDescriptor * descriptor);
nsresult GetFileForEntry(nsCacheEntry * entry,
nsIFile ** result);
/**
* Methods called by any cache classes
*/
static
nsCacheService * GlobalInstance(void) { return gService; };
nsresult DoomEntry(nsCacheEntry * entry);
nsresult DoomEntry_Locked(nsCacheEntry * entry);
/**
* Methods called by nsCachePrefObserver
*/
void SetCacheDevicesEnabled(PRBool disk, PRBool memory);
private:
/**
* Internal Methods
*/
nsresult CreateDiskDevice();
nsresult CreateMemoryDevice();
nsresult CreateRequest(nsCacheSession * session,
const char * clientKey,
nsCacheAccessMode accessRequested,
PRBool blockingMode,
nsICacheListener * listener,
nsCacheRequest ** request);
nsresult NotifyListener(nsCacheRequest * request,
nsICacheEntryDescriptor * descriptor,
nsCacheAccessMode accessGranted,
nsresult error);
nsresult ActivateEntry(nsCacheRequest * request, nsCacheEntry ** entry);
nsCacheDevice * EnsureEntryHasDevice(nsCacheEntry * entry);
nsCacheEntry * SearchCacheDevices(nsCString * key, nsCacheStoragePolicy policy);
void DeactivateEntry(nsCacheEntry * entry);
nsresult ProcessRequest(nsCacheRequest * request,
PRBool calledFromOpenCacheEntry,
nsICacheEntryDescriptor ** result);
nsresult ProcessPendingRequests(nsCacheEntry * entry);
void ClearPendingRequests(nsCacheEntry * entry);
void ClearDoomList(void);
void ClearActiveEntries(void);
static
PLDHashOperator PR_CALLBACK DeactivateAndClearEntry(PLDHashTable * table,
PLDHashEntryHdr * hdr,
PRUint32 number,
void * arg);
#if defined(PR_LOGGING)
void LogCacheStatistics();
#endif
/**
* Data Members
*/
static nsCacheService * gService; // there can be only one...
nsCOMPtr<nsIEventQueueService> mEventQService;
nsCOMPtr<nsIProxyObjectManager> mProxyObjectManager;
PRLock* mCacheServiceLock;
PRBool mEnableMemoryDevice;
PRBool mEnableDiskDevice;
nsCacheDevice * mMemoryDevice;
nsCacheDevice * mDiskDevice;
nsCacheEntryHashTable mActiveEntries;
PRCList mDoomedEntries;
// stats
PRUint32 mTotalEntries;
PRUint32 mCacheHits;
PRUint32 mCacheMisses;
PRUint32 mMaxKeyLength;
PRUint32 mMaxDataSize;
PRUint32 mMaxMetaSize;
// Unexpected error totals
PRUint32 mDeactivateFailures;
PRUint32 mDeactivatedUnboundEntries;
};
#endif // _nsCacheService_h_

View File

@@ -0,0 +1,104 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheSession.h, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#include "nsCacheSession.h"
#include "nsCacheService.h"
NS_IMPL_ISUPPORTS1(nsCacheSession, nsICacheSession)
nsCacheSession::nsCacheSession(const char * clientID,
nsCacheStoragePolicy storagePolicy,
PRBool streamBased)
: mClientID(clientID),
mInfo(0)
{
NS_INIT_ISUPPORTS();
SetStoragePolicy(storagePolicy);
if (streamBased) MarkStreamBased();
else SetStoragePolicy(nsICache::STORE_IN_MEMORY);
}
nsCacheSession::~nsCacheSession()
{
/* destructor code */
// notify service we are going away?
}
NS_IMETHODIMP nsCacheSession::GetDoomEntriesIfExpired(PRBool *result)
{
NS_ENSURE_ARG_POINTER(result);
*result = WillDoomEntriesIfExpired();
return NS_OK;
}
NS_IMETHODIMP nsCacheSession::SetDoomEntriesIfExpired(PRBool doomEntriesIfExpired)
{
if (doomEntriesIfExpired) MarkDoomEntriesIfExpired();
else ClearDoomEntriesIfExpired();
return NS_OK;
}
NS_IMETHODIMP
nsCacheSession::OpenCacheEntry(const char * key,
nsCacheAccessMode accessRequested,
PRBool blockingMode,
nsICacheEntryDescriptor ** result)
{
nsresult rv;
rv = nsCacheService::GlobalInstance()->OpenCacheEntry(this,
key,
accessRequested,
blockingMode,
nsnull, // no listener
result);
return rv;
}
NS_IMETHODIMP nsCacheSession::AsyncOpenCacheEntry(const char *key,
nsCacheAccessMode accessRequested,
nsICacheListener *listener)
{
nsresult rv;
rv = nsCacheService::GlobalInstance()->OpenCacheEntry(this,
key,
accessRequested,
nsICache::BLOCKING,
listener,
nsnull); // no result
if (rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION) rv = NS_OK;
return rv;
}
NS_IMETHODIMP nsCacheSession::EvictEntries()
{
return nsCacheService::GlobalInstance()->EvictEntriesForSession(this);
}

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheSession.h, released February 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
*/
#ifndef _nsCacheSession_h_
#define _nsCacheSession_h_
#include "nspr.h"
#include "nsError.h"
#include "nsICacheSession.h"
#include "nsString.h"
class nsCacheSession : public nsICacheSession
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHESESSION
nsCacheSession(const char * clientID, nsCacheStoragePolicy storagePolicy, PRBool streamBased);
virtual ~nsCacheSession();
nsCString * ClientID() { return &mClientID; }
enum SessionInfo {
eStoragePolicyMask = 0x000000FF,
eStreamBasedMask = 0x00000100,
eDoomEntriesIfExpiredMask = 0x00001000
};
void MarkStreamBased() { mInfo |= eStreamBasedMask; }
void ClearStreamBased() { mInfo &= ~eStreamBasedMask; }
PRBool IsStreamBased() { return (mInfo & eStreamBasedMask) != 0; }
void MarkDoomEntriesIfExpired() { mInfo |= eDoomEntriesIfExpiredMask; }
void ClearDoomEntriesIfExpired() { mInfo &= ~eDoomEntriesIfExpiredMask; }
PRBool WillDoomEntriesIfExpired() { return (mInfo & eDoomEntriesIfExpiredMask); }
nsCacheStoragePolicy StoragePolicy()
{
return (nsCacheStoragePolicy)(mInfo & eStoragePolicyMask);
}
void SetStoragePolicy(nsCacheStoragePolicy policy)
{
NS_ASSERTION(policy <= 0xFF, "too many bits in nsCacheStoragePolicy");
mInfo &= ~eStoragePolicyMask; // clear storage policy bits
mInfo |= policy;
}
private:
nsCString mClientID;
PRUint32 mInfo;
};
#endif // _nsCacheSession_h_

43
mozilla/netwerk/cache/src/nsDiskCache.h vendored Normal file
View File

@@ -0,0 +1,43 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsCacheDevice.h, released March 9, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard <beard@netscape.com>
* Gordon Sheridan <gordon@netscape.com>
*/
#ifndef _nsDiskCache_h_
#define _nsDiskCache_h_
#include "nsCacheEntry.h"
class nsDiskCache {
public:
enum {
kCurrentVersion = 0x00010003 // XXX whats the format?
};
enum { kData, kMetaData };
static PLDHashNumber Hash(const char* key);
};
#endif // _nsDiskCache_h_

View File

@@ -0,0 +1,348 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheBinding.cpp, released May 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
* Gordon Sheridan <gordon@netscape.com>
*/
#include <limits.h>
#include "nsDiskCacheBinding.h"
/******************************************************************************
* static hash table callback functions
*
*****************************************************************************/
#ifdef XP_MAC
#pragma mark -
#pragma mark HASHTABLE CALLBACKS
#endif
struct HashTableEntry : PLDHashEntryHdr {
nsDiskCacheBinding * mBinding;
};
static const void * PR_CALLBACK
GetKey(PLDHashTable * /*table*/, PLDHashEntryHdr * header)
{
return (void*) ((HashTableEntry *)header)->mBinding->mRecord.HashNumber();
}
static PLDHashNumber PR_CALLBACK
HashKey( PLDHashTable *table, const void *key)
{
return (PLDHashNumber) key;
}
static PRBool PR_CALLBACK
MatchEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr * header,
const void * key)
{
HashTableEntry * hashEntry = (HashTableEntry *) header;
return (hashEntry->mBinding->mRecord.HashNumber() == (PLDHashNumber) key);
}
static void PR_CALLBACK
MoveEntry(PLDHashTable * /* table */,
const PLDHashEntryHdr * src,
PLDHashEntryHdr * dst)
{
((HashTableEntry *)dst)->mBinding = ((HashTableEntry *)src)->mBinding;
}
static void PR_CALLBACK
ClearEntry(PLDHashTable * /* table */,
PLDHashEntryHdr * header)
{
((HashTableEntry *)header)->mBinding = nsnull;
}
/******************************************************************************
* Utility Functions
*****************************************************************************/
#ifdef XP_MAC
#pragma mark -
#pragma mark DISK CACHE BINDERY
#endif
nsDiskCacheBinding *
GetCacheEntryBinding(nsCacheEntry * entry)
{
nsCOMPtr<nsISupports> data;
nsresult rv = entry->GetData(getter_AddRefs(data));
if (NS_FAILED(rv)) return nsnull;
return (nsDiskCacheBinding *)data.get();
}
/******************************************************************************
* nsDiskCacheBinding
*****************************************************************************/
NS_IMPL_THREADSAFE_ISUPPORTS0(nsDiskCacheBinding);
nsDiskCacheBinding::nsDiskCacheBinding(nsCacheEntry* entry, nsDiskCacheRecord * record)
: mCacheEntry(entry)
{
NS_ASSERTION(record->ValidRecord(), "bad record");
NS_INIT_ISUPPORTS();
PR_INIT_CLIST(this);
mRecord = *record;
mDoomed = entry->IsDoomed();
mGeneration = record->Generation(); // 0 == uninitialized, or data & meta using block files
}
nsDiskCacheBinding::~nsDiskCacheBinding()
{
NS_ASSERTION(PR_CLIST_IS_EMPTY(this), "binding deleted while still on list");
if (!PR_CLIST_IS_EMPTY(this))
PR_REMOVE_LINK(this); // XXX why are we still on a list?
}
/******************************************************************************
* nsDiskCacheBindery
*
* Keeps track of bound disk cache entries to detect for collisions.
*
*****************************************************************************/
PLDHashTableOps nsDiskCacheBindery::ops =
{
PL_DHashAllocTable,
PL_DHashFreeTable,
GetKey,
HashKey,
MatchEntry,
MoveEntry,
ClearEntry,
PL_DHashFinalizeStub
};
nsDiskCacheBindery::nsDiskCacheBindery()
: initialized(PR_FALSE)
{
}
nsDiskCacheBindery::~nsDiskCacheBindery()
{
if (initialized)
PL_DHashTableFinish(&table);
}
nsresult
nsDiskCacheBindery::Init()
{
nsresult rv = NS_OK;
initialized = PL_DHashTableInit(&table, &ops, nsnull, sizeof(HashTableEntry), 0);
if (!initialized) rv = NS_ERROR_OUT_OF_MEMORY;
return rv;
}
nsDiskCacheBinding *
nsDiskCacheBindery::CreateBinding(nsCacheEntry * entry,
nsDiskCacheRecord * record)
{
NS_ASSERTION(initialized, "nsDiskCacheBindery not initialized");
nsCOMPtr<nsISupports> data;
nsresult rv = entry->GetData(getter_AddRefs(data));
if (NS_FAILED(rv) || data) {
NS_ASSERTION(!data, "cache entry already has bind data");
return nsnull;
}
nsDiskCacheBinding * binding = new nsDiskCacheBinding(entry, record);
if (!binding) return nsnull;
// give ownership of the binding to the entry
entry->SetData(binding);
// add binding to collision detection system
rv = AddBinding(binding);
if (NS_FAILED(rv)) {
entry->SetData(nsnull);
return nsnull;
}
return binding;
}
/**
* FindActiveEntry : to find active colliding entry so we can doom it
*/
nsDiskCacheBinding *
nsDiskCacheBindery::FindActiveBinding(PRUint32 hashNumber)
{
NS_ASSERTION(initialized, "nsDiskCacheBindery not initialized");
// find hash entry for key
HashTableEntry * hashEntry;
hashEntry = (HashTableEntry *) PL_DHashTableOperate(&table, (void*) hashNumber, PL_DHASH_LOOKUP);
if (PL_DHASH_ENTRY_IS_FREE(hashEntry)) return nsnull;
// walk list looking for active entry
NS_ASSERTION(hashEntry->mBinding, "hash entry left with no binding");
nsDiskCacheBinding * binding = hashEntry->mBinding;
while (binding->mCacheEntry->IsDoomed()) {
binding = (nsDiskCacheBinding *)PR_NEXT_LINK(binding);
if (binding == hashEntry->mBinding) return nsnull;
}
return binding;
}
/**
* FindBinding : to identify whether a record is 'in use' so we don't evict it
*/
nsDiskCacheBinding *
nsDiskCacheBindery::FindBinding(nsDiskCacheRecord * record)
{
NS_ASSERTION(initialized, "nsDiskCacheBindery not initialized");
// find hash entry for key
HashTableEntry * hashEntry;
hashEntry = (HashTableEntry *) PL_DHashTableOperate(&table, (void*) record->HashNumber(), PL_DHASH_LOOKUP);
if (PL_DHASH_ENTRY_IS_FREE(hashEntry)) return nsnull;
// walk list looking for matching record (match on MetaLocation)
NS_ASSERTION(hashEntry->mBinding, "hash entry left with no binding");
nsDiskCacheBinding * binding = hashEntry->mBinding;
while (binding->mRecord.MetaLocation() != record->MetaLocation()) {
binding = (nsDiskCacheBinding *)PR_NEXT_LINK(binding);
if (binding == hashEntry->mBinding) return nsnull;
}
return binding;
}
/**
* AddBinding
*
* Called from FindEntry() if we read an entry off of disk
* - it may already have a generation number
* - a generation number conflict is an error
*
* Called from BindEntry()
* - a generation number needs to be assigned
*/
nsresult
nsDiskCacheBindery::AddBinding(nsDiskCacheBinding * binding)
{
NS_ENSURE_ARG_POINTER(binding);
NS_ASSERTION(initialized, "nsDiskCacheBindery not initialized");
// find hash entry for key
HashTableEntry * hashEntry;
hashEntry = (HashTableEntry *) PL_DHashTableOperate(&table,
(void*) binding->mRecord.HashNumber(),
PL_DHASH_ADD);
if (!hashEntry) return NS_ERROR_OUT_OF_MEMORY;
if (hashEntry->mBinding == nsnull) {
hashEntry->mBinding = binding;
if (binding->mGeneration == 0)
binding->mGeneration = 1; // if generation uninitialized, set it to 1
return NS_OK;
}
// insert binding in generation order
nsDiskCacheBinding * p = hashEntry->mBinding;
PRBool calcGeneration = (binding->mGeneration == 0); // do we need to calculate generation?
if (calcGeneration) binding->mGeneration = 1; // initialize to 1 if uninitialized
while (1) {
if (binding->mGeneration < p->mGeneration) {
// here we are
PR_INSERT_BEFORE(binding, p);
if (hashEntry->mBinding == p)
hashEntry->mBinding = binding;
}
if (binding->mGeneration == p->mGeneration) {
if (calcGeneration) ++binding->mGeneration; // try the next generation
else {
NS_ASSERTION(binding->mGeneration != p->mGeneration, "generations collide!");
return NS_ERROR_UNEXPECTED;
}
}
p = (nsDiskCacheBinding *)PR_NEXT_LINK(p);
if (p == hashEntry->mBinding) {
// end of line: insert here or die
p = (nsDiskCacheBinding *)PR_PREV_LINK(p); // back up and check generation
if (p->mGeneration == 255) {
NS_ASSERTION(p->mGeneration < 255, "generation capacity at full, the engines canna take it cap'n");
return NS_ERROR_UNEXPECTED;
}
PR_INSERT_BEFORE(binding, hashEntry->mBinding);
}
}
return NS_OK;
}
/**
* RemoveBinding : remove binding from collision detection on deactivation
*/
void
nsDiskCacheBindery::RemoveBinding(nsDiskCacheBinding * binding)
{
NS_ASSERTION(initialized, "nsDiskCacheBindery not initialized");
if (!initialized) return;
HashTableEntry * hashEntry;
void * key = (void *)binding->mRecord.HashNumber();
hashEntry = (HashTableEntry*) PL_DHashTableOperate(&table, (void*) key, PL_DHASH_LOOKUP);
if (!PL_DHASH_ENTRY_IS_BUSY(hashEntry)) {
NS_ASSERTION(PL_DHASH_ENTRY_IS_BUSY(hashEntry), "binding not in disk cache hashtable!");
return;
}
if (binding == hashEntry->mBinding) {
if (PR_CLIST_IS_EMPTY(binding)) {
// remove this hash entry
(void) PL_DHashTableOperate(&table, (void*) binding->mRecord.HashNumber(), PL_DHASH_REMOVE);
return;
} else {
// promote next binding to head, and unlink this binding
hashEntry->mBinding = (nsDiskCacheBinding *)PR_NEXT_LINK(binding);
}
}
PR_REMOVE_AND_INIT_LINK(binding);
}

View File

@@ -0,0 +1,143 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheBinding.h, released May 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
*/
#ifndef _nsDiskCacheBinding_h_
#define _nsDiskCacheBinding_h_
#include "nspr.h"
#include "pldhash.h"
#include "nsISupports.h"
#include "nsCacheEntry.h"
#ifdef MOZ_NEW_CACHE_REUSE_TRANSPORTS
#include "nsITransport.h"
#endif
#include "nsDiskCacheMap.h"
/******************************************************************************
* nsDiskCacheBinding
*
* Created for disk cache specific data and stored in nsCacheEntry.mData as
* an nsISupports. Also stored in nsDiskCacheHashTable, with collisions
* linked by the PRCList.
*
*****************************************************************************/
class nsDiskCacheBinding : public nsISupports, public PRCList {
public:
NS_DECL_ISUPPORTS
nsDiskCacheBinding(nsCacheEntry* entry, nsDiskCacheRecord * record);
virtual ~nsDiskCacheBinding();
#ifdef MOZ_NEW_CACHE_REUSE_TRANSPORTS
/**
* Maps a cache access mode to a cached nsITransport for that access
* mode. We keep these cached to avoid repeated trips to the
* file transport service.
*/
nsCOMPtr<nsITransport>& getTransport(nsCacheAccessMode mode)
{
return mTransports[mode - 1];
}
#endif
// XXX make friends
public:
nsCacheEntry* mCacheEntry; // back pointer to parent nsCacheEntry
nsDiskCacheRecord mRecord;
PRBool mDoomed; // record is not stored in cache map
PRUint8 mGeneration; // possibly just reservation
private:
#ifdef MOZ_NEW_CACHE_REUSE_TRANSPORTS
nsCOMPtr<nsITransport> mTransports[3];
#endif
};
/******************************************************************************
* Utility Functions
*****************************************************************************/
nsDiskCacheBinding * GetCacheEntryBinding(nsCacheEntry * entry);
/******************************************************************************
* nsDiskCacheBindery
*
* Used to keep track of nsDiskCacheBinding associated with active/bound (and
* possibly doomed) entries. Lookups on 4 byte disk hash to find collisions
* (which need to be doomed, instead of just evicted. Collisions are linked
* using a PRCList to keep track of current generation number.
*
* Used to detect hash number collisions, and find available generation numbers.
*
* Not all nsDiskCacheBinding have a generation number.
*
* Generation numbers may be aquired late, or lost (when data fits in block file)
*
* Collisions can occur:
* BindEntry() - hashnumbers collide (possibly different keys)
*
* Generation number required:
* DeactivateEntry() - metadata written to disk, may require file
* GetFileForEntry() - force data to require file
* writing to stream - data size may require file
*
* Binding can be kept in PRCList in order of generation numbers.
* Binding with no generation number can be Appended to PRCList (last).
*
*****************************************************************************/
class nsDiskCacheBindery {
public:
nsDiskCacheBindery();
~nsDiskCacheBindery();
nsresult Init();
nsDiskCacheBinding * CreateBinding(nsCacheEntry * entry,
nsDiskCacheRecord * record);
nsDiskCacheBinding * FindActiveBinding(PRUint32 hashNumber);
nsDiskCacheBinding * FindBinding(nsDiskCacheRecord * record);
nsresult AddBinding(nsDiskCacheBinding * binding);
void RemoveBinding(nsDiskCacheBinding * binding);
private:
// member variables
static PLDHashTableOps ops;
PLDHashTable table;
PRBool initialized;
};
#endif /* _nsDiskCacheBinding_h_ */

View File

@@ -0,0 +1,422 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheBlockFile.cpp, released April 12, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
*/
#include "nsCRT.h"
#include "nsDiskCacheBlockFile.h"
/******************************************************************************
* nsDiskCacheBlockFile -
*****************************************************************************/
/******************************************************************************
* Open
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::Open( nsILocalFile * blockFile, PRUint32 blockSize)
{
PRStatus err = PR_SUCCESS;
PRInt32 fileSize;
mBlockSize = blockSize;
// open the file
nsresult rv = blockFile->OpenNSPRFileDesc(PR_RDWR | PR_CREATE_FILE, 00666, &mFD);
if (NS_FAILED(rv)) return rv; // unable to open or create file
// allocate bit map buffer
mBitMap = new PRUint8[kBitMapBytes];
if (!mBitMap) {
rv = NS_ERROR_OUT_OF_MEMORY;
goto error_exit;
}
// check if we just creating the file
fileSize = PR_Available(mFD);
if (fileSize < 0) {
// XXX an error occurred. We could call PR_GetError(), but how would that help?
rv = NS_ERROR_UNEXPECTED;
goto error_exit;
}
mEndOfFile = fileSize;
if (mEndOfFile == 0) {
// initialize bit map and write it
nsCRT::zero(mBitMap, kBitMapBytes);
PRInt32 bytesWritten = PR_Write(mFD, mBitMap, kBitMapBytes);
if (bytesWritten < kBitMapBytes) goto error_exit;
mEndOfFile = kBitMapBytes;
} else if (mEndOfFile < kBitMapBytes) {
rv = NS_ERROR_UNEXPECTED; // XXX NS_ERROR_CACHE_INVALID;
goto error_exit;
} else {
// read the bit map
PRInt32 bytesRead = PR_Read(mFD, mBitMap, kBitMapBytes);
if (bytesRead < kBitMapBytes) {
rv = NS_ERROR_UNEXPECTED;
goto error_exit;
}
// validate block file
rv = ValidateFile();
if (NS_FAILED(rv)) goto error_exit;
}
return NS_OK;
error_exit:
if (mFD) {
(void) PR_Close(mFD);
mFD = nsnull;
}
if (mBitMap) {
delete [] mBitMap;
mBitMap = nsnull;
}
return rv;
}
/******************************************************************************
* Close
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::Close()
{
if (!mFD) return NS_OK;
nsresult rv = FlushBitMap();
PRStatus err = PR_Close(mFD);
mFD = nsnull;
if (mBitMap) {
delete [] mBitMap;
mBitMap = nsnull;
}
if (NS_SUCCEEDED(rv) && (err != PR_SUCCESS))
rv = NS_ERROR_UNEXPECTED;
return rv;
}
/******************************************************************************
* Trim
*
* Truncate the block file to the end of the last allocated block.
*
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::Trim()
{
return NS_OK;
}
/******************************************************************************
* AllocateBlocks
*
* Allocates 1-4 blocks, using a first fit strategy,
* so that no group of blocks spans a quad block boundary.
*
* Returns block number of first block allocated or -1 on failure.
*
*****************************************************************************/
PRInt32
nsDiskCacheBlockFile::AllocateBlocks(PRInt32 numBlocks)
{
if (!mFD) return -1; // NS_ERROR_NOT_AVAILABLE;
// return -1 if unable to allocate blocks
// PRUint8 mask = (0x01 << numBlocks) - 1;
int i = 0;
PRUint8 mapByte;
PRUint8 mask;
// presume allocation will succeed
PRBool oldValue = mBitMapDirty;
mBitMapDirty = PR_TRUE;
while ((mBitMap[i] == 0xFF) && (i < kBitMapBytes)) ++i; // find first block with a free bit
if (numBlocks == 1) {
if (i < kBitMapBytes) {
// don't need a while loop, because we know there's at least 1 free bit in this byte
mapByte = ~mBitMap[i]; // flip bits so free bits are 1
/*
* // Linear search for first free bit in byte
* mask = 0x01;
* for (int j=0; j<8; ++j, mask <<= 1)
* if (mask & mapByte) {mBitMap[i] |= mask; return (i * 8 + j); }
*/
// Binary search for first free bit in byte
PRUint8 bit = 0;
if ((mapByte & 0x0F) == 0) { bit |= 4; mapByte >>= 4; }
if ((mapByte & 0x03) == 0) { bit |= 2; mapByte >>= 2; }
if ((mapByte & 0x01) == 0) { bit |= 1; mapByte >>= 1; }
mBitMap[i] |= (PRUint8)1 << bit;
return i * 8 + bit;
}
} else if (numBlocks == 2) {
while (i < kBitMapBytes) {
mapByte = ~mBitMap[i]; // flip bits so free bits are 1
mask = 0x03;
// check for fit in lower quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 1); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 2); } mask <<= 2;
// check for fit in upper quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 4); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 5); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 6); }
++i;
}
} else if (numBlocks == 3) {
while (i < kBitMapBytes) {
mapByte = ~mBitMap[i]; // flip bits so free bits are 1
mask = 0x07;
// check for fit in lower quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 1); } mask <<= 3;
// check for fit in upper quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 4); } mask <<= 1;
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 5); }
++i;
}
} else if (numBlocks == 4) {
while (i < kBitMapBytes) {
mapByte = ~mBitMap[i]; // flip bits so free bits are 1
mask = 0x0F;
// check for fit in lower quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8); } mask <<= 4;
// check for fit in upper quad bits
if ((mask & mapByte) == mask) { mBitMap[i] |= mask; return (i * 8 + 4); }
++i;
}
}
mBitMapDirty = oldValue;
return -1;
}
/******************************************************************************
* DeallocateBlocks
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::DeallocateBlocks( PRInt32 startBlock, PRInt32 numBlocks)
{
if (!mFD) return NS_ERROR_NOT_AVAILABLE;
if ((startBlock < 0) || (startBlock > kBitMapBytes * 8 - 1) ||
(numBlocks < 1) || (numBlocks > 4))
return NS_ERROR_ILLEGAL_VALUE;
PRInt32 startByte = startBlock / 8;
PRUint8 startBit = startBlock % 8;
// make sure requested deallocation doesn't span a byte boundary
if ((startBlock + numBlocks - 1) / 8 != startByte) return NS_ERROR_UNEXPECTED;
PRUint8 mask = ((0x01 << numBlocks) - 1) << startBit;
PRUint8 mapByte = ~mBitMap[startByte]; // flip so allocated bits are zero
// make sure requested deallocation is currently allocated
if (mapByte & mask) return NS_ERROR_ABORT;
mBitMap[startByte] ^= mask; // flips the bits off;
mBitMapDirty = PR_TRUE;
// XXX rv = FlushBitMap(); // coherency vs. performance
return NS_OK;
}
/******************************************************************************
* WriteBlocks
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::WriteBlocks( void * buffer,
PRInt32 startBlock,
PRInt32 numBlocks)
{
// presume buffer != nsnull
if (!mFD) return NS_ERROR_NOT_AVAILABLE;
nsresult rv = VerifyAllocation(startBlock, numBlocks);
if (NS_FAILED(rv)) return rv;
// seek to block position
PRInt32 blockPos = kBitMapBytes + startBlock * mBlockSize;
PRInt32 filePos = PR_Seek(mFD, blockPos, PR_SEEK_SET);
if (filePos != blockPos) return NS_ERROR_UNEXPECTED;
if (mEndOfFile < (blockPos + numBlocks * mBlockSize))
mEndOfFile = (blockPos + numBlocks * mBlockSize);
// write the blocks
PRInt32 bytesToWrite = numBlocks * mBlockSize;
PRInt32 bytesWritten = PR_Write(mFD, buffer, bytesToWrite);
if (bytesWritten < bytesToWrite) return NS_ERROR_UNEXPECTED;
// write the bit map and flush the file
// XXX rv = FlushBitMap();
return rv;
}
/******************************************************************************
* ReadBlocks
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::ReadBlocks( void * buffer,
PRInt32 startBlock,
PRInt32 numBlocks)
{
// presume buffer != nsnull
if (!mFD) return NS_ERROR_NOT_AVAILABLE;
nsresult rv = VerifyAllocation(startBlock, numBlocks);
if (NS_FAILED(rv)) return rv;
// seek to block position
PRInt32 blockPos = kBitMapBytes + startBlock * mBlockSize;
PRInt32 filePos = PR_Seek(mFD, blockPos, PR_SEEK_SET);
if (filePos != blockPos) return NS_ERROR_UNEXPECTED;
// read the blocks
PRInt32 bytesToRead = numBlocks * mBlockSize;
PRInt32 bytesRead = PR_Read(mFD, buffer, bytesToRead);
if (bytesRead < bytesToRead) return NS_ERROR_UNEXPECTED;
return rv;
}
/******************************************************************************
* FlushBitMap
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::FlushBitMap()
{
if (!mBitMapDirty) return NS_OK;
// seek to bitmap
PRInt32 filePos = PR_Seek(mFD, 0, PR_SEEK_SET);
if (filePos != 0) return NS_ERROR_UNEXPECTED;
// write bitmap
PRInt32 bytesWritten = PR_Write(mFD, mBitMap, kBitMapBytes);
if (bytesWritten < kBitMapBytes) return NS_ERROR_UNEXPECTED;
PRStatus err = PR_Sync(mFD);
if (err != PR_SUCCESS) return NS_ERROR_UNEXPECTED;
mBitMapDirty = PR_FALSE;
return NS_OK;
}
/******************************************************************************
* ValidateFile
*
* Check size of file against last bit allocated for mBlockSize.
*
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::ValidateFile()
{
PRInt32 estimatedSize = kBitMapBytes;
PRInt32 lastBlock = LastBlock();
if (lastBlock >= 0)
estimatedSize += (lastBlock + 1) * mBlockSize;
// seek to beginning
PRInt32 filePos = PR_Seek(mFD, 0, PR_SEEK_SET);
if (filePos != 0) return NS_ERROR_UNEXPECTED;
PRInt32 fileSize = PR_Available(mFD);
if (estimatedSize > fileSize)
return NS_ERROR_UNEXPECTED;
return NS_OK;
}
/******************************************************************************
* VerfiyAllocation
*
* Return values:
* NS_OK if all bits are marked allocated
* NS_ERROR_ILLEGAL_VALUE if parameters don't obey constraints
* NS_ERROR_FAILURE if some or all the bits are marked unallocated
*
*****************************************************************************/
nsresult
nsDiskCacheBlockFile::VerifyAllocation( PRInt32 startBlock, PRInt32 numBlocks)
{
if ((startBlock < 0) || (startBlock > kBitMapBytes * 8 - 1) ||
(numBlocks < 1) || (numBlocks > 4))
return NS_ERROR_ILLEGAL_VALUE;
PRInt32 startByte = startBlock / 8;
PRUint8 startBit = startBlock % 8;
// make sure requested deallocation doesn't span a byte boundary
if ((startBlock + numBlocks - 1) / 8 != startByte) return NS_ERROR_ILLEGAL_VALUE;
PRUint8 mask = ((0x01 << numBlocks) - 1) << startBit;
// check if all specified blocks are currently allocated
if ((mBitMap[startByte] & mask) != mask) return NS_ERROR_FAILURE;
return NS_OK;
}
/******************************************************************************
* LastBlock
*
* Return last block allocated or -1 if no blocks are allocated.
*
*****************************************************************************/
PRInt32
nsDiskCacheBlockFile::LastBlock()
{
// search for last byte in mBitMap with allocated bits
PRInt32 i = kBitMapBytes;
while (--i >= 0) {
if (mBitMap[i]) break;
}
if (i >= 0) {
// binary search to find last allocated bit in byte
PRUint8 mapByte = mBitMap[i];
PRUint8 lastBit = 7;
if ((mapByte & 0xF0) == 0) { lastBit ^= 4; mapByte <<= 4; }
if ((mapByte & 0xC0) == 0) { lastBit ^= 2; mapByte <<= 2; }
if ((mapByte & 0x80) == 0) { lastBit ^= 1; mapByte <<= 1; }
return i * 8 + lastBit;
}
return -1;
}

View File

@@ -0,0 +1,76 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheBlockFile.h, released April 12, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
*/
#ifndef _nsDiskCacheBlockFile_h_
#define _nsDiskCacheBlockFile_h_
#include "nsILocalFile.h"
#include "nspr.h"
enum { kBitMapBytes = 4096 };
/******************************************************************************
* nsDiskCacheBlockFile
*
* The structure of a cache block file is a 4096 bytes bit map, followed by
* some number of blocks of mBlockSize. The creator of a
* nsDiskCacheBlockFile object must provide the block size for a given file.
*
*****************************************************************************/
class nsDiskCacheBlockFile {
public:
nsDiskCacheBlockFile()
: mFD(nsnull)
, mBlockSize(0)
, mEndOfFile(0)
, mBitMap(nsnull)
, mBitMapDirty(PR_FALSE)
{}
~nsDiskCacheBlockFile() { (void) Close(); }
nsresult Open( nsILocalFile * blockFile, PRUint32 blockSize);
nsresult Close();
nsresult Trim();
PRInt32 AllocateBlocks( PRInt32 numBlocks);
nsresult DeallocateBlocks( PRInt32 startBlock, PRInt32 numBlocks);
nsresult WriteBlocks( void * buffer, PRInt32 startBlock, PRInt32 numBlocks);
nsresult ReadBlocks( void * buffer, PRInt32 startBlock, PRInt32 numBlocks);
private:
nsresult FlushBitMap();
nsresult ValidateFile(); // called by Open()
nsresult VerifyAllocation( PRInt32 startBlock, PRInt32 numBLocks);
PRInt32 LastBlock();
/**
* Data members
*/
PRFileDesc * mFD;
PRUint32 mBlockSize;
PRUint32 mEndOfFile;
PRUint8 * mBitMap; // XXX future: array of bit map blocks
PRBool mBitMapDirty;
};
#endif // _nsDiskCacheBlockFile_h_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,96 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheDevice.h, released February 20, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
*/
#ifndef _nsDiskCacheDevice_h_
#define _nsDiskCacheDevice_h_
#include "nsCacheDevice.h"
#include "nsDiskCacheBinding.h"
#include "nsDiskCacheBlockFile.h"
#include "nsDiskCacheEntry.h"
#include "nsILocalFile.h"
#include "nsIObserver.h"
class nsDiskCacheMap;
class nsDiskCacheDevice : public nsCacheDevice {
public:
nsDiskCacheDevice();
virtual ~nsDiskCacheDevice();
static nsresult Create(nsCacheDevice **result);
virtual nsresult Init();
virtual nsresult Shutdown();
virtual const char * GetDeviceID(void);
virtual nsCacheEntry * FindEntry(nsCString * key);
virtual nsresult DeactivateEntry(nsCacheEntry * entry);
virtual nsresult BindEntry(nsCacheEntry * entry);
virtual void DoomEntry( nsCacheEntry * entry );
virtual nsresult GetTransportForEntry(nsCacheEntry * entry,
nsCacheAccessMode mode,
nsITransport ** result);
virtual nsresult GetFileForEntry(nsCacheEntry * entry,
nsIFile ** result);
virtual nsresult OnDataSizeChange(nsCacheEntry * entry, PRInt32 deltaSize);
virtual nsresult Visit(nsICacheVisitor * visitor);
virtual nsresult EvictEntries(const char * clientID);
/* private: */
void setPrefsObserver(nsIObserver * observer);
void getPrefsObserver(nsIObserver ** result);
void setCacheDirectory(nsILocalFile * directory);
void getCacheDirectory(nsILocalFile ** result);
void setCacheCapacity(PRUint32 capacity);
PRUint32 getCacheCapacity();
PRUint32 getCacheSize();
PRUint32 getEntryCount();
private:
/**
* Private methods
*/
nsresult InitializeCacheDirectory();
nsresult GetCacheTrashDirectory(nsIFile ** result);
nsresult EvictDiskCacheEntries();
/**
* Member variables
*/
PRBool mInitialized;
nsCOMPtr<nsIObserver> mPrefsObserver; // XXX ?
nsCOMPtr<nsILocalFile> mCacheDirectory;
nsDiskCacheBindery mBindery;
PRUint32 mCacheCapacity; // XXX need soft/hard limits, currentTotal
nsDiskCacheMap * mCacheMap;
};
#endif // _nsDiskCacheDevice_h_

View File

@@ -0,0 +1,211 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheEntry.cpp, released May 10, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
*/
#include "nsDiskCache.h"
#include "nsDiskCacheEntry.h"
#include "nsDiskCacheBinding.h"
#include "nsDiskCacheMap.h"
#include "nsCache.h"
/******************************************************************************
* nsDiskCacheEntry
*****************************************************************************/
/**
* CreateCacheEntry()
*
* Creates an nsCacheEntry and sets all fields except for the binding.
*/
nsCacheEntry *
nsDiskCacheEntry::CreateCacheEntry(nsCacheDevice * device)
{
nsCacheEntry * entry = nsnull;
nsresult rv = nsCacheEntry::Create(mKeyStart,
nsICache::STREAM_BASED,
nsICache::STORE_ON_DISK,
device,
&entry);
if (NS_FAILED(rv) || !entry) return nsnull;
entry->SetFetchCount(mFetchCount);
entry->SetLastFetched(mLastFetched);
entry->SetLastModified(mLastModified);
entry->SetExpirationTime(mExpirationTime);
entry->SetCacheDevice(device);
// XXX why does nsCacheService have to fill out device in BindEntry()?
entry->SetDataSize(mDataSize);
rv = entry->UnflattenMetaData(&mKeyStart[mKeySize], mMetaDataSize);
if (NS_FAILED(rv)) {
delete entry;
return nsnull;
}
return entry;
}
/**
* CheckConsistency()
*
* Perform a few simple checks to verify the data looks reasonable.
*/
PRBool
nsDiskCacheEntry::CheckConsistency(PRUint32 size)
{
if ((mHeaderVersion != nsDiskCache::kCurrentVersion) ||
(Size() > size) ||
(mKeySize == 0) ||
(mKeyStart[mKeySize - 1] != 0)) // key is null terminated
return PR_FALSE;
return PR_TRUE;
}
/**
* CreateDiskCacheEntry(nsCacheEntry * entry)
*
* Prepare an nsCacheEntry for writing to disk
*/
nsDiskCacheEntry *
CreateDiskCacheEntry(nsDiskCacheBinding * binding)
{
nsCacheEntry * entry = binding->mCacheEntry;
if (!entry) return nsnull;
PRUint32 keySize = entry->Key()->Length() + 1;
PRUint32 size = sizeof(nsDiskCacheEntry) +
keySize + entry->MetaDataSize();
// pad size so we can write to block files without overrunning buffer
PRInt32 pad = size;
if (pad < 1024) pad = 1024;
else if (pad < 4096) pad = 4096;
else if (pad < 16384) pad = 16384;
// XXX be more precise
nsDiskCacheEntry * diskEntry = (nsDiskCacheEntry *)new char[pad];
if (!diskEntry) return nsnull;
diskEntry->mHeaderVersion = nsDiskCache::kCurrentVersion;
diskEntry->mMetaLocation = binding->mRecord.MetaLocation();
diskEntry->mFetchCount = entry->FetchCount();
diskEntry->mLastFetched = entry->LastFetched();
diskEntry->mLastModified = entry->LastModified();
diskEntry->mExpirationTime = entry->ExpirationTime();
diskEntry->mDataSize = entry->DataSize();
diskEntry->mKeySize = keySize;
diskEntry->mMetaDataSize = entry->MetaDataSize();
nsCRT::memcpy(diskEntry->mKeyStart, entry->Key()->get(),keySize);
// XXX FIXME FlattenMetaData should not allocate a buffer
char * metaData = nsnull;
PRUint32 metaSize = 0;
nsresult rv = entry->FlattenMetaData(&metaData, &metaSize);
if (NS_FAILED(rv)) {
delete diskEntry;
return nsnull;
}
diskEntry->mMetaDataSize = metaSize;
if (metaSize)
nsCRT::memcpy(&diskEntry->mKeyStart[keySize], metaData, metaSize);
delete metaData;
return diskEntry;
}
/******************************************************************************
* nsDiskCacheEntryInfo
*****************************************************************************/
NS_IMPL_ISUPPORTS1(nsDiskCacheEntryInfo, nsICacheEntryInfo);
NS_IMETHODIMP nsDiskCacheEntryInfo::GetClientID(char ** clientID)
{
NS_ENSURE_ARG_POINTER(clientID);
return ClientIDFromCacheKey(nsLiteralCString(mDiskEntry->mKeyStart), clientID);
}
extern const char DISK_CACHE_DEVICE_ID[];
NS_IMETHODIMP nsDiskCacheEntryInfo::GetDeviceID(char ** deviceID)
{
NS_ENSURE_ARG_POINTER(deviceID);
*deviceID = nsCRT::strdup(mDeviceID);
return *deviceID ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetKey(char ** clientKey)
{
NS_ENSURE_ARG_POINTER(clientKey);
return ClientKeyFromCacheKey(nsLiteralCString(mDiskEntry->mKeyStart), clientKey);
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetFetchCount(PRInt32 *aFetchCount)
{
NS_ENSURE_ARG_POINTER(aFetchCount);
*aFetchCount = mDiskEntry->mFetchCount;
return NS_OK;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetLastFetched(PRUint32 *aLastFetched)
{
NS_ENSURE_ARG_POINTER(aLastFetched);
*aLastFetched = mDiskEntry->mLastFetched;
return NS_OK;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetLastModified(PRUint32 *aLastModified)
{
NS_ENSURE_ARG_POINTER(aLastModified);
*aLastModified = mDiskEntry->mLastModified;
return NS_OK;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetExpirationTime(PRUint32 *aExpirationTime)
{
NS_ENSURE_ARG_POINTER(aExpirationTime);
*aExpirationTime = mDiskEntry->mExpirationTime;
return NS_OK;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::IsStreamBased(PRBool *aStreamBased)
{
NS_ENSURE_ARG_POINTER(aStreamBased);
*aStreamBased = PR_TRUE;
return NS_OK;
}
NS_IMETHODIMP nsDiskCacheEntryInfo::GetDataSize(PRUint32 *aDataSize)
{
NS_ENSURE_ARG_POINTER(aDataSize);
*aDataSize = mDiskEntry->mDataSize;
return NS_OK;
}

View File

@@ -0,0 +1,126 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsMemoryCacheDevice.cpp, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
*/
#ifndef _nsDiskCacheEntry_h_
#define _nsDiskCacheEntry_h_
#include "nsDiskCacheMap.h"
#include "nsCacheEntry.h"
#include "nsICacheVisitor.h"
#include "nspr.h"
#include "nscore.h"
#include "nsError.h"
/******************************************************************************
* nsDiskCacheEntry
*****************************************************************************/
struct nsDiskCacheEntry {
PRUint32 mHeaderVersion; // useful for stand-alone metadata files
PRUint32 mMetaLocation; // for verification
PRInt32 mFetchCount;
PRUint32 mLastFetched;
PRUint32 mLastModified;
PRUint32 mExpirationTime;
PRUint32 mDataSize;
PRUint32 mKeySize; // includes terminating null byte
PRUint32 mMetaDataSize; // includes terminating null byte
char mKeyStart[1]; // start of key data
// mMetaDataStart = mKeyStart[mKeySize];
PRUint32 Size() { return sizeof(nsDiskCacheEntry)
- sizeof(char) // subtract default key size
+ mKeySize // plus actual key size
+ mMetaDataSize;
}
nsCacheEntry * CreateCacheEntry(nsCacheDevice * device);
PRBool CheckConsistency(PRUint32 size);
void Swap() // host to network (memory to disk)
{
#if defined(IS_LITTLE_ENDIAN)
mHeaderVersion = ::PR_htonl(mHeaderVersion);
mMetaLocation = ::PR_htonl(mMetaLocation);
mFetchCount = ::PR_htonl(mFetchCount);
mLastFetched = ::PR_htonl(mLastFetched);
mLastModified = ::PR_htonl(mLastModified);
mExpirationTime = ::PR_htonl(mExpirationTime);
mDataSize = ::PR_htonl(mDataSize);
mKeySize = ::PR_htonl(mKeySize);
mMetaDataSize = ::PR_htonl(mMetaDataSize);
#endif
}
void Unswap() // network to host (disk to memory)
{
#if defined(IS_LITTLE_ENDIAN)
mHeaderVersion = ::PR_ntohl(mHeaderVersion);
mMetaLocation = ::PR_ntohl(mMetaLocation);
mFetchCount = ::PR_ntohl(mFetchCount);
mLastFetched = ::PR_ntohl(mLastFetched);
mLastModified = ::PR_ntohl(mLastModified);
mExpirationTime = ::PR_ntohl(mExpirationTime);
mDataSize = ::PR_ntohl(mDataSize);
mKeySize = ::PR_ntohl(mKeySize);
mMetaDataSize = ::PR_ntohl(mMetaDataSize);
#endif
}
};
nsDiskCacheEntry * CreateDiskCacheEntry(nsDiskCacheBinding * binding);
/******************************************************************************
* nsDiskCacheEntryInfo
*****************************************************************************/
class nsDiskCacheEntryInfo : public nsICacheEntryInfo {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHEENTRYINFO
nsDiskCacheEntryInfo(const char * deviceID, nsDiskCacheEntry * diskEntry)
: mDeviceID(deviceID)
, mDiskEntry(diskEntry)
{
NS_INIT_ISUPPORTS();
}
virtual ~nsDiskCacheEntryInfo() {}
const char* Key() { return mDiskEntry->mKeyStart; }
private:
const char * mDeviceID;
nsDiskCacheEntry * mDiskEntry;
};
#endif /* _nsDiskCacheEntry_h_ */

View File

@@ -0,0 +1,836 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheMap.cpp, released March 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
* Gordon Sheridan <gordon@netscape.com>
*/
#include "nsDiskCacheMap.h"
#include "nsDiskCacheBinding.h"
#include "nsDiskCacheEntry.h"
#include "nsCache.h"
#include "nsCRT.h"
#include <string.h>
/******************************************************************************
* nsDiskCacheBucket
*****************************************************************************/
void
nsDiskCacheBucket::Swap()
{
nsDiskCacheRecord * record = &mRecords[0];
for (int i = 0; i < kRecordsPerBucket; ++i) {
if (record->HashNumber() == 0)
break;
record->Swap();
}
}
void
nsDiskCacheBucket::Unswap()
{
nsDiskCacheRecord * record = &mRecords[0];
for (int i = 0; i < kRecordsPerBucket; ++i) {
if (record->HashNumber() == 0)
break;
record->Unswap();
}
}
PRUint32
nsDiskCacheBucket::CountRecords()
{
if (mRecords[0].HashNumber() == 0) return 0;
PRUint32 i = kRecordsPerBucket >> 1;
PRUint32 offset = kRecordsPerBucket >> 2;
while (offset > 0) {
if (mRecords[i].HashNumber()) i += offset;
else i -= offset;
offset >>= 1;
}
if (mRecords[i].HashNumber() != 0)
++i;
return i;
}
PRUint32
nsDiskCacheBucket::EvictionRank()
{
PRUint32 rank = 0;
for (int i = CountRecords() - 1; i >= 0; --i) {
if (rank < mRecords[i].EvictionRank())
rank = mRecords[i].EvictionRank();
}
return rank;
}
PRInt32
nsDiskCacheBucket::VisitEachRecord(nsDiskCacheRecordVisitor * visitor,
PRUint32 evictionRank,
PRUint32 * result)
{
PRUint32 recordsDeleted = 0;
PRInt32 rv = kVisitNextRecord;
PRInt32 last = CountRecords() - 1;
// call visitor for each entry (equal or greater than evictionRank)
for (int i = last; i >= 0; i--) {
if (evictionRank > mRecords[i].EvictionRank()) continue;
rv = visitor->VisitRecord(&mRecords[i]);
if (rv == kVisitNextRecord) continue;
if (rv == kDeleteRecordAndContinue) {
mRecords[i] = mRecords[last];
mRecords[last].SetHashNumber(0);
--last;
++recordsDeleted;
continue;
}
*result = recordsDeleted;
return kStopVisitingRecords; // rv == kStopVisitingRecords
}
*result = recordsDeleted;
return rv;
}
/******************************************************************************
* nsDiskCacheMap
*****************************************************************************/
/**
* File operations
*/
nsresult
nsDiskCacheMap::Open(nsILocalFile * cacheDirectory)
{
NS_ENSURE_ARG_POINTER(cacheDirectory);
if (mMapFD) return NS_ERROR_ALREADY_INITIALIZED;
mCacheDirectory = cacheDirectory; // save a reference for ourselves
// create nsILocalFile for _CACHE_MAP_
nsresult rv;
nsCOMPtr<nsIFile> file;
rv = cacheDirectory->Clone(getter_AddRefs(file));
nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(file, &rv));
if (NS_FAILED(rv)) return rv;
rv = localFile->Append("_CACHE_MAP_");
if (NS_FAILED(rv)) return rv;
// open the file
rv = localFile->OpenNSPRFileDesc(PR_RDWR | PR_CREATE_FILE, 00666, &mMapFD);
if (NS_FAILED(rv)) return rv; // unable to open or create file
// check size of map file
PRUint32 mapSize = PR_Available(mMapFD);
if (mapSize < 0) {
rv = NS_ERROR_UNEXPECTED;
goto error_exit;
}
if (mapSize == 0) {
// create the file - initialize in memory
mHeader.mVersion = nsDiskCache::kCurrentVersion;
mHeader.mDataSize = 0;
mHeader.mEntryCount = 0;
mHeader.mIsDirty = PR_TRUE;
for (int i = 0; i < kBucketsPerTable; ++i) {
mHeader.mEvictionRank[i] = 0;
}
nsCRT::zero(mHeader.reserved, nsDiskCacheHeader::kReservedBytes);
nsCRT::zero(mBuckets, sizeof(nsDiskCacheBucket) * kBucketsPerTable);
} else if (mapSize == kCacheMapSize) {
// read it in
PRUint32 bytesRead = PR_Read(mMapFD, &mHeader, kCacheMapSize);
if (kCacheMapSize != bytesRead) {
rv = NS_ERROR_UNEXPECTED;
goto error_exit;
}
mHeader.Unswap();
if (mHeader.mIsDirty || mHeader.mVersion != nsDiskCache::kCurrentVersion) {
rv = NS_ERROR_FILE_CORRUPTED;
goto error_exit;
}
// Unswap each bucket
for (PRUint32 i = 0; i < kBucketsPerTable; ++i) {
mBuckets[i].Unswap();
}
// XXX verify entry count, check size(?)
} else {
rv = NS_ERROR_FILE_CORRUPTED;
goto error_exit;
}
rv = OpenBlockFiles();
if (NS_FAILED(rv)) goto error_exit;
// set dirty bit and flush header
mHeader.mIsDirty = PR_TRUE;
rv = FlushHeader();
if (NS_FAILED(rv)) goto error_exit;
return NS_OK;
error_exit:
(void) CloseBlockFiles();
if (mMapFD) {
(void) PR_Close(mMapFD);
mMapFD = nsnull;
}
return rv;
}
nsresult
nsDiskCacheMap::Close()
{
if (!mMapFD) return NS_OK;
// close block files
nsresult rv = CloseBlockFiles();
if (NS_FAILED(rv)) goto exit; // this is going to be a mess...
// write map record buckets
rv = FlushBuckets(PR_FALSE); // don't bother swapping buckets back
if (NS_FAILED(rv)) goto exit;
// clear dirty bit
mHeader.mIsDirty = PR_FALSE;
rv = FlushHeader();
exit:
PRStatus err = PR_Close(mMapFD);
mMapFD = nsnull;
if (NS_FAILED(rv)) return rv;
return err == PR_SUCCESS ? NS_OK : NS_ERROR_UNEXPECTED;
}
nsresult
nsDiskCacheMap::FlushHeader()
{
if (!mMapFD) return NS_ERROR_NOT_AVAILABLE;
// seek to beginning of cache map
PRInt32 filePos = PR_Seek(mMapFD, 0, PR_SEEK_SET);
if (filePos != 0) return NS_ERROR_UNEXPECTED;
// write the header
mHeader.Swap();
PRInt32 bytesWritten = PR_Write(mMapFD, &mHeader, sizeof(nsDiskCacheHeader));
mHeader.Unswap();
if (sizeof(nsDiskCacheHeader) != bytesWritten) {
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
nsresult
nsDiskCacheMap::FlushBuckets(PRBool unswap)
{
if (!mMapFD) return NS_ERROR_NOT_AVAILABLE;
// seek to beginning of buckets
PRInt32 filePos = PR_Seek(mMapFD, sizeof(nsDiskCacheHeader), PR_SEEK_SET);
if (filePos != sizeof(nsDiskCacheHeader)) return NS_ERROR_UNEXPECTED;
// Swap each bucket
for (PRUint32 i = 0; i < kBucketsPerTable; ++i) {
mBuckets[i].Swap();
}
PRInt32 bytesWritten = PR_Write(mMapFD, &mBuckets, sizeof(nsDiskCacheBucket) * kBucketsPerTable);
if (unswap) {
// Unswap each bucket
for (PRUint32 i = 0; i < kBucketsPerTable; ++i) {
mBuckets[i].Unswap();
}
}
if ( sizeof(nsDiskCacheBucket) * kBucketsPerTable != bytesWritten) {
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
/**
* Record operations
*/
nsresult
nsDiskCacheMap::AddRecord( nsDiskCacheRecord * mapRecord,
nsDiskCacheRecord * oldRecord)
{
nsresult rv;
PRUint32 hashNumber = mapRecord->HashNumber();
nsDiskCacheBucket * bucket;
PRUint32 bucketIndex = GetBucketIndex(hashNumber);
int i;
oldRecord->SetHashNumber(0); // signify no record
rv = GetBucketForHashNumber(hashNumber, &bucket);
if (NS_FAILED(rv)) return rv;
nsDiskCacheRecord * mostEvictable = &bucket->mRecords[0];
for (i = 0; i < kRecordsPerBucket; ++i) {
if (bucket->mRecords[i].HashNumber() == 0) {
// stick the new record here
bucket->mRecords[i] = *mapRecord;
++mHeader.mEntryCount;
// update eviction rank in header if necessary
if (mHeader.mEvictionRank[bucketIndex] < mapRecord->EvictionRank())
mHeader.mEvictionRank[bucketIndex] = mapRecord->EvictionRank();
NS_ASSERTION(mHeader.mEvictionRank[bucketIndex] == bucket->EvictionRank(), "whao!");
return NS_OK;
}
if (bucket->mRecords[i].EvictionRank() > mostEvictable->EvictionRank())
mostEvictable = &bucket->mRecords[i];
}
*oldRecord = *mostEvictable; // i == kRecordsPerBucket, so evict the mostEvictable
*mostEvictable = *mapRecord; // replace it with the new record
// check if we need to update mostEvictable entry in header
if ((oldRecord->HashNumber() != 0) ||
(mapRecord->EvictionRank() > mHeader.mEvictionRank[bucketIndex])) {
mHeader.mEvictionRank[bucketIndex] = bucket->EvictionRank();
}
NS_ASSERTION(mHeader.mEvictionRank[bucketIndex] == bucket->EvictionRank(), "whao!");
return NS_OK;
}
nsresult
nsDiskCacheMap::UpdateRecord( nsDiskCacheRecord * mapRecord)
{
PRUint32 hashNumber = mapRecord->HashNumber();
nsDiskCacheBucket * bucket;
nsresult rv = GetBucketForHashNumber(hashNumber, &bucket);
if (NS_FAILED(rv)) return rv;
for (int i = 0; i < kRecordsPerBucket; ++i) {
if (bucket->mRecords[i].HashNumber() == mapRecord->HashNumber()) {
PRUint32 oldRank = bucket->mRecords[i].EvictionRank();
// stick the new record here
bucket->mRecords[i] = *mapRecord;
// update eviction rank in header if necessary
PRUint32 bucketIndex = GetBucketIndex(mapRecord->HashNumber());
if (mHeader.mEvictionRank[bucketIndex] < mapRecord->EvictionRank())
mHeader.mEvictionRank[bucketIndex] = mapRecord->EvictionRank();
else if (mHeader.mEvictionRank[bucketIndex] == oldRank)
mHeader.mEvictionRank[bucketIndex] = bucket->EvictionRank();
NS_ASSERTION(mHeader.mEvictionRank[bucketIndex] == bucket->EvictionRank(), "whao!");
return NS_OK;
}
}
return NS_ERROR_UNEXPECTED;
}
nsresult
nsDiskCacheMap::FindRecord( PRUint32 hashNumber, nsDiskCacheRecord * result)
{
nsDiskCacheBucket * bucket;
nsresult rv = GetBucketForHashNumber(hashNumber, &bucket);
if (NS_FAILED(rv)) return rv;
for (int i = 0; i < kRecordsPerBucket; ++i) {
if (bucket->mRecords[i].HashNumber() == 0) break;
if (bucket->mRecords[i].HashNumber() == hashNumber) {
*result = bucket->mRecords[i]; // copy the record
NS_ASSERTION(result->ValidRecord(), "bad cache map record");
return NS_OK;
}
}
return NS_ERROR_CACHE_KEY_NOT_FOUND;
}
nsresult
nsDiskCacheMap::DeleteRecord( nsDiskCacheRecord * mapRecord)
{
nsDiskCacheBucket * bucket;
nsresult rv = GetBucketForHashNumber(mapRecord->HashNumber(), &bucket);
if (NS_FAILED(rv)) return rv;
PRUint32 count = bucket->CountRecords();
for (PRUint32 i = 0; i < count; ++i) {
if (bucket->mRecords[i].HashNumber() == mapRecord->HashNumber()) {
// found it, now delete it.
PRUint32 evictionRank = bucket->mRecords[i].EvictionRank();
NS_ASSERTION(evictionRank == mapRecord->EvictionRank(), "evictionRank out of sync");
if (i != (count - 1)) { // if not the last record, shift last record into opening
bucket->mRecords[i] = bucket->mRecords[count - 1];
}
bucket->mRecords[count - 1].SetHashNumber(0); // clear last record
mHeader.mEntryCount--;
// update eviction rank
PRUint32 bucketIndex = GetBucketIndex(mapRecord->HashNumber());
if (mHeader.mEvictionRank[bucketIndex] <= evictionRank) {
mHeader.mEvictionRank[bucketIndex] = bucket->EvictionRank();
}
NS_ASSERTION(mHeader.mEvictionRank[bucketIndex] == bucket->EvictionRank(), "whao!");
return NS_OK;
}
}
return NS_ERROR_UNEXPECTED;
}
/**
* VisitRecords
*
* Visit every record in cache map in the most convenient order
*/
nsresult
nsDiskCacheMap::VisitRecords( nsDiskCacheRecordVisitor * visitor)
{
for (PRUint32 i = 0; i < kBucketsPerTable; ++i) {
// get bucket
PRUint32 recordsDeleted;
PRBool continueFlag = mBuckets[i].VisitEachRecord(visitor, 0, &recordsDeleted);
if (recordsDeleted) {
// recalc eviction rank
mHeader.mEvictionRank[i] = mBuckets[i].EvictionRank();
mHeader.mEntryCount -= recordsDeleted;
// XXX write bucket
}
NS_ASSERTION(mHeader.mEvictionRank[i] == mBuckets[i].EvictionRank(), "whao!");
if (!continueFlag) break;
}
return NS_OK;
}
/**
* EvictRecords
*
* Just like VisitRecords, but visits the records in order of their eviction rank
*/
nsresult
nsDiskCacheMap::EvictRecords( nsDiskCacheRecordVisitor * visitor)
{
while (1) {
// find bucket with highest eviction rank
PRUint32 rank = 0;
PRUint32 index = 0;
for (int i = 0; i < kBucketsPerTable; ++i) {
if (rank < mHeader.mEvictionRank[i]) {
rank = mHeader.mEvictionRank[i];
index = i;
}
}
NS_ASSERTION(mHeader.mEvictionRank[index] == mBuckets[index].EvictionRank(),
"header eviction rank out of sync");
// visit records in bucket with eviction ranks >= target eviction rank
PRUint32 recordsDeleted;
PRBool continueFlag = mBuckets[index].VisitEachRecord(visitor, rank, &recordsDeleted);
if (recordsDeleted) {
// recalc eviction rank
mHeader.mEvictionRank[index] = mBuckets[index].EvictionRank();
mHeader.mEntryCount -= recordsDeleted;
// XXX write bucket
}
if (!continueFlag) break;
// break if visitor returned stop
}
return NS_OK;
}
nsresult
nsDiskCacheMap::OpenBlockFiles()
{
// create nsILocalFile for block file
nsCOMPtr<nsILocalFile> blockFile;
nsresult rv;
for (int i = 0; i < 3; ++i) {
rv = GetBlockFileForIndex(i, getter_AddRefs(blockFile));
if (NS_FAILED(rv)) goto error_exit;
PRUint32 blockSize = GetBlockSizeForIndex(i);
rv = mBlockFile[i].Open(blockFile, blockSize);
if (NS_FAILED(rv)) goto error_exit;
}
return NS_OK;
error_exit:
(void)CloseBlockFiles(); // we already have an error to report
return rv;
}
nsresult
nsDiskCacheMap::CloseBlockFiles()
{
nsresult rv, rv2 = NS_OK;
for (int i=0; i < 3; ++i) {
rv = mBlockFile[i].Close();
if (NS_FAILED(rv)) rv2 = rv; // if one or more errors, report at least one
}
return rv2;
}
nsresult
nsDiskCacheMap::ReadDiskCacheEntry(nsDiskCacheRecord * record, nsDiskCacheEntry ** result)
{
nsresult rv;
nsDiskCacheEntry * diskEntry = nsnull;
PRUint32 metaFile = record->MetaFile();
PRFileDesc * fd = nsnull;
*result = nsnull;
if (metaFile == 0) { // entry/metadata stored in separate file
// open and read the file
nsCOMPtr<nsILocalFile> file;
rv = GetLocalFileForDiskCacheRecord(record, nsDiskCache::kMetaData, getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
PRFileDesc * fd = nsnull;
nsresult rv = file->OpenNSPRFileDesc(PR_RDONLY, 00666, &fd);
if (NS_FAILED(rv)) return rv;
PRInt32 fileSize = PR_Available(fd);
if (fileSize < 0) {
// XXX an error occurred. We could call PR_GetError(), but how would that help?
rv = NS_ERROR_UNEXPECTED;
goto exit;
}
diskEntry = (nsDiskCacheEntry *) new char[fileSize];
if (!diskEntry) {
rv = NS_ERROR_OUT_OF_MEMORY;
goto exit;
}
PRInt32 bytesRead = PR_Read(fd, diskEntry, fileSize);
if (bytesRead < fileSize) {
rv = NS_ERROR_UNEXPECTED;
goto exit;
}
} else if (metaFile < 4) { // XXX magic number: use constant
// entry/metadata stored in cache block file
// allocate buffer
PRUint32 blockSize = GetBlockSizeForIndex(metaFile - 1);
PRUint32 blockCount = record->MetaBlockCount();
diskEntry = (nsDiskCacheEntry *) new char[blockSize * blockCount];
// read diskEntry
rv = mBlockFile[metaFile - 1].ReadBlocks((char *)diskEntry,
record->MetaStartBlock(),
blockCount);
if (NS_FAILED(rv)) goto exit;
}
diskEntry->Unswap(); // disk to memory
// pass ownership to caller
*result = diskEntry;
diskEntry = nsnull;
exit:
// XXX auto ptr would be nice
if (fd) (void) PR_Close(fd);
delete diskEntry;
return rv;
}
nsresult
nsDiskCacheMap::WriteDiskCacheEntry(nsDiskCacheBinding * binding)
{
nsresult rv = NS_OK;
nsDiskCacheEntry * diskEntry = CreateDiskCacheEntry(binding);
if (!diskEntry) return NS_ERROR_UNEXPECTED;
binding->mRecord.SetEvictionRank(ULONG_MAX - SecondsFromPRTime(PR_Now()));
PRUint32 size = diskEntry->Size();
PRUint32 fileIndex;
PRUint32 blocks;
if (size < 1024) { // block size 256
fileIndex = 1;
blocks = size / 256 + 1;
} else if (size < 4096) { // block size 1024
fileIndex = 2;
blocks = size / 1024 + 1;
} else if (size < 16384) { // block size 4096
fileIndex = 3;
blocks = size / 4096 + 1;
} else { // separate file
fileIndex = 0;
}
PRUint32 metaFile = binding->mRecord.MetaFile();
// Deallocate old storage if necessary
if (binding->mRecord.MetaLocationInitialized()) {
// we have existing storage
if ((metaFile == 0) && (fileIndex == 0)) { // keeping the separate file
// just decrement total
// XXX if bindRecord.MetaFileSize == USHRT_MAX, stat the file to see how big it is
DecrementTotalSize(binding->mRecord.MetaFileSize() * 1024);
NS_ASSERTION(binding->mRecord.MetaFileGeneration() == binding->mGeneration,
"generations out of sync");
} else {
rv = DeleteStorage(&binding->mRecord, nsDiskCache::kMetaData);
if (NS_FAILED(rv)) return rv;
}
}
if (fileIndex == 0) {
// Write entry data to separate file
PRUint32 metaFileSizeK = ((size + 0x0399) >> 10); // round up to nearest 1k
nsCOMPtr<nsILocalFile> localFile;
// XXX handle metaFileSizeK > USHRT_MAX
binding->mRecord.SetMetaFileGeneration(binding->mGeneration);
binding->mRecord.SetMetaFileSize(metaFileSizeK);
rv = UpdateRecord(&binding->mRecord);
if (NS_FAILED(rv)) goto exit;
rv = GetLocalFileForDiskCacheRecord(&binding->mRecord,
nsDiskCache::kMetaData,
getter_AddRefs(localFile));
if (NS_FAILED(rv)) goto exit;
// open the file
PRFileDesc * fd;
rv = localFile->OpenNSPRFileDesc(PR_RDWR | PR_TRUNCATE | PR_CREATE_FILE, 00666, &fd);
if (NS_FAILED(rv)) goto exit; // unable to open or create file
// write the file
diskEntry->Swap();
PRInt32 bytesWritten = PR_Write(fd, diskEntry, size);
PRStatus err = PR_Close(mMapFD);
if ((bytesWritten != size) || (err != PR_SUCCESS)) {
rv = NS_ERROR_UNEXPECTED;
goto exit;
}
// XXX handle metaFileSizeK == USHRT_MAX
IncrementTotalSize(metaFileSizeK * 1024);
} else {
// write entry data to disk cache block file
PRInt32 startBlock = mBlockFile[fileIndex - 1].AllocateBlocks(blocks);
if (startBlock < 0) {
rv = NS_ERROR_UNEXPECTED;
goto exit;
}
// update binding and cache map record
binding->mRecord.SetMetaBlocks(fileIndex, startBlock, blocks);
rv = UpdateRecord(&binding->mRecord);
if (NS_FAILED(rv)) goto exit;
// XXX we should probably write out bucket ourselves
// write data
diskEntry->Swap();
rv = mBlockFile[fileIndex - 1].WriteBlocks(diskEntry, startBlock, blocks);
if (NS_FAILED(rv)) goto exit;
IncrementTotalSize(blocks * GetBlockSizeForIndex(fileIndex - 1));
}
exit:
return rv;
}
nsresult
nsDiskCacheMap::DoomRecord(nsDiskCacheRecord * record)
{
nsresult rv = DeleteRecord(record);
// XXX future: add record to doomed record journal
return rv;
}
nsresult
nsDiskCacheMap::DeleteStorage(nsDiskCacheRecord * record)
{
nsresult rv1 = DeleteStorage(record, nsDiskCache::kData);
nsresult rv2 = DeleteStorage(record, nsDiskCache::kMetaData);
return NS_FAILED(rv1) ? rv1 : rv2;
}
nsresult
nsDiskCacheMap::DeleteStorage(nsDiskCacheRecord * record, PRBool metaData)
{
nsresult rv;
PRUint32 fileIndex = metaData ? record->MetaFile() : record->DataFile();
nsCOMPtr<nsIFile> file;
if (fileIndex == 0) {
// delete the file
PRUint32 sizeK = metaData ? record->MetaFileSize() : record->DataFileSize();
// XXX if sizeK == USHRT_MAX, stat file for actual size
rv = GetFileForDiskCacheRecord(record, metaData, getter_AddRefs(file));
if (NS_SUCCEEDED(rv)) {
rv = file->Delete(PR_FALSE); // false == non-recursive
}
DecrementTotalSize(sizeK * 1024);
} else if (fileIndex < 4) {
// deallocate blocks
PRInt32 startBlock = metaData ? record->MetaStartBlock() : record->DataStartBlock();
PRInt32 blockCount = metaData ? record->MetaBlockCount() : record->DataBlockCount();
rv = mBlockFile[fileIndex - 1].DeallocateBlocks(startBlock, blockCount);
DecrementTotalSize(blockCount * GetBlockSizeForIndex(fileIndex - 1));
}
return rv;
}
nsresult
nsDiskCacheMap::DeleteRecordAndStorage(nsDiskCacheRecord * record)
{
nsresult rv1 = DeleteStorage(record);
nsresult rv2 = DeleteRecord(record);
return NS_FAILED(rv1) ? rv1 : rv2;
}
nsresult
nsDiskCacheMap::GetFileForDiskCacheRecord(nsDiskCacheRecord * record,
PRBool meta,
nsIFile ** result)
{
if (!mCacheDirectory) return NS_ERROR_NOT_AVAILABLE;
nsCOMPtr<nsIFile> file;
nsresult rv = mCacheDirectory->Clone(getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
PRInt16 generation = record->Generation();
char name[32];
::sprintf(name, "%08X%c%02X", record->HashNumber(), (meta ? 'm' : 'd'), generation);
rv = file->Append(name);
if (NS_FAILED(rv)) return rv;
NS_IF_ADDREF(*result = file);
return rv;
}
nsresult
nsDiskCacheMap::GetLocalFileForDiskCacheRecord(nsDiskCacheRecord * record,
PRBool meta,
nsILocalFile ** result)
{
nsCOMPtr<nsIFile> file;
nsresult rv = GetFileForDiskCacheRecord(record, meta, getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(file, &rv);
if (NS_FAILED(rv)) return rv;
NS_IF_ADDREF(*result = localFile);
return rv;
}
nsresult
nsDiskCacheMap::GetBlockFileForIndex(PRUint32 index, nsILocalFile ** result)
{
if (!mCacheDirectory) return NS_ERROR_NOT_AVAILABLE;
nsCOMPtr<nsIFile> file;
nsresult rv = mCacheDirectory->Clone(getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
char name[32];
::sprintf(name, "_CACHE_%03d_", index + 1);
rv = file->Append(name);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsILocalFile> localFile = do_QueryInterface(file, &rv);
NS_IF_ADDREF(*result = localFile);
return rv;
}
PRUint32
nsDiskCacheMap::GetBlockSizeForIndex(PRUint32 index)
{
return 256 << (2 * (index)); // XXX magic numbers
}

View File

@@ -0,0 +1,499 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsDiskCacheMap.h, released March 23, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick C. Beard <beard@netscape.com>
* Gordon Sheridan <gordon@netscape.com>
*/
#ifndef _nsDiskCacheMap_h_
#define _nsDiskCacheMap_h_
#include <limits.h>
#include "prtypes.h"
#include "prnetdb.h"
#include "nsDebug.h"
#include "nsError.h"
#include "nsILocalFile.h"
#include "nsDiskCache.h"
#include "nsDiskCacheBlockFile.h"
class nsDiskCacheBinding;
class nsDiskCacheEntry;
/******************************************************************************
* nsDiskCacheRecord
*
* Cache Location Format
*
* 1000 0000 0000 0000 0000 0000 0000 0000 : initialized bit
*
* 0011 0000 0000 0000 0000 0000 0000 0000 : File Selector (0 = separate file)
* 0000 0011 0000 0000 0000 0000 0000 0000 : number of extra contiguous blocks 1-4
* 0100 1100 0000 0000 0000 0000 0000 0000 : reserved bits
* 0000 0000 1111 1111 1111 1111 1111 1111 : block# 0-16777216 (2^24)
*
* 0000 0000 1111 1111 1111 1111 0000 0000 : eFileSizeMask (size of file in k: see note)
* 0000 0000 0000 0000 0000 0000 1111 1111 : eFileGenerationMask
*
* File Selector:
* 0 = separate file on disk
* 1 = 256 byte block file
* 2 = 1k block file
* 3 = 4k block file
*
* eFileSizeMask note: Files larger than 64 Mb have zero size stored in the
* location. The file itself must be examined to determine
* its actual size.
*
*****************************************************************************/
class nsDiskCacheRecord {
private:
PRUint32 mHashNumber;
PRUint32 mEvictionRank;
PRUint32 mDataLocation;
PRUint32 mMetaLocation;
enum {
eLocationInitializedMask = 0x80000000,
eLocationSelectorMask = 0x30000000,
eLocationSelectorOffset = 28,
eExtraBlocksMask = 0x03000000,
eExtraBlocksOffset = 24,
eReservedMask = 0x4C000000,
eBlockNumberMask = 0x00FFFFFF,
eFileSizeMask = 0x00FFFF00,
eFileSizeOffset = 8,
eFileGenerationMask = 0x000000FF,
eFileReservedMask = 0x4F000000
};
public:
nsDiskCacheRecord()
: mHashNumber(0), mEvictionRank(0), mDataLocation(0), mMetaLocation(0)
{
}
PRBool ValidRecord()
{
if ((mDataLocation & eReservedMask) || (mMetaLocation & eReservedMask))
return PR_FALSE;
return PR_TRUE;
}
// HashNumber accessors
PRUint32 HashNumber() const { return mHashNumber; }
void SetHashNumber( PRUint32 hashNumber) { mHashNumber = hashNumber; }
// EvictionRank accessors
PRUint32 EvictionRank() const { return mEvictionRank; }
void SetEvictionRank( PRUint32 rank) { mEvictionRank = rank; }
// DataLocation accessors
PRBool DataLocationInitialized() { return mDataLocation & eLocationInitializedMask; }
PRUint32 DataLocation() { return mDataLocation; }
void SetDataLocation( PRUint32 location) { mDataLocation = location; }
PRUint32 DataFile() const
{
return (PRUint32)(mDataLocation & eLocationSelectorMask) >> eLocationSelectorOffset;
}
void SetDataBlocks( PRUint32 index, PRUint32 startBlock, PRUint32 blockCount)
{
// clear everything
mDataLocation = 0;
// set file index
NS_ASSERTION( index < 4,"invalid location index");
NS_ASSERTION( index > 0,"invalid location index");
mDataLocation |= (index << eLocationSelectorOffset) & eLocationSelectorMask;
// set startBlock
NS_ASSERTION(startBlock == (startBlock & eBlockNumberMask), "invalid block number");
mDataLocation |= startBlock & eBlockNumberMask;
// set blockCount
NS_ASSERTION( (blockCount>=1) && (blockCount<=4),"invalid block count");
blockCount = --blockCount;
mDataLocation |= (blockCount << eExtraBlocksOffset) & eExtraBlocksMask;
mDataLocation |= eLocationInitializedMask;
}
PRUint32 DataBlockCount() const
{
return (PRUint32)((mDataLocation & eExtraBlocksMask) >> eExtraBlocksOffset) + 1;
}
PRUint32 DataStartBlock() const
{
return (mDataLocation & eBlockNumberMask);
}
PRUint32 DataFileSize() const { return (mDataLocation & eFileSizeMask) >> eFileSizeOffset; }
void SetDataFileSize(PRUint32 size)
{
NS_ASSERTION((mDataLocation & eFileReservedMask) == 0, "bad location");
mDataLocation &= ~eFileSizeMask; // clear eFileSizeMask
mDataLocation |= (size << eFileSizeOffset) & eFileSizeMask;
}
PRUint16 DataFileGeneration() const
{
return (mDataLocation & eFileGenerationMask);
}
void SetDataFileGeneration( PRUint8 generation)
{
// clear everything, (separate file index = 0)
mDataLocation = 0;
mDataLocation |= generation & eFileGenerationMask;
mDataLocation |= eLocationInitializedMask;
}
// MetaLocation accessors
PRBool MetaLocationInitialized() { return mMetaLocation & eLocationInitializedMask; }
PRUint32 MetaLocation() { return mMetaLocation; }
void SetMetaLocation( PRUint32 location) { mMetaLocation = location; }
PRUint32 MetaFile() const
{
return (PRUint32)(mMetaLocation & eLocationSelectorMask) >> eLocationSelectorOffset;
}
void SetMetaBlocks( PRUint32 index, PRUint32 startBlock, PRUint32 blockCount)
{
// clear everything
mMetaLocation = 0;
// set file index
NS_ASSERTION( index < 4, "invalid location index");
NS_ASSERTION( index > 0, "invalid location index");
mMetaLocation |= (index << eLocationSelectorOffset) & eLocationSelectorMask;
// set startBlock
NS_ASSERTION(startBlock == (startBlock & eBlockNumberMask), "invalid block number");
mMetaLocation |= startBlock & eBlockNumberMask;
// set blockCount
NS_ASSERTION( (blockCount>=1) && (blockCount<=4),"invalid block count");
blockCount = --blockCount;
mMetaLocation |= (blockCount << eExtraBlocksOffset) & eExtraBlocksMask;
mMetaLocation |= eLocationInitializedMask;
}
PRUint32 MetaBlockCount() const
{
return (PRUint32)((mMetaLocation & eExtraBlocksMask) >> eExtraBlocksOffset) + 1;
}
PRUint32 MetaStartBlock() const
{
return (mMetaLocation & eBlockNumberMask);
}
PRUint32 MetaFileSize() const { return (mMetaLocation & eFileSizeMask) >> eFileSizeOffset; }
void SetMetaFileSize(PRUint32 size)
{
mMetaLocation &= ~eFileSizeMask; // clear eFileSizeMask
mMetaLocation |= (size << eFileSizeOffset) & eFileSizeMask;
}
PRUint16 MetaFileGeneration() const
{
return (mMetaLocation & eFileGenerationMask);
}
void SetMetaFileGeneration( PRUint8 generation)
{
// clear everything, (separate file index = 0)
mMetaLocation = 0;
mMetaLocation |= generation & eFileGenerationMask;
mMetaLocation |= eLocationInitializedMask;
}
PRUint8 Generation() const
{
if ((mDataLocation & eLocationInitializedMask) &&
(DataFile() == 0))
return DataFileGeneration();
if ((mMetaLocation & eLocationInitializedMask) &&
(MetaFile() == 0))
return MetaFileGeneration();
return 0; // no generation
}
void Swap()
{
#if defined(IS_LITTLE_ENDIAN)
mHashNumber = ::PR_htonl(mHashNumber);
mEvictionRank = ::PR_htonl(mEvictionRank);
mDataLocation = ::PR_htonl(mDataLocation);
mMetaLocation = ::PR_htonl(mMetaLocation);
#endif
}
void Unswap()
{
#if defined(IS_LITTLE_ENDIAN)
mHashNumber = ::PR_ntohl(mHashNumber);
mEvictionRank = ::PR_ntohl(mEvictionRank);
mDataLocation = ::PR_ntohl(mDataLocation);
mMetaLocation = ::PR_ntohl(mMetaLocation);
#endif
}
};
/******************************************************************************
* nsDiskCacheRecordVisitor
*****************************************************************************/
enum { kDeleteRecordAndContinue = -1,
kStopVisitingRecords = 0,
kVisitNextRecord = 1
};
class nsDiskCacheRecordVisitor {
public:
virtual PRInt32 VisitRecord( nsDiskCacheRecord * mapRecord) = 0;
};
/******************************************************************************
* nsDiskCacheBucket
*****************************************************************************/
enum {
kRecordsPerBucket = 256,
kBucketsPerTable = (1 << 5) // must be a power of 2!
};
struct nsDiskCacheBucket {
nsDiskCacheRecord mRecords[kRecordsPerBucket];
void Swap();
void Unswap();
PRUint32 CountRecords();
PRUint32 EvictionRank(); // return largest rank in bucket
PRInt32 VisitEachRecord( nsDiskCacheRecordVisitor * visitor,
PRUint32 evictionRank,
PRUint32 * recordsDeleted);
};
/******************************************************************************
* nsDiskCacheHeader
*****************************************************************************/
struct nsDiskCacheHeader {
PRUint32 mVersion; // cache version.
PRInt32 mDataSize; // size of cache in bytes.
PRInt32 mEntryCount; // number of entries stored in cache.
PRUint32 mIsDirty; // dirty flag.
PRUint32 mEvictionRank[kBucketsPerTable];
// pad to blocksize
enum { kReservedBytes = sizeof(nsDiskCacheBucket)
- sizeof(PRUint32) * 4 // version, size, count, dirty
- sizeof(PRUint32) * kBucketsPerTable // eviction array
};
PRUint8 reserved[kReservedBytes];
// XXX need a bitmap?
nsDiskCacheHeader()
: mVersion(nsDiskCache::kCurrentVersion)
, mDataSize(0)
, mEntryCount(0)
, mIsDirty(PR_TRUE)
{}
void Swap()
{
#if defined(IS_LITTLE_ENDIAN)
mVersion = ::PR_htonl(mVersion);
mDataSize = ::PR_htonl(mDataSize);
mEntryCount = ::PR_htonl(mEntryCount);
mIsDirty = ::PR_htonl(mIsDirty);
#endif
}
void Unswap()
{
#if defined(IS_LITTLE_ENDIAN)
mVersion = ::PR_ntohl(mVersion);
mDataSize = ::PR_ntohl(mDataSize);
mEntryCount = ::PR_ntohl(mEntryCount);
mIsDirty = ::PR_ntohl(mIsDirty);
#endif
}
};
/******************************************************************************
* nsDiskCacheMap
*****************************************************************************/
// XXX fixed capacity for 8192 entries. Future: make dynamic
enum {
kCacheMapSize = sizeof(nsDiskCacheHeader) +
kBucketsPerTable * sizeof(nsDiskCacheBucket)
};
class nsDiskCacheMap {
public:
nsDiskCacheMap()
: mCacheDirectory(nsnull)
, mMapFD(nsnull)
{
NS_ASSERTION(sizeof(nsDiskCacheHeader) == sizeof(nsDiskCacheBucket), "structure misalignment");
}
~nsDiskCacheMap() { (void) Close(); }
/**
* File Operations
*
* Open
*
* Creates a new cache map file if one doesn't exist.
* Returns error if it detects change in format or cache wasn't closed.
*/
nsresult Open( nsILocalFile * cacheDirectory);
nsresult Close();
// nsresult Flush();
nsresult FlushHeader();
nsresult FlushBuckets( PRBool unswap);
/**
* Record operations
*/
nsresult AddRecord( nsDiskCacheRecord * mapRecord, nsDiskCacheRecord * oldRecord);
nsresult UpdateRecord( nsDiskCacheRecord * mapRecord);
nsresult FindRecord( PRUint32 hashNumber, nsDiskCacheRecord * mapRecord);
nsresult DeleteRecord( nsDiskCacheRecord * mapRecord);
nsresult VisitRecords( nsDiskCacheRecordVisitor * visitor);
nsresult EvictRecords( nsDiskCacheRecordVisitor * visitor);
/**
* Disk Entry operations
*/
nsresult DoomRecord( nsDiskCacheRecord * record);
nsresult DeleteStorage( nsDiskCacheRecord * record);
nsresult DeleteRecordAndStorage( nsDiskCacheRecord * record);
nsresult GetFileForDiskCacheRecord( nsDiskCacheRecord * record,
PRBool meta,
nsIFile ** result);
nsresult GetLocalFileForDiskCacheRecord( nsDiskCacheRecord * record,
PRBool meta,
nsILocalFile ** result);
nsresult ReadDiskCacheEntry( nsDiskCacheRecord * record,
nsDiskCacheEntry ** result);
nsresult WriteDiskCacheEntry( nsDiskCacheBinding * binding);
/**
* Statistical Operations
*/
void IncrementTotalSize( PRInt32 delta)
{
NS_ASSERTION(mHeader.mDataSize >= 0, "disk cache size negative?");
mHeader.mDataSize += delta;
mHeader.mIsDirty = PR_TRUE;
}
void DecrementTotalSize( PRInt32 delta)
{
mHeader.mDataSize -= delta;
mHeader.mIsDirty = PR_TRUE;
NS_ASSERTION(mHeader.mDataSize >= 0, "disk cache size negative?");
}
PRInt32 TotalSize() { return mHeader.mDataSize; }
PRInt32 EntryCount() { return mHeader.mEntryCount; }
private:
/**
* Private methods
*/
nsresult OpenBlockFiles();
nsresult CloseBlockFiles();
nsresult GetBlockFileForIndex( PRUint32 index, nsILocalFile ** result);
PRUint32 GetBlockSizeForIndex( PRUint32 index);
nsresult DeleteStorage( nsDiskCacheRecord * record, PRBool metaData);
nsresult GetBucketForHashNumber( PRUint32 hashNumber, nsDiskCacheBucket ** result)
{
*result = &mBuckets[GetBucketIndex(hashNumber)];
return NS_OK;
}
PRUint32 GetBucketIndex( PRUint32 hashNumber)
{
return (hashNumber & (kBucketsPerTable - 1));
}
/**
* data members
*/
private:
nsCOMPtr<nsILocalFile> mCacheDirectory;
PRFileDesc * mMapFD;
nsDiskCacheBlockFile mBlockFile[3];
nsDiskCacheHeader mHeader;
nsDiskCacheBucket mBuckets[kBucketsPerTable];
};
#endif // _nsDiskCacheMap_h_

View File

@@ -0,0 +1,496 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsMemoryCacheDevice.cpp, released February 22, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
*/
#include "nsMemoryCacheDevice.h"
#include "nsCacheService.h"
#include "nsICacheService.h"
#include "nsIComponentManager.h"
#include "nsNetCID.h"
#include "nsIObserverService.h"
#include "nsIPref.h"
#include "nsICacheVisitor.h"
#include "nsITransport.h"
#include "signal.h"
static NS_DEFINE_CID(kStorageTransportCID, NS_STORAGETRANSPORT_CID);
const char *gMemoryDeviceID = "memory";
const char *gMemoryCacheSizePref = "browser.cache.memory_cache_size";
nsMemoryCacheDevice::nsMemoryCacheDevice()
: mEvictionThreshold(40 * 1024),
mHardLimit(0),
mSoftLimit(0),
mTotalSize(0),
mInactiveSize(0),
mEntryCount(0),
mMaxEntryCount(0)
{
PR_INIT_CLIST(&mEvictionList[mostLikelyToEvict]);
PR_INIT_CLIST(&mEvictionList[leastLikelyToEvict]);
}
nsMemoryCacheDevice::~nsMemoryCacheDevice()
{
#if DEBUG
printf("### starting ~nsMemoryCacheDevice()\n");
#endif
nsresult rv;
NS_WITH_SERVICE(nsIPref, prefs, NS_PREF_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
prefs->UnregisterCallback(gMemoryCacheSizePref, MemoryCacheSizeChanged, this);
}
Shutdown();
}
int PR_CALLBACK
nsMemoryCacheDevice::MemoryCacheSizeChanged(const char * pref, void * closure)
{
nsresult rv;
PRUint32 softLimit = 0;
nsMemoryCacheDevice * device = (nsMemoryCacheDevice *)closure;
NS_WITH_SERVICE(nsIPref, prefs, NS_PREF_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
rv = prefs->GetIntPref(gMemoryCacheSizePref, (PRInt32 *)&softLimit);
if (NS_FAILED(rv)) return rv;
softLimit *= 1024; // convert k into bytes
PRUint32 hardLimit = softLimit + 1024*1024*2; // XXX find better limit than +2Meg
device->AdjustMemoryLimits(softLimit, hardLimit);
return 0; // XXX what are we supposed to return?
}
nsresult
nsMemoryCacheDevice::Init()
{
nsresult rv;
rv = mMemCacheEntries.Init();
// set some default memory limits, in case prefs aren't available
mSoftLimit = 1024 * 1024 * 3;
mHardLimit = mSoftLimit + 1024 *1024 * 2;
// read user prefs for memory cache limits
NS_WITH_SERVICE(nsIPref, prefs, NS_PREF_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = prefs->RegisterCallback(gMemoryCacheSizePref, MemoryCacheSizeChanged, this);
if (NS_FAILED(rv)) return rv;
// Initialize the pref
MemoryCacheSizeChanged(gMemoryCacheSizePref, this);
}
// Register as a memory pressure observer
NS_WITH_SERVICE(nsIObserverService,
observerService,
NS_OBSERVERSERVICE_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv)) {
// XXX rv = observerServcie->AddObserver(this, NS_MEMORY_PRESSURE_TOPIC);
}
// Ignore failure of memory pressure registration
return rv;
}
nsresult
nsMemoryCacheDevice::Shutdown()
{
mMemCacheEntries.Shutdown();
// evict all entries
nsCacheEntry * entry, * next;
for (int i=mostLikelyToEvict; i <= leastLikelyToEvict; ++i) {
entry = (nsCacheEntry *)PR_LIST_HEAD(&mEvictionList[i]);
while (entry != &mEvictionList[i]) {
NS_ASSERTION(entry->IsInUse() == PR_FALSE, "### shutting down with active entries.\n");
next = (nsCacheEntry *)PR_NEXT_LINK(entry);
PR_REMOVE_AND_INIT_LINK(entry);
// update statistics
PRUint32 memoryRecovered = entry->Size();
mTotalSize -= memoryRecovered;
mInactiveSize -= memoryRecovered;
--mEntryCount;
delete entry;
entry = next;
}
}
/*
* we're not factoring in changes to meta data yet...
* NS_ASSERTION(mTotalSize == 0, "### mem cache leaking entries?\n");
*/
NS_ASSERTION(mInactiveSize == 0, "### mem cache leaking entries?\n");
NS_ASSERTION(mEntryCount == 0, "### mem cache leaking entries?\n");
return NS_OK;
}
const char *
nsMemoryCacheDevice::GetDeviceID()
{
return gMemoryDeviceID;
}
nsCacheEntry *
nsMemoryCacheDevice::FindEntry(nsCString * key)
{
nsCacheEntry * entry = mMemCacheEntries.GetEntry(key);
if (!entry) return nsnull;
// move entry to the tail of an eviction list
PR_REMOVE_AND_INIT_LINK(entry);
PR_APPEND_LINK(entry, &mEvictionList[EvictionList(entry, 0)]);
mInactiveSize -= entry->Size();
return entry;
}
nsresult
nsMemoryCacheDevice::DeactivateEntry(nsCacheEntry * entry)
{
if (entry->IsDoomed()) {
#if debug
// XXX verify we've removed it from mMemCacheEntries & eviction list
#endif
// update statistics
mTotalSize -= entry->Size();
--mEntryCount;
delete entry;
return NS_OK;
}
nsCacheEntry * ourEntry = mMemCacheEntries.GetEntry(entry->Key());
NS_ASSERTION(ourEntry, "DeactivateEntry called for an entry we don't have!");
NS_ASSERTION(entry == ourEntry, "entry doesn't match ourEntry");
if (ourEntry != entry)
return NS_ERROR_INVALID_POINTER;
mInactiveSize += entry->Size();
EvictEntriesIfNecessary();
return NS_OK;
}
nsresult
nsMemoryCacheDevice::BindEntry(nsCacheEntry * entry)
{
NS_ASSERTION(PR_CLIST_IS_EMPTY(entry),"entry is already on a list!");
if (!entry->IsDoomed()) {
// append entry to the eviction list
PR_APPEND_LINK(entry, &mEvictionList[EvictionList(entry, 0)]);
// add entry to hashtable of mem cache entries
nsresult rv = mMemCacheEntries.AddEntry(entry);
if (NS_FAILED(rv)) {
PR_REMOVE_AND_INIT_LINK(entry);
return rv;
}
}
// add size of entry to memory totals
++mEntryCount;
if (mMaxEntryCount < mEntryCount) mMaxEntryCount = mEntryCount;
mTotalSize += entry->Size();
EvictEntriesIfNecessary();
return NS_OK;
}
void
nsMemoryCacheDevice::DoomEntry(nsCacheEntry * entry)
{
// XXX debug code to verify we have entry
mMemCacheEntries.RemoveEntry(entry);
// remove entry from our eviction list
PR_REMOVE_AND_INIT_LINK(entry);
}
nsresult
nsMemoryCacheDevice::GetTransportForEntry( nsCacheEntry * entry,
nsCacheAccessMode mode,
nsITransport ** transport )
{
NS_ENSURE_ARG_POINTER(entry);
NS_ENSURE_ARG_POINTER(transport);
nsCOMPtr<nsISupports> data;
nsresult rv = entry->GetData(getter_AddRefs(data));
if (NS_FAILED(rv))
return rv;
if (data)
return CallQueryInterface(data, transport);
else {
// create a new transport for this entry
rv = nsComponentManager::CreateInstance(kStorageTransportCID,
nsnull,
NS_GET_IID(nsITransport),
(void **) transport);
if (NS_FAILED(rv)) return rv;
entry->SetData(*transport);
return NS_OK;
}
}
nsresult
nsMemoryCacheDevice::GetFileForEntry( nsCacheEntry * entry,
nsIFile ** result )
{
return NS_ERROR_NOT_IMPLEMENTED;
}
nsresult
nsMemoryCacheDevice::OnDataSizeChange( nsCacheEntry * entry, PRInt32 deltaSize)
{
if (entry->IsStreamData()) {
// we have the right to refuse or pre-evict
}
// adjust our totals
mTotalSize += deltaSize;
if (!entry->IsDoomed()) {
// move entry to the tail of the appropriate eviction list
PR_REMOVE_AND_INIT_LINK(entry);
PR_APPEND_LINK(entry, &mEvictionList[EvictionList(entry, deltaSize)]);
}
EvictEntriesIfNecessary();
return NS_OK;
}
void
nsMemoryCacheDevice::AdjustMemoryLimits(PRUint32 softLimit, PRUint32 hardLimit)
{
mSoftLimit = softLimit;
mHardLimit = hardLimit;
EvictEntriesIfNecessary();
}
void
nsMemoryCacheDevice::EvictEntry(nsCacheEntry * entry)
{
// remove entry from our hashtable
mMemCacheEntries.RemoveEntry(entry);
// remove entry from the eviction list
PR_REMOVE_AND_INIT_LINK(entry);
// update statistics
PRUint32 memoryRecovered = entry->Size();
mTotalSize -= memoryRecovered;
mInactiveSize -= memoryRecovered;
--mEntryCount;
delete entry;
}
void
nsMemoryCacheDevice::EvictEntriesIfNecessary(void)
{
nsCacheEntry * entry, * next;
if ((mTotalSize < mHardLimit) && (mInactiveSize < mSoftLimit))
return;
for (int i=mostLikelyToEvict; i<=leastLikelyToEvict; ++i) {
entry = (nsCacheEntry *)PR_LIST_HEAD(&mEvictionList[i]);
while (entry != &mEvictionList[i]) {
if (entry->IsInUse()) {
entry = (nsCacheEntry *)PR_NEXT_LINK(entry);
continue;
}
next = (nsCacheEntry *)PR_NEXT_LINK(entry);
EvictEntry(entry);
entry = next;
if ((mTotalSize < mHardLimit) && (mInactiveSize < mSoftLimit))
return;
}
}
}
int
nsMemoryCacheDevice::EvictionList(nsCacheEntry * entry, PRUint32 deltaSize)
{
PRUint32 size = entry->Size() + deltaSize;
if ((size > mEvictionThreshold) || (entry->ExpirationTime() != 0))
return mostLikelyToEvict;
return leastLikelyToEvict;
}
nsresult
nsMemoryCacheDevice::Visit(nsICacheVisitor * visitor)
{
nsMemoryCacheDeviceInfo * deviceInfo = new nsMemoryCacheDeviceInfo(this);
nsCOMPtr<nsICacheDeviceInfo> deviceRef(deviceInfo);
if (!deviceInfo) return NS_ERROR_OUT_OF_MEMORY;
PRBool keepGoing;
nsresult rv = visitor->VisitDevice(gMemoryDeviceID, deviceInfo, &keepGoing);
if (NS_FAILED(rv)) return rv;
if (!keepGoing)
return NS_OK;
nsCacheEntry * entry;
nsCOMPtr<nsICacheEntryInfo> entryRef;
for (int i=mostLikelyToEvict; i <= leastLikelyToEvict; ++i) {
entry = (nsCacheEntry *)PR_LIST_HEAD(&mEvictionList[i]);
while (entry != &mEvictionList[i]) {
nsCacheEntryInfo * entryInfo = new nsCacheEntryInfo(entry);
if (!entryInfo) return NS_ERROR_OUT_OF_MEMORY;
entryRef = entryInfo;
rv = visitor->VisitEntry(gMemoryDeviceID, entryInfo, &keepGoing);
entryInfo->DetachEntry();
if (NS_FAILED(rv)) return rv;
if (!keepGoing) break;
entry = (nsCacheEntry *)PR_NEXT_LINK(entry);
}
}
return NS_OK;
}
nsresult
nsMemoryCacheDevice::EvictEntries(const char * clientID)
{
nsCacheEntry * entry;
PRUint32 prefixLength = (clientID ? nsCRT::strlen(clientID) : 0);
for (int i=mostLikelyToEvict; i<=leastLikelyToEvict; ++i) {
PRCList * elem = PR_LIST_HEAD(&mEvictionList[i]);
while (elem != &mEvictionList[i]) {
entry = (nsCacheEntry *)elem;
elem = PR_NEXT_LINK(elem);
const char * key = entry->Key()->get();
if (clientID && nsCRT::strncmp(clientID, key, prefixLength) != 0)
continue;
if (entry->IsInUse()) {
nsresult rv = nsCacheService::GlobalInstance()->DoomEntry_Locked(entry);
if (NS_FAILED(rv)) return rv;
} else {
EvictEntry(entry);
}
}
}
return NS_OK;
}
/******************************************************************************
* nsMemoryCacheDeviceInfo - for implementing about:cache
*****************************************************************************/
NS_IMPL_ISUPPORTS1(nsMemoryCacheDeviceInfo, nsICacheDeviceInfo);
NS_IMETHODIMP
nsMemoryCacheDeviceInfo::GetDescription(char ** result)
{
NS_ENSURE_ARG_POINTER(result);
*result = nsCRT::strdup("Memory cache device");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsMemoryCacheDeviceInfo::GetUsageReport(char ** result)
{
NS_ENSURE_ARG_POINTER(result);
*result = nsCRT::strdup("Memory cache usage report:");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsMemoryCacheDeviceInfo::GetEntryCount(PRUint32 * result)
{
NS_ENSURE_ARG_POINTER(result);
// XXX compare calculated count vs. mEntryCount
*result = mDevice->mEntryCount;
return NS_OK;
}
NS_IMETHODIMP
nsMemoryCacheDeviceInfo::GetTotalSize(PRUint32 * result)
{
NS_ENSURE_ARG_POINTER(result);
*result = mDevice->mTotalSize;
return NS_OK;
}
NS_IMETHODIMP
nsMemoryCacheDeviceInfo::GetMaximumSize(PRUint32 * result)
{
NS_ENSURE_ARG_POINTER(result);
*result = mDevice->mHardLimit;
return NS_OK;
}

View File

@@ -0,0 +1,119 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Mozilla 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/MPL/
*
* 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 nsMemoryCacheDevice.h, released February 20, 2001.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Gordon Sheridan, 20-February-2001
*/
#ifndef _nsMemoryCacheDevice_h_
#define _nsMemoryCacheDevice_h_
#include "nsCacheDevice.h"
#include "pldhash.h"
#include "nsCacheEntry.h"
class nsMemoryCacheDeviceInfo;
/******************************************************************************
* nsMemoryCacheDevice
******************************************************************************/
class nsMemoryCacheDevice : public nsCacheDevice
{
public:
nsMemoryCacheDevice();
virtual ~nsMemoryCacheDevice();
virtual nsresult Init();
virtual nsresult Shutdown();
virtual const char * GetDeviceID(void);
virtual nsresult BindEntry( nsCacheEntry * entry );
virtual nsCacheEntry * FindEntry( nsCString * key );
virtual void DoomEntry( nsCacheEntry * entry );
virtual nsresult DeactivateEntry( nsCacheEntry * entry );
virtual nsresult GetTransportForEntry( nsCacheEntry * entry,
nsCacheAccessMode mode,
nsITransport **transport );
virtual nsresult GetFileForEntry( nsCacheEntry * entry,
nsIFile ** result );
virtual nsresult OnDataSizeChange( nsCacheEntry * entry, PRInt32 deltaSize );
virtual nsresult Visit( nsICacheVisitor * visitor );
virtual nsresult EvictEntries(const char * clientID);
static int PR_CALLBACK MemoryCacheSizeChanged(const char * pref, void * closure);
private:
friend class nsMemoryCacheDeviceInfo;
void AdjustMemoryLimits( PRUint32 softLimit, PRUint32 hardLimit);
void EvictEntry( nsCacheEntry * entry );
void EvictEntriesIfNecessary();
int EvictionList(nsCacheEntry * entry, PRUint32 deltaSize);
/*
* Data members
*/
nsCacheEntryHashTable mMemCacheEntries;
enum { mostLikelyToEvict = 0, leastLikelyToEvict = 1 }; // constants to differentiate eviction lists
PRCList mEvictionList[2];
PRUint32 mEvictionThreshold;
PRUint32 mHardLimit;
PRUint32 mSoftLimit;
PRUint32 mTotalSize;
PRUint32 mInactiveSize;
PRUint32 mEntryCount;
PRUint32 mMaxEntryCount;
// XXX what other stats do we want to keep?
};
/******************************************************************************
* nsMemoryCacheDeviceInfo - used to call nsIVisitor for about:cache
******************************************************************************/
class nsMemoryCacheDeviceInfo : public nsICacheDeviceInfo {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICACHEDEVICEINFO
nsMemoryCacheDeviceInfo(nsMemoryCacheDevice* device)
: mDevice(device)
{
NS_INIT_ISUPPORTS();
}
virtual ~nsMemoryCacheDeviceInfo() {}
private:
nsMemoryCacheDevice* mDevice;
};
#endif // _nsMemoryCacheDevice_h_

231
mozilla/netwerk/cache/src/win32.order vendored Normal file
View File

@@ -0,0 +1,231 @@
?AddRef@nsCacheEntryDescriptor@@UAGKXZ ; 35743
?HashKey@nsCacheEntryHashTable@@CAIPAUPLDHashTable@@PBX@Z ; 29743
?Release@nsCacheEntryDescriptor@@UAGKXZ ; 21199
??_EnsCString@@UAEPAXI@Z ; 19905
?AddRef@nsCacheSession@@UAGKXZ ; 17435
?GetEntry@nsCacheEntryHashTable@@QAEPAVnsCacheEntry@@PBVnsCString@@@Z ; 17433
?SecondsFromPRTime@@YAI_J@Z ; 14263
?CalculateSize@nsCacheMetaData@@CA?AW4PLDHashOperator@@PAUPLDHashTable@@PAUPLDHashEntryHdr@@IPAX@Z ; 14243
?Release@nsCacheEntryInfo@@UAGKXZ ; 10964
?GetLastModified@nsDiskCacheEntryInfo@@UAGIPAI@Z ; 9800
?Release@nsANSIOutputStream@@UAGKXZ ; 9758
?MatchEntry@nsCacheEntryHashTable@@CAHPAUPLDHashTable@@PBUPLDHashEntryHdr@@PBX@Z ; 9663
?QueryInterface@nsCacheEntryInfo@@UAGIABUnsID@@PAPAX@Z ; 8638
??Rdo_QueryElementAt@@UBEIABUnsID@@PAPAX@Z ; 8638
?assign_assuming_AddRef@nsCOMPtr_base@@IAEXPAVnsISupports@@@Z ; 8259
??0nsDiskCacheRecord@@QAE@XZ ; 8192
?EnsureEntryHasDevice@nsCacheService@@AAEPAVnsCacheDevice@@PAVnsCacheEntry@@@Z ; 7918
?MoveEntry@nsCacheEntryHashTable@@CAXPAUPLDHashTable@@PBUPLDHashEntryHdr@@PAU3@@Z ; 7653
?GetKey@nsCacheEntryHashTable@@CAPBXPAUPLDHashTable@@PAUPLDHashEntryHdr@@@Z ; 7653
?Close@nsANSIOutputStream@@UAGIXZ ; 7092
?Write@nsANSIOutputStream@@UAGIPBDIPAI@Z ; 7067
?AccumulateElements@nsCacheMetaData@@CA?AW4PLDHashOperator@@PAUPLDHashTable@@PAUPLDHashEntryHdr@@IPAX@Z ; 7063
?Release@nsDiskCacheDeviceInfo@@UAGKXZ ; 6471
?CreateRequest@nsCacheService@@AAEIPAVnsCacheSession@@PBDHPAVnsICacheListener@@PAPAVnsCacheRequest@@@Z ; 6468
?ActivateEntry@nsCacheService@@AAEIPAVnsCacheRequest@@PAPAVnsCacheEntry@@@Z ; 6468
?ProcessRequest@nsCacheService@@AAEIPAVnsCacheRequest@@PAPAVnsICacheEntryDescriptor@@@Z ; 6468
??1nsCacheRequest@@AAE@XZ ; 6468
?OpenCacheEntry@nsCacheService@@QAEIPAVnsCacheSession@@PBDHPAVnsICacheListener@@PAPAVnsICacheEntryDescriptor@@@Z ; 6468
??0nsCacheRequest@@AAE@PAVnsCString@@PAVnsICacheListener@@HPAVnsCacheSession@@@Z ; 6468
?Hash@nsDiskCacheEntry@@SAIPBD@Z ; 6166
?HashKey@nsDiskCacheEntryHashTable@@CAIPAUPLDHashTable@@PBX@Z ; 6037
?EvictEntriesIfNecessary@nsMemoryCacheDevice@@AAEXXZ ; 5780
?TouchData@nsCacheEntry@@QAEXXZ ; 5503
?OpenCacheEntry@nsCacheSession@@UAGIPBDHPAPAVnsICacheEntryDescriptor@@@Z ; 5165
?RequestAccess@nsCacheEntry@@QAEIPAVnsCacheRequest@@PAH@Z ; 5099
?Fetched@nsCacheEntry@@QAEXXZ ; 5094
??0nsTransportWrapper@nsCacheEntryDescriptor@@QAE@XZ ; 5092
?CreateDescriptor@nsCacheEntry@@QAEIPAVnsCacheRequest@@HPAPAVnsICacheEntryDescriptor@@@Z ; 5092
??0nsCacheEntryDescriptor@@QAE@PAVnsCacheEntry@@H@Z ; 5092
?RemoveDescriptor@nsCacheEntry@@QAEHPAVnsCacheEntryDescriptor@@@Z ; 5090
?CloseDescriptor@nsCacheService@@QAEXPAVnsCacheEntryDescriptor@@@Z ; 5090
?Close@nsCacheEntryDescriptor@@UAGIXZ ; 5090
??_GnsCacheEntryDescriptor@@UAEPAXI@Z ; 5090
??1nsCacheEntryDescriptor@@UAE@XZ ; 5090
?SearchCacheDevices@nsCacheService@@AAEPAVnsCacheEntry@@PAVnsCString@@H@Z ; 4993
?AddEntry@nsCacheEntryHashTable@@QAEIPAVnsCacheEntry@@@Z ; 4993
?FindEntry@nsMemoryCacheDevice@@UAEPAVnsCacheEntry@@PAVnsCString@@@Z ; 4993
?ClearEntry@nsCacheEntryHashTable@@CAXPAUPLDHashTable@@PAUPLDHashEntryHdr@@@Z ; 4993
?RemoveEntry@nsCacheEntryHashTable@@QAEXPAVnsCacheEntry@@@Z ; 4921
?GetData@nsCacheEntry@@QAEIPAPAVnsISupports@@@Z ; 4811
?Release@nsDiskCacheEntry@@UAGKXZ ; 4784
?RequestDataSizeChange@nsCacheEntryDescriptor@@QAEIH@Z ; 4127
?OnDataSizeChange@nsCacheService@@QAEIPAVnsCacheEntry@@H@Z ; 4127
?SetElement@nsCacheMetaData@@QAEIABVnsACString@@0@Z ; 3682
?ClearEntry@nsCacheMetaData@@CAXPAUPLDHashTable@@PAUPLDHashEntryHdr@@@Z ; 3681
?FreeElements@nsCacheMetaData@@CA?AW4PLDHashOperator@@PAUPLDHashTable@@PAUPLDHashEntryHdr@@IPAX@Z ; 3681
?GetEntry@nsDiskCacheEntryHashTable@@QAEPAVnsDiskCacheEntry@@PBD@Z ; 3651
?GetRecord@nsDiskCacheMap@@QAEPAVnsDiskCacheRecord@@I@Z ; 3650
?Size@nsCacheMetaData@@QAEIXZ ; 3628
?DeactivateEntry@nsCacheService@@AAEXPAVnsCacheEntry@@@Z ; 3619
?TouchMetaData@nsCacheEntry@@QAEXXZ ; 3601
?SetMetaDataElement@nsCacheEntryDescriptor@@UAGIPBD0@Z ; 3601
?SetMetaDataElement@nsCacheEntry@@QAEIABVnsACString@@0@Z ; 3601
?getFileForHashNumber@nsDiskCacheDevice@@QAEIIHIPAPAVnsIFile@@@Z ; 3587
?Read@nsANSIInputStream@@UAGIPADIPAI@Z ; 3570
?getFileForDiskCacheEntry@nsDiskCacheDevice@@QAEIPAVnsDiskCacheEntry@@HPAPAVnsIFile@@@Z ; 3560
?Unswap@MetaDataHeader@@QAEXXZ ; 3545
??1MetaDataFile@@QAE@XZ ; 3545
?OnDataSizeChange@nsDiskCacheDevice@@UAEIPAVnsCacheEntry@@H@Z ; 3210
?ProcessPendingRequests@nsCacheService@@AAEIPAVnsCacheEntry@@@Z ; 2800
??0nsCacheEntry@@QAE@PAVnsCString@@HH@Z ; 2673
??1nsCacheEntry@@QAE@XZ ; 2673
?MarkValid@nsCacheEntryDescriptor@@UAGIXZ ; 2592
?ValidateEntry@nsCacheService@@QAEIPAVnsCacheEntry@@@Z ; 2592
?GetCacheElement@nsCacheEntryDescriptor@@UAGIPAPAVnsISupports@@@Z ; 2413
?MatchEntry@nsDiskCacheEntryHashTable@@CAHPAUPLDHashTable@@PBUPLDHashEntryHdr@@PBX@Z ; 2383
?Release@nsANSIInputStream@@UAGKXZ ; 2380
?AddRef@nsANSIInputStream@@UAGKXZ ; 2380
?MatchEntry@nsCacheMetaData@@CAHPAUPLDHashTable@@PBUPLDHashEntryHdr@@PBX@Z ; 2365
?GetMetaDataElement@nsCacheEntry@@QAEIABVnsACString@@PAPBV2@@Z ; 2365
?GetElement@nsCacheMetaData@@QAEPBVnsACString@@PBV2@@Z ; 2365
?GetMetaDataElement@nsCacheEntryDescriptor@@UAGIPBDPAPAD@Z ; 2365
?openOutputStream@nsDiskCacheDevice@@SAIPAVnsIFile@@PAPAVnsIOutputStream@@@Z ; 2356
?updateDiskCacheEntry@nsDiskCacheDevice@@QAEIPAVnsDiskCacheEntry@@@Z ; 2356
??0nsANSIOutputStream@@QAE@PAU_iobuf@@@Z ; 2356
??_EnsANSIOutputStream@@UAEPAXI@Z ; 2356
??1nsANSIOutputStream@@UAE@XZ ; 2356
?Swap@MetaDataHeader@@QAEXXZ ; 2355
?FlattenMetaData@nsCacheMetaData@@QAEIPAPADPAI@Z ; 2355
?Init@MetaDataFile@@QAEIPAVnsCacheEntry@@@Z ; 2355
?updateCacheMap@nsDiskCacheDevice@@QAEIPAVnsDiskCacheEntry@@@Z ; 2355
??0MetaDataHeader@@QAE@PAVnsCacheEntry@@@Z ; 2355
?Write@MetaDataFile@@QAEIPAVnsIOutputStream@@@Z ; 2355
?FlattenMetaData@nsCacheEntry@@QAEIPAPADPAI@Z ; 2355
?DeactivateEntry@nsMemoryCacheDevice@@UAEIPAVnsCacheEntry@@@Z ; 2322
?SetExpirationTime@nsCacheEntryDescriptor@@UAGII@Z ; 2259
?QueryInterface@nsCacheEntryDescriptor@@UAGIABUnsID@@PAPAX@Z ; 2186
?GetDataSize@nsCacheEntryDescriptor@@UAGIPAI@Z ; 2107
?OnDataSizeChange@nsMemoryCacheDevice@@UAEIPAVnsCacheEntry@@H@Z ; 2082
?SetDataSize@nsCacheEntryDescriptor@@UAGII@Z ; 2082
?Write@nsOutputStreamWrapper@nsCacheEntryDescriptor@@UAGIPBDIPAI@Z ; 2045
?OnWrite@nsOutputStreamWrapper@nsCacheEntryDescriptor@@AAEII@Z ; 2045
?GetNonBlocking@nsOutputStreamWrapper@nsCacheEntryDescriptor@@UAGIPAH@Z ; 1550
?SetCacheElement@nsCacheEntryDescriptor@@UAGIPAVnsISupports@@@Z ; 1376
?BindEntry@nsMemoryCacheDevice@@UAEIPAVnsCacheEntry@@@Z ; 1376
?AsyncOpenCacheEntry@nsCacheSession@@UAGIPBDHPAVnsICacheListener@@@Z ; 1303
?NotifyListener@nsCacheService@@AAEIPAVnsCacheRequest@@PAVnsICacheEntryDescriptor@@HI@Z ; 1303
??0nsCacheMetaData@@QAE@XZ ; 1298
??1nsCacheMetaData@@QAE@XZ ; 1298
?FindEntry@nsDiskCacheDevice@@UAEPAVnsCacheEntry@@PAVnsCString@@@Z ; 1295
?Init@nsCacheMetaData@@QAEIXZ ; 1295
?Finalize@nsCacheMetaData@@CAXPAUPLDHashTable@@@Z ; 1295
?Create@nsCacheMetaData@@SAPAV1@XZ ; 1295
?getTransportForFile@nsDiskCacheDevice@@SAIPAVnsIFile@@HPAPAVnsITransport@@@Z ; 1199
?GetTransportForEntry@nsDiskCacheDevice@@UAEIPAVnsCacheEntry@@HPAPAVnsITransport@@@Z ; 1198
?AddRef@nsTransportWrapper@nsCacheEntryDescriptor@@UAGKXZ ; 1198
?EnsureTransportWithAccess@nsTransportWrapper@nsCacheEntryDescriptor@@QAEIH@Z ; 1198
?GetTransport@nsCacheEntryDescriptor@@UAGIPAPAVnsITransport@@@Z ; 1198
?GetTransportForEntry@nsCacheService@@QAEIPAVnsCacheEntry@@HPAPAVnsITransport@@@Z ; 1198
?Release@nsTransportWrapper@nsCacheEntryDescriptor@@UAGKXZ ; 1198
?GetSecurityInfo@nsCacheEntryDescriptor@@UAGIPAPAVnsISupports@@@Z ; 1195
?GetSecurityInfo@nsCacheEntry@@QAEIPAPAVnsISupports@@@Z ; 1195
??1nsDiskCacheEntry@@UAE@XZ ; 1193
??0nsDiskCacheEntry@@QAE@PAVnsCacheEntry@@@Z ; 1193
??_EnsDiskCacheEntry@@UAEPAXI@Z ; 1193
?DeactivateEntry@nsDiskCacheDevice@@UAEIPAVnsCacheEntry@@@Z ; 1193
?AddEntry@nsDiskCacheEntryHashTable@@QAEIPAVnsDiskCacheEntry@@@Z ; 1193
?ClearEntry@nsDiskCacheEntryHashTable@@CAXPAUPLDHashTable@@PAUPLDHashEntryHdr@@@Z ; 1193
?RemoveEntry@nsDiskCacheEntryHashTable@@QAEXPAVnsDiskCacheEntry@@@Z ; 1193
?openInputStream@nsDiskCacheDevice@@SAIPAVnsIFile@@PAPAVnsIInputStream@@@Z ; 1191
??1nsANSIInputStream@@UAE@XZ ; 1190
?Read@MetaDataFile@@QAEIPAVnsIInputStream@@@Z ; 1190
??0nsANSIInputStream@@QAE@PAU_iobuf@@@Z ; 1190
??_EnsANSIInputStream@@UAEPAXI@Z ; 1190
??0MetaDataHeader@@QAE@XZ ; 1190
?OpenOutputStream@nsTransportWrapper@nsCacheEntryDescriptor@@UAGIIIIPAPAVnsIOutputStream@@@Z ; 1166
?BindEntry@nsDiskCacheDevice@@UAEIPAVnsCacheEntry@@@Z ; 1166
?IsAllowedOnDisk@nsCacheEntry@@QAEHXZ ; 1166
??1nsOutputStreamWrapper@nsCacheEntryDescriptor@@UAE@XZ ; 1165
?NewOutputStreamWrapper@nsCacheEntryDescriptor@@CAIPAPAVnsIOutputStream@@PAV1@PAV2@@Z ; 1165
?GetAccessGranted@nsCacheEntryDescriptor@@UAGIPAH@Z ; 1165
??0nsOutputStreamWrapper@nsCacheEntryDescriptor@@QAE@PAV1@PAVnsIOutputStream@@@Z ; 1165
?Init@nsOutputStreamWrapper@nsCacheEntryDescriptor@@QAEIXZ ; 1165
??_GnsOutputStreamWrapper@nsCacheEntryDescriptor@@UAEPAXI@Z ; 1165
??0MetaDataFile@@QAE@XZ ; 1163
?GetDataSize@nsDiskCacheEntryInfo@@UAGIPAI@Z ; 1163
??_GnsDiskCacheEntryInfo@@UAEPAXI@Z ; 1163
?Swap@nsDiskCacheRecord@@QAEXXZ ; 1123
?Unswap@nsDiskCacheRecord@@QAEXXZ ; 1123
?GetExpirationTime@nsCacheEntryDescriptor@@UAGIPAI@Z ; 1118
?GetKey@nsDiskCacheEntryHashTable@@CAPBXPAUPLDHashTable@@PAUPLDHashEntryHdr@@@Z ; 395
?MoveEntry@nsDiskCacheEntryHashTable@@CAXPAUPLDHashTable@@PBUPLDHashEntryHdr@@PAU3@@Z ; 395
?DoomEntry_Locked@nsCacheService@@QAEIPAVnsCacheEntry@@@Z ; 106
?DoomEntry@nsCacheService@@QAEIPAVnsCacheEntry@@@Z ; 104
?Doom@nsCacheEntryDescriptor@@UAGIXZ ; 104
?FreeCacheEntries@nsCacheEntryHashTable@@CA?AW4PLDHashOperator@@PAUPLDHashTable@@PAUPLDHashEntryHdr@@IPAX@Z ; 72
?AsyncRead@nsTransportWrapper@nsCacheEntryDescriptor@@UAGIPAVnsIStreamListener@@PAVnsISupports@@IIIPAPAVnsIRequest@@@Z ; 32
??_H@YGXPAXIHP6EX0@Z@Z ; 32
?getFileForKey@nsDiskCacheDevice@@QAEIPBDHIPAPAVnsIFile@@@Z ; 27
?UnflattenMetaData@nsCacheMetaData@@QAEIPADI@Z ; 27
?UnflattenMetaData@nsCacheEntry@@QAEIPADI@Z ; 27
?readDiskCacheEntry@nsDiskCacheDevice@@QAEIPBDPAPAVnsDiskCacheEntry@@@Z ; 27
?GetLastModified@nsCacheEntryDescriptor@@UAGIPAI@Z ; 25
?AddRef@nsDiskCacheObserver@@UAGKXZ ; 12
?Release@nsDiskCacheObserver@@UAGKXZ ; 12
?AddRef@nsCacheService@@UAGKXZ ; 9
?Release@nsCacheService@@UAGKXZ ; 9
?QueryInterface@nsDiskCacheObserver@@UAGIABUnsID@@PAPAX@Z ; 6
?QueryInterface@nsCacheService@@UAGIABUnsID@@PAPAX@Z ; 6
?do_GetService@@YA?BVnsGetServiceByContractID@@PBDPAI@Z ; 5
?DeleteRecord@nsDiskCacheMap@@QAEXI@Z ; 3
??0nsCacheSession@@QAE@PBDHH@Z ; 3
??1nsCacheSession@@UAE@XZ ; 3
??_EnsCacheSession@@UAEPAXI@Z ; 3
?deleteDiskCacheEntry@nsDiskCacheDevice@@QAEIPAVnsDiskCacheEntry@@@Z ; 3
?DoomEntry@nsDiskCacheDevice@@UAEXPAVnsCacheEntry@@@Z ; 3
?CreateSession@nsCacheService@@UAGIPBDHHPAPAVnsICacheSession@@@Z ; 3
?setPrefsObserver@nsDiskCacheDevice@@QAEXPAVnsIObserver@@@Z ; 2
?VisitEntries@nsDiskCacheEntryHashTable@@QAEXPAVVisitor@1@@Z ; 2
?DetachDescriptors@nsCacheEntry@@AAEXXZ ; 2
?ClearPendingRequests@nsCacheService@@AAEXPAVnsCacheEntry@@@Z ; 2
?SetDoomEntriesIfExpired@nsCacheSession@@UAGIH@Z ; 2
?Finalize@nsCacheEntryHashTable@@CAXPAUPLDHashTable@@@Z ; 2
?DeactivateAndClearEntry@nsCacheService@@CA?AW4PLDHashOperator@@PAUPLDHashTable@@PAUPLDHashEntryHdr@@IPAX@Z ; 2
?Init@nsCacheEntryHashTable@@QAEIXZ ; 2
?updateDiskCacheEntries@nsDiskCacheDevice@@QAEIXZ ; 2
?scanDiskCacheEntries@nsDiskCacheDevice@@QAEIPAPAVnsISupportsArray@@@Z ; 2
?AdjustMemoryLimits@nsMemoryCacheDevice@@AAEXII@Z ; 1
_NSGetModule ; 1
?Finalize@nsDiskCacheEntryHashTable@@CAXPAUPLDHashTable@@@Z ; 1
??0nsMemoryCacheDevice@@QAE@XZ ; 1
?evictDiskCacheEntries@nsDiskCacheDevice@@QAEIXZ ; 1
??0nsDiskCacheMap@@QAE@XZ ; 1
?ClearActiveEntries@nsCacheService@@AAEXXZ ; 1
?setCacheCapacity@nsDiskCacheDevice@@QAEXI@Z ; 1
?Init@nsDiskCacheEntryHashTable@@QAEIXZ ; 1
?DoomEntry@nsMemoryCacheDevice@@UAEXPAVnsCacheEntry@@@Z ; 1
?getPrefsObserver@nsDiskCacheDevice@@QAEXPAPAVnsIObserver@@@Z ; 1
??_EnsMemoryCacheDevice@@UAEPAXI@Z ; 1
?setCacheDirectory@nsDiskCacheDevice@@QAEXPAVnsILocalFile@@@Z ; 1
?Shutdown@nsCacheService@@UAGIXZ ; 1
??_GnsCacheService@@UAEPAXI@Z ; 1
?ClearDoomList@nsCacheService@@AAEXXZ ; 1
?QueryInterface@nsANSIOutputStream@@UAGIABUnsID@@PAPAX@Z ; 1
?Init@nsCacheService@@UAGIXZ ; 1
??0nsDiskCacheDevice@@QAE@XZ ; 1
?Swap@nsDiskCacheHeader@@QAEXXZ ; 1
?GetFileForEntry@nsCacheService@@QAEIPAVnsCacheEntry@@PAPAVnsIFile@@@Z ; 1
??_GnsDiskCacheDevice@@UAEPAXI@Z ; 1
??1nsCacheService@@UAE@XZ ; 1
?GetFileForEntry@nsDiskCacheDevice@@UAEIPAVnsCacheEntry@@PAPAVnsIFile@@@Z ; 1
?Init@nsMemoryCacheDevice@@UAEIXZ ; 1
?GetFile@nsCacheEntryDescriptor@@UAGIPAPAVnsIFile@@@Z ; 1
?Seek@nsANSIOutputStream@@UAGIHH@Z ; 1
?MemoryCacheSizeChanged@nsMemoryCacheDevice@@SAHPBDPAX@Z ; 1
?SetStoragePolicy@nsCacheEntryDescriptor@@UAGIH@Z ; 1
??0nsCacheService@@QAE@XZ ; 1
?Observe@nsCacheService@@UAGIPAVnsISupports@@PBG1@Z ; 1
?writeCacheMap@nsDiskCacheDevice@@QAEIXZ ; 1
?Init@nsDiskCacheDevice@@UAEIXZ ; 1
?Create@nsCacheService@@SGIPAVnsISupports@@ABUnsID@@PAPAX@Z ; 1
?NS_GetSpecialDirectory@@YAIPBDPAPAVnsIFile@@@Z ; 1
??1nsDiskCacheDevice@@UAE@XZ ; 1
?readCacheMap@nsDiskCacheDevice@@QAEIXZ ; 1
??1nsDiskCacheMap@@QAE@XZ ; 1
??_EnsDiskCacheObserver@@UAEPAXI@Z ; 1
?Unswap@nsDiskCacheHeader@@QAEXXZ ; 1
?CreateDiskDevice@nsCacheService@@AAEIXZ ; 1
??1nsMemoryCacheDevice@@UAE@XZ ; 1
?Shutdown@nsDiskCacheDevice@@UAEIXZ ; 1
?Write@nsDiskCacheMap@@QAEIPAVnsIOutputStream@@@Z ; 1