Bug 248970 - Private Browsing mode (global toggle for saving/caching everything) [cache part]; r=cbiesinger,dcamp sr=cbiesinger

This commit is contained in:
Ehsan Akhgari 2008-10-25 13:56:20 +03:30
parent 0aefd37c4a
commit 7324bfd3ea
3 changed files with 382 additions and 15 deletions

View File

@ -23,6 +23,8 @@
*
* Contributor(s):
* Gordon Sheridan, 10-February-2001
* Michael Ventnor <m.ventnor@gmail.com>
* Ehsan Akhgari <ehsan.akhgari@gmail.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
@ -66,6 +68,8 @@
#include "nsProxyRelease.h"
#include "nsVoidArray.h"
#include "nsDeleteDir.h"
#include "nsIPrivateBrowsingService.h"
#include "nsNetCID.h"
#include <math.h> // for log()
@ -94,7 +98,8 @@
static const char * observerList[] = {
"profile-before-change",
"profile-after-change",
NS_XPCOM_SHUTDOWN_OBSERVER_ID
NS_XPCOM_SHUTDOWN_OBSERVER_ID,
NS_PRIVATE_BROWSING_SWITCH_TOPIC
};
static const char * prefList[] = {
#ifdef NECKO_DISK_CACHE
@ -125,6 +130,7 @@ public:
, mOfflineCacheCapacity(0)
, mMemoryCacheEnabled(PR_TRUE)
, mMemoryCacheCapacity(-1)
, mInPrivateBrowsing(PR_FALSE)
{
}
@ -158,6 +164,8 @@ private:
PRBool mMemoryCacheEnabled;
PRInt32 mMemoryCacheCapacity;
PRBool mInPrivateBrowsing;
};
NS_IMPL_ISUPPORTS1(nsCacheProfilePrefObserver, nsIObserver)
@ -179,7 +187,6 @@ nsCacheProfilePrefObserver::Install()
rv2 = rv;
}
// install preferences observer
nsCOMPtr<nsIPrefBranch2> branch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!branch) return NS_ERROR_FAILURE;
@ -190,6 +197,12 @@ nsCacheProfilePrefObserver::Install()
rv2 = rv;
}
// determine the initial status of the private browsing mode
nsCOMPtr<nsIPrivateBrowsingService> pbs =
do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
if (pbs)
pbs->GetPrivateBrowsingEnabled(&mInPrivateBrowsing);
// Determine if we have a profile already
// Install() is called *after* the profile-after-change notification
// when there is only a single profile, or it is specified on the
@ -276,10 +289,12 @@ nsCacheProfilePrefObserver::Observe(nsISupports * subject,
// which preference changed?
if (!strcmp(DISK_CACHE_ENABLE_PREF, data.get())) {
rv = branch->GetBoolPref(DISK_CACHE_ENABLE_PREF,
&mDiskCacheEnabled);
if (NS_FAILED(rv)) return rv;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
if (!mInPrivateBrowsing) {
rv = branch->GetBoolPref(DISK_CACHE_ENABLE_PREF,
&mDiskCacheEnabled);
if (NS_FAILED(rv)) return rv;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
}
} else if (!strcmp(DISK_CACHE_CAPACITY_PREF, data.get())) {
@ -302,10 +317,12 @@ nsCacheProfilePrefObserver::Observe(nsISupports * subject,
// which preference changed?
if (!strcmp(OFFLINE_CACHE_ENABLE_PREF, data.get())) {
rv = branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
if (NS_FAILED(rv)) return rv;
nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
if (!mInPrivateBrowsing) {
rv = branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
if (NS_FAILED(rv)) return rv;
nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
}
} else if (!strcmp(OFFLINE_CACHE_CAPACITY_PREF, data.get())) {
@ -338,6 +355,45 @@ nsCacheProfilePrefObserver::Observe(nsISupports * subject,
&mMemoryCacheCapacity);
nsCacheService::SetMemoryCache();
}
} else if (!strcmp(NS_PRIVATE_BROWSING_SWITCH_TOPIC, topic)) {
if (!strcmp(NS_PRIVATE_BROWSING_ENTER, data.get())) {
mInPrivateBrowsing = PR_TRUE;
nsCacheService::OnEnterExitPrivateBrowsing();
#ifdef NECKO_DISK_CACHE
mDiskCacheEnabled = PR_FALSE;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
#endif // !NECKO_DISK_CACHE
#ifdef NECKO_OFFLINE_CACHE
mOfflineCacheEnabled = PR_FALSE;
nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
#endif // !NECKO_OFFLINE_CACHE
} else if (!strcmp(NS_PRIVATE_BROWSING_LEAVE, data.get())) {
mInPrivateBrowsing = PR_FALSE;
nsCacheService::OnEnterExitPrivateBrowsing();
#if defined(NECKO_DISK_CACHE) || defined(NECKO_OFFLINE_CACHE)
nsCOMPtr<nsIPrefBranch> branch = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
#endif // !NECKO_DISK_CACHE && !NECKO_OFFLINE_CACHE
#ifdef NECKO_DISK_CACHE
mDiskCacheEnabled = PR_TRUE; // by default enabled
(void) branch->GetBoolPref(DISK_CACHE_ENABLE_PREF,
&mDiskCacheEnabled);
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
#endif // !NECKO_DISK_CACHE
#ifdef NECKO_OFFLINE_CACHE
mOfflineCacheEnabled = PR_TRUE; // by default enabled
(void) branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
#endif // !NECKO_OFFLINE_CACHE
}
}
return NS_OK;
@ -351,8 +407,10 @@ nsCacheProfilePrefObserver::ReadPrefs(nsIPrefBranch* branch)
#ifdef NECKO_DISK_CACHE
// read disk cache device prefs
mDiskCacheEnabled = PR_TRUE; // presume disk cache is enabled
(void) branch->GetBoolPref(DISK_CACHE_ENABLE_PREF, &mDiskCacheEnabled);
if (!mInPrivateBrowsing) {
mDiskCacheEnabled = PR_TRUE; // presume disk cache is enabled
(void) branch->GetBoolPref(DISK_CACHE_ENABLE_PREF, &mDiskCacheEnabled);
}
mDiskCacheCapacity = DISK_CACHE_CAPACITY;
(void)branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &mDiskCacheCapacity);
@ -405,9 +463,11 @@ nsCacheProfilePrefObserver::ReadPrefs(nsIPrefBranch* branch)
#ifdef NECKO_OFFLINE_CACHE
// read offline cache device prefs
mOfflineCacheEnabled = PR_TRUE; // presume offline cache is enabled
(void) branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
if (!mInPrivateBrowsing) {
mOfflineCacheEnabled = PR_TRUE; // presume offline cache is enabled
(void) branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
}
mOfflineCacheCapacity = OFFLINE_CACHE_CAPACITY;
(void)branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF,
@ -2013,3 +2073,18 @@ nsCacheService::LogCacheStatistics()
mDeactivatedUnboundEntries));
}
#endif
void
nsCacheService::OnEnterExitPrivateBrowsing()
{
if (!gService) return;
nsCacheServiceAutoLock lock;
gService->DoomActiveEntries();
if (gService->mMemoryDevice) {
// clear memory cache
gService->mMemoryDevice->EvictEntries(nsnull);
}
}

View File

@ -25,6 +25,7 @@
* Gordon Sheridan <gordon@netscape.com>
* Patrick C. Beard <beard@netscape.com>
* Darin Fisher <darin@netscape.com>
* Ehsan Akhgari <ehsan.akhgari@gmail.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
@ -156,6 +157,8 @@ public:
static void SetMemoryCache();
static void OnEnterExitPrivateBrowsing();
nsresult Init();
void Shutdown();
private:

View File

@ -0,0 +1,289 @@
/* ***** 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 Private Browsing Tests.
*
* The Initial Developer of the Original Code is
* Ehsan Akhgari.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ehsan Akhgari <ehsan.akhgari@gmail.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either of 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 ***** */
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
// names for cache devices
const kDiskDevice = "disk";
const kMemoryDevice = "memory";
const kOfflineDevice = "offline";
// the name for our cache session
const kPrivateBrowsing = "PrivateBrowsing";
var _PBSvc = null;
function get_privatebrowsing_service() {
if (_PBSvc)
return _PBSvc;
try {
_PBSvc = Cc["@mozilla.org/privatebrowsing;1"].
getService(Ci.nsIPrivateBrowsingService);
if (_PBSvc) {
var observer = {
QueryInterface: function (iid) {
const interfaces = [Ci.nsIObserver,
Ci.nsISupports];
if (!interfaces.some(function(v) iid.equals(v)))
throw Cr.NS_ERROR_NO_INTERFACE;
return this;
},
observe: function (subject, topic, data) {
subject.QueryInterface(Ci.nsISupportsPRUint32);
subject.data = 0;
}
};
var os = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
os.addObserver(observer, "private-browsing-enter", false);
}
return _PBSvc;
} catch (e) {}
return null;
}
var _CSvc = null;
function get_cache_service() {
if (_CSvc)
return _CSvc;
return _CSvc = Cc["@mozilla.org/network/cache-service;1"].
getService(Ci.nsICacheService);
}
function setup_profile_dir() {
var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
var leafRandomName = "Cache" + Math.floor(Math.random() * 10000);
var dir = dirSvc.get("TmpD", Ci.nsILocalFile);
dir.append(leafRandomName);
dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
var provider = {
getFile: function(prop, persistent) {
persistent.value = true;
if (prop == "ProfLD" ||
prop == "ProfD" ||
prop == "cachePDir")
return dir;
throw Cr.NS_ERROR_FAILURE;
},
QueryInterface: function(iid) {
if (iid.equals(Ci.nsIDirectoryProvider) ||
iid.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
dirSvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);
}
function check_devices_available(devices) {
var cs = get_cache_service();
var found_devices = [];
var visitor = {
visitDevice: function (deviceID, deviceInfo) {
found_devices.push(deviceID);
return false;
},
visitEntry: function (deviceID, entryInfo) {
do_throw("nsICacheVisitor.visitEntry should not be called " +
"when checking the availability of devices");
}
};
// get the list of active devices
cs.visitEntries(visitor);
// see if any of the required devices was missing
if (devices.sort().toString() != found_devices.sort().toString()) {
do_throw("Expected to find these devices: \"" + devices.sort().toString() +
"\", but found these instead: \"" + found_devices.sort().toString() + "\"");
}
// see if any extra devices have been found
if (found_devices.length > devices.length) {
do_throw("Expected to find these devices: [" + devices.join(", ") +
"], but instead got: [" + found_devices.join(", ") + "]");
}
}
function get_device_entry_count(device) {
var cs = get_cache_service();
var entry_count = -1;
var visitor = {
visitDevice: function (deviceID, deviceInfo) {
if (device == deviceID)
entry_count = deviceInfo.entryCount;
return false;
},
visitEntry: function (deviceID, entryInfo) {
do_throw("nsICacheVisitor.visitEntry should not be called " +
"when checking the availability of devices");
}
};
// get the device entry count
cs.visitEntries(visitor);
return entry_count;
}
function store_in_cache(aKey, aContent, aWhere) {
var storageFlag, streaming = true;
if (aWhere == kDiskDevice)
storageFlag = Ci.nsICache.STORE_ON_DISK;
else if (aWhere == kOfflineDevice)
storageFlag = Ci.nsICache.STORE_OFFLINE;
else if (aWhere == kMemoryDevice)
storageFlag = Ci.nsICache.STORE_IN_MEMORY;
var cache = get_cache_service();
var session = cache.createSession(kPrivateBrowsing, storageFlag, streaming);
var cacheEntry = session.openCacheEntry(aKey, Ci.nsICache.ACCESS_WRITE, true);
var oStream = cacheEntry.openOutputStream(0);
var written = oStream.write(aContent, aContent.length);
if (written != aContent.length) {
do_throw("oStream.write has not written all data!\n" +
" Expected: " + aContent.length + "\n" +
" Actual: " + written + "\n");
}
oStream.close();
cacheEntry.close();
}
function make_input_stream_scriptable(input) {
var wrapper = Cc["@mozilla.org/scriptableinputstream;1"].
createInstance(Ci.nsIScriptableInputStream);
wrapper.init(input);
return wrapper;
}
function retrieve_from_cache(aKey, aWhere) {
var storageFlag, streaming = true;
if (aWhere == kDiskDevice)
storageFlag = Ci.nsICache.STORE_ANYWHERE;
else if (aWhere == kOfflineDevice)
storageFlag = Ci.nsICache.STORE_OFFLINE;
else if (aWhere == kMemoryDevice)
storageFlag = Ci.nsICache.STORE_ANYWHERE;
var cache = get_cache_service();
var session = cache.createSession(kPrivateBrowsing, storageFlag, streaming);
try {
var cacheEntry = session.openCacheEntry(aKey, Ci.nsICache.ACCESS_READ, true);
} catch (e) {
if (e.result == Cr.NS_ERROR_CACHE_KEY_NOT_FOUND ||
e.result == Cr.NS_ERROR_FAILURE)
// a key not found error is expected here, so we will simply return null
// to let the caller know that no data was retrieved. We also expect
// a generic failure error in case of the offline cache.
return null;
else
do_throw(e); // throw the textual error description
}
var iStream = make_input_stream_scriptable(cacheEntry.openInputStream(0));
var read = iStream.read(iStream.available());
iStream.close();
cacheEntry.close();
return read;
}
function run_test() {
var pb = get_privatebrowsing_service();
if (pb) { // Private Browsing might not be available
const kCacheA = "cache-A",
kCacheB = "cache-B",
kCacheC = "cache-C",
kTestContent = "test content";
// Simulate a profile dir for xpcshell
setup_profile_dir();
var cs = get_cache_service();
// Start off with an empty cache
cs.evictEntries(Ci.nsICache.STORE_ANYWHERE);
// Store cache-A, cache-B and cache-C
store_in_cache(kCacheA, kTestContent, kMemoryDevice);
store_in_cache(kCacheB, kTestContent, kDiskDevice);
store_in_cache(kCacheC, kTestContent, kOfflineDevice);
// Make sure all three cache devices are available initially
check_devices_available([kMemoryDevice, kDiskDevice, kOfflineDevice]);
// Check if cache-A, cache-B and cache-C are avilable
do_check_eq(retrieve_from_cache(kCacheA, kMemoryDevice), kTestContent);
do_check_eq(retrieve_from_cache(kCacheB, kDiskDevice), kTestContent);
do_check_eq(retrieve_from_cache(kCacheC, kOfflineDevice), kTestContent);
// Enter private browsing mode
pb.privateBrowsingEnabled = true;
// Make sure none of cache-A, cache-B and cache-C are available
do_check_eq(retrieve_from_cache(kCacheA, kMemoryDevice), null);
do_check_eq(retrieve_from_cache(kCacheB, kDiskDevice), null);
do_check_eq(retrieve_from_cache(kCacheC, kOfflineDevice), null);
// Make sure only the memory device is available
check_devices_available([kMemoryDevice]);
// Make sure the memory device is empty
do_check_eq(get_device_entry_count(kMemoryDevice), 0);
// Exit private browsing mode
pb.privateBrowsingEnabled = false;
// Make sure all three cache devices are available after leaving the private mode
check_devices_available([kMemoryDevice, kDiskDevice, kOfflineDevice]);
// Check if cache-A is gone, and cache-B and cache-C are still avilable
do_check_eq(retrieve_from_cache(kCacheA, kMemoryDevice), null);
do_check_eq(retrieve_from_cache(kCacheB, kDiskDevice), kTestContent);
do_check_eq(retrieve_from_cache(kCacheC, kOfflineDevice), kTestContent);
}
}