Bug 248970 - Private Browsing mode (global toggle for saving/caching everything) [cookie part]; r=dwitte,mconnor sr=bzbarsky
authorEhsan Akhgari <ehsan.akhgari@gmail.com>
Mon, 20 Oct 2008 00:42:53 +0330
changeset 20636 53b78b1b3910
parent 20635 ab63f0d13ea8
child 20637 e9b859357547
push id3021
push userehsan.akhgari@gmail.com
push date2008-10-19 21:18 +0000
Treeherderresults
reviewersdwitte, mconnor, bzbarsky
bugs248970
milestone1.9.1b2pre
Bug 248970 - Private Browsing mode (global toggle for saving/caching everything) [cookie part]; r=dwitte,mconnor sr=bzbarsky
browser/components/preferences/cookies.js
netwerk/cookie/public/nsICookieService.idl
netwerk/cookie/src/nsCookieService.cpp
netwerk/cookie/src/nsCookieService.h
netwerk/test/unit/test_bug248970_cookie.js
--- a/browser/components/preferences/cookies.js
+++ b/browser/components/preferences/cookies.js
@@ -54,42 +54,54 @@ var gCookiesWindow = {
     var os = Components.classes["@mozilla.org/observer-service;1"]
                        .getService(Components.interfaces.nsIObserverService);
     os.addObserver(this, "cookie-changed", false);
     os.addObserver(this, "perm-changed", false);
     
     this._bundle = document.getElementById("bundlePreferences");
     this._tree = document.getElementById("cookiesList");
     
-    this._loadCookies();
-    this._tree.treeBoxObject.view = this._view;
-    this.sort("rawHost");
-    if (this._view.rowCount > 0) 
-      this._tree.view.selection.select(0);
-
-    if ("arguments" in window && window.arguments[0] &&
-        window.arguments[0].filterString)
-    {
-      document.getElementById("filter").value = window.arguments[0].filterString;
-      this.filter();
-    }
-
-    this._saveState();
+    this._populateList(true);
       
     document.getElementById("filter").focus();
   },
   
   uninit: function ()
   {
     var os = Components.classes["@mozilla.org/observer-service;1"]
                        .getService(Components.interfaces.nsIObserverService);
     os.removeObserver(this, "cookie-changed");
     os.removeObserver(this, "perm-changed");
   },
   
+  _populateList: function (aInitialLoad)
+  {
+    this._loadCookies();
+    this._tree.treeBoxObject.view = this._view;
+    if (aInitialLoad)
+      this.sort("rawHost");
+    if (this._view.rowCount > 0) 
+      this._tree.view.selection.select(0);
+
+    if (aInitialLoad) {
+      if ("arguments" in window && window.arguments[0] &&
+          window.arguments[0].filterString)
+      {
+        document.getElementById("filter").value = window.arguments[0].filterString;
+        this.filter();
+      }
+    }
+    else {
+      if (document.getElementById("filter").value != "")
+        this.filter();
+    }
+
+    this._saveState();
+  },
+  
   _cookieEquals: function (aCookieA, aCookieB, aStrippedHost)
   {
     return aCookieA.rawHost == aStrippedHost &&
            aCookieA.name == aCookieB.name &&
            aCookieA.path == aCookieB.path;
   },
   
   observe: function (aCookie, aTopic, aData) 
@@ -108,16 +120,23 @@ var gCookiesWindow = {
       this._hosts = {};
       this._hostOrder = [];
     
       var oldRowCount = this._view._rowCount;
       this._view._rowCount = 0;
       this._tree.treeBoxObject.rowCountChanged(0, -oldRowCount);
       this._view.selection.clearSelection();
     }
+    else if (aData == "reload") {
+      // first, clear any existing entries
+      this.observe(aCookie, aTopic, "cleared");
+
+      // then, reload the list
+      this._populateList(false);
+    }
     
     // We don't yet handle aData == "deleted" - it's a less common case
     // and is rather complicated as selection tracking is difficult
   },
   
   _handleCookieChanged: function (changedCookie, strippedHost) 
   {
     var rowIndex = 0;
--- a/netwerk/cookie/public/nsICookieService.idl
+++ b/netwerk/cookie/public/nsICookieService.idl
@@ -61,16 +61,18 @@ interface nsIChannel;
  * data   : "deleted"
  *          a cookie was deleted. the subject is the deleted cookie.
  *          "added"
  *          a cookie was added. the subject is the added cookie.
  *          "changed"
  *          a cookie was changed. the subject is the new cookie.
  *          "cleared"
  *          the entire cookie list was cleared. the subject is null.
+ *          "reload"
+ *          the entire cookie list should be reloaded.  the subject is null.
  *
  * topic  : "cookie-rejected"
  *          broadcast whenever a cookie was rejected from being set as a
  *          result of user prefs.
  * subject: an nsIURI interface pointer representing the URI that attempted
  *          to set the cookie.
  * data   : none.
  */
--- a/netwerk/cookie/src/nsCookieService.cpp
+++ b/netwerk/cookie/src/nsCookieService.cpp
@@ -17,16 +17,18 @@
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 2003
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Daniel Witte (dwitte@stanford.edu)
  *   Michiel van Leeuwen (mvl@exedo.nl)
+ *   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
  * 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
@@ -62,16 +64,18 @@
 #include "prprf.h"
 #include "nsNetUtil.h"
 #include "nsNetCID.h"
 #include "nsAppDirectoryServiceDefs.h"
 #include "mozIStorageService.h"
 #include "mozIStorageStatement.h"
 #include "mozIStorageConnection.h"
 #include "mozStorageHelper.h"
+#include "nsIPrivateBrowsingService.h"
+#include "nsNetCID.h"
 
 /******************************************************************************
  * nsCookieService impl:
  * useful types & constants
  ******************************************************************************/
 
 // XXX_hack. See bug 178993.
 // This is a hack to hide HttpOnly cookies from older browsers
@@ -404,23 +408,24 @@ NS_IMPL_ISUPPORTS5(nsCookieService,
                    nsIObserver,
                    nsISupportsWeakReference)
 
 nsCookieService::nsCookieService()
  : mCookieCount(0)
  , mCookiesPermissions(BEHAVIOR_ACCEPT)
  , mMaxNumberOfCookies(kMaxNumberOfCookies)
  , mMaxCookiesPerHost(kMaxCookiesPerHost)
+ , mHostTable(&mDefaultHostTable)
 {
 }
 
 nsresult
 nsCookieService::Init()
 {
-  if (!mHostTable.Init()) {
+  if (!mHostTable->Init()) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   nsresult rv;
   mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // init our pref and observer
@@ -437,16 +442,27 @@ nsCookieService::Init()
   rv = InitDB();
   if (NS_FAILED(rv))
     COOKIE_LOGSTRING(PR_LOG_WARNING, ("Init(): InitDB() gave error %x", rv));
 
   mObserverService = do_GetService("@mozilla.org/observer-service;1");
   if (mObserverService) {
     mObserverService->AddObserver(this, "profile-before-change", PR_TRUE);
     mObserverService->AddObserver(this, "profile-do-change", PR_TRUE);
+    mObserverService->AddObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC, PR_TRUE);
+
+    nsCOMPtr<nsIPrivateBrowsingService> pbs =
+      do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
+    if (pbs) {
+      PRBool inPrivateBrowsing = PR_FALSE;
+      pbs->GetPrivateBrowsingEnabled(&inPrivateBrowsing);
+      if (inPrivateBrowsing) {
+        Observe(nsnull, NS_PRIVATE_BROWSING_SWITCH_TOPIC, NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).get());
+      }
+    }
   }
 
   mPermissionService = do_GetService(NS_COOKIEPERMISSION_CONTRACTID);
   if (!mPermissionService) {
     NS_WARNING("nsICookiePermission implementation not available - some features won't work!");
     COOKIE_LOGSTRING(PR_LOG_WARNING, ("Init(): nsICookiePermission implementation not available"));
   }
 
@@ -634,16 +650,41 @@ nsCookieService::Observe(nsISupports    
   } else if (!strcmp(aTopic, "profile-do-change")) {
     // the profile has already changed; init the db from the new location
     InitDB();
 
   } else if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
     nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(aSubject);
     if (prefBranch)
       PrefChanged(prefBranch);
+  } else if (!strcmp(aTopic, NS_PRIVATE_BROWSING_SWITCH_TOPIC)) {
+    if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).Equals(aData)) {
+      // backup the existing in-memory DB
+      if (mPrivateHostTable.IsInitialized() || mPrivateHostTable.Init()) {
+        mHostTable = &mPrivateHostTable;
+        mCookieCount = mHostTable->Count();
+        NotifyChanged(nsnull, NS_LITERAL_STRING("cleared").get());
+      }
+      // close the connection to the on-disk DB
+      mStmtInsert = nsnull;
+      mStmtDelete = nsnull;
+      mStmtUpdate = nsnull;
+      mDBConn = nsnull;
+      // continue to use the in-memory DB
+    } else if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_LEAVE).Equals(aData)) {
+      // open the connection to the on-disk DB
+      InitDB();
+      // restore the in-memory DB as it was prior to private browsing
+      if (mPrivateHostTable.IsInitialized())
+        mPrivateHostTable.Clear();
+      mHostTable = &mDefaultHostTable;
+      mCookieCount = mHostTable->Count();
+      NotifyChanged(nsnull, NS_LITERAL_STRING("reload").get());
+      // continue to use both on-disk and in-memory DB
+    }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCookieService::GetCookieString(nsIURI     *aHostURI,
                                  nsIChannel *aChannel,
@@ -826,17 +867,17 @@ COMArrayCallback(nsCookieEntry *aEntry,
 }
 
 NS_IMETHODIMP
 nsCookieService::GetEnumerator(nsISimpleEnumerator **aEnumerator)
 {
   nsCOMArray<nsICookie> cookieList(mCookieCount);
   nsGetEnumeratorData data(&cookieList, PR_Now() / PR_USEC_PER_SEC);
 
-  mHostTable.EnumerateEntries(COMArrayCallback, &data);
+  mHostTable->EnumerateEntries(COMArrayCallback, &data);
 
   return NS_NewArrayEnumerator(aEnumerator, cookieList);
 }
 
 NS_IMETHODIMP
 nsCookieService::Add(const nsACString &aDomain,
                      const nsACString &aPath,
                      const nsACString &aName,
@@ -1167,17 +1208,17 @@ nsCookieService::GetCookieInternal(nsIUR
   PRInt64 currentTime = currentTimeInUsec / PR_USEC_PER_SEC;
   const char *currentDot = hostFromURI.get();
   const char *nextDot = currentDot + 1;
   PRBool stale = PR_FALSE;
 
   // begin hash lookup, walking up the subdomain levels.
   // we use nextDot to force a lookup of the original host (without leading dot).
   do {
-    nsCookieEntry *entry = mHostTable.GetEntry(currentDot);
+    nsCookieEntry *entry = mHostTable->GetEntry(currentDot);
     cookie = entry ? entry->Head() : nsnull;
     for (; cookie; cookie = cookie->Next()) {
       // if the cookie is secure and the host scheme isn't, we can't send it
       if (cookie->IsSecure() && !isSecure) {
         continue;
       }
 
       // if the cookie is httpOnly and it's not going directly to the HTTP
@@ -2004,17 +2045,17 @@ nsCookieService::GetExpiry(nsCookieAttri
  * private cookielist management functions
  ******************************************************************************/
 
 void
 nsCookieService::RemoveAllFromMemory()
 {
   // clearing the hashtable will call each nsCookieEntry's dtor,
   // which releases all their respective children.
-  mHostTable.Clear();
+  mHostTable->Clear();
   mCookieCount = 0;
 }
 
 PLDHashOperator
 removeExpiredCallback(nsCookieEntry *aEntry,
                       void          *aArg)
 {
   const PRInt64 &currentTime = *static_cast<PRInt64*>(aArg);
@@ -2030,17 +2071,17 @@ removeExpiredCallback(nsCookieEntry *aEn
 
 // removes any expired cookies from memory
 void
 nsCookieService::RemoveExpiredCookies(PRInt64 aCurrentTime)
 {
 #ifdef PR_LOGGING
   PRUint32 initialCookieCount = mCookieCount;
 #endif
-  mHostTable.EnumerateEntries(removeExpiredCallback, &aCurrentTime);
+  mHostTable->EnumerateEntries(removeExpiredCallback, &aCurrentTime);
   COOKIE_LOGSTRING(PR_LOG_DEBUG, ("RemoveExpiredCookies(): %ld purged; %ld remain", initialCookieCount - mCookieCount, mCookieCount));
 }
 
 // find whether a given cookie has been previously set. this is provided by the
 // nsICookieManager2 interface.
 NS_IMETHODIMP
 nsCookieService::CookieExists(nsICookie2 *aCookie,
                               PRBool     *aFoundCookie)
@@ -2070,17 +2111,17 @@ nsCookieService::CountCookiesFromHostInt
 {
   PRUint32 countFromHost = 0;
 
   nsCAutoString hostWithDot(NS_LITERAL_CSTRING(".") + aHost);
 
   const char *currentDot = hostWithDot.get();
   const char *nextDot = currentDot + 1;
   do {
-    nsCookieEntry *entry = mHostTable.GetEntry(currentDot);
+    nsCookieEntry *entry = mHostTable->GetEntry(currentDot);
     for (nsListIter iter(entry); iter.current; ++iter) {
       // only count non-expired cookies
       if (iter.current->Expiry() > aData.currentTime) {
         ++countFromHost;
 
         // check if we've found the oldest cookie so far
         if (aData.oldestTime > iter.current->LastAccessed()) {
           aData.oldestTime = iter.current->LastAccessed();
@@ -2114,17 +2155,17 @@ nsCookieService::CountCookiesFromHost(co
 // find an exact cookie specified by host, name, and path that hasn't expired.
 PRBool
 nsCookieService::FindCookie(const nsAFlatCString &aHost,
                             const nsAFlatCString &aName,
                             const nsAFlatCString &aPath,
                             nsListIter           &aIter,
                             PRInt64               aCurrentTime)
 {
-  nsCookieEntry *entry = mHostTable.GetEntry(aHost.get());
+  nsCookieEntry *entry = mHostTable->GetEntry(aHost.get());
   for (aIter = nsListIter(entry); aIter.current; ++aIter) {
     if (aIter.current->Expiry() > aCurrentTime &&
         aPath.Equals(aIter.current->Path()) &&
         aName.Equals(aIter.current->Name())) {
       return PR_TRUE;
     }
   }
 
@@ -2151,17 +2192,17 @@ nsCookieService::RemoveCookieFromList(ns
       COOKIE_LOGSTRING(PR_LOG_WARNING, ("RemoveCookieFromList(): removing from db gave error %x", rv));
     }
   }
 
   if (!aIter.prev && !aIter.current->Next()) {
     // we're removing the last element in the list - so just remove the entry
     // from the hash. note that the entryclass' dtor will take care of
     // releasing this last element for us!
-    mHostTable.RawRemoveEntry(aIter.entry);
+    mHostTable->RawRemoveEntry(aIter.entry);
     aIter.current = nsnull;
 
   } else {
     // just remove the element from the list, and increment the iterator
     nsCookie *next = aIter.current->Next();
     NS_RELEASE(aIter.current);
     if (aIter.prev) {
       // element to remove is not the head
@@ -2206,17 +2247,17 @@ bindCookieParameters(mozIStorageStatemen
   
   rv = aStmt->BindInt32Parameter(8, aCookie->IsHttpOnly());
   return rv;
 }
 
 PRBool
 nsCookieService::AddCookieToList(nsCookie *aCookie, PRBool aWriteToDB)
 {
-  nsCookieEntry *entry = mHostTable.PutEntry(aCookie->Host().get());
+  nsCookieEntry *entry = mHostTable->PutEntry(aCookie->Host().get());
 
   if (!entry) {
     NS_ERROR("can't insert element into a null entry!");
     return PR_FALSE;
   }
 
   NS_ADDREF(aCookie);
 
@@ -2284,11 +2325,10 @@ findOldestCallback(nsCookieEntry *aEntry
     }
   }
   return PL_DHASH_NEXT;
 }
 
 void
 nsCookieService::FindOldestCookie(nsEnumerationData &aData)
 {
-  mHostTable.EnumerateEntries(findOldestCallback, &aData);
+  mHostTable->EnumerateEntries(findOldestCallback, &aData);
 }
-
--- a/netwerk/cookie/src/nsCookieService.h
+++ b/netwerk/cookie/src/nsCookieService.h
@@ -17,16 +17,18 @@
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 2003
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Daniel Witte (dwitte@stanford.edu)
  *   Michiel van Leeuwen (mvl@exedo.nl)
+ *   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
  * 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
@@ -193,17 +195,19 @@ class nsCookieService : public nsICookie
     nsCOMPtr<mozIStorageStatement>   mStmtInsert;
     nsCOMPtr<mozIStorageStatement>   mStmtDelete;
     nsCOMPtr<mozIStorageStatement>   mStmtUpdate;
     nsCOMPtr<nsIObserverService>     mObserverService;
     nsCOMPtr<nsICookiePermission>    mPermissionService;
     nsCOMPtr<nsIEffectiveTLDService> mTLDService;
 
     // impl members
-    nsTHashtable<nsCookieEntry>   mHostTable;
+    nsTHashtable<nsCookieEntry>  *mHostTable;
+    nsTHashtable<nsCookieEntry>   mDefaultHostTable;
+    nsTHashtable<nsCookieEntry>   mPrivateHostTable;
     PRUint32                      mCookieCount;
 
     // cached prefs
     PRUint8                       mCookiesPermissions;   // BEHAVIOR_{ACCEPT, REJECTFOREIGN, REJECT}
     PRUint16                      mMaxNumberOfCookies;
     PRUint16                      mMaxCookiesPerHost;
 
     // private static member, used to cache a ptr to nsCookieService,
new file mode 100644
--- /dev/null
+++ b/netwerk/test/unit/test_bug248970_cookie.js
@@ -0,0 +1,198 @@
+/* ***** 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 ***** */
+
+var _PBSvc = null;
+function get_PBSvc() {
+  if (_PBSvc)
+    return _PBSvc;
+
+  try {
+    _PBSvc = Components.classes["@mozilla.org/privatebrowsing;1"].
+             getService(Components.interfaces.nsIPrivateBrowsingService);
+    if (_PBSvc) {
+      var observer = {
+        QueryInterface: function (iid) {
+          const interfaces = [Components.interfaces.nsIObserver,
+                              Components.interfaces.nsISupports];
+          if (!interfaces.some(function(v) iid.equals(v)))
+            throw Components.results.NS_ERROR_NO_INTERFACE;
+          return this;
+        },
+        observe: function (subject, topic, data) {
+          subject.QueryInterface(Components.interfaces.nsISupportsPRUint32);
+          subject.data = 0;
+        }
+      };
+      var os = Components.classes["@mozilla.org/observer-service;1"].
+               getService(Components.interfaces.nsIObserverService);
+      os.addObserver(observer, "private-browsing-enter", false);
+    }
+    return _PBSvc;
+  } catch (e) {}
+  return null;
+}
+
+var _CMSvc = null;
+function get_CookieManager() {
+  if (_CMSvc)
+    return _CMSvc;
+
+  return _CMSvc = Components.classes["@mozilla.org/cookiemanager;1"].
+                  getService(Components.interfaces.nsICookieManager2);
+}
+
+function is_cookie_available1(domain, path, name, value,
+                              secure, httponly, session, expires) {
+  var cm = get_CookieManager();
+  var enumerator = cm.enumerator;
+  while (enumerator.hasMoreElements()) {
+    var cookie = enumerator.getNext().QueryInterface(Components.interfaces.nsICookie);
+    if (cookie.host == domain &&
+        cookie.path == path &&
+        cookie.name == name &&
+        cookie.value == value &&
+        cookie.isSecure == secure &&
+        cookie.expires == expires)
+      return true;
+  }
+  return false;
+}
+
+function is_cookie_available2(domain, path, name, value,
+                              secure, httponly, session, expires) {
+  var cookie = {
+    name: name,
+    value: value,
+    isDomain: true,
+    host: domain,
+    path: path,
+    isSecure: secure,
+    expires: expires,
+    status: 0,
+    policy: 0,
+    isSession: session,
+    expiry: expires,
+    isHttpOnly: httponly,
+    QueryInterface: function(iid) {
+      var validIIDs = [Components.interfaces.nsISupports,
+                       Components.interfaces.nsICookie,
+                       Components.interfaces.nsICookie2];
+      for (var i = 0; i < validIIDs.length; ++i) {
+        if (iid == validIIDs[i])
+          return this;
+      }
+      throw Components.results.NS_ERROR_NO_INTERFACE;
+    }
+  };
+
+  var cm = get_CookieManager();
+  return cm.cookieExists(cookie);
+}
+
+var cc_observer = null;
+function setup_cookie_changed_observer() {
+  cc_observer = {
+    gotCleared: false,
+    gotReloaded: false,
+    QueryInterface: function (iid) {
+      const interfaces = [Components.interfaces.nsIObserver,
+                          Components.interfaces.nsISupports];
+      if (!interfaces.some(function(v) iid.equals(v)))
+        throw Components.results.NS_ERROR_NO_INTERFACE;
+      return this;
+    },
+    observe: function (subject, topic, data) {
+      if (topic == "cookie-changed") {
+        if (!subject) {
+          if (data == "cleared")
+            this.gotCleared = true;
+          else if (data == "reload")
+            this.gotReloaded = true;
+        }
+      }
+    }
+  };
+  var os = Components.classes["@mozilla.org/observer-service;1"].
+           getService(Components.interfaces.nsIObserverService);
+  os.addObserver(cc_observer, "cookie-changed", false);
+}
+
+function run_test() {
+  var pb = get_PBSvc();
+  if (pb) { // Private Browsing might not be available
+    var cm = get_CookieManager();
+    do_check_neq(cm, null);
+
+    setup_cookie_changed_observer();
+    do_check_neq(cc_observer, null);
+
+    try {
+      // create Cookie-A
+      const time = (new Date("Jan 1, 2030")).getTime() / 1000;
+      cm.add("pbtest.example.com", "/", "C1", "V1", false, true, false, time);
+      // make sure Cookie-A is retrievable
+      do_check_true(is_cookie_available1("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+      do_check_true(is_cookie_available2("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+      // enter private browsing mode
+      pb.privateBrowsingEnabled = true;
+      // make sure the "cleared" notification was fired
+      do_check_true(cc_observer.gotCleared);
+      // make sure Cookie-A is not retrievable
+      do_check_false(is_cookie_available1("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+      do_check_false(is_cookie_available2("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+      // create Cookie-B
+      const time2 = (new Date("Jan 2, 2030")).getTime() / 1000;
+      cm.add("pbtest2.example.com", "/", "C2", "V2", false, true, false, time2);
+      // make sure Cookie-B is retrievable
+      do_check_true(is_cookie_available1("pbtest2.example.com", "/", "C2", "V2", false, true, false, time2));
+      do_check_true(is_cookie_available2("pbtest2.example.com", "/", "C2", "V2", false, true, false, time2));
+      // exit private browsing mode
+      pb.privateBrowsingEnabled = false;
+      // make sure the "reload" notification was fired
+      do_check_true(cc_observer.gotReloaded);
+      // make sure Cookie-B is not retrievable
+      do_check_false(is_cookie_available1("pbtest2.example.com", "/", "C2", "V2", false, true, false, time2));
+      do_check_false(is_cookie_available2("pbtest2.example.com", "/", "C2", "V2", false, true, false, time2));
+      // make sure Cookie-A is retrievable
+      do_check_true(is_cookie_available1("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+      do_check_true(is_cookie_available2("pbtest.example.com", "/", "C1", "V1", false, true, false, time));
+    } catch (e) {
+      do_throw("Unexpected exception while testing cookies: " + e);
+    }
+  }
+  do_test_finished();
+}