Merge m-c to m-i.
authorMs2ger <ms2ger@gmail.com>
Sun, 23 Jun 2013 13:44:01 +0200
changeset 147692 2fb1cc6eb83d8ce51dcee983f72801c50c1d04b1
parent 147651 4c4f75c20e9ba7448417307d1fccc25b2ab8e234 (current diff)
parent 147691 6409ddd66eaab0264b587118bd43c2039ee2d346 (diff)
child 147693 19675f2a58f5547fad2d70b797c678b1988e1ce2
push id2697
push userbbajaj@mozilla.com
push dateMon, 05 Aug 2013 18:49:53 +0000
treeherdermozilla-beta@dfec938c7b63 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone24.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge m-c to m-i.
security/manager/locales/en-US/chrome/pippki/validation.dtd
security/manager/pki/resources/content/crlImportDialog.js
security/manager/pki/resources/content/crlImportDialog.xul
security/manager/pki/resources/content/crlManager.js
security/manager/pki/resources/content/crlManager.xul
security/manager/pki/resources/content/pref-crlupdate.js
security/manager/pki/resources/content/pref-crlupdate.xul
security/manager/pki/resources/content/serverCrlNextupdate.js
security/manager/pki/resources/content/serverCrlNextupdate.xul
security/manager/ssl/public/nsICRLInfo.idl
security/manager/ssl/public/nsICRLManager.idl
security/manager/ssl/src/nsCRLInfo.cpp
security/manager/ssl/src/nsCRLInfo.h
security/manager/ssl/src/nsCRLManager.cpp
security/manager/ssl/src/nsCRLManager.h
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -1022,17 +1022,16 @@ pref("services.sync.prefs.sync.privacy.c
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.history", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.offlineApps", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.passwords", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.sessions", true);
 pref("services.sync.prefs.sync.privacy.clearOnShutdown.siteSettings", true);
 pref("services.sync.prefs.sync.privacy.donottrackheader.enabled", true);
 pref("services.sync.prefs.sync.privacy.donottrackheader.value", true);
 pref("services.sync.prefs.sync.privacy.sanitize.sanitizeOnShutdown", true);
-pref("services.sync.prefs.sync.security.OCSP.disable_button.managecrl", true);
 pref("services.sync.prefs.sync.security.OCSP.enabled", true);
 pref("services.sync.prefs.sync.security.OCSP.require", true);
 pref("services.sync.prefs.sync.security.default_personal_cert", true);
 pref("services.sync.prefs.sync.security.tls.version.min", true);
 pref("services.sync.prefs.sync.security.tls.version.max", true);
 pref("services.sync.prefs.sync.signon.rememberSignons", true);
 pref("services.sync.prefs.sync.spellchecker.dictionary", true);
 pref("services.sync.prefs.sync.xpinstall.whitelist.required", true);
--- a/browser/base/content/aboutDialog.js
+++ b/browser/base/content/aboutDialog.js
@@ -297,16 +297,25 @@ appUpdater.prototype =
       gAppUpdater.isChecking = false;
       gAppUpdater.update = gAppUpdater.aus.
                            selectUpdate(aUpdates, aUpdates.length);
       if (!gAppUpdater.update) {
         gAppUpdater.selectPanel("noUpdatesFound");
         return;
       }
 
+      if (gAppUpdater.update.unsupported) {
+        if (gAppUpdater.update.detailsURL) {
+          let unsupportedLink = document.getElementById("unsupportedLink");
+          unsupportedLink.href = gAppUpdater.update.detailsURL;
+        }
+        gAppUpdater.selectPanel("unsupportedSystem");
+        return;
+      }
+
       if (!gAppUpdater.aus.canApplyUpdates) {
         gAppUpdater.selectPanel("manualUpdate");
         return;
       }
 
       // Firefox no longer displays a license for updates and the licenseURL
       // check is just in case a distibution does.
       if (gAppUpdater.update.billboardURL || gAppUpdater.update.licenseURL) {
--- a/browser/base/content/aboutDialog.xul
+++ b/browser/base/content/aboutDialog.xul
@@ -77,16 +77,19 @@
                 <label>&update.noUpdatesFound;</label>
               </hbox>
               <hbox id="otherInstanceHandlingUpdates" align="center">
                 <label>&update.otherInstanceHandlingUpdates;</label>
               </hbox>
               <hbox id="manualUpdate" align="center">
                 <label>&update.manual.start;</label><label id="manualLink" class="text-link"/><label>&update.manual.end;</label>
               </hbox>
+              <hbox id="unsupportedSystem" align="center">
+                <label>&update.unsupported.start;</label><label id="unsupportedLink" class="text-link">&update.unsupported.linkText;</label><label>&update.unsupported.end;</label>
+              </hbox>
             </deck>
 #endif
           </vbox>
 
 #if MOZ_UPDATE_CHANNEL != release
 #ifdef MOZ_UPDATER
           <description class="text-blurb" id="currentChannelText">
             &channel.description.start;<label id="currentChannel"/>&channel.description.end;
--- a/browser/components/preferences/advanced.js
+++ b/browser/components/preferences/advanced.js
@@ -800,26 +800,16 @@ var gAdvancedPane = {
   showCertificates: function ()
   {
     document.documentElement.openWindow("mozilla:certmanager",
                                         "chrome://pippki/content/certManager.xul",
                                         "", null);
   },
 
   /**
-   * Displays a dialog which describes the user's CRLs.
-   */
-  showCRLs: function ()
-  {
-    document.documentElement.openWindow("mozilla:crlmanager",
-                                        "chrome://pippki/content/crlManager.xul",
-                                        "", null);
-  },
-
-  /**
    * Displays a dialog in which OCSP preferences can be configured.
    */
   showOCSP: function ()
   {
     document.documentElement.openSubDialog("chrome://mozapps/content/preferences/ocsp.xul",
                                            "", null);
   },
 
--- a/browser/components/preferences/advanced.xul
+++ b/browser/components/preferences/advanced.xul
@@ -96,19 +96,16 @@
       <preference id="browser.search.update"           name="browser.search.update"           type="bool"/>
 
       <!-- Encryption tab -->
       <preference id="security.default_personal_cert"  name="security.default_personal_cert"  type="string"/>
 
       <preference id="security.disable_button.openCertManager"
                   name="security.disable_button.openCertManager"
                   type="bool"/>
-      <preference id="security.OCSP.disable_button.managecrl"
-                  name="security.OCSP.disable_button.managecrl"
-                  type="bool"/>
       <preference id="security.disable_button.openDeviceManager"
                   name="security.disable_button.openDeviceManager"
                   type="bool"/>
     </preferences>
 
 #ifdef HAVE_SHELL_SERVICE
     <stringbundle id="bundleShell" src="chrome://browser/locale/shellservice.properties"/>
     <stringbundle id="bundleBrand" src="chrome://branding/locale/brand.properties"/>
@@ -419,42 +416,28 @@
               <radio label="&certs.auto;" accesskey="&certs.auto.accesskey;"
                      value="Select Automatically"/>
               <radio label="&certs.ask;" accesskey="&certs.ask.accesskey;"
                      value="Ask Every Time"/>
             </radiogroup>
 
             <separator/>
 
-#ifdef XP_MACOSX
-            <vbox>
-#endif
             <hbox>
               <button id="viewCertificatesButton"
                       label="&viewCerts.label;" accesskey="&viewCerts.accesskey;"
                       oncommand="gAdvancedPane.showCertificates();"
                       preference="security.disable_button.openCertManager"/>
-              <button id="viewCRLButton"
-                      label="&viewCRLs.label;" accesskey="&viewCRLs.accesskey;"
-                      oncommand="gAdvancedPane.showCRLs();"
-                      preference="security.OCSP.disable_button.managecrl"/>
               <button id="verificationButton"
                       label="&verify2.label;" accesskey="&verify2.accesskey;"
                       oncommand="gAdvancedPane.showOCSP();"/>
-#ifdef XP_MACOSX
-            </hbox>
-            <hbox>
-#endif
               <button id="viewSecurityDevicesButton"
                       label="&viewSecurityDevices.label;" accesskey="&viewSecurityDevices.accesskey;"
                       oncommand="gAdvancedPane.showSecurityDevices();"
                       preference="security.disable_button.openDeviceManager"/>
             </hbox>
-#ifdef XP_MACOSX
-            </vbox>
-#endif
         </tabpanel>
 
       </tabpanels>
     </tabbox>
   </prefpane>
 
 </overlay>
--- a/browser/components/preferences/in-content/advanced.js
+++ b/browser/components/preferences/in-content/advanced.js
@@ -764,26 +764,16 @@ var gAdvancedPane = {
   showCertificates: function ()
   {
     openDialog("chrome://pippki/content/certManager.xul",
                "mozilla:certmanager",
                "model=yes", null);
   },
 
   /**
-   * Displays a dialog which describes the user's CRLs.
-   */
-  showCRLs: function ()
-  {
-    openDialog("chrome://pippki/content/crlManager.xul",
-               "mozilla:crlmanager",
-               "model=yes", null);
-  },
-
-  /**
    * Displays a dialog in which OCSP preferences can be configured.
    */
   showOCSP: function ()
   {
     openDialog("chrome://mozapps/content/preferences/ocsp.xul",
                "mozilla:crlmanager",
                "model=yes", null);
   },
--- a/browser/components/preferences/in-content/advanced.xul
+++ b/browser/components/preferences/in-content/advanced.xul
@@ -112,19 +112,16 @@
   <!-- Encryption tab -->
   <preference id="security.default_personal_cert"
               name="security.default_personal_cert"
               type="string"/>
 
   <preference id="security.disable_button.openCertManager"
               name="security.disable_button.openCertManager"
               type="bool"/>
-  <preference id="security.OCSP.disable_button.managecrl"
-              name="security.OCSP.disable_button.managecrl"
-              type="bool"/>
   <preference id="security.disable_button.openDeviceManager"
               name="security.disable_button.openDeviceManager"
               type="bool"/>
 </preferences>
 
 #ifdef HAVE_SHELL_SERVICE
   <stringbundle id="bundleShell" src="chrome://browser/locale/shellservice.properties"/>
   <stringbundle id="bundleBrand" src="chrome://branding/locale/brand.properties"/>
@@ -441,20 +438,16 @@
 #ifdef XP_MACOSX
         <vbox>
 #endif
         <hbox>
           <button id="viewCertificatesButton"
                   label="&viewCerts.label;" accesskey="&viewCerts.accesskey;"
                   oncommand="gAdvancedPane.showCertificates();"
                   preference="security.disable_button.openCertManager"/>
-          <button id="viewCRLButton"
-                  label="&viewCRLs.label;" accesskey="&viewCRLs.accesskey;"
-                  oncommand="gAdvancedPane.showCRLs();"
-                  preference="security.OCSP.disable_button.managecrl"/>
           <button id="verificationButton"
                   label="&verify2.label;" accesskey="&verify2.accesskey;"
                   oncommand="gAdvancedPane.showOCSP();"/>
 #ifdef XP_MACOSX
         </hbox>
         <hbox>
 #endif
           <button id="viewSecurityDevicesButton"
--- a/browser/components/test/browser_bug538331.js
+++ b/browser/components/test/browser_bug538331.js
@@ -15,17 +15,17 @@ const XML_EMPTY = "<?xml version=\"1.0\"
                   "\"http://www.mozilla.org/2005/app-update\"></updates>";
 
 const XML_PREFIX =  "<updates xmlns=\"http://www.mozilla.org/2005/app-update\"" +
                     "><update appVersion=\"1.0\" buildID=\"20080811053724\" " +
                     "channel=\"nightly\" displayVersion=\"Version 1.0\" " +
                     "extensionVersion=\"1.0\" installDate=\"1238441400314\" " +
                     "isCompleteUpdate=\"true\" name=\"Update Test 1.0\" " +
                     "serviceURL=\"https://example.com/\" showNeverForVersion=" +
-                    "\"false\" showPrompt=\"false\" showSurvey=\"false\" type=" +
+                    "\"false\" showPrompt=\"false\" type=" +
                     "\"minor\" version=\"version 1.0\" detailsURL=" +
                     "\"http://example.com/\" previousAppVersion=\"1.0\" " +
                     "statusText=\"The Update was successfully installed\" " +
                     "foregroundDownload=\"true\"";
 
 const XML_SUFFIX = "><patch type=\"complete\" URL=\"http://example.com/\" " +
                    "hashFunction=\"MD5\" hashValue=" +
                    "\"6232cd43a1c77e30191c53a329a3f99d\" size=\"775\" " +
--- a/browser/locales/en-US/chrome/browser/aboutDialog.dtd
+++ b/browser/locales/en-US/chrome/browser/aboutDialog.dtd
@@ -61,16 +61,26 @@
 
 <!-- LOCALIZATION NOTE (update.manual.start,update.manual.end): update.manual.start and update.manual.end
      all go into one line and have an anchor in between with text that is the same as the link to a site
      to download the latest version of Firefox (e.g. http://www.firefox.com). As this is all in one line,
      try to make the localized text short (see bug 596813 for screenshots). -->
 <!ENTITY update.manual.start        "Updates available at ">
 <!ENTITY update.manual.end          "">
 
+<!-- LOCALIZATION NOTE (update.unsupported.start,update.unsupported.linkText,update.unsupported.end):
+     update.unsupported.start, update.unsupported.linkText, and
+     update.unsupported.end all go into one line with linkText being wrapped in
+     an anchor that links to a site to provide additional information regarding
+     why the system is no longer supported. As this is all in one line, try to
+     make the localized text short (see bug 843497 for screenshots). -->
+<!ENTITY update.unsupported.start    "You can not perform further updates on this system. ">
+<!ENTITY update.unsupported.linkText "Learn more">
+<!ENTITY update.unsupported.end      "">
+
 <!-- LOCALIZATION NOTE (update.downloading.start,update.downloading.end): update.downloading.start and 
      update.downloading.end all go into one line, with the amount downloaded inserted in between. As this
      is all in one line, try to make the localized text short (see bug 596813 for screenshots). The — is
      the "em dash" (long dash).
      example: Downloading update — 111 KB of 13 MB -->
 <!ENTITY update.downloading.start   "Downloading update — ">
 <!ENTITY update.downloading.end     "">
 
--- a/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
@@ -125,14 +125,12 @@
 <!ENTITY certificateTab.label            "Certificates">
 <!ENTITY certSelection.description       "When a server requests my personal certificate:">
 <!ENTITY certs.auto                      "Select one automatically">
 <!ENTITY certs.auto.accesskey            "l">
 <!ENTITY certs.ask                       "Ask me every time">
 <!ENTITY certs.ask.accesskey             "i">
 <!ENTITY viewCerts.label                 "View Certificates">
 <!ENTITY viewCerts.accesskey             "s">
-<!ENTITY viewCRLs.label                  "Revocation Lists">
-<!ENTITY viewCRLs.accesskey              "R">
 <!ENTITY verify2.label                   "Validation">
 <!ENTITY verify2.accesskey               "V">
 <!ENTITY viewSecurityDevices.label       "Security Devices">
 <!ENTITY viewSecurityDevices.accesskey   "y">
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -334,17 +334,16 @@ DOMInterfaces = {
         'lastElementChild', 'previousElementSibling', 'nextElementSibling',
         'getAttributeNode', 'getAttributeNodeNS', 'querySelector'
     ]
 },
 
 'Event': [
 {
     'nativeType': 'nsDOMEvent',
-    'hasXPConnectImpls': True
 },
 {
     'nativeType': 'JSObject',
     'workers': True,
     'skipGen': True
 }],
 
 'EventListener': [
--- a/dom/workers/URL.cpp
+++ b/dom/workers/URL.cpp
@@ -126,35 +126,50 @@ public:
     MOZ_ASSERT(aBlob);
   }
 
   void
   MainThreadRun()
   {
     AssertIsOnMainThread();
 
+    nsCOMPtr<nsIPrincipal> principal;
+    nsIDocument* doc = nullptr;
+
     nsCOMPtr<nsPIDOMWindow> window = mWorkerPrivate->GetWindow();
-    nsIDocument* doc = window->GetExtantDoc();
-    if (!doc) {
-      SetDOMStringToNull(mURL);
-      return;
+    if (window) {
+      doc = window->GetExtantDoc();
+      if (!doc) {
+        SetDOMStringToNull(mURL);
+        return;
+      }
+
+      principal = doc->NodePrincipal();
+    } else {
+      MOZ_ASSERT(mWorkerPrivate->IsChromeWorker());
+      principal = mWorkerPrivate->GetPrincipal();
     }
 
     nsCString url;
     nsresult rv = nsHostObjectProtocolHandler::AddDataEntry(
         NS_LITERAL_CSTRING(BLOBURI_SCHEME),
-        mBlob, doc->NodePrincipal(), url);
+        mBlob, principal, url);
 
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to add data entry for the blob!");
       SetDOMStringToNull(mURL);
       return;
     }
 
-    doc->RegisterHostObjectUri(url);
+    if (doc) {
+      doc->RegisterHostObjectUri(url);
+    } else {
+      mWorkerPrivate->RegisterHostObjectURI(url);
+    }
+
     mURL = NS_ConvertUTF8toUTF16(url);
   }
 };
 
 // This class revokes an URL on the main thread.
 class RevokeURLRunnable : public URLRunnable
 {
 private:
@@ -167,34 +182,51 @@ public:
     mURL(aURL)
   {}
 
   void
   MainThreadRun()
   {
     AssertIsOnMainThread();
 
+    nsCOMPtr<nsIPrincipal> principal;
+    nsIDocument* doc = nullptr;
+
     nsCOMPtr<nsPIDOMWindow> window = mWorkerPrivate->GetWindow();
-    nsIDocument* doc = window->GetExtantDoc();
-    if (!doc) {
-      return;
+    if (window) {
+      doc = window->GetExtantDoc();
+      if (!doc) {
+        return;
+      }
+
+      principal = doc->NodePrincipal();
+    } else {
+      MOZ_ASSERT(mWorkerPrivate->IsChromeWorker());
+      principal = mWorkerPrivate->GetPrincipal();
     }
 
     NS_ConvertUTF16toUTF8 url(mURL);
 
-    nsIPrincipal* principal =
+    nsIPrincipal* urlPrincipal =
       nsHostObjectProtocolHandler::GetDataEntryPrincipal(url);
 
     bool subsumes;
-    if (principal &&
-        NS_SUCCEEDED(doc->NodePrincipal()->Subsumes(principal, &subsumes)) &&
+    if (urlPrincipal &&
+        NS_SUCCEEDED(principal->Subsumes(urlPrincipal, &subsumes)) &&
         subsumes) {
-      doc->UnregisterHostObjectUri(url);
+      if (doc) {
+        doc->UnregisterHostObjectUri(url);
+      }
+
       nsHostObjectProtocolHandler::RemoveDataEntry(url);
     }
+
+    if (!window) {
+      mWorkerPrivate->UnregisterHostObjectURI(url);
+    }
   }
 };
 
 // static
 void
 URL::CreateObjectURL(const WorkerGlobalObject& aGlobal, JSObject* aBlob,
                      const mozilla::dom::objectURLOptionsWorkers& aOptions,
                      nsString& aResult, mozilla::ErrorResult& aRv)
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -21,16 +21,17 @@
 #include "nsPIDOMWindow.h"
 #include "nsITextToSubURI.h"
 #include "nsITimer.h"
 #include "nsIURI.h"
 #include "nsIURL.h"
 #include "nsIXPConnect.h"
 #include "nsIXPCScriptNotify.h"
 #include "nsPrintfCString.h"
+#include "nsHostObjectProtocolHandler.h"
 
 #include <algorithm>
 #include "jsfriendapi.h"
 #include "jsdbgapi.h"
 #include "jsfriendapi.h"
 #include "jsprf.h"
 #include "js/MemoryMetrics.h"
 #include "mozilla/Attributes.h"
@@ -524,42 +525,51 @@ JSStructuredCloneCallbacks gMainThreadCh
   MainThreadChromeWorkerStructuredCloneCallbacks::Write,
   MainThreadChromeWorkerStructuredCloneCallbacks::Error
 };
 
 class MainThreadReleaseRunnable : public nsRunnable
 {
   nsCOMPtr<nsIThread> mThread;
   nsTArray<nsCOMPtr<nsISupports> > mDoomed;
+  nsTArray<nsCString> mHostObjectURIs;
 
 public:
   MainThreadReleaseRunnable(nsCOMPtr<nsIThread>& aThread,
-                            nsTArray<nsCOMPtr<nsISupports> >& aDoomed)
+                            nsTArray<nsCOMPtr<nsISupports> >& aDoomed,
+                            nsTArray<nsCString>& aHostObjectURIs)
   {
     mThread.swap(aThread);
     mDoomed.SwapElements(aDoomed);
-  }
-
-  MainThreadReleaseRunnable(nsTArray<nsCOMPtr<nsISupports> >& aDoomed)
+    mHostObjectURIs.SwapElements(aHostObjectURIs);
+  }
+
+  MainThreadReleaseRunnable(nsTArray<nsCOMPtr<nsISupports> >& aDoomed,
+                            nsTArray<nsCString>& aHostObjectURIs)
   {
     mDoomed.SwapElements(aDoomed);
+    mHostObjectURIs.SwapElements(aHostObjectURIs);
   }
 
   NS_IMETHOD
   Run()
   {
     mDoomed.Clear();
 
     if (mThread) {
       RuntimeService* runtime = RuntimeService::GetService();
       NS_ASSERTION(runtime, "This should never be null!");
 
       runtime->NoteIdleThread(mThread);
     }
 
+    for (uint32_t i = 0, len = mHostObjectURIs.Length(); i < len; ++i) {
+      nsHostObjectProtocolHandler::RemoveDataEntry(mHostObjectURIs[i]);
+    }
+
     return NS_OK;
   }
 };
 
 class WorkerFinishedRunnable : public WorkerControlRunnable
 {
   WorkerPrivate* mFinishedWorker;
   nsCOMPtr<nsIThread> mThread;
@@ -587,18 +597,21 @@ public:
   }
 
   bool
   WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate)
   {
     nsTArray<nsCOMPtr<nsISupports> > doomed;
     mFinishedWorker->ForgetMainThreadObjects(doomed);
 
+    nsTArray<nsCString> hostObjectURIs;
+    mFinishedWorker->StealHostObjectURIs(hostObjectURIs);
+
     nsRefPtr<MainThreadReleaseRunnable> runnable =
-      new MainThreadReleaseRunnable(mThread, doomed);
+      new MainThreadReleaseRunnable(mThread, doomed, hostObjectURIs);
     if (NS_FAILED(NS_DispatchToMainThread(runnable, NS_DISPATCH_NORMAL))) {
       NS_WARNING("Failed to dispatch, going to leak!");
     }
 
     mFinishedWorker->Finish(aCx);
 
     RuntimeService* runtime = RuntimeService::GetService();
     NS_ASSERTION(runtime, "This should never be null!");
@@ -636,18 +649,21 @@ public:
     RuntimeService* runtime = RuntimeService::GetService();
     NS_ASSERTION(runtime, "This should never be null!");
 
     runtime->UnregisterWorker(cx, mFinishedWorker);
 
     nsTArray<nsCOMPtr<nsISupports> > doomed;
     mFinishedWorker->ForgetMainThreadObjects(doomed);
 
+    nsTArray<nsCString> hostObjectURIs;
+    mFinishedWorker->StealHostObjectURIs(hostObjectURIs);
+
     nsRefPtr<MainThreadReleaseRunnable> runnable =
-      new MainThreadReleaseRunnable(doomed);
+      new MainThreadReleaseRunnable(doomed, hostObjectURIs);
     if (NS_FAILED(NS_DispatchToCurrentThread(runnable))) {
       NS_WARNING("Failed to dispatch, going to leak!");
     }
 
     if (mThread) {
       runtime->NoteIdleThread(mThread);
     }
 
@@ -4290,16 +4306,39 @@ WorkerPrivate::AssertIsOnWorkerThread() 
   }
   else {
     NS_ERROR("Trying to assert thread identity after thread has been "
              "shutdown!");
   }
 }
 #endif
 
+template <class Derived>
+void
+WorkerPrivateParent<Derived>::RegisterHostObjectURI(const nsACString& aURI)
+{
+  AssertIsOnMainThread();
+  mHostObjectURIs.AppendElement(aURI);
+}
+
+template <class Derived>
+void
+WorkerPrivateParent<Derived>::UnregisterHostObjectURI(const nsACString& aURI)
+{
+  AssertIsOnMainThread();
+  mHostObjectURIs.RemoveElement(aURI);
+}
+
+template <class Derived>
+void
+WorkerPrivateParent<Derived>::StealHostObjectURIs(nsTArray<nsCString>& aArray)
+{
+  aArray.SwapElements(mHostObjectURIs);
+}
+
 WorkerCrossThreadDispatcher*
 WorkerPrivate::GetCrossThreadDispatcher()
 {
   mozilla::MutexAutoLock lock(mMutex);
   if (!mCrossThreadDispatcher && mStatus <= Running) {
     mCrossThreadDispatcher = new WorkerCrossThreadDispatcher(this);
   }
   return mCrossThreadDispatcher;
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -272,16 +272,19 @@ private:
   nsCOMPtr<nsIURI> mScriptURI;
   nsCOMPtr<nsIPrincipal> mPrincipal;
   nsCOMPtr<nsIChannel> mChannel;
   nsCOMPtr<nsIContentSecurityPolicy> mCSP;
 
   // Only used for top level workers.
   nsTArray<nsRefPtr<WorkerRunnable> > mQueuedRunnables;
 
+  // Only for ChromeWorkers without window and only touched on the main thread.
+  nsTArray<nsCString> mHostObjectURIs;
+
   // Protected by mMutex.
   JSSettings mJSSettings;
 
   uint64_t mBusyCount;
   Status mParentStatus;
   bool mJSObjectRooted;
   bool mParentSuspended;
   bool mIsChromeWorker;
@@ -610,16 +613,20 @@ public:
   void
   AssertIsOnParentThread() const
   { }
 
   void
   AssertInnerWindowIsCorrect() const
   { }
 #endif
+
+  void RegisterHostObjectURI(const nsACString& aURI);
+  void UnregisterHostObjectURI(const nsACString& aURI);
+  void StealHostObjectURIs(nsTArray<nsCString>& aArray);
 };
 
 class WorkerPrivate : public WorkerPrivateParent<WorkerPrivate>
 {
   friend class WorkerPrivateParent<WorkerPrivate>;
   typedef WorkerPrivateParent<WorkerPrivate> ParentType;
 
   struct TimeoutInfo;
--- a/dom/workers/test/Makefile.in
+++ b/dom/workers/test/Makefile.in
@@ -143,14 +143,17 @@ MOCHITEST_CHROME_FILES = \
   WorkerTest.jsm \
   WorkerTest_worker.js \
   WorkerTest_subworker.js \
   chromeWorker_worker.js \
   chromeWorker_subworker.js \
   test_workersDisabled.xul \
   workersDisabled_worker.js \
   dom_worker_helper.js \
+  test_bug883784.xul \
+  test_bug883784.jsm \
+  url_worker.js \
   $(NULL)
 
 libs:: $(_SUBDIRMOCHITEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)/subdir
 
 include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/test_bug883784.jsm
@@ -0,0 +1,35 @@
+this.EXPORTED_SYMBOLS = ["Test"];
+
+this.Test = {
+  start: function(ok, is, finish) {
+    let worker = new ChromeWorker("url_worker.js");
+    worker.onmessage = function(event) {
+
+      if (event.data.type == 'finish') {
+        finish();
+      } else if (event.data.type == 'status') {
+        ok(event.data.status, event.data.msg);
+      } else if (event.data.type == 'url') {
+        var xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
+                  .createInstance(Components.interfaces.nsIXMLHttpRequest);
+        xhr.open('GET', event.data.url, false);
+        xhr.onreadystatechange = function() {
+          if (xhr.readyState == 4) {
+            ok(true, "Blob readable!");
+          }
+        }
+        xhr.send();
+      }
+    };
+
+    var self = this;
+    worker.onerror = function(event) {
+      is(event.target, worker);
+      ok(false, "Worker had an error: " + event.data);
+      self.worker.terminate();
+      finish();
+    };
+
+    worker.postMessage(true);
+  }
+};
new file mode 100644
--- /dev/null
+++ b/dom/workers/test/test_bug883784.xul
@@ -0,0 +1,36 @@
+<?xml version="1.0"?>
+<!--
+  Any copyright is dedicated to the Public Domain.
+  http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<window title="DOM Worker Threads Test"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        onload="test();">
+
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+  <script type="application/javascript"
+          src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
+  <script type="application/javascript" src="dom_worker_helper.js"/>
+
+  <script type="application/javascript">
+  <![CDATA[
+
+    function test()
+    {
+      waitForWorkerFinish();
+
+      Components.utils.import("chrome://mochitests/content/chrome/dom/workers/test/test_bug883784.jsm");
+      Test.start(ok, is, finish);
+    }
+
+  ]]>
+  </script>
+
+  <body xmlns="http://www.w3.org/1999/xhtml">
+    <p id="display"></p>
+    <div id="content" style="display:none;"></div>
+    <pre id="test"></pre>
+  </body>
+  <label id="test-result"/>
+</window>
--- a/gfx/cairo/README
+++ b/gfx/cairo/README
@@ -201,16 +201,18 @@ handle-multi-path-clip.patch: bug 813124
 win32-gdi-font-cache.patch: Bug 717178, cache GDI font faces to reduce usage of GDI resources
 
 win32-gdi-font-cache-no-HFONT.patch: Bug 717178, don't cache GDI font faces when an HFONT belonging to the caller is passed in
 
 fix-win32-font-assertion.patch: Bug 838617, fix assertion from bug 717178 that was in the wrong place
 
 xlib-flush-glyphs.patch: bug 839745, flush glyphs when necessary
 
+dasharray-zero-gap.patch: bug 885585, ensure strokes get painted when the gaps in a dash array are all zero length
+
 ==== pixman patches ====
 
 pixman-android-cpu-detect.patch: Add CPU detection support for Android, where we can't reliably access /proc/self/auxv.
 
 pixman-rename-and-endian.patch: include cairo-platform.h for renaming of external symbols and endian macros
 
 NOTE: we previously supported ARM assembler on MSVC, this has been removed because of the maintenance burden
 
--- a/gfx/cairo/cairo/src/cairo-quartz-surface.c
+++ b/gfx/cairo/cairo/src/cairo-quartz-surface.c
@@ -2573,29 +2573,43 @@ static cairo_int_status_t
 
     if (style->dash && style->num_dashes) {
 #define STATIC_DASH 32
 	cairo_quartz_float_t sdash[STATIC_DASH];
 	cairo_quartz_float_t *fdash = sdash;
 	unsigned int max_dashes = style->num_dashes;
 	unsigned int k;
 
-	if (style->num_dashes%2)
-	    max_dashes *= 2;
-	if (max_dashes > STATIC_DASH)
-	    fdash = _cairo_malloc_ab (max_dashes, sizeof (cairo_quartz_float_t));
-	if (fdash == NULL)
-	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
-
-	for (k = 0; k < max_dashes; k++)
-	    fdash[k] = (cairo_quartz_float_t) style->dash[k % style->num_dashes];
-
-	CGContextSetLineDash (surface->cgContext, style->dash_offset, fdash, max_dashes);
-	if (fdash != sdash)
-	    free (fdash);
+	bool set_line_dash = false;
+	if (style->num_dashes % 2 == 0) {
+	    for (k = 1; k < max_dashes; k++) {
+		if (style->dash[k]) {
+		    set_line_dash = true;
+		    break;
+		}
+	    }
+	} else
+	    set_line_dash = true;
+
+	if (set_line_dash) {
+	    if (style->num_dashes%2)
+		max_dashes *= 2;
+	    if (max_dashes > STATIC_DASH)
+		fdash = _cairo_malloc_ab (max_dashes, sizeof (cairo_quartz_float_t));
+	    if (fdash == NULL)
+		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
+
+	    for (k = 0; k < max_dashes; k++)
+		fdash[k] = (cairo_quartz_float_t) style->dash[k % style->num_dashes];
+
+	    CGContextSetLineDash (surface->cgContext, style->dash_offset, fdash, max_dashes);
+	    if (fdash != sdash)
+		free (fdash);
+	} else
+	    CGContextSetLineDash (state.context, 0, NULL, 0);
     } else
 	CGContextSetLineDash (state.context, 0, NULL, 0);
 
 
     _cairo_quartz_cairo_path_to_quartz_context (path, state.context);
 
     _cairo_quartz_cairo_matrix_to_quartz (ctm, &strokeTransform);
     CGContextConcatCTM (state.context, strokeTransform);
new file mode 100644
--- /dev/null
+++ b/gfx/cairo/dasharray-zero-gap.patch
@@ -0,0 +1,60 @@
+diff --git a/gfx/cairo/cairo/src/cairo-quartz-surface.c b/gfx/cairo/cairo/src/cairo-quartz-surface.c
+--- a/gfx/cairo/cairo/src/cairo-quartz-surface.c
++++ b/gfx/cairo/cairo/src/cairo-quartz-surface.c
+@@ -2573,29 +2573,43 @@ static cairo_int_status_t
+ 
+     if (style->dash && style->num_dashes) {
+ #define STATIC_DASH 32
+ 	cairo_quartz_float_t sdash[STATIC_DASH];
+ 	cairo_quartz_float_t *fdash = sdash;
+ 	unsigned int max_dashes = style->num_dashes;
+ 	unsigned int k;
+ 
+-	if (style->num_dashes%2)
+-	    max_dashes *= 2;
+-	if (max_dashes > STATIC_DASH)
+-	    fdash = _cairo_malloc_ab (max_dashes, sizeof (cairo_quartz_float_t));
+-	if (fdash == NULL)
+-	    return _cairo_error (CAIRO_STATUS_NO_MEMORY);
+-
+-	for (k = 0; k < max_dashes; k++)
+-	    fdash[k] = (cairo_quartz_float_t) style->dash[k % style->num_dashes];
+-
+-	CGContextSetLineDash (surface->cgContext, style->dash_offset, fdash, max_dashes);
+-	if (fdash != sdash)
+-	    free (fdash);
++	bool set_line_dash = false;
++	if (style->num_dashes % 2 == 0) {
++	    for (k = 1; k < max_dashes; k++) {
++		if (style->dash[k]) {
++		    set_line_dash = true;
++		    break;
++		}
++	    }
++	} else
++	    set_line_dash = true;
++
++	if (set_line_dash) {
++	    if (style->num_dashes%2)
++		max_dashes *= 2;
++	    if (max_dashes > STATIC_DASH)
++		fdash = _cairo_malloc_ab (max_dashes, sizeof (cairo_quartz_float_t));
++	    if (fdash == NULL)
++		return _cairo_error (CAIRO_STATUS_NO_MEMORY);
++
++	    for (k = 0; k < max_dashes; k++)
++		fdash[k] = (cairo_quartz_float_t) style->dash[k % style->num_dashes];
++
++	    CGContextSetLineDash (surface->cgContext, style->dash_offset, fdash, max_dashes);
++	    if (fdash != sdash)
++		free (fdash);
++	} else
++	    CGContextSetLineDash (state.context, 0, NULL, 0);
+     } else
+ 	CGContextSetLineDash (state.context, 0, NULL, 0);
+ 
+ 
+     _cairo_quartz_cairo_path_to_quartz_context (path, state.context);
+ 
+     _cairo_quartz_cairo_matrix_to_quartz (ctm, &strokeTransform);
+     CGContextConcatCTM (state.context, strokeTransform);
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -3708,31 +3708,31 @@ nsDisplayTransform::GetResultingTransfor
     // Correct the translation components for zoom:
     float pixelsPerCSSPx = frame->PresContext()->AppUnitsPerCSSPixel() /
                              aAppUnitsPerPixel;
     transformFromSVGParent.x0 *= pixelsPerCSSPx;
     transformFromSVGParent.y0 *= pixelsPerCSSPx;
     result = result * gfx3DMatrix::From2D(transformFromSVGParent);
   }
 
-  if (nsLayoutUtils::Are3DTransformsEnabled() && aProperties.mChildPerspective > 0.0) {
+  if (aProperties.mChildPerspective > 0.0) {
     gfx3DMatrix perspective;
     perspective._34 =
       -1.0 / NSAppUnitsToFloatPixels(aProperties.mChildPerspective, aAppUnitsPerPixel);
     /* At the point when perspective is applied, we have been translated to the transform origin.
      * The translation to the perspective origin is the difference between these values.
      */
     result = result * nsLayoutUtils::ChangeMatrixBasis(aProperties.mToPerspectiveOrigin - aProperties.mToMozOrigin, perspective);
   }
 
-  gfxPoint3D rounded(hasSVGTransforms ? newOrigin.x : NS_round(newOrigin.x), 
-                     hasSVGTransforms ? newOrigin.y : NS_round(newOrigin.y), 
+  gfxPoint3D rounded(hasSVGTransforms ? newOrigin.x : NS_round(newOrigin.x),
+                     hasSVGTransforms ? newOrigin.y : NS_round(newOrigin.y),
                      0);
-  
-  if (frame && frame->Preserves3D() && nsLayoutUtils::Are3DTransformsEnabled()) {
+
+  if (frame && frame->Preserves3D()) {
       // Include the transform set on our parent
       NS_ASSERTION(frame->GetParent() &&
                    frame->GetParent()->IsTransformed() &&
                    frame->GetParent()->Preserves3DChildren(),
                    "Preserve3D mismatch!");
       FrameTransformProperties props(frame->GetParent(),
                                      aAppUnitsPerPixel,
                                      nullptr);
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -302,31 +302,16 @@ nsLayoutUtils::GetMaximumAnimatedScale(n
   if (result == gfxSize()) {
     return gfxSize(1, 1);
   }
 
   return result;
 }
 
 bool
-nsLayoutUtils::Are3DTransformsEnabled()
-{
-  static bool s3DTransformsEnabled;
-  static bool s3DTransformPrefCached = false;
-
-  if (!s3DTransformPrefCached) {
-    s3DTransformPrefCached = true;
-    Preferences::AddBoolVarCache(&s3DTransformsEnabled,
-                                 "layout.3d-transforms.enabled");
-  }
-
-  return s3DTransformsEnabled;
-}
-
-bool
 nsLayoutUtils::AreAsyncAnimationsEnabled()
 {
   static bool sAreAsyncAnimationsEnabled;
   static bool sAsyncPrefCached = false;
 
   if (!sAsyncPrefCached) {
     sAsyncPrefCached = true;
     Preferences::AddBoolVarCache(&sAreAsyncAnimationsEnabled,
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -1575,21 +1575,16 @@ public:
   /**
    * Returns true if the content node has animations or transitions that can be
    * performed on the compositor.
    */
   static bool HasAnimationsForCompositor(nsIContent* aContent,
                                          nsCSSProperty aProperty);
 
   /**
-   * Checks if CSS 3D transforms are currently enabled.
-   */
-  static bool Are3DTransformsEnabled();
-
-  /**
    * Checks if off-main-thread animations are enabled.
    */
   static bool AreAsyncAnimationsEnabled();
 
   /**
    * Checks if we should warn about animations that can't be async
    */
   static bool IsAnimationLoggingEnabled();
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -304,16 +304,17 @@ fuzzy-if(OSX==10.7,6,2) fuzzy-if(OSX==10
 == text-layout-05.svg text-layout-05-ref.svg
 fuzzy-if(cocoaWidget&&layersGPUAccelerated,1,3) == text-layout-06.svg text-layout-06-ref.svg
 == text-layout-07.svg text-layout-07-ref.svg
 pref(svg.text.css-frames.enabled,true) == text-layout-08.svg text-layout-08-ref.svg
 == text-scale-01.svg text-scale-01-ref.svg
 HTTP(..) == text-scale-02.svg text-scale-02-ref.svg
 HTTP(..) == text-scale-03.svg text-scale-03-ref.svg
 == text-stroke-scaling-01.svg text-stroke-scaling-01-ref.svg
+== stroke-dasharray-01.svg stroke-dasharray-01-ref.svg
 == stroke-dasharray-and-pathLength-01.svg pass.svg
 == stroke-dasharray-and-text-01.svg stroke-dasharray-and-text-01-ref.svg 
 == stroke-linecap-square-w-zero-length-segs-01.svg pass.svg
 == stroke-linecap-square-w-zero-length-segs-02.svg pass.svg
 == textPath-01.svg textPath-01-ref.svg
 == textPath-02.svg pass.svg
 == textPath-03.svg pass.svg
 == text-style-01a.svg text-style-01-ref.svg
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/stroke-dasharray-01-ref.svg
@@ -0,0 +1,13 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg">
+  <title>Reference for a stroke with a dasharray whose gaps add up to 0 still painting</title>
+  <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=885585 -->
+
+  <g fill="none" stroke="black" stroke-width="2">
+    <path d="M 100,100 v 100"/>
+    <path d="M 110,100 h 100"/>
+  </g>
+</svg>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/stroke-dasharray-01.svg
@@ -0,0 +1,13 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg">
+  <title>Test for a stroke with a dasharray whose gaps add up to 0 still painting</title>
+  <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=885585 -->
+
+  <g fill="none" stroke="black" stroke-width="2" stroke-dasharray="10 0">
+    <path d="M 100,100 v 100"/>
+    <path d="M 110,100 h 100"/>
+  </g>
+</svg>
--- a/layout/style/nsCSSParser.cpp
+++ b/layout/style/nsCSSParser.cpp
@@ -667,17 +667,17 @@ protected:
   void SetParsingCompoundProperty(bool aBool) {
     mParsingCompoundProperty = aBool;
   }
   bool IsParsingCompoundProperty(void) const {
     return mParsingCompoundProperty;
   }
 
   /* Functions for transform Parsing */
-  bool ParseSingleTransform(bool aIsPrefixed, nsCSSValue& aValue, bool& aIs3D);
+  bool ParseSingleTransform(bool aIsPrefixed, nsCSSValue& aValue);
   bool ParseFunction(nsCSSKeyword aFunction, const int32_t aAllowedTypes[],
                      int32_t aVariantMaskAll, uint16_t aMinElems,
                      uint16_t aMaxElems, nsCSSValue &aValue);
   bool ParseFunctionInternals(const int32_t aVariantMask[],
                               int32_t aVariantMaskAll,
                               uint16_t aMinElems,
                               uint16_t aMaxElems,
                               InfallibleTArray<nsCSSValue>& aOutput);
@@ -9842,18 +9842,17 @@ CSSParserImpl::ParseFunction(nsCSSKeywor
  * @param aMaxElems [out] The maximum number of elements to read
  * @param aVariantMask [out] The variant mask to use during parsing
  * @return Whether the information was loaded successfully.
  */
 static bool GetFunctionParseInformation(nsCSSKeyword aToken,
                                         bool aIsPrefixed,
                                         uint16_t &aMinElems,
                                         uint16_t &aMaxElems,
-                                        const int32_t *& aVariantMask,
-                                        bool &aIs3D)
+                                        const int32_t *& aVariantMask)
 {
 /* These types represent the common variant masks that will be used to
    * parse out the individual functions.  The order in the enumeration
    * must match the order in which the masks are declared.
    */
   enum { eLengthPercentCalc,
          eLengthCalc,
          eTwoLengthPercentCalcs,
@@ -9898,71 +9897,63 @@ static bool GetFunctionParseInformation(
 
 #ifdef DEBUG
   static const uint8_t kVariantMaskLengths[eNumVariantMasks] =
     {1, 1, 2, 3, 1, 2, 1, 1, 2, 3, 4, 6, 6, 16, 16};
 #endif
 
   int32_t variantIndex = eNumVariantMasks;
 
-  aIs3D = false;
-
   switch (aToken) {
   case eCSSKeyword_translatex:
   case eCSSKeyword_translatey:
     /* Exactly one length or percent. */
     variantIndex = eLengthPercentCalc;
     aMinElems = 1U;
     aMaxElems = 1U;
     break;
   case eCSSKeyword_translatez:
     /* Exactly one length */
     variantIndex = eLengthCalc;
     aMinElems = 1U;
     aMaxElems = 1U;
-    aIs3D = true;
     break;
   case eCSSKeyword_translate3d:
     /* Exactly two lengthds or percents and a number */
     variantIndex = eTwoLengthPercentCalcsOneLengthCalc;
     aMinElems = 3U;
     aMaxElems = 3U;
-    aIs3D = true;
     break;
   case eCSSKeyword_scalez:
-    aIs3D = true;
   case eCSSKeyword_scalex:
   case eCSSKeyword_scaley:
     /* Exactly one scale factor. */
     variantIndex = eNumber;
     aMinElems = 1U;
     aMaxElems = 1U;
     break;
   case eCSSKeyword_scale3d:
     /* Exactly three scale factors. */
     variantIndex = eThreeNumbers;
     aMinElems = 3U;
     aMaxElems = 3U;
-    aIs3D = true;
     break;
   case eCSSKeyword_rotatex:
   case eCSSKeyword_rotatey:
-    aIs3D = true;
   case eCSSKeyword_rotate:
   case eCSSKeyword_rotatez:
     /* Exactly one angle. */
     variantIndex = eAngle;
     aMinElems = 1U;
     aMaxElems = 1U;
     break;
   case eCSSKeyword_rotate3d:
     variantIndex = eThreeNumbersOneAngle;
     aMinElems = 4U;
     aMaxElems = 4U;
-    aIs3D = true;
     break;
   case eCSSKeyword_translate:
     /* One or two lengths or percents. */
     variantIndex = eTwoLengthPercentCalcs;
     aMinElems = 1U;
     aMaxElems = 2U;
     break;
   case eCSSKeyword_skew:
@@ -9995,24 +9986,22 @@ static bool GetFunctionParseInformation(
     aMinElems = 6U;
     aMaxElems = 6U;
     break;
   case eCSSKeyword_matrix3d:
     /* 16 matrix values, all numbers */
     variantIndex = aIsPrefixed ? eMatrix3dPrefixed : eMatrix3d;
     aMinElems = 16U;
     aMaxElems = 16U;
-    aIs3D = true;
     break;
   case eCSSKeyword_perspective:
     /* Exactly one scale number. */
     variantIndex = ePositiveLength;
     aMinElems = 1U;
     aMaxElems = 1U;
-    aIs3D = true;
     break;
   default:
     /* Oh dear, we didn't match.  Report an error. */
     return false;
   }
 
   NS_ASSERTION(aMinElems > 0, "Didn't update minimum elements!");
   NS_ASSERTION(aMaxElems > 0, "Didn't update maximum elements!");
@@ -10029,33 +10018,32 @@ static bool GetFunctionParseInformation(
 
   return true;
 }
 
 /* Reads a single transform function from the tokenizer stream, reporting an
  * error if something goes wrong.
  */
 bool
-CSSParserImpl::ParseSingleTransform(bool aIsPrefixed,
-                                    nsCSSValue& aValue, bool& aIs3D)
+CSSParserImpl::ParseSingleTransform(bool aIsPrefixed, nsCSSValue& aValue)
 {
   if (!GetToken(true))
     return false;
 
   if (mToken.mType != eCSSToken_Function) {
     UngetToken();
     return false;
   }
 
   const int32_t* variantMask;
   uint16_t minElems, maxElems;
   nsCSSKeyword keyword = nsCSSKeywords::LookupKeyword(mToken.mIdent);
 
   if (!GetFunctionParseInformation(keyword, aIsPrefixed,
-                                   minElems, maxElems, variantMask, aIs3D))
+                                   minElems, maxElems, variantMask))
     return false;
 
   return ParseFunction(keyword, variantMask, 0, minElems, maxElems, aValue);
 }
 
 /* Parses a transform property list by continuously reading in properties
  * and constructing a matrix from it.
  */
@@ -10065,21 +10053,17 @@ bool CSSParserImpl::ParseTransform(bool 
   if (ParseVariant(value, VARIANT_INHERIT | VARIANT_NONE, nullptr)) {
     // 'inherit', 'initial', and 'none' must be alone
     if (!ExpectEndProperty()) {
       return false;
     }
   } else {
     nsCSSValueList* cur = value.SetListValue();
     for (;;) {
-      bool is3D;
-      if (!ParseSingleTransform(aIsPrefixed, cur->mValue, is3D)) {
-        return false;
-      }
-      if (is3D && !nsLayoutUtils::Are3DTransformsEnabled()) {
+      if (!ParseSingleTransform(aIsPrefixed, cur->mValue)) {
         return false;
       }
       if (CheckEndProperty()) {
         break;
       }
       cur->mNext = new nsCSSValueList;
       cur = cur->mNext;
     }
@@ -10111,19 +10095,17 @@ bool CSSParserImpl::ParseTransformOrigin
                       "inherit/initial only half?");
     AppendValue(prop, position.mXValue);
   } else {
     nsCSSValue value;
     if (aPerspective) {
       value.SetPairValue(position.mXValue, position.mYValue);
     } else {
       nsCSSValue depth;
-      if (!nsLayoutUtils::Are3DTransformsEnabled() ||
-          // only try parsing if 3-D transforms are enabled
-          !ParseVariant(depth, VARIANT_LENGTH | VARIANT_CALC, nullptr)) {
+      if (!ParseVariant(depth, VARIANT_LENGTH | VARIANT_CALC, nullptr)) {
         depth.SetFloatValue(0.0f, eCSSUnit_Pixel);
       }
       value.SetTripletValue(position.mXValue, position.mYValue, depth);
     }
 
     AppendValue(prop, value);
   }
   return true;
--- a/layout/style/test/property_database.js
+++ b/layout/style/test/property_database.js
@@ -1103,54 +1103,52 @@ var gCSSProperties = {
 			"translate(3%, 5px)", "translate(5px, 3%)",
 			"matrix(1, 2, 3, 4, 5, 6)",
 			/* valid calc() values */
 			"translatex(calc(5px + 10%))",
 			"translatey(calc(0.25 * 5px + 10% / 3))",
 			"translate(calc(5px - 10% * 3))",
 			"translate(calc(5px - 3 * 10%), 50px)",
 			"translate(-50px, calc(5px - 10% * 3))",
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
 			"translatez(1px)", "translatez(4em)", "translatez(-4px)",
 			"translatez(0px)", "translatez(2px) translatez(5px)",
 			"translate3d(3px, 4px, 5px)", "translate3d(2em, 3px, 1em)",
 			"translatex(2px) translate3d(4px, 5px, 6px) translatey(1px)",
 			"scale3d(4, 4, 4)", "scale3d(-2, 3, -7)", "scalez(4)",
 			"scalez(-6)", "rotate3d(2, 3, 4, 45deg)",
 			"rotate3d(-3, 7, 0, 12rad)", "rotatex(15deg)", "rotatey(-12grad)",
 			"rotatez(72rad)", "rotatex(0.125turn)", "perspective(1000px)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)",
-		] : []),
+		],
 		invalid_values: ["1px", "#0000ff", "red", "auto",
 			"translatex(1)", "translatey(1)", "translate(2)",
 			"translate(-3, -4)",
 			"translatex(1px 1px)", "translatex(translatex(1px))",
 			"translatex(#0000ff)", "translatex(red)", "translatey()",
 			"matrix(1px, 2px, 3px, 4px, 5px, 6px)", "scale(150%)",
 			"skewx(red)", "matrix(1%, 0, 0, 0, 0px, 0px)",
 			"matrix(0, 1%, 2, 3, 4px,5px)", "matrix(0, 1, 2%, 3, 4px, 5px)",
 			"matrix(0, 1, 2, 3%, 4%, 5%)", "matrix(1, 2, 3, 4, 5px, 6%)",
 			"matrix(1, 2, 3, 4, 5%, 6px)", "matrix(1, 2, 3, 4, 5%, 6%)",
 			"matrix(1, 2, 3, 4, 5px, 6em)",
 			/* invalid calc() values */
 			"translatey(-moz-min(5px,10%))",
 			"translatex(-moz-max(5px,10%))",
 			"translate(10px, calc(min(5px,10%)))",
 			"translate(calc(max(5px,10%)), 10%)",
-			"matrix(1, 0, 0, 1, max(5px * 3), calc(10% - 3px))"
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
+			"matrix(1, 0, 0, 1, max(5px * 3), calc(10% - 3px))",
 			"perspective(0px)", "perspective(-10px)", "matrix3d(dinosaur)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15%, 16)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16px)",
 			"rotatey(words)", "rotatex(7)", "translate3d(3px, 4px, 1px, 7px)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13px, 14em, 15px, 16)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 20%, 10%, 15, 16)"
-		] : [])
+		],
 	},
 	"transform-origin": {
 		domProp: "transformOrigin",
 		inherited: false,
 		type: CSS_TYPE_LONGHAND,
 		/* no subproperties */
 		prerequisites: { "width": "10px", "height": "10px", "display": "block"},
 		initial_values: [ "50% 50%", "center", "center center" ],
@@ -1164,21 +1162,20 @@ var gCSSProperties = {
 			"calc(20px) 10px",
 			"10px calc(20px)",
 			"calc(20px) 25%",
 			"25% calc(20px)",
 			"calc(20px) calc(20px)",
 			"calc(20px + 1em) calc(20px / 2)",
 			"calc(20px + 50%) calc(50% - 10px)",
 			"calc(-20px) calc(-50%)",
-			"calc(-20%) calc(-50%)"
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
+			"calc(-20%) calc(-50%)",
 			"6px 5px 5px",
 			"top center 10px"
-		] : []),
+		],
 		invalid_values: ["red", "auto", "none", "0.5 0.5", "40px #0000ff",
 						 "border", "center red", "right diagonal",
 						 "#00ffff bottom"]
 	},
 	"perspective-origin": {
 		domProp: "perspectiveOrigin",
 		inherited: false,
 		type: CSS_TYPE_LONGHAND,
@@ -3735,53 +3732,51 @@ var gCSSProperties = {
 			"translate(calc(5px - 3 * 10%), 50px)",
 			"translate(-50px, calc(5px - 10% * 3))",
 			/* valid only when prefixed */
 			"matrix(1, 2, 3, 4, 5px, 6%)",
 			"matrix(1, 2, 3, 4, 5%, 6px)",
 			"matrix(1, 2, 3, 4, 5%, 6%)",
 			"matrix(1, 2, 3, 4, 5px, 6em)",
 			"matrix(1, 0, 0, 1, calc(5px * 3), calc(10% - 3px))",
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
 			"translatez(1px)", "translatez(4em)", "translatez(-4px)",
 			"translatez(0px)", "translatez(2px) translatez(5px)",
 			"translate3d(3px, 4px, 5px)", "translate3d(2em, 3px, 1em)",
 			"translatex(2px) translate3d(4px, 5px, 6px) translatey(1px)",
 			"scale3d(4, 4, 4)", "scale3d(-2, 3, -7)", "scalez(4)",
 			"scalez(-6)", "rotate3d(2, 3, 4, 45deg)",
 			"rotate3d(-3, 7, 0, 12rad)", "rotatex(15deg)", "rotatey(-12grad)",
 			"rotatez(72rad)", "rotatex(0.125turn)", "perspective(1000px)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)",
 			/* valid only when prefixed */
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13px, 14em, 15px, 16)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 20%, 10%, 15, 16)",
-		] : []),
+		],
 		invalid_values: ["1px", "#0000ff", "red", "auto",
 			"translatex(1)", "translatey(1)", "translate(2)",
 			"translate(-3, -4)",
 			"translatex(1px 1px)", "translatex(translatex(1px))",
 			"translatex(#0000ff)", "translatex(red)", "translatey()",
 			"matrix(1px, 2px, 3px, 4px, 5px, 6px)", "scale(150%)",
 			"skewx(red)", "matrix(1%, 0, 0, 0, 0px, 0px)",
 			"matrix(0, 1%, 2, 3, 4px,5px)", "matrix(0, 1, 2%, 3, 4px, 5px)",
 			"matrix(0, 1, 2, 3%, 4%, 5%)",
 			/* invalid calc() values */
 			"translatey(-moz-min(5px,10%))",
 			"translatex(-moz-max(5px,10%))",
 			"translate(10px, calc(min(5px,10%)))",
 			"translate(calc(max(5px,10%)), 10%)",
-			"matrix(1, 0, 0, 1, max(5px * 3), calc(10% - 3px))"
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
+			"matrix(1, 0, 0, 1, max(5px * 3), calc(10% - 3px))",
 			"perspective(0px)", "perspective(-10px)", "matrix3d(dinosaur)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15%, 16)",
 			"matrix3d(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16px)",
 			"rotatey(words)", "rotatex(7)", "translate3d(3px, 4px, 1px, 7px)",
-		] : [])
+		],
 	},
 	"-moz-transform-origin": {
 		domProp: "MozTransformOrigin",
 		inherited: false,
 		type: CSS_TYPE_SHORTHAND_AND_LONGHAND,
 		alias_for: "transform-origin",
 		subproperties: [ "transform-origin" ],
 		prerequisites: { "width": "10px", "height": "10px", "display": "block"},
@@ -3796,21 +3791,20 @@ var gCSSProperties = {
 			"calc(20px) 10px",
 			"10px calc(20px)",
 			"calc(20px) 25%",
 			"25% calc(20px)",
 			"calc(20px) calc(20px)",
 			"calc(20px + 1em) calc(20px / 2)",
 			"calc(20px + 50%) calc(50% - 10px)",
 			"calc(-20px) calc(-50%)",
-			"calc(-20%) calc(-50%)"
-		].concat(SpecialPowers.getBoolPref("layout.3d-transforms.enabled") ? [
+			"calc(-20%) calc(-50%)",
 			"6px 5px 5px",
 			"top center 10px"
-		] : []),
+		],
 		invalid_values: ["red", "auto", "none", "0.5 0.5", "40px #0000ff",
 						 "border", "center red", "right diagonal",
 						 "#00ffff bottom"]
 	},
 	"-moz-perspective-origin": {
 		domProp: "MozPerspectiveOrigin",
 		inherited: false,
 		type: CSS_TYPE_SHORTHAND_AND_LONGHAND,
--- a/layout/style/test/test_transitions_per_property.html
+++ b/layout/style/test/test_transitions_per_property.html
@@ -290,74 +290,65 @@ var transformTests = [
     expected: c_rot_15 },
   { start: 'none', end: c_rot_60,
     expected: c_rot_15 },
   { start: 'none', end: 'rotate(360deg)',
     expected_uncomputed: 'rotate(90deg)',
     expected: computeMatrix('rotate(90deg)') },
   { start: 'none', end: 'rotatez(360deg)',
     expected_uncomputed: 'rotate(90deg)',
-    expected: computeMatrix('rotate(90deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotate(90deg)') },
   { start: 'none', end: 'rotate(720deg)',
     expected_uncomputed: 'rotate(180deg)',
     expected: computeMatrix('rotate(180deg)') },
   { start: 'none', end: 'rotate(720deg)',
     expected_uncomputed: 'rotatez(180deg)',
-    expected: computeMatrix('rotate(180deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotate(180deg)') },
   { start: 'none', end: 'rotate(1080deg)',
     expected_uncomputed: 'rotate(270deg)',
     expected: computeMatrix('rotate(270deg)') },
   { start: 'none', end: 'rotate(1080deg)',
     expected_uncomputed: 'rotate(270deg)',
-    expected: computeMatrix('rotatez(270deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotatez(270deg)') },
   { start: 'none', end: 'rotate(1440deg)',
     expected_uncomputed: 'rotate(360deg)',
     expected: computeMatrix('scale(1)'),
     round_error_ok: true },
   { start: 'none', end: 'rotatey(60deg)',
     expected_uncomputed: 'rotatey(15deg)',
-    expected: computeMatrix('rotatey(15deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotatey(15deg)') },
   { start: 'none', end: 'rotatey(720deg)',
     expected_uncomputed: 'rotatey(180deg)',
-    expected: computeMatrix('rotatey(180deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotatey(180deg)') },
   { start: 'none', end: 'rotatex(60deg)',
     expected_uncomputed: 'rotatex(15deg)',
-    expected: computeMatrix('rotatex(15deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotatex(15deg)') },
   { start: 'none', end: 'rotatex(720deg)',
     expected_uncomputed: 'rotatex(180deg)',
-    expected: computeMatrix('rotatex(180deg)'),
-    requires_3d: true },
+    expected: computeMatrix('rotatex(180deg)') },
 
   // translate
   { start: 'translate(20px)', end: 'none',
     expected_uncomputed: 'translate(15px)',
     expected: 'matrix(1, 0, 0, 1, 15, 0)' },
   { start: 'translate(20px, 12px)', end: 'none',
     expected_uncomputed: 'translate(15px, 9px)',
     expected: 'matrix(1, 0, 0, 1, 15, 9)' },
   { start: 'translateX(-20px)', end: 'none',
     expected_uncomputed: 'translateX(-15px)',
     expected: 'matrix(1, 0, 0, 1, -15, 0)' },
   { start: 'translateY(-40px)', end: 'none',
     expected_uncomputed: 'translateY(-30px)',
     expected: 'matrix(1, 0, 0, 1, 0, -30)' },
   { start: 'translateZ(40px)', end: 'none',
     expected_uncomputed: 'translateZ(30px)',
-    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 30, 1)',
-    requires_3d: true },
+    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 30, 1)' },
   { start: 'none', end: 'translate3D(40px, 60px, -40px)',
     expected_uncomputed: 'translate3D(10px, 15px, -10px)',
-    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 15, -10, 1)',
-    requires_3d: true },
+    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 15, -10, 1)' },
   // percentages are relative to 300px (width) and 50px (height)
   // per the prerequisites in property_database.js
   { start: 'translate(20%)', end: 'none',
     expected_uncomputed: 'translate(15%)',
     expected: 'matrix(1, 0, 0, 1, 45, 0)',
     round_error_ok: true },
   { start: 'translate(20%, 12%)', end: 'none',
     expected_uncomputed: 'translate(15%, 9%)',
@@ -422,22 +413,20 @@ var transformTests = [
   { start: 'scaleX(3)', end: 'none',
     expected_uncomputed: 'scaleX(2.5)',
     expected: 'matrix(2.5, 0, 0, 1, 0, 0)' },
   { start: 'scaleY(5)', end: 'none',
     expected_uncomputed: 'scaleY(4)',
     expected: 'matrix(1, 0, 0, 4, 0, 0)' },
   { start: 'scaleZ(5)', end: 'none',
     expected_uncomputed: 'scaleZ(4)',
-    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1)',
-    requires_3d: true },
+    expected: 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1)' },
   { start: 'none', end: 'scale3D(5, 5, 5)',
     expected_uncomputed: 'scale3D(2, 2, 2)',
-    expected: 'matrix3d(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)',
-    requires_3d: true },
+    expected: 'matrix3d(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1)' },
 
   // skew
   { start: 'skewX(45deg)', end: 'none',
     expected_uncomputed: 'skewX(33.75deg)' },
   { start: 'skewY(45deg)', end: 'none',
     expected_uncomputed: 'skewY(33.75deg)' },
   { start: 'skew(45deg)', end: 'none',
     expected_uncomputed: 'skew(33.75deg)' },
@@ -692,21 +681,16 @@ for (prop in supported_properties) {
 div.style.removeProperty("transition");
 
 function get_distance(prop, v1, v2)
 {
   return SpecialPowers.DOMWindowUtils
            .computeAnimationDistance(div, prop, v1, v2);
 }
 
-function transform3D_enabled()
-{
-  return SpecialPowers.getBoolPref("layout.3d-transforms.enabled");
-}
-
 function check_distance(prop, start, quarter, end)
 {
   var sq = get_distance(prop, start, quarter);
   var se = get_distance(prop, start, end);
   var qe = get_distance(prop, quarter, end);
 
   ok(Math.abs((sq * 4 - se) / se) < 0.0001, "property '" + prop + "': distance " + sq + " from start '" + start + "' to quarter '" + quarter + "' should be quarter distance " + se + " from start '" + start + "' to end '" + end + "'");
   ok(Math.abs((qe * 4 - se * 3) / se) < 0.0001, "property '" + prop + "': distance " + qe + " from quarter '" + quarter + "' to end '" + end + "' should be three quarters distance " + se + " from start '" + start + "' to end '" + end + "'");
@@ -1650,19 +1634,16 @@ function test_transform_transition(prop)
       } else {
         test.expected = computeMatrix(v);
       }
     }
   }
 
   for (var i in transformTests) {
     var test = transformTests[i];
-    if (test.requires_3d && !transform3D_enabled()) {
-      continue;
-    }
     div.style.setProperty("transition-property", "none", "");
     div.style.setProperty(prop, test.start, "");
     cs.getPropertyValue(prop);
     div.style.setProperty("transition-property", prop, "");
     div.style.setProperty(prop, test.end, "");
     var actual = cs.getPropertyValue(prop);
     if (!test.round_error_ok || actual == test.expected) {
       // In most cases, we'll get an exact match, but in some cases
@@ -1703,22 +1684,16 @@ function nextAsyncTransformTest()
   var test = transformTests[transformTestIndex];
 
   if (transformTestIndex >= transformTests.length) {
     transformDiv.style.removeProperty("transition");
     SimpleTest.finish();
     return;
   }
 
-  if (test.requires_3d && !transform3D_enabled()) {
-    transformTestIndex++;
-    window.requestAnimationFrame(nextAsyncTransformTest);
-    return;
-  }
-
   transformDiv.style.setProperty("transition-property", "none", "");
   transformDiv.style.setProperty("transform", test.start, "");
   transformCs.getPropertyValue("transform");
   transformDiv.style.setProperty("transition-property", "transform", "");
   transformDiv.style.setProperty("transform", test.end, "");
   transformCs.getPropertyValue("transform");
 
   window.requestAnimationFrame(checkAsyncTransformTest);
--- a/media/webrtc/trunk/webrtc/system_wrappers/source/thread_posix.cc
+++ b/media/webrtc/trunk/webrtc/system_wrappers/source/thread_posix.cc
@@ -202,21 +202,31 @@ ThreadPosix::~ThreadPosix() {
 bool ThreadPosix::Start(unsigned int& thread_id)
 {
   if (!run_function_) {
     return false;
   }
   int result = pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_DETACHED);
   // Set the stack stack size to 1M.
   result |= pthread_attr_setstacksize(&attr_, 1024 * 1024);
+#if 0
+// Temporarily remove the attempt to set this to real-time scheduling.
+//
+// See: https://code.google.com/p/webrtc/issues/detail?id=1956
+//
+// To be removed when upstream is fixed.
 #ifdef WEBRTC_THREAD_RR
   const int policy = SCHED_RR;
 #else
   const int policy = SCHED_FIFO;
 #endif
+#else
+  const int policy = SCHED_OTHER;
+#endif
+
   event_->Reset();
   // If pthread_create was successful, a thread was created and is running.
   // Don't return false if it was successful since if there are any other
   // failures the state will be: thread was started but not configured as
   // asked for. However, the caller of this API will assume that a false
   // return value means that the thread never started.
   result |= pthread_create(&thread_, &attr_, &StartThread, this);
   if (result != 0) {
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/AlignRightLinkPreference.java
@@ -0,0 +1,22 @@
+/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+package org.mozilla.gecko;
+
+import android.content.Context;
+import android.util.AttributeSet;
+
+class AlignRightLinkPreference extends LinkPreference {
+
+    public AlignRightLinkPreference(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        setLayoutResource(R.layout.preference_rightalign_icon);
+    }
+
+    public AlignRightLinkPreference(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+        setLayoutResource(R.layout.preference_rightalign_icon);
+    }
+}
--- a/mobile/android/base/GeckoPreferences.java
+++ b/mobile/android/base/GeckoPreferences.java
@@ -10,18 +10,20 @@ import org.mozilla.gecko.background.comm
 import org.mozilla.gecko.background.healthreport.HealthReportConstants;
 import org.mozilla.gecko.util.GeckoEventListener;
 import org.mozilla.gecko.GeckoPreferenceFragment;
 import org.mozilla.gecko.util.ThreadUtils;
 
 import org.json.JSONArray;
 import org.json.JSONObject;
 
+import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Dialog;
+import android.app.Fragment;
 import android.app.NotificationManager;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.os.Build;
 import android.os.Bundle;
 import android.preference.CheckBoxPreference;
@@ -66,16 +68,19 @@ public class GeckoPreferences
     private static String PREFS_ANNOUNCEMENTS_ENABLED = NON_PREF_PREFIX + "privacy.announcements.enabled";
     private static String PREFS_DATA_REPORTING_PREFERENCES = NON_PREF_PREFIX + "datareporting.preferences";
     private static String PREFS_TELEMETRY_ENABLED = "datareporting.telemetry.enabled";
     private static String PREFS_CRASHREPORTER_ENABLED = "datareporting.crashreporter.submitEnabled";
     private static String PREFS_MENU_CHAR_ENCODING = "browser.menu.showCharacterEncoding";
     private static String PREFS_MP_ENABLED = "privacy.masterpassword.enabled";
     private static String PREFS_UPDATER_AUTODOWNLOAD = "app.update.autodownload";
     private static String PREFS_GEO_REPORTING = "app.geo.reportdata";
+    private static String PREFS_HEALTHREPORT_LINK = NON_PREF_PREFIX + "healthreport.link";
+
+    private static int REQUEST_CODE_PREF_SCREEN = 5;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         // For fragment-capable devices, display the default fragment if no explicit fragment to show.
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB &&
             !getIntent().hasExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT)) {
             setupTopLevelFragmentIntent();
         }
@@ -173,16 +178,47 @@ public class GeckoPreferences
         super.onResume();
 
         if (getApplication() instanceof GeckoApplication) {
             ((GeckoApplication) getApplication()).onActivityResume(this);
         }
     }
 
     @Override
+    public void startActivity(Intent intent) {
+        // For settings, we want to be able to pass results up the chain
+        // of preference screens so Settings can behave as a single unit.
+        // Specifically, when we open a link, we want to back out of all
+        // the settings screens.
+        // We need to start nested PreferenceScreens withStartActivityForResult().
+        // Android doesn't let us do that (see Preference.onClick), so we're overriding here.
+        startActivityForResult(intent, REQUEST_CODE_PREF_SCREEN);
+    }
+
+    @Override
+    public void startWithFragment(String fragmentName, Bundle args,
+            Fragment resultTo, int resultRequestCode, int titleRes, int shortTitleRes) {
+        // Overriding because we want to use startActivityForResult for Fragment intents.
+        Intent intent = onBuildStartFragmentIntent(fragmentName, args, titleRes, shortTitleRes);
+        if (resultTo == null) {
+            startActivityForResult(intent, REQUEST_CODE_PREF_SCREEN);
+        } else {
+            resultTo.startActivityForResult(intent, resultRequestCode);
+        }
+    }
+
+    @Override
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        if (REQUEST_CODE_PREF_SCREEN == requestCode && Activity.RESULT_CANCELED == resultCode) {
+            setResult(Activity.RESULT_CANCELED);
+            finish();
+        }
+    }
+
+    @Override
     public void handleMessage(String event, JSONObject message) {
         try {
             if (event.equals("Sanitize:Finished")) {
                 boolean success = message.getBoolean("success");
                 final int stringRes = success ? R.string.private_data_success : R.string.private_data_fail;
                 final Context context = this;
                 ThreadUtils.postToUiThread(new Runnable () {
                     @Override
@@ -230,29 +266,34 @@ public class GeckoPreferences
                         preferences.removePreference(pref);
                         i--;
                         continue;
                     }
                 }
                 setupPreferences((PreferenceGroup) pref, prefs);
             } else {
                 pref.setOnPreferenceChangeListener(this);
-                if (PREFS_UPDATER_AUTODOWNLOAD.equals(key) && !AppConstants.MOZ_UPDATER) {
+                if (!AppConstants.MOZ_UPDATER &&
+                    PREFS_UPDATER_AUTODOWNLOAD.equals(key)) {
                     preferences.removePreference(pref);
                     i--;
                     continue;
-                } else if (PREFS_TELEMETRY_ENABLED.equals(key) && !AppConstants.MOZ_TELEMETRY_REPORTING) {
+                } else if (!AppConstants.MOZ_TELEMETRY_REPORTING &&
+                           PREFS_TELEMETRY_ENABLED.equals(key)) {
                     preferences.removePreference(pref);
                     i--;
                     continue;
-                } else if (PREFS_HEALTHREPORT_UPLOAD_ENABLED.equals(key) && !AppConstants.MOZ_SERVICES_HEALTHREPORT) {
+                } else if (!AppConstants.MOZ_SERVICES_HEALTHREPORT &&
+                           (PREFS_HEALTHREPORT_UPLOAD_ENABLED.equals(key) ||
+                            PREFS_HEALTHREPORT_LINK.equals(key))) {
                     preferences.removePreference(pref);
                     i--;
                     continue;
-                } else if (PREFS_CRASHREPORTER_ENABLED.equals(key) && !AppConstants.MOZ_CRASHREPORTER) {
+                } else if (!AppConstants.MOZ_CRASHREPORTER &&
+                           PREFS_CRASHREPORTER_ENABLED.equals(key)) {
                     preferences.removePreference(pref);
                     i--;
                     continue;
                 }
 
                 // Some Preference UI elements are not actually preferences,
                 // but they require a key to work correctly. For example,
                 // "Clear private data" requires a key for its state to be
@@ -408,16 +449,17 @@ public class GeckoPreferences
             PrefsHelper.setPref(prefName, newValue);
         }
         if (preference instanceof ListPreference) {
             // We need to find the entry for the new value
             int newIndex = ((ListPreference) preference).findIndexOfValue((String) newValue);
             CharSequence newEntry = ((ListPreference) preference).getEntries()[newIndex];
             ((ListPreference) preference).setSummary(newEntry);
         } else if (preference instanceof LinkPreference) {
+            setResult(Activity.RESULT_CANCELED);
             finish();
         } else if (preference instanceof FontSizePreference) {
             final FontSizePreference fontSizePref = (FontSizePreference) preference;
             fontSizePref.setSummary(fontSizePref.getSavedFontSizeName());
         }
         return true;
     }
 
--- a/mobile/android/base/Makefile.in
+++ b/mobile/android/base/Makefile.in
@@ -47,16 +47,17 @@ UTIL_JAVA_FILES := \
 AIDL_AUTOGEN_FILES = \
   braille/com/googlecode/eyesfree/braille/selfbraille/ISelfBrailleService.java \
   $(NULL)
 
 FENNEC_JAVA_FILES = \
   ANRReporter.java \
   ActivityHandlerHelper.java \
   AlertNotification.java \
+  AlignRightLinkPreference.java \
   AllCapsTextView.java \
   AndroidImport.java \
   AndroidImportPreference.java \
   AnimatedHeightLayout.java \
   AppNotificationClient.java \
   AwesomeBar.java \
   AwesomebarResultHandler.java \
   AwesomeBarTabs.java \
@@ -468,16 +469,17 @@ RES_LAYOUT = \
   res/layout/launch_app_list.xml \
   res/layout/launch_app_listitem.xml \
   res/layout/menu_action_bar.xml \
   res/layout/menu_item_action_view.xml \
   res/layout/menu_popup.xml \
   res/layout/notification_icon_text.xml \
   res/layout/notification_progress.xml \
   res/layout/notification_progress_text.xml \
+  res/layout/preference_rightalign_icon.xml \
   res/layout/site_setting_item.xml \
   res/layout/site_setting_title.xml \
   res/layout/setup_screen.xml \
   res/layout/shared_ui_components.xml \
   res/layout/site_identity.xml \
   res/layout/remote_tabs_child.xml \
   res/layout/remote_tabs_group.xml \
   res/layout/tabs_panel.xml \
--- a/mobile/android/base/locales/en-US/android_strings.dtd
+++ b/mobile/android/base/locales/en-US/android_strings.dtd
@@ -142,17 +142,18 @@ size. -->
 
 <!-- Localization note (datareporting_fhr_title, datareporting_fhr_summary,
      reporting_telemetry_title, datareporting_telemetry_summary,
      datareporting_crashreporter_summary) : These match the strings in
      en-US/chrome/browser/preferences/advanced.dtd (healthReportSection.label,
      healthReportDesc.label, telemetrySection.label, telemetryDesc.label,
      crashReporterDesc.label). -->
 <!ENTITY datareporting_fhr_title "&brandShortName; Health Report">
-<!ENTITY datareporting_fhr_summary "Helps you understand your browser performance and shares data with &vendorShortName; about your browser health">
+<!ENTITY datareporting_fhr_summary "Shares data with &vendorShortName; about your browser health and helps you understand your browser performance">
+<!ENTITY datareporting_abouthr_title "View my Health Report">
 <!ENTITY datareporting_telemetry_title "Telemetry">
 <!ENTITY datareporting_telemetry_summary "Shares performance, usage, hardware and customization data about your browser with &vendorShortName; to help us make &brandShortName; better">
 <!ENTITY datareporting_crashreporter_summary "&brandShortName; submits crash reports to help &vendorShortName; make your browser more stable and secure">
 <!-- Localization note (datareporting_crashreporter_title_short) : This string matches
      (crashReporterSection.label) in en-US/chrome/browser/preferences/advanced.dtd.-->
 <!ENTITY datareporting_crashreporter_title_short "Crash Reporter">
 <!ENTITY datareporting_wifi_title "&vendorShortName; location services">
 <!ENTITY datareporting_wifi_summary "Help improve geolocation services for the Open Web by letting &brandShortName; collect and send anonymous cellular tower data">
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/resources/layout/preference_rightalign_icon.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+   - License, v. 2.0. If a copy of the MPL was not distributed with this
+   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!-- This custom layout matches the Android layout for preferences in
+     padding and margins, so it is visually consistent. -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+      android:layout_width="match_parent"
+      android:layout_height="wrap_content"
+      android:orientation="horizontal"
+      android:paddingRight="?android:attr/scrollbarSize">
+
+    <RelativeLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:gravity="right"
+        android:layout_marginLeft="15dip"
+        android:layout_marginRight="6dip"
+        android:layout_marginTop="6dip"
+        android:layout_marginBottom="6dip"
+        android:paddingRight="6dip"
+        android:layout_weight="1">
+
+        <TextView android:id="@+android:id/title"
+            android:layout_gravity="right"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:singleLine="true"
+            android:textAppearance="?android:attr/textAppearanceSmall"
+            android:ellipsize="marquee"
+            android:fadingEdge="horizontal" />
+
+    </RelativeLayout>
+
+    <ImageView android:src="@drawable/menu_item_more"
+               android:layout_width="wrap_content"
+               android:layout_height="wrap_content"
+               android:layout_gravity="center_vertical"
+               android:paddingRight="16dp" />
+
+</LinearLayout>
--- a/mobile/android/base/resources/xml/preferences_datareporting.xml
+++ b/mobile/android/base/resources/xml/preferences_datareporting.xml
@@ -8,23 +8,26 @@
                   xmlns:gecko="http://schemas.android.com/apk/res-auto"
                   android:title="@string/pref_category_datareporting"
                   android:enabled="false">
 
     <CheckBoxPreference android:key="datareporting.telemetry.enabled"
                         android:title="@string/datareporting_telemetry_title"
                         android:summary="@string/datareporting_telemetry_summary" />
 
-    <CheckBoxPreference android:key="android.not_a_preference.healthreport.uploadEnabled"
-                        android:title="@string/datareporting_fhr_title"
-                        android:summary="@string/datareporting_fhr_summary"
-                        android:defaultValue="true" />
-
     <CheckBoxPreference android:key="datareporting.crashreporter.submitEnabled"
                         android:title="@string/datareporting_crashreporter_title_short"
                         android:summary="@string/datareporting_crashreporter_summary"
                         android:defaultValue="false" />
 
     <CheckBoxPreference android:key="app.geo.reportdata"
                         android:title="@string/datareporting_wifi_title"
                         android:summary="@string/datareporting_wifi_summary" />
 
+    <CheckBoxPreference android:key="android.not_a_preference.healthreport.uploadEnabled"
+                        android:title="@string/datareporting_fhr_title"
+                        android:summary="@string/datareporting_fhr_summary"
+                        android:defaultValue="true" />
+
+    <org.mozilla.gecko.AlignRightLinkPreference android:key="android.not_a_preference.healthreport.link"
+                                                android:title="@string/datareporting_abouthr_title"
+                                                url="about:healthreport" />
 </PreferenceScreen>
--- a/mobile/android/base/strings.xml.in
+++ b/mobile/android/base/strings.xml.in
@@ -140,16 +140,17 @@
   <string name="datareporting_notification_summary">&datareporting_notification_summary;</string>
   <string name="datareporting_notification_summary_short">&datareporting_notification_summary_short;</string>
   <string name="datareporting_notification_ticker_text">&datareporting_notification_ticker_text;</string>
 
   <string name="datareporting_telemetry_title">&datareporting_telemetry_title;</string>
   <string name="datareporting_telemetry_summary">&datareporting_telemetry_summary;</string>
   <string name="datareporting_fhr_title">&datareporting_fhr_title;</string>
   <string name="datareporting_fhr_summary">&datareporting_fhr_summary;</string>
+  <string name="datareporting_abouthr_title">&datareporting_abouthr_title;</string>
   <string name="datareporting_crashreporter_title_short">&datareporting_crashreporter_title_short;</string>
   <string name="datareporting_crashreporter_summary">&datareporting_crashreporter_summary;</string>
   <string name="datareporting_wifi_title">&datareporting_wifi_title;</string>
   <string name="datareporting_wifi_summary">&datareporting_wifi_summary;</string>
 
   <string name="go">&go;</string>
   <string name="search">&search;</string>
   <string name="reload">&reload;</string>
--- a/mobile/android/components/NSSDialogService.js
+++ b/mobile/android/components/NSSDialogService.js
@@ -141,22 +141,16 @@ NSSDialogs.prototype = {
                           ["certmgr.issued", aCert.validity.notBeforeLocalDay,
                            "certmgr.expires", aCert.validity.notAfterLocalDay])})
      .addLabel({ label: this.certInfoSection("certmgr.fingerprints.label",
                           ["certmgr.certdetail.sha1fingerprint", aCert.sha1Fingerprint,
                            "certmgr.certdetail.md5fingerprint", aCert.md5Fingerprint], false) });
     this.showPrompt(p);
   },
 
-  crlImportStatusDialog: function(aCtx, aCrl) {
-    // this dialog is never shown in Fennec; in Desktop it is shown after importing a CRL
-    // via Preferences->Advanced->Encryption->Revocation Lists->Import.
-    throw "Unimplemented";
-  },
-
   viewCertDetails: function(details) {
     let p = this.getPrompt(this.getString("clientAuthAsk.message3"),
                     '',
                     [ this.getString("nssdialogs.ok.label") ]);
     p.addLabel({ label: details });
     this.showPrompt(p);
   },
 
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -4099,19 +4099,16 @@ pref("full-screen-api.content-only", fal
 pref("full-screen-api.pointer-lock.enabled", true);
 
 // DOM idle observers API
 pref("dom.idle-observers-api.enabled", true);
 
 // Time limit, in milliseconds, for nsEventStateManager::IsHandlingUserInput().
 // Used to detect long running handlers of user-generated events.
 pref("dom.event.handling-user-input-time-limit", 1000);
- 
-//3D Transforms
-pref("layout.3d-transforms.enabled", true);
 
 // Whether we should layerize all animated images (if otherwise possible).
 pref("layout.animated-image-layers.enabled", false);
 
 pref("dom.vibrator.enabled", true);
 pref("dom.vibrator.max_vibrate_ms", 10000);
 pref("dom.vibrator.max_vibrate_list_len", 128);
 
--- a/netwerk/build/nsNetModule.cpp
+++ b/netwerk/build/nsNetModule.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "necko-config.h"
 
-#define ALLOW_LATE_NSHTTP_H_INCLUDE 1
+#define ALLOW_LATE_HTTPLOG_H_INCLUDE 1
 #include "base/basictypes.h"
 
 #include "nsCOMPtr.h"
 #include "nsIClassInfoImpl.h"
 #include "mozilla/ModuleUtils.h"
 #include "nsIComponentManager.h"
 #include "nsIServiceManager.h"
 #include "nsICategoryManager.h"
@@ -32,16 +32,17 @@
 #include "nsMimeTypes.h"
 #include "nsNetStrings.h"
 #include "nsDNSPrefetch.h"
 #include "nsAboutProtocolHandler.h"
 #include "nsXULAppAPI.h"
 #include "nsCategoryCache.h"
 #include "nsIContentSniffer.h"
 #include "nsNetUtil.h"
+#include "mozilla/net/NeckoChild.h"
 
 #include "nsNetCID.h"
 
 #if defined(XP_MACOSX)
 #if !defined(__LP64__)
 #define BUILD_APPLEFILE_DECODER 1
 #endif
 #else
new file mode 100644
--- /dev/null
+++ b/netwerk/ipc/NeckoChannelParams.ipdlh
@@ -0,0 +1,85 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set sw=2 ts=8 et tw=80 ft=c: */
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include URIParams;
+include InputStreamParams;
+include "mozilla/net/PHttpChannelParams.h";
+
+using mozilla::void_t;
+using RequestHeaderTuples;
+using nsHttpAtom;
+
+namespace mozilla {
+namespace net {
+
+//-----------------------------------------------------------------------------
+// HTTP IPDL structs
+//-----------------------------------------------------------------------------
+
+struct HttpChannelOpenArgs
+{
+  URIParams                   uri;
+  // - TODO: bug 571161: unclear if any HTTP channel clients ever
+  // set originalURI != uri (about:credits?); also not clear if
+  // chrome channel would ever need to know.  Get rid of next arg?
+  OptionalURIParams           original;
+  OptionalURIParams           doc;
+  OptionalURIParams           referrer;
+  OptionalURIParams           apiRedirectTo;
+  uint32_t                    loadFlags;
+  RequestHeaderTuples         requestHeaders;
+  nsHttpAtom                  requestMethod;
+  OptionalInputStreamParams   uploadStream;
+  bool                        uploadStreamHasHeaders;
+  uint16_t                    priority;
+  uint8_t                     redirectionLimit;
+  bool                        allowPipelining;
+  bool                        forceAllowThirdPartyCookie;
+  bool                        resumeAt;
+  uint64_t                    startPos;
+  nsCString                   entityID;
+  bool                        chooseApplicationCache;
+  nsCString                   appCacheClientID;
+  bool                        allowSpdy;
+};
+
+struct HttpChannelConnectArgs
+{
+  uint32_t channelId;
+};
+
+union HttpChannelCreationArgs
+{
+  HttpChannelOpenArgs;      // For AsyncOpen: the common case.
+  HttpChannelConnectArgs;   // Used for redirected-to channels
+};
+
+//-----------------------------------------------------------------------------
+// FTP IPDL structs
+//-----------------------------------------------------------------------------
+
+struct FTPChannelOpenArgs
+{
+  URIParams uri;
+  uint64_t startPos;
+  nsCString entityID;
+  OptionalInputStreamParams uploadStream;
+};
+
+struct FTPChannelConnectArgs
+{
+  uint32_t channelId;
+};
+
+union FTPChannelCreationArgs
+{
+  FTPChannelOpenArgs;      // For AsyncOpen: the common case.
+  FTPChannelConnectArgs;   // Used for redirected-to channels
+};
+
+} // namespace ipc
+} // namespace mozilla
--- a/netwerk/ipc/NeckoChild.cpp
+++ b/netwerk/ipc/NeckoChild.cpp
@@ -57,17 +57,18 @@ void NeckoChild::DestroyNeckoChild()
     Send__delete__(gNeckoChild); 
     gNeckoChild = nullptr;
     alreadyDestroyed = true;
   }
 }
 
 PHttpChannelChild*
 NeckoChild::AllocPHttpChannel(PBrowserChild* browser,
-                              const SerializedLoadContext& loadContext)
+                              const SerializedLoadContext& loadContext,
+                              const HttpChannelCreationArgs& aOpenArgs)
 {
   // We don't allocate here: instead we always use IPDL constructor that takes
   // an existing HttpChildChannel
   NS_NOTREACHED("AllocPHttpChannel should not be called on child");
   return nullptr;
 }
 
 bool 
@@ -77,17 +78,18 @@ NeckoChild::DeallocPHttpChannel(PHttpCha
 
   HttpChannelChild* child = static_cast<HttpChannelChild*>(channel);
   child->ReleaseIPDLReference();
   return true;
 }
 
 PFTPChannelChild*
 NeckoChild::AllocPFTPChannel(PBrowserChild* aBrowser,
-                             const SerializedLoadContext& aSerialized)
+                             const SerializedLoadContext& aSerialized,
+                             const FTPChannelCreationArgs& aOpenArgs)
 {
   // We don't allocate here: see FTPChannelChild::AsyncOpen()
   NS_RUNTIMEABORT("AllocPFTPChannel should not be called");
   return nullptr;
 }
 
 bool
 NeckoChild::DeallocPFTPChannel(PFTPChannelChild* channel)
--- a/netwerk/ipc/NeckoChild.h
+++ b/netwerk/ipc/NeckoChild.h
@@ -21,25 +21,28 @@ class NeckoChild :
 public:
   NeckoChild();
   virtual ~NeckoChild();
 
   static void InitNeckoChild();
   static void DestroyNeckoChild();
 
 protected:
-  virtual PHttpChannelChild* AllocPHttpChannel(PBrowserChild*,
-                                              const SerializedLoadContext&);
+  virtual PHttpChannelChild*
+    AllocPHttpChannel(PBrowserChild*, const SerializedLoadContext&,
+                      const HttpChannelCreationArgs& aOpenArgs);
   virtual bool DeallocPHttpChannel(PHttpChannelChild*);
   virtual PCookieServiceChild* AllocPCookieService();
   virtual bool DeallocPCookieService(PCookieServiceChild*);
   virtual PWyciwygChannelChild* AllocPWyciwygChannel();
   virtual bool DeallocPWyciwygChannel(PWyciwygChannelChild*);
-  virtual PFTPChannelChild* AllocPFTPChannel(PBrowserChild* aBrowser,
-                                             const SerializedLoadContext& aSerialized);
+  virtual PFTPChannelChild*
+    AllocPFTPChannel(PBrowserChild* aBrowser,
+                     const SerializedLoadContext& aSerialized,
+                     const FTPChannelCreationArgs& aOpenArgs);
   virtual bool DeallocPFTPChannel(PFTPChannelChild*);
   virtual PWebSocketChild* AllocPWebSocket(PBrowserChild*, const SerializedLoadContext&);
   virtual bool DeallocPWebSocket(PWebSocketChild*);
   virtual PTCPSocketChild* AllocPTCPSocket(const nsString& aHost,
                                            const uint16_t& aPort,
                                            const bool& useSSL,
                                            const nsString& aBinaryType,
                                            PBrowserChild* aBrowser);
--- a/netwerk/ipc/NeckoParent.cpp
+++ b/netwerk/ipc/NeckoParent.cpp
@@ -30,16 +30,22 @@ using mozilla::dom::TCPSocketParent;
 using IPC::SerializedLoadContext;
 
 namespace mozilla {
 namespace net {
 
 // C++ file contents
 NeckoParent::NeckoParent()
 {
+  // Init HTTP protocol handler now since we need atomTable up and running very
+  // early (IPDL argument handling for PHttpChannel constructor needs it) so
+  // normal init (during 1st Http channel request) isn't early enough.
+  nsCOMPtr<nsIProtocolHandler> proto =
+    do_GetService("@mozilla.org/network/protocol;1?name=http");
+
   if (UsingNeckoIPCSecurity()) {
     // cache values for core/packaged apps basepaths
     nsAutoString corePath, webPath;
     nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID);
     if (appsService) {
       appsService->GetCoreAppsBasePath(corePath);
       appsService->GetWebAppsBasePath(webPath);
     }
@@ -148,17 +154,18 @@ NeckoParent::CreateChannelLoadContext(PB
     aResult = new LoadContext(aSerialized, topFrameElement, appId, inBrowser);
   }
 
   return nullptr;
 }
 
 PHttpChannelParent*
 NeckoParent::AllocPHttpChannel(PBrowserParent* aBrowser,
-                               const SerializedLoadContext& aSerialized)
+                               const SerializedLoadContext& aSerialized,
+                               const HttpChannelCreationArgs& aOpenArgs)
 {
   nsCOMPtr<nsILoadContext> loadContext;
   const char *error = CreateChannelLoadContext(aBrowser, aSerialized,
                                                loadContext);
   if (error) {
     printf_stderr("NeckoParent::AllocPHttpChannel: "
                   "FATAL error: %s: KILLING CHILD PROCESS\n",
                   error);
@@ -173,19 +180,31 @@ NeckoParent::AllocPHttpChannel(PBrowserP
 bool
 NeckoParent::DeallocPHttpChannel(PHttpChannelParent* channel)
 {
   HttpChannelParent *p = static_cast<HttpChannelParent *>(channel);
   p->Release();
   return true;
 }
 
+bool
+NeckoParent::RecvPHttpChannelConstructor(
+                      PHttpChannelParent* aActor,
+                      PBrowserParent* aBrowser,
+                      const SerializedLoadContext& aSerialized,
+                      const HttpChannelCreationArgs& aOpenArgs)
+{
+  HttpChannelParent* p = static_cast<HttpChannelParent*>(aActor);
+  return p->Init(aOpenArgs);
+}
+
 PFTPChannelParent*
 NeckoParent::AllocPFTPChannel(PBrowserParent* aBrowser,
-                              const SerializedLoadContext& aSerialized)
+                              const SerializedLoadContext& aSerialized,
+                              const FTPChannelCreationArgs& aOpenArgs)
 {
   nsCOMPtr<nsILoadContext> loadContext;
   const char *error = CreateChannelLoadContext(aBrowser, aSerialized,
                                                loadContext);
   if (error) {
     printf_stderr("NeckoParent::AllocPFTPChannel: "
                   "FATAL error: %s: KILLING CHILD PROCESS\n",
                   error);
@@ -200,16 +219,27 @@ NeckoParent::AllocPFTPChannel(PBrowserPa
 bool
 NeckoParent::DeallocPFTPChannel(PFTPChannelParent* channel)
 {
   FTPChannelParent *p = static_cast<FTPChannelParent *>(channel);
   p->Release();
   return true;
 }
 
+bool
+NeckoParent::RecvPFTPChannelConstructor(
+                      PFTPChannelParent* aActor,
+                      PBrowserParent* aBrowser,
+                      const SerializedLoadContext& aSerialized,
+                      const FTPChannelCreationArgs& aOpenArgs)
+{
+  FTPChannelParent* p = static_cast<FTPChannelParent*>(aActor);
+  return p->Init(aOpenArgs);
+}
+
 PCookieServiceParent* 
 NeckoParent::AllocPCookieService()
 {
   return new CookieServiceParent();
 }
 
 bool 
 NeckoParent::DeallocPCookieService(PCookieServiceParent* cs)
--- a/netwerk/ipc/NeckoParent.h
+++ b/netwerk/ipc/NeckoParent.h
@@ -46,25 +46,40 @@ public:
    */
   MOZ_WARN_UNUSED_RESULT
   static const char*
   CreateChannelLoadContext(PBrowserParent* aBrowser,
                            const SerializedLoadContext& aSerialized,
                            nsCOMPtr<nsILoadContext> &aResult);
 
 protected:
-  virtual PHttpChannelParent* AllocPHttpChannel(PBrowserParent*,
-                                                const SerializedLoadContext&);
+  virtual PHttpChannelParent*
+    AllocPHttpChannel(PBrowserParent*, const SerializedLoadContext&,
+                      const HttpChannelCreationArgs& aOpenArgs);
+  virtual bool
+    RecvPHttpChannelConstructor(
+                      PHttpChannelParent* aActor,
+                      PBrowserParent* aBrowser,
+                      const SerializedLoadContext& aSerialized,
+                      const HttpChannelCreationArgs& aOpenArgs);
   virtual bool DeallocPHttpChannel(PHttpChannelParent*);
   virtual PCookieServiceParent* AllocPCookieService();
   virtual bool DeallocPCookieService(PCookieServiceParent*);
   virtual PWyciwygChannelParent* AllocPWyciwygChannel();
   virtual bool DeallocPWyciwygChannel(PWyciwygChannelParent*);
-  virtual PFTPChannelParent* AllocPFTPChannel(PBrowserParent* aBrowser,
-                                              const SerializedLoadContext& aSerialized);
+  virtual PFTPChannelParent*
+    AllocPFTPChannel(PBrowserParent* aBrowser,
+                     const SerializedLoadContext& aSerialized,
+                     const FTPChannelCreationArgs& aOpenArgs);
+  virtual bool
+    RecvPFTPChannelConstructor(
+                      PFTPChannelParent* aActor,
+                      PBrowserParent* aBrowser,
+                      const SerializedLoadContext& aSerialized,
+                      const FTPChannelCreationArgs& aOpenArgs);
   virtual bool DeallocPFTPChannel(PFTPChannelParent*);
   virtual PWebSocketParent* AllocPWebSocket(PBrowserParent* browser,
                                             const SerializedLoadContext& aSerialized);
   virtual bool DeallocPWebSocket(PWebSocketParent*);
   virtual PTCPSocketParent* AllocPTCPSocket(const nsString& aHost,
                                             const uint16_t& aPort,
                                             const bool& useSSL,
                                             const nsString& aBinaryType,
--- a/netwerk/ipc/PNecko.ipdl
+++ b/netwerk/ipc/PNecko.ipdl
@@ -9,26 +9,29 @@ include protocol PContent;
 include protocol PHttpChannel;
 include protocol PCookieService;
 include protocol PBrowser;
 include protocol PWyciwygChannel;
 include protocol PFTPChannel;
 include protocol PWebSocket;
 include protocol PTCPSocket;
 include protocol PRemoteOpenFile;
+include protocol PBlob; //FIXME: bug #792908
+
 include URIParams;
+include InputStreamParams;
+include NeckoChannelParams;
 
 include "SerializedLoadContext.h";
 
 using IPC::SerializedLoadContext;
 
 namespace mozilla {
 namespace net {
 
-
 //-------------------------------------------------------------------
 sync protocol PNecko
 {
   manager PContent;
   manages PHttpChannel;
   manages PCookieService;
   manages PWyciwygChannel;
   manages PFTPChannel;
@@ -36,19 +39,22 @@ sync protocol PNecko
   manages PTCPSocket;
   manages PRemoteOpenFile;
 
 parent:
   __delete__();
 
   PCookieService();
   PHttpChannel(nullable PBrowser browser,
-               SerializedLoadContext loadContext);
+               SerializedLoadContext loadContext,
+               HttpChannelCreationArgs args);
   PWyciwygChannel();
-  PFTPChannel(PBrowser browser, SerializedLoadContext loadContext);
+  PFTPChannel(PBrowser browser, SerializedLoadContext loadContext,
+              FTPChannelCreationArgs args);
+
   PWebSocket(PBrowser browser, SerializedLoadContext loadContext);
   PTCPSocket(nsString host, uint16_t port, bool useSSL, nsString binaryType,
              nullable PBrowser browser);
 
   // Request that the parent open a file.
   PRemoteOpenFile(URIParams fileuri, nullable PBrowser browser);
 
   HTMLDNSPrefetch(nsString hostname, uint16_t flags);
--- a/netwerk/ipc/ipdl.mk
+++ b/netwerk/ipc/ipdl.mk
@@ -1,9 +1,10 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 IPDLSRCS =          \
   PNecko.ipdl       \
   PRemoteOpenFile.ipdl \
+  NeckoChannelParams.ipdlh \
   $(NULL)
 
--- a/netwerk/protocol/ftp/FTPChannelChild.cpp
+++ b/netwerk/protocol/ftp/FTPChannelChild.cpp
@@ -164,32 +164,35 @@ FTPChannelChild::AsyncOpen(::nsIStreamLi
   GetCallback(iTabChild);
   if (iTabChild) {
     tabChild = static_cast<mozilla::dom::TabChild*>(iTabChild.get());
   }
   if (MissingRequiredTabChild(tabChild, "ftp")) {
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
-  // FIXME: like bug 558623, merge constructor+SendAsyncOpen into 1 IPC msg
-  gNeckoChild->SendPFTPChannelConstructor(this, tabChild, IPC::SerializedLoadContext(this));
   mListener = listener;
   mListenerContext = aContext;
 
   // add ourselves to the load group. 
   if (mLoadGroup)
     mLoadGroup->AddRequest(this, nullptr);
 
-  URIParams uri;
-  SerializeURI(nsBaseChannel::URI(), uri);
-
   OptionalInputStreamParams uploadStream;
   SerializeInputStream(mUploadStream, uploadStream);
 
-  SendAsyncOpen(uri, mStartPos, mEntityID, uploadStream);
+  FTPChannelOpenArgs openArgs;
+  SerializeURI(nsBaseChannel::URI(), openArgs.uri());
+  openArgs.startPos() = mStartPos;
+  openArgs.entityID() = mEntityID;
+  openArgs.uploadStream() = uploadStream;
+
+  gNeckoChild->
+    SendPFTPChannelConstructor(this, tabChild, IPC::SerializedLoadContext(this),
+                               openArgs);
 
   // The socket transport layer in the chrome process now has a logical ref to
   // us until OnStopRequest is called.
   AddIPDLReference();
 
   mIsPending = true;
   mWasOpened = true;
 
@@ -512,22 +515,23 @@ FTPChannelChild::ConnectParent(uint32_t 
   if (iTabChild) {
     tabChild = static_cast<mozilla::dom::TabChild*>(iTabChild.get());
   }
 
   // The socket transport in the chrome process now holds a logical ref to us
   // until OnStopRequest, or we do a redirect, or we hit an IPDL error.
   AddIPDLReference();
 
+  FTPChannelConnectArgs connectArgs(id);
+
   if (!gNeckoChild->SendPFTPChannelConstructor(this, tabChild,
-                                               IPC::SerializedLoadContext(this)))
+                                               IPC::SerializedLoadContext(this),
+                                               connectArgs)) {
     return NS_ERROR_FAILURE;
-
-  if (!SendConnectChannel(id))
-    return NS_ERROR_FAILURE;
+  }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 FTPChannelChild::CompleteRedirectSetup(nsIStreamListener *listener,
                                        nsISupports *aContext)
 {
--- a/netwerk/protocol/ftp/FTPChannelParent.cpp
+++ b/netwerk/protocol/ftp/FTPChannelParent.cpp
@@ -55,30 +55,54 @@ NS_IMPL_ISUPPORTS4(FTPChannelParent,
                    nsIParentChannel,
                    nsIInterfaceRequestor,
                    nsIRequestObserver)
 
 //-----------------------------------------------------------------------------
 // FTPChannelParent::PFTPChannelParent
 //-----------------------------------------------------------------------------
 
+//-----------------------------------------------------------------------------
+// FTPChannelParent methods
+//-----------------------------------------------------------------------------
+
 bool
-FTPChannelParent::RecvAsyncOpen(const URIParams& aURI,
-                                const uint64_t& aStartPos,
-                                const nsCString& aEntityID,
-                                const OptionalInputStreamParams& aUploadStream)
+FTPChannelParent::Init(const FTPChannelCreationArgs& aArgs)
+{
+  switch (aArgs.type()) {
+  case FTPChannelCreationArgs::TFTPChannelOpenArgs:
+  {
+    const FTPChannelOpenArgs& a = aArgs.get_FTPChannelOpenArgs();
+    return DoAsyncOpen(a.uri(), a.startPos(), a.entityID(), a.uploadStream());
+  }
+  case FTPChannelCreationArgs::TFTPChannelConnectArgs:
+  {
+    const FTPChannelConnectArgs& cArgs = aArgs.get_FTPChannelConnectArgs();
+    return ConnectChannel(cArgs.channelId());
+  }
+  default:
+    NS_NOTREACHED("unknown open type");
+    return false;
+  }
+}
+
+bool
+FTPChannelParent::DoAsyncOpen(const URIParams& aURI,
+                              const uint64_t& aStartPos,
+                              const nsCString& aEntityID,
+                              const OptionalInputStreamParams& aUploadStream)
 {
   nsCOMPtr<nsIURI> uri = DeserializeURI(aURI);
   if (!uri)
       return false;
 
 #ifdef DEBUG
   nsCString uriSpec;
   uri->GetSpec(uriSpec);
-  LOG(("FTPChannelParent RecvAsyncOpen [this=%p uri=%s]\n",
+  LOG(("FTPChannelParent DoAsyncOpen [this=%p uri=%s]\n",
        this, uriSpec.get()));
 #endif
 
   nsresult rv;
   nsCOMPtr<nsIIOService> ios(do_GetIOService(&rv));
   if (NS_FAILED(rv))
     return SendFailedAsyncOpen(rv);
 
@@ -112,17 +136,17 @@ FTPChannelParent::RecvAsyncOpen(const UR
   rv = mChannel->AsyncOpen(this, nullptr);
   if (NS_FAILED(rv))
     return SendFailedAsyncOpen(rv);
   
   return true;
 }
 
 bool
-FTPChannelParent::RecvConnectChannel(const uint32_t& channelId)
+FTPChannelParent::ConnectChannel(const uint32_t& channelId)
 {
   nsresult rv;
 
   LOG(("Looking for a registered channel [this=%p, id=%d]", this, channelId));
 
   nsCOMPtr<nsIChannel> channel;
   rv = NS_LinkRedirectChannels(channelId, this, getter_AddRefs(channel));
   if (NS_SUCCEEDED(rv))
--- a/netwerk/protocol/ftp/FTPChannelParent.h
+++ b/netwerk/protocol/ftp/FTPChannelParent.h
@@ -29,22 +29,27 @@ public:
   NS_DECL_NSIREQUESTOBSERVER
   NS_DECL_NSISTREAMLISTENER
   NS_DECL_NSIPARENTCHANNEL
   NS_DECL_NSIINTERFACEREQUESTOR
 
   FTPChannelParent(nsILoadContext* aLoadContext, PBOverrideStatus aOverrideStatus);
   virtual ~FTPChannelParent();
 
+  bool Init(const FTPChannelCreationArgs& aOpenArgs);
+
 protected:
-  virtual bool RecvAsyncOpen(const URIParams& uri,
-                             const uint64_t& startPos,
-                             const nsCString& entityID,
-                             const OptionalInputStreamParams& uploadStream) MOZ_OVERRIDE;
-  virtual bool RecvConnectChannel(const uint32_t& channelId) MOZ_OVERRIDE;
+  bool DoAsyncOpen(const URIParams& aURI, const uint64_t& aStartPos,
+                   const nsCString& aEntityID,
+                   const OptionalInputStreamParams& aUploadStream);
+
+  // used to connect redirected-to channel in parent with just created
+  // ChildChannel.  Used during HTTP->FTP redirects.
+  bool ConnectChannel(const uint32_t& channelId);
+
   virtual bool RecvCancel(const nsresult& status) MOZ_OVERRIDE;
   virtual bool RecvSuspend() MOZ_OVERRIDE;
   virtual bool RecvResume() MOZ_OVERRIDE;
 
   virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE;
 
   nsRefPtr<nsFtpChannel> mChannel;
 
--- a/netwerk/protocol/ftp/PFTPChannel.ipdl
+++ b/netwerk/protocol/ftp/PFTPChannel.ipdl
@@ -4,38 +4,37 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 include protocol PNecko;
 include InputStreamParams;
 include URIParams;
 
+//FIXME: bug #792908 (NeckoChannelParams already included by PNecko)
+include NeckoChannelParams;
 include protocol PBlob; //FIXME: bug #792908
 
 include "SerializedLoadContext.h";
 
 using PRTime;
 
 namespace mozilla {
 namespace net {
 
 async protocol PFTPChannel
 {
   manager PNecko;
 
 parent:
+  // Note: channels are opened during construction, so no open method here:
+  // see PNecko.ipdl
+
   __delete__();
 
-  AsyncOpen(URIParams uri,
-            uint64_t startPos,
-            nsCString entityID,
-            OptionalInputStreamParams uploadStream);
-
-  ConnectChannel(uint32_t channelId);
   Cancel(nsresult status);
   Suspend();
   Resume();
 
 child:
   OnStartRequest(int64_t aContentLength, nsCString aContentType,
                  PRTime aLastModified, nsCString aEntityID, URIParams aURI);
   OnDataAvailable(nsCString data, uint64_t offset, uint32_t count);
--- a/netwerk/protocol/http/ASpdySession.cpp
+++ b/netwerk/protocol/http/ASpdySession.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpHandler.h"
 
 #include "ASpdySession.h"
 #include "SpdySession2.h"
 #include "SpdySession3.h"
 
 #include "mozilla/Telemetry.h"
--- a/netwerk/protocol/http/ConnectionDiagnostics.cpp
+++ b/netwerk/protocol/http/ConnectionDiagnostics.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpConnectionMgr.h"
 #include "nsHttpConnection.h"
 #include "SpdySession2.h"
 #include "SpdySession3.h"
 #include "nsHttpHandler.h"
 #include "nsIConsoleService.h"
 
 using namespace mozilla;
--- a/netwerk/protocol/http/HttpBaseChannel.cpp
+++ b/netwerk/protocol/http/HttpBaseChannel.cpp
@@ -1,15 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "mozilla/net/HttpBaseChannel.h"
 
 #include "nsHttpHandler.h"
 #include "nsMimeTypes.h"
 #include "nsNetUtil.h"
 
 #include "nsICachingChannel.h"
 #include "nsISeekableStream.h"
--- a/netwerk/protocol/http/HttpBaseChannel.h
+++ b/netwerk/protocol/http/HttpBaseChannel.h
@@ -29,16 +29,18 @@
 #include "nsIResumableChannel.h"
 #include "nsITraceableChannel.h"
 #include "nsILoadContext.h"
 #include "mozilla/net/NeckoCommon.h"
 #include "nsThreadUtils.h"
 #include "PrivateBrowsingChannel.h"
 #include "mozilla/net/DNS.h"
 
+extern PRLogModuleInfo *gHttpLog;
+
 namespace mozilla {
 namespace net {
 
 /*
  * This class is a partial implementation of nsIHttpChannel.  It contains code
  * shared by nsHttpChannel and HttpChannelChild.
  * - Note that this class has nothing to do with nsBaseChannel, which is an
  *   earlier effort at a base class for channels that somehow never made it all
@@ -334,35 +336,36 @@ private:
 protected:
   // Function to be called at resume time
   void (T::* mCallOnResume)(void);
 };
 
 template <class T>
 nsresult HttpAsyncAborter<T>::AsyncAbort(nsresult status)
 {
-  LOG(("HttpAsyncAborter::AsyncAbort [this=%p status=%x]\n", mThis, status));
+  PR_LOG(gHttpLog, 4,
+         ("HttpAsyncAborter::AsyncAbort [this=%p status=%x]\n", mThis, status));
 
   mThis->mStatus = status;
   mThis->mIsPending = false;
 
   // if this fails?  Callers ignore our return value anyway....
   return AsyncCall(&T::HandleAsyncAbort);
 }
 
 // Each subclass needs to define its own version of this (which just calls this
 // base version), else we wind up casting base/derived member function ptrs
 template <class T>
 inline void HttpAsyncAborter<T>::HandleAsyncAbort()
 {
   NS_PRECONDITION(!mCallOnResume, "How did that happen?");
 
   if (mThis->mSuspendCount) {
-    LOG(("Waiting until resume to do async notification [this=%p]\n",
-         mThis));
+    PR_LOG(gHttpLog, 4,
+           ("Waiting until resume to do async notification [this=%p]\n", mThis));
     mCallOnResume = &T::HandleAsyncAbort;
     return;
   }
 
   mThis->DoNotifyListener();
 
   // finally remove ourselves from the load group.
   if (mThis->mLoadGroup)
--- a/netwerk/protocol/http/HttpChannelChild.cpp
+++ b/netwerk/protocol/http/HttpChannelChild.cpp
@@ -1,15 +1,18 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/net/NeckoChild.h"
 #include "mozilla/net/HttpChannelChild.h"
 
 #include "nsStringStream.h"
 #include "nsHttpHandler.h"
 #include "nsMimeTypes.h"
@@ -809,24 +812,24 @@ HttpChannelChild::ConnectParent(uint32_t
   if (MissingRequiredTabChild(tabChild, "http")) {
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
   // The socket transport in the chrome process now holds a logical ref to us
   // until OnStopRequest, or we do a redirect, or we hit an IPDL error.
   AddIPDLReference();
 
-  if (!gNeckoChild->SendPHttpChannelConstructor(
-                      this, tabChild, IPC::SerializedLoadContext(this))) {
+  HttpChannelConnectArgs connectArgs(id);
+  if (!gNeckoChild->
+        SendPHttpChannelConstructor(this, tabChild,
+                                    IPC::SerializedLoadContext(this),
+                                    connectArgs)) {
     return NS_ERROR_FAILURE;
   }
 
-  if (!SendConnectChannel(id))
-    return NS_ERROR_FAILURE;
-
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HttpChannelChild::CompleteRedirectSetup(nsIStreamListener *listener,
                                         nsISupports *aContext)
 {
   LOG(("HttpChannelChild::FinishRedirectSetup [this=%p]\n", this));
@@ -1040,53 +1043,57 @@ HttpChannelChild::AsyncOpen(nsIStreamLis
       }
     }
   }
 
   //
   // Send request to the chrome process...
   //
 
-  // FIXME: bug 558623: Combine constructor and SendAsyncOpen into one IPC msg
-
   mozilla::dom::TabChild* tabChild = nullptr;
   nsCOMPtr<nsITabChild> iTabChild;
   GetCallback(iTabChild);
   if (iTabChild) {
     tabChild = static_cast<mozilla::dom::TabChild*>(iTabChild.get());
   }
   if (MissingRequiredTabChild(tabChild, "http")) {
     return NS_ERROR_ILLEGAL_VALUE;
   }
 
+  HttpChannelOpenArgs openArgs;
+  // No access to HttpChannelOpenArgs members, but they each have a
+  // function with the struct name that returns a ref.
+  SerializeURI(mURI, openArgs.uri());
+  SerializeURI(mOriginalURI, openArgs.original());
+  SerializeURI(mDocumentURI, openArgs.doc());
+  SerializeURI(mReferrer, openArgs.referrer());
+  SerializeURI(mAPIRedirectToURI, openArgs.apiRedirectTo());
+  openArgs.loadFlags() = mLoadFlags;
+  openArgs.requestHeaders() = mClientSetRequestHeaders;
+  openArgs.requestMethod() = mRequestHead.Method();
+  SerializeInputStream(mUploadStream, openArgs.uploadStream());
+  openArgs.uploadStreamHasHeaders() = mUploadStreamHasHeaders;
+  openArgs.priority() = mPriority;
+  openArgs.redirectionLimit() = mRedirectionLimit;
+  openArgs.allowPipelining() = mAllowPipelining;
+  openArgs.forceAllowThirdPartyCookie() = mForceAllowThirdPartyCookie;
+  openArgs.resumeAt() = mSendResumeAt;
+  openArgs.startPos() = mStartPos;
+  openArgs.entityID() = mEntityID;
+  openArgs.chooseApplicationCache() = mChooseApplicationCache;
+  openArgs.appCacheClientID() = appCacheClientId;
+  openArgs.allowSpdy() = mAllowSpdy;
+
   // The socket transport in the chrome process now holds a logical ref to us
   // until OnStopRequest, or we do a redirect, or we hit an IPDL error.
   AddIPDLReference();
 
   gNeckoChild->SendPHttpChannelConstructor(this, tabChild,
-                                           IPC::SerializedLoadContext(this));
-
-  URIParams uri;
-  SerializeURI(mURI, uri);
-
-  OptionalURIParams originalURI, documentURI, referrer, redirectURI;
-  SerializeURI(mOriginalURI, originalURI);
-  SerializeURI(mDocumentURI, documentURI);
-  SerializeURI(mReferrer, referrer);
-  SerializeURI(mAPIRedirectToURI, redirectURI);
-
-  OptionalInputStreamParams uploadStream;
-  SerializeInputStream(mUploadStream, uploadStream);
-
-  SendAsyncOpen(uri, originalURI, documentURI, referrer, redirectURI, mLoadFlags,
-                mClientSetRequestHeaders, mRequestHead.Method(), uploadStream,
-                mUploadStreamHasHeaders, mPriority, mRedirectionLimit,
-                mAllowPipelining, mForceAllowThirdPartyCookie, mSendResumeAt,
-                mStartPos, mEntityID, mChooseApplicationCache,
-                appCacheClientId, mAllowSpdy);
+                                           IPC::SerializedLoadContext(this),
+                                           openArgs);
 
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // HttpChannelChild::nsIHttpChannel
 //-----------------------------------------------------------------------------
 
--- a/netwerk/protocol/http/HttpChannelParent.cpp
+++ b/netwerk/protocol/http/HttpChannelParent.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "mozilla/net/HttpChannelParent.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/unused.h"
 #include "HttpChannelParentListener.h"
 #include "nsHttpHandler.h"
 #include "nsNetUtil.h"
 #include "nsISupportsPriority.h"
@@ -61,16 +64,43 @@ void
 HttpChannelParent::ActorDestroy(ActorDestroyReason why)
 {
   // We may still have refcount>0 if nsHttpChannel hasn't called OnStopRequest
   // yet, but child process has crashed.  We must not try to send any more msgs
   // to child, or IPDL will kill chrome process, too.
   mIPCClosed = true;
 }
 
+bool
+HttpChannelParent::Init(const HttpChannelCreationArgs& aArgs)
+{
+  switch (aArgs.type()) {
+  case HttpChannelCreationArgs::THttpChannelOpenArgs:
+  {
+    const HttpChannelOpenArgs& a = aArgs.get_HttpChannelOpenArgs();
+    return DoAsyncOpen(a.uri(), a.original(), a.doc(), a.referrer(),
+                       a.apiRedirectTo(), a.loadFlags(), a.requestHeaders(),
+                       a.requestMethod(), a.uploadStream(),
+                       a.uploadStreamHasHeaders(), a.priority(),
+                       a.redirectionLimit(), a.allowPipelining(),
+                       a.forceAllowThirdPartyCookie(), a.resumeAt(),
+                       a.startPos(), a.entityID(), a.chooseApplicationCache(),
+                       a.appCacheClientID(), a.allowSpdy());
+  }
+  case HttpChannelCreationArgs::THttpChannelConnectArgs:
+  {
+    const HttpChannelConnectArgs& cArgs = aArgs.get_HttpChannelConnectArgs();
+    return ConnectChannel(cArgs.channelId());
+  }
+  default:
+    NS_NOTREACHED("unknown open type");
+    return false;
+  }
+}
+
 //-----------------------------------------------------------------------------
 // HttpChannelParent::nsISupports
 //-----------------------------------------------------------------------------
 
 NS_IMPL_ISUPPORTS6(HttpChannelParent,
                    nsIInterfaceRequestor,
                    nsIProgressEventSink,
                    nsIRequestObserver,
@@ -103,17 +133,17 @@ HttpChannelParent::GetInterface(const ns
   return QueryInterface(aIID, result);
 }
 
 //-----------------------------------------------------------------------------
 // HttpChannelParent::PHttpChannelParent
 //-----------------------------------------------------------------------------
 
 bool
-HttpChannelParent::RecvAsyncOpen(const URIParams&           aURI,
+HttpChannelParent::DoAsyncOpen(  const URIParams&           aURI,
                                  const OptionalURIParams&   aOriginalURI,
                                  const OptionalURIParams&   aDocURI,
                                  const OptionalURIParams&   aReferrerURI,
                                  const OptionalURIParams&   aAPIRedirectToURI,
                                  const uint32_t&            loadFlags,
                                  const RequestHeaderTuples& requestHeaders,
                                  const nsHttpAtom&          requestMethod,
                                  const OptionalInputStreamParams& uploadStream,
@@ -232,17 +262,17 @@ HttpChannelParent::RecvAsyncOpen(const U
   rv = httpChan->AsyncOpen(channelListener, nullptr);
   if (NS_FAILED(rv))
     return SendFailedAsyncOpen(rv);
 
   return true;
 }
 
 bool
-HttpChannelParent::RecvConnectChannel(const uint32_t& channelId)
+HttpChannelParent::ConnectChannel(const uint32_t& channelId)
 {
   nsresult rv;
 
   LOG(("Looking for a registered channel [this=%p, id=%d]", this, channelId));
   rv = NS_LinkRedirectChannels(channelId, this, getter_AddRefs(mChannel));
   LOG(("  found channel %p, rv=%08x", mChannel.get(), rv));
 
   if (mPBOverride != kPBOverride_Unset) {
--- a/netwerk/protocol/http/HttpChannelParent.h
+++ b/netwerk/protocol/http/HttpChannelParent.h
@@ -44,39 +44,44 @@ public:
   NS_DECL_NSIPROGRESSEVENTSINK
   NS_DECL_NSIINTERFACEREQUESTOR
 
   HttpChannelParent(mozilla::dom::PBrowserParent* iframeEmbedding,
                     nsILoadContext* aLoadContext,
                     PBOverrideStatus aStatus);
   virtual ~HttpChannelParent();
 
+  bool Init(const HttpChannelCreationArgs& aOpenArgs);
+
 protected:
-  virtual bool RecvAsyncOpen(const URIParams&           uri,
-                             const OptionalURIParams&   originalUri,
-                             const OptionalURIParams&   docUri,
-                             const OptionalURIParams&   referrerUri,
-                             const OptionalURIParams&   internalRedirectUri,
-                             const uint32_t&            loadFlags,
-                             const RequestHeaderTuples& requestHeaders,
-                             const nsHttpAtom&          requestMethod,
-                             const OptionalInputStreamParams& uploadStream,
-                             const bool&              uploadStreamHasHeaders,
-                             const uint16_t&            priority,
-                             const uint8_t&             redirectionLimit,
-                             const bool&              allowPipelining,
-                             const bool&              forceAllowThirdPartyCookie,
-                             const bool&                doResumeAt,
-                             const uint64_t&            startPos,
-                             const nsCString&           entityID,
-                             const bool&                chooseApplicationCache,
-                             const nsCString&           appCacheClientID,
-                             const bool&                allowSpdy) MOZ_OVERRIDE;
+  // used to connect redirected-to channel in parent with just created
+  // ChildChannel.  Used during redirects.
+  bool ConnectChannel(const uint32_t& channelId);
 
-  virtual bool RecvConnectChannel(const uint32_t& channelId);
+  bool DoAsyncOpen(const URIParams&           uri,
+                   const OptionalURIParams&   originalUri,
+                   const OptionalURIParams&   docUri,
+                   const OptionalURIParams&   referrerUri,
+                   const OptionalURIParams&   internalRedirectUri,
+                   const uint32_t&            loadFlags,
+                   const RequestHeaderTuples& requestHeaders,
+                   const nsHttpAtom&          requestMethod,
+                   const OptionalInputStreamParams& uploadStream,
+                   const bool&                uploadStreamHasHeaders,
+                   const uint16_t&            priority,
+                   const uint8_t&             redirectionLimit,
+                   const bool&                allowPipelining,
+                   const bool&                forceAllowThirdPartyCookie,
+                   const bool&                doResumeAt,
+                   const uint64_t&            startPos,
+                   const nsCString&           entityID,
+                   const bool&                chooseApplicationCache,
+                   const nsCString&           appCacheClientID,
+                   const bool&                allowSpdy);
+
   virtual bool RecvSetPriority(const uint16_t& priority);
   virtual bool RecvSetCacheTokenCachedCharset(const nsCString& charset);
   virtual bool RecvSuspend();
   virtual bool RecvResume();
   virtual bool RecvCancel(const nsresult& status);
   virtual bool RecvRedirect2Verify(const nsresult& result,
                                    const RequestHeaderTuples& changedHeaders,
                                    const OptionalURIParams&   apiRedirectUri);
--- a/netwerk/protocol/http/HttpChannelParentListener.cpp
+++ b/netwerk/protocol/http/HttpChannelParentListener.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "HttpChannelParentListener.h"
 #include "mozilla/net/HttpChannelParent.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/unused.h"
 #include "nsHttpChannel.h"
 #include "nsHttpHandler.h"
 #include "nsNetUtil.h"
--- a/netwerk/protocol/http/HttpInfo.cpp
+++ b/netwerk/protocol/http/HttpInfo.cpp
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http:mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpHandler.h"
 #include "HttpInfo.h"
 
 
 void
 mozilla::net::HttpInfo::
 GetHttpConnectionData(nsTArray<HttpRetParams>* args)
 {
copy from netwerk/protocol/http/nsHttp.h
copy to netwerk/protocol/http/HttpLog.h
--- a/netwerk/protocol/http/nsHttp.h
+++ b/netwerk/protocol/http/HttpLog.h
@@ -1,45 +1,54 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef nsHttp_h__
-#define nsHttp_h__
+#ifndef HttpLog_h__
+#define HttpLog_h__
+
+
+/*******************************************************************************
+ *  This file should ONLY be #included by source (.cpp) files in the /http
+ *  directory, not headers (.h).  If you need to use LOG() in a .h file, call
+ *  PR_LOG directly.
+ *
+ *  This file should also be the first #include in your file.
+ *
+ *  Yes, this is kludgy.
+ *******************************************************************************/
+
 
+// e10s mess: IPDL-generated headers include chromium files that both #include
+// prlog.h, and #define LOG in conflict with this file.
+// Solution: (as described in bug 545995)
+// 1) ensure that this file is #included before any IPDL-generated files and
+//    anything else that #includes prlog.h, so that we can make sure prlog.h
+//    sees FORCE_PR_LOG
+// 2) #include IPDL boilerplate, and then undef LOG so our LOG wins.
+// 3) nsNetModule.cpp does its own crazy stuff with #including prlog.h
+//    multiple times; allow it to define ALLOW_LATE_HTTPLOG_H_INCLUDE to bypass
+//    check.
+#if defined(PR_LOG) && !defined(ALLOW_LATE_HTTPLOG_H_INCLUDE)
+#error "If HttpLog.h #included it must come before any IPDL-generated files or other files that #include prlog.h"
+#endif
+
+// NeckoChild.h will include chromium, which will include prlog.h so define
+// PR_FORCE before we do that.
 #if defined(MOZ_LOGGING)
 #define FORCE_PR_LOG
 #endif
 
-// e10s mess: IPDL-generatd headers include chromium which both #includes
-// prlog.h, and #defines LOG in conflict with this file.
-// Solution: (as described in bug 545995)
-// 1) ensure that this file is #included before any IPDL-generated files and
-//    anything else that #includes prlog.h, so that we can make sure prlog.h
-//    sees FORCE_PR_LOG if needed.
-// 2) #include IPDL boilerplate, and then undef LOG so our LOG wins.
-// 3) nsNetModule.cpp does its own crazy stuff with #including prlog.h
-//    multiple times; allow it to define ALLOW_LATE_NSHTTP_H_INCLUDE to bypass
-//    check.
-#if defined(PR_LOG) && !defined(ALLOW_LATE_NSHTTP_H_INCLUDE)
-#error "If nsHttp.h #included it must come before any IPDL-generated files or other files that #include prlog.h"
-#endif
 #include "mozilla/net/NeckoChild.h"
+
+// Get rid of Chromium's LOG definition
 #undef LOG
 
-#include "plstr.h"
-#include "prlog.h"
-#include "prtime.h"
-#include "nsISupportsUtils.h"
-#include "nsPromiseFlatString.h"
-#include "nsURLHelper.h"
-#include "netCore.h"
-
 #if defined(PR_LOGGING)
 //
 // Log module for HTTP Protocol logging...
 //
 // To enable logging (see prlog.h for full details):
 //
 //    set NSPR_LOG_MODULES=nsHttp:5
 //    set NSPR_LOG_FILE=http.log
@@ -58,169 +67,9 @@ extern PRLogModuleInfo *gHttpLog;
 #define LOG(args) LOG4(args)
 
 #define LOG1_ENABLED() PR_LOG_TEST(gHttpLog, 1)
 #define LOG2_ENABLED() PR_LOG_TEST(gHttpLog, 2)
 #define LOG3_ENABLED() PR_LOG_TEST(gHttpLog, 3)
 #define LOG4_ENABLED() PR_LOG_TEST(gHttpLog, 4)
 #define LOG_ENABLED() LOG4_ENABLED()
 
-// http version codes
-#define NS_HTTP_VERSION_UNKNOWN  0
-#define NS_HTTP_VERSION_0_9      9
-#define NS_HTTP_VERSION_1_0     10
-#define NS_HTTP_VERSION_1_1     11
-
-typedef uint8_t nsHttpVersion;
-
-//-----------------------------------------------------------------------------
-// http connection capabilities
-//-----------------------------------------------------------------------------
-
-#define NS_HTTP_ALLOW_KEEPALIVE      (1<<0)
-#define NS_HTTP_ALLOW_PIPELINING     (1<<1)
-
-// a transaction with this caps flag will continue to own the connection,
-// preventing it from being reclaimed, even after the transaction completes.
-#define NS_HTTP_STICKY_CONNECTION    (1<<2)
-
-// a transaction with this caps flag will, upon opening a new connection,
-// bypass the local DNS cache
-#define NS_HTTP_REFRESH_DNS          (1<<3)
-
-// a transaction with this caps flag will not pass SSL client-certificates
-// to the server (see bug #466080), but is may also be used for other things
-#define NS_HTTP_LOAD_ANONYMOUS       (1<<4)
-
-// a transaction with this caps flag keeps timing information
-#define NS_HTTP_TIMING_ENABLED       (1<<5)
-
-// a transaction with this flag blocks the initiation of other transactons
-// in the same load group until it is complete
-#define NS_HTTP_LOAD_AS_BLOCKING     (1<<6)
-
-// Disallow the use of the SPDY protocol. This is meant for the contexts
-// such as HTTP upgrade which are nonsensical for SPDY, it is not the
-// SPDY configuration variable.
-#define NS_HTTP_DISALLOW_SPDY        (1<<7)
-
-// a transaction with this flag loads without respect to whether the load
-// group is currently blocking on some resources
-#define NS_HTTP_LOAD_UNBLOCKED       (1<<8)
-
-//-----------------------------------------------------------------------------
-// some default values
-//-----------------------------------------------------------------------------
-
-#define NS_HTTP_DEFAULT_PORT  80
-#define NS_HTTPS_DEFAULT_PORT 443
-
-#define NS_HTTP_HEADER_SEPS ", \t"
-
-//-----------------------------------------------------------------------------
-// http atoms...
-//-----------------------------------------------------------------------------
-
-struct nsHttpAtom
-{
-    operator const char *() const { return _val; }
-    const char *get() const { return _val; }
-
-    void operator=(const char *v) { _val = v; }
-    void operator=(const nsHttpAtom &a) { _val = a._val; }
-
-    // private
-    const char *_val;
-};
-
-struct nsHttp
-{
-    static nsresult CreateAtomTable();
-    static void DestroyAtomTable();
-
-    // The mutex is valid any time the Atom Table is valid
-    // This mutex is used in the unusual case that the network thread and
-    // main thread might access the same data
-    static mozilla::Mutex *GetLock();
-
-    // will dynamically add atoms to the table if they don't already exist
-    static nsHttpAtom ResolveAtom(const char *);
-    static nsHttpAtom ResolveAtom(const nsACString &s)
-    {
-        return ResolveAtom(PromiseFlatCString(s).get());
-    }
-
-    // returns true if the specified token [start,end) is valid per RFC 2616
-    // section 2.2
-    static bool IsValidToken(const char *start, const char *end);
-
-    static inline bool IsValidToken(const nsCString &s) {
-        const char *start = s.get();
-        return IsValidToken(start, start + s.Length());
-    }
-
-    // find the first instance (case-insensitive comparison) of the given
-    // |token| in the |input| string.  the |token| is bounded by elements of
-    // |separators| and may appear at the beginning or end of the |input|
-    // string.  null is returned if the |token| is not found.  |input| may be
-    // null, in which case null is returned.
-    static const char *FindToken(const char *input, const char *token,
-                                 const char *separators);
-
-    // This function parses a string containing a decimal-valued, non-negative
-    // 64-bit integer.  If the value would exceed INT64_MAX, then false is
-    // returned.  Otherwise, this function returns true and stores the
-    // parsed value in |result|.  The next unparsed character in |input| is
-    // optionally returned via |next| if |next| is non-null.
-    //
-    // TODO(darin): Replace this with something generic.
-    //
-    static bool ParseInt64(const char *input, const char **next,
-                             int64_t *result);
-
-    // Variant on ParseInt64 that expects the input string to contain nothing
-    // more than the value being parsed.
-    static inline bool ParseInt64(const char *input, int64_t *result) {
-        const char *next;
-        return ParseInt64(input, &next, result) && *next == '\0';
-    }
-
-    // Return whether the HTTP status code represents a permanent redirect
-    static bool IsPermanentRedirect(uint32_t httpStatus);
-
-    // Return whether upon a redirect code of httpStatus for method, the
-    // request method should be rewritten to GET.
-    static bool ShouldRewriteRedirectToGET(uint32_t httpStatus, nsHttpAtom method);
-
-    // Return whether the specified method is safe as per RFC 2616,
-    // Section 9.1.1.
-    static bool IsSafeMethod(nsHttpAtom method);
-
-    // Declare all atoms
-    //
-    // The atom names and values are stored in nsHttpAtomList.h and are brought
-    // to you by the magic of C preprocessing.  Add new atoms to nsHttpAtomList
-    // and all support logic will be auto-generated.
-    //
-#define HTTP_ATOM(_name, _value) static nsHttpAtom _name;
-#include "nsHttpAtomList.h"
-#undef HTTP_ATOM
-};
-
-//-----------------------------------------------------------------------------
-// utilities...
-//-----------------------------------------------------------------------------
-
-static inline uint32_t
-PRTimeToSeconds(PRTime t_usec)
-{
-    return uint32_t( t_usec / PR_USEC_PER_SEC );
-}
-
-#define NowInSeconds() PRTimeToSeconds(PR_Now())
-
-// Round q-value to 2 decimal places; return 2 most significant digits as uint.
-#define QVAL_TO_UINT(q) ((unsigned int) ((q + 0.005) * 100.0))
-
-#define HTTP_LWS " \t"
-#define HTTP_HEADER_VALUE_SEPS HTTP_LWS ","
-
-#endif // nsHttp_h__
+#endif // HttpLog_h__
--- a/netwerk/protocol/http/NullHttpTransaction.cpp
+++ b/netwerk/protocol/http/NullHttpTransaction.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "NullHttpTransaction.h"
 #include "nsProxyRelease.h"
 #include "nsHttpHandler.h"
 
 namespace mozilla {
 namespace net {
 
--- a/netwerk/protocol/http/PHttpChannel.ipdl
+++ b/netwerk/protocol/http/PHttpChannel.ipdl
@@ -26,43 +26,18 @@ namespace mozilla {
 namespace net {
 
 //-------------------------------------------------------------------
 protocol PHttpChannel
 {
   manager PNecko;
 
 parent:
-  AsyncOpen(URIParams           uri,
-            // - TODO: bug 571161: unclear if any HTTP channel clients ever
-            // set originalURI != uri (about:credits?); also not clear if
-            // chrome channel would ever need to know.  Get rid of next arg?
-            OptionalURIParams   original,
-            OptionalURIParams   doc,
-            OptionalURIParams   referrer,
-            OptionalURIParams   apiRedirectTo,
-            uint32_t            loadFlags,
-            RequestHeaderTuples requestHeaders,
-            nsHttpAtom          requestMethod,
-            OptionalInputStreamParams uploadStream,
-            bool                uploadStreamHasHeaders,
-            uint16_t            priority,
-            uint8_t             redirectionLimit,
-            bool                allowPipelining,
-            bool                forceAllowThirdPartyCookie,
-            bool                resumeAt,
-            uint64_t            startPos,
-            nsCString           entityID,
-            bool                chooseApplicationCache,
-            nsCString           appCacheClientID,
-            bool                allowSpdy);
-
-  // Used to connect redirected-to channel on the parent with redirected-to
-  // channel on the child.
-  ConnectChannel(uint32_t channelId);
+  // Note: channels are opened during construction, so no open method here:
+  // see PNecko.ipdl
 
   SetPriority(uint16_t priority);
 
   SetCacheTokenCachedCharset(nsCString charset);
 
   UpdateAssociatedContentSecurity(int32_t broken,
                                   int32_t no);
   Suspend();
--- a/netwerk/protocol/http/PHttpChannelParams.h
+++ b/netwerk/protocol/http/PHttpChannelParams.h
@@ -20,16 +20,22 @@
 
 namespace mozilla {
 namespace net {
 
 struct RequestHeaderTuple {
   nsCString mHeader;
   nsCString mValue;
   bool      mMerge;
+
+  bool operator ==(const RequestHeaderTuple &other) const {
+    return mHeader.Equals(other.mHeader) &&
+           mValue.Equals(other.mValue) &&
+           mMerge == other.mMerge;
+  }
 };
 
 typedef nsTArray<RequestHeaderTuple> RequestHeaderTuples;
 
 } // namespace net
 } // namespace mozilla
 
 namespace IPC {
--- a/netwerk/protocol/http/SpdyPush3.cpp
+++ b/netwerk/protocol/http/SpdyPush3.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include <algorithm>
 
 #include "nsDependentString.h"
 #include "SpdyPush3.h"
 
 namespace mozilla {
 namespace net {
 
--- a/netwerk/protocol/http/SpdySession2.cpp
+++ b/netwerk/protocol/http/SpdySession2.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "SpdySession2.h"
 #include "SpdyStream2.h"
 #include "nsHttpConnection.h"
 #include "nsHttpHandler.h"
 #include "prnetdb.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/Preferences.h"
--- a/netwerk/protocol/http/SpdySession3.cpp
+++ b/netwerk/protocol/http/SpdySession3.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "mozilla/Telemetry.h"
 #include "mozilla/Preferences.h"
 #include "nsHttp.h"
 #include "nsHttpHandler.h"
 #include "nsHttpConnection.h"
 #include "nsILoadGroup.h"
 #include "prprf.h"
 #include "prnetdb.h"
--- a/netwerk/protocol/http/SpdyStream2.cpp
+++ b/netwerk/protocol/http/SpdyStream2.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "SpdySession2.h"
 #include "SpdyStream2.h"
 #include "nsAlgorithm.h"
 #include "prnetdb.h"
 #include "nsHttpRequestHead.h"
 #include "mozilla/Telemetry.h"
 #include "nsISocketTransport.h"
--- a/netwerk/protocol/http/SpdyStream3.cpp
+++ b/netwerk/protocol/http/SpdyStream3.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "mozilla/Telemetry.h"
 #include "nsAlgorithm.h"
 #include "nsHttp.h"
 #include "nsHttpHandler.h"
 #include "nsHttpRequestHead.h"
 #include "nsISocketTransport.h"
 #include "nsISupportsPriority.h"
 #include "prnetdb.h"
--- a/netwerk/protocol/http/nsHttp.cpp
+++ b/netwerk/protocol/http/nsHttp.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "pldhash.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/HashFunctions.h"
 #include "nsCRT.h"
 #include "prbit.h"
 
 using namespace mozilla;
--- a/netwerk/protocol/http/nsHttp.h
+++ b/netwerk/protocol/http/nsHttp.h
@@ -2,71 +2,23 @@
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsHttp_h__
 #define nsHttp_h__
 
-#if defined(MOZ_LOGGING)
-#define FORCE_PR_LOG
-#endif
-
-// e10s mess: IPDL-generatd headers include chromium which both #includes
-// prlog.h, and #defines LOG in conflict with this file.
-// Solution: (as described in bug 545995)
-// 1) ensure that this file is #included before any IPDL-generated files and
-//    anything else that #includes prlog.h, so that we can make sure prlog.h
-//    sees FORCE_PR_LOG if needed.
-// 2) #include IPDL boilerplate, and then undef LOG so our LOG wins.
-// 3) nsNetModule.cpp does its own crazy stuff with #including prlog.h
-//    multiple times; allow it to define ALLOW_LATE_NSHTTP_H_INCLUDE to bypass
-//    check.
-#if defined(PR_LOG) && !defined(ALLOW_LATE_NSHTTP_H_INCLUDE)
-#error "If nsHttp.h #included it must come before any IPDL-generated files or other files that #include prlog.h"
-#endif
-#include "mozilla/net/NeckoChild.h"
-#undef LOG
-
 #include "plstr.h"
-#include "prlog.h"
 #include "prtime.h"
 #include "nsISupportsUtils.h"
 #include "nsPromiseFlatString.h"
 #include "nsURLHelper.h"
 #include "netCore.h"
-
-#if defined(PR_LOGGING)
-//
-// Log module for HTTP Protocol logging...
-//
-// To enable logging (see prlog.h for full details):
-//
-//    set NSPR_LOG_MODULES=nsHttp:5
-//    set NSPR_LOG_FILE=http.log
-//
-// this enables PR_LOG_ALWAYS level information and places all output in
-// the file http.log
-//
-extern PRLogModuleInfo *gHttpLog;
-#endif
-
-// http logging
-#define LOG1(args) PR_LOG(gHttpLog, 1, args)
-#define LOG2(args) PR_LOG(gHttpLog, 2, args)
-#define LOG3(args) PR_LOG(gHttpLog, 3, args)
-#define LOG4(args) PR_LOG(gHttpLog, 4, args)
-#define LOG(args) LOG4(args)
-
-#define LOG1_ENABLED() PR_LOG_TEST(gHttpLog, 1)
-#define LOG2_ENABLED() PR_LOG_TEST(gHttpLog, 2)
-#define LOG3_ENABLED() PR_LOG_TEST(gHttpLog, 3)
-#define LOG4_ENABLED() PR_LOG_TEST(gHttpLog, 4)
-#define LOG_ENABLED() LOG4_ENABLED()
+#include "mozilla/Mutex.h"
 
 // http version codes
 #define NS_HTTP_VERSION_UNKNOWN  0
 #define NS_HTTP_VERSION_0_9      9
 #define NS_HTTP_VERSION_1_0     10
 #define NS_HTTP_VERSION_1_1     11
 
 typedef uint8_t nsHttpVersion;
--- a/netwerk/protocol/http/nsHttpActivityDistributor.cpp
+++ b/netwerk/protocol/http/nsHttpActivityDistributor.cpp
@@ -1,12 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpActivityDistributor.h"
 #include "nsIChannel.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsNetUtil.h"
 #include "nsThreadUtils.h"
 
 using namespace mozilla;
--- a/netwerk/protocol/http/nsHttpAuthCache.cpp
+++ b/netwerk/protocol/http/nsHttpAuthCache.cpp
@@ -1,13 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpAuthCache.h"
 #include <stdlib.h>
 #include "base/compiler_specific.h"
 #include "nsHttp.h"
 #include "nsString.h"
 #include "nsCRT.h"
 #include "prprf.h"
 #include "mozIApplicationClearPrivateDataParams.h"
--- a/netwerk/protocol/http/nsHttpAuthManager.cpp
+++ b/netwerk/protocol/http/nsHttpAuthManager.cpp
@@ -1,13 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpHandler.h"
 #include "nsHttpChannel.h"
 #include "nsHttpAuthManager.h"
 #include "nsReadableUtils.h"
 #include "nsNetUtil.h"
 #include "nsIPrincipal.h"
 
 NS_IMPL_ISUPPORTS1(nsHttpAuthManager, nsIHttpAuthManager)
--- a/netwerk/protocol/http/nsHttpBasicAuth.cpp
+++ b/netwerk/protocol/http/nsHttpBasicAuth.cpp
@@ -1,18 +1,19 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <stdlib.h>
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpBasicAuth.h"
 #include "plbase64.h"
-#include "plstr.h"
 #include "nsString.h"
 
 //-----------------------------------------------------------------------------
 // nsHttpBasicAuth <public>
 //-----------------------------------------------------------------------------
 
 nsHttpBasicAuth::nsHttpBasicAuth()
 {
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set expandtab ts=4 sw=4 sts=4 cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpChannel.h"
 #include "nsHttpHandler.h"
 #include "nsStandardURL.h"
 #include "nsIApplicationCacheService.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIAuthInformation.h"
 #include "nsICryptoHash.h"
--- a/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp
+++ b/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set expandtab ts=4 sw=4 sts=4 cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpChannelAuthProvider.h"
 #include "nsNetUtil.h"
 #include "nsHttpHandler.h"
 #include "nsIHttpAuthenticator.h"
 #include "nsIAuthPrompt2.h"
 #include "nsIAuthPromptProvider.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
--- a/netwerk/protocol/http/nsHttpChunkedDecoder.cpp
+++ b/netwerk/protocol/http/nsHttpChunkedDecoder.cpp
@@ -1,13 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpChunkedDecoder.h"
 #include "nsHttp.h"
 #include <algorithm>
 
 //-----------------------------------------------------------------------------
 // nsHttpChunkedDecoder <public>
 //-----------------------------------------------------------------------------
 
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpConnection.h"
 #include "nsHttpTransaction.h"
 #include "nsHttpRequestHead.h"
 #include "nsHttpResponseHead.h"
 #include "nsHttpHandler.h"
 #include "nsIOService.h"
 #include "nsISocketTransportService.h"
 #include "nsISocketTransport.h"
--- a/netwerk/protocol/http/nsHttpConnectionInfo.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionInfo.cpp
@@ -1,15 +1,43 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set sw=4 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpConnectionInfo.h"
 
+nsHttpConnectionInfo::nsHttpConnectionInfo(const nsACString &host, int32_t port,
+                                           nsProxyInfo* proxyInfo,
+                                           bool usingSSL)
+    : mRef(0)
+    , mProxyInfo(proxyInfo)
+    , mUsingSSL(usingSSL)
+    , mUsingConnect(false)
+{
+    LOG(("Creating nsHttpConnectionInfo @%x\n", this));
+
+    mUsingHttpProxy = (proxyInfo && proxyInfo->IsHTTP());
+
+    if (mUsingHttpProxy) {
+        mUsingConnect = mUsingSSL;  // SSL always uses CONNECT
+        uint32_t resolveFlags = 0;
+        if (NS_SUCCEEDED(mProxyInfo->GetResolveFlags(&resolveFlags)) &&
+            resolveFlags & nsIProtocolProxyService::RESOLVE_ALWAYS_TUNNEL) {
+            mUsingConnect = true;
+        }
+    }
+
+    SetOriginServer(host, port);
+}
+
 void
 nsHttpConnectionInfo::SetOriginServer(const nsACString &host, int32_t port)
 {
     mHost = host;
     mPort = port == -1 ? DefaultPort() : port;
 
     //
     // build hash key:
--- a/netwerk/protocol/http/nsHttpConnectionInfo.h
+++ b/netwerk/protocol/http/nsHttpConnectionInfo.h
@@ -1,59 +1,42 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set sw=4 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsHttpConnectionInfo_h__
 #define nsHttpConnectionInfo_h__
 
 #include "nsHttp.h"
 #include "nsProxyInfo.h"
 #include "nsCOMPtr.h"
 #include "nsDependentString.h"
 #include "nsString.h"
 #include "plstr.h"
 #include "nsCRT.h"
 #include "nsIProtocolProxyService.h"
 
+extern PRLogModuleInfo *gHttpLog;
+
 //-----------------------------------------------------------------------------
 // nsHttpConnectionInfo - holds the properties of a connection
 //-----------------------------------------------------------------------------
 
 class nsHttpConnectionInfo
 {
 public:
     nsHttpConnectionInfo(const nsACString &host, int32_t port,
                          nsProxyInfo* proxyInfo,
-                         bool usingSSL=false)
-        : mRef(0)
-        , mProxyInfo(proxyInfo)
-        , mUsingSSL(usingSSL)
-        , mUsingConnect(false)
-    {
-        LOG(("Creating nsHttpConnectionInfo @%x\n", this));
-
-        mUsingHttpProxy = (proxyInfo && proxyInfo->IsHTTP());
-
-        if (mUsingHttpProxy) {
-            mUsingConnect = mUsingSSL;  // SSL always uses CONNECT
-            uint32_t resolveFlags = 0;
-            if (NS_SUCCEEDED(mProxyInfo->GetResolveFlags(&resolveFlags)) &&
-                resolveFlags & nsIProtocolProxyService::RESOLVE_ALWAYS_TUNNEL) {
-                mUsingConnect = true;
-            }
-        }
-
-        SetOriginServer(host, port);
-    }
+                         bool usingSSL=false);
 
    ~nsHttpConnectionInfo()
     {
-        LOG(("Destroying nsHttpConnectionInfo @%x\n", this));
+        PR_LOG(gHttpLog, 4, ("Destroying nsHttpConnectionInfo @%x\n", this));
     }
 
     nsrefcnt AddRef()
     {
         nsrefcnt n = NS_AtomicIncrementRefcnt(mRef);
         NS_LOG_ADDREF(this, n, "nsHttpConnectionInfo", sizeof(*this));
         return n;
     }
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -1,13 +1,16 @@
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpConnectionMgr.h"
 #include "nsHttpConnection.h"
 #include "nsHttpPipeline.h"
 #include "nsHttpHandler.h"
 #include "nsIHttpChannelInternal.h"
 #include "nsNetCID.h"
 #include "nsCOMPtr.h"
 #include "nsNetUtil.h"
--- a/netwerk/protocol/http/nsHttpDigestAuth.cpp
+++ b/netwerk/protocol/http/nsHttpDigestAuth.cpp
@@ -1,28 +1,29 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <stdlib.h>
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpDigestAuth.h"
 #include "nsIHttpAuthenticableChannel.h"
 #include "nsIServiceManager.h"
 #include "nsXPCOM.h"
 #include "nsISupportsPrimitives.h"
 #include "nsIURI.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsEscape.h"
 #include "nsNetCID.h"
 #include "plbase64.h"
-#include "plstr.h"
 #include "prprf.h"
 #include "nsCRT.h"
 
 //-----------------------------------------------------------------------------
 // nsHttpDigestAuth <public>
 //-----------------------------------------------------------------------------
 
 nsHttpDigestAuth::nsHttpDigestAuth()
--- a/netwerk/protocol/http/nsHttpHandler.cpp
+++ b/netwerk/protocol/http/nsHttpHandler.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpHandler.h"
 #include "nsHttpChannel.h"
 #include "nsHttpConnection.h"
 #include "nsHttpResponseHead.h"
 #include "nsHttpTransaction.h"
 #include "nsHttpAuthCache.h"
 #include "nsStandardURL.h"
--- a/netwerk/protocol/http/nsHttpHeaderArray.cpp
+++ b/netwerk/protocol/http/nsHttpHeaderArray.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 ci et: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpHeaderArray.h"
 #include "nsHttp.h"
 
 //-----------------------------------------------------------------------------
 // nsHttpHeaderArray <public>
 //-----------------------------------------------------------------------------
 nsresult
 nsHttpHeaderArray::SetHeader(nsHttpAtom header,
--- a/netwerk/protocol/http/nsHttpNTLMAuth.cpp
+++ b/netwerk/protocol/http/nsHttpNTLMAuth.cpp
@@ -1,14 +1,16 @@
 /* vim:set ts=4 sw=4 sts=4 et ci: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <stdlib.h>
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpNTLMAuth.h"
 #include "nsIComponentManager.h"
 #include "nsIAuthModule.h"
 #include "nsCOMPtr.h"
 #include "plbase64.h"
 #include "prnetdb.h"
 
--- a/netwerk/protocol/http/nsHttpPipeline.cpp
+++ b/netwerk/protocol/http/nsHttpPipeline.cpp
@@ -1,14 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <stdlib.h>
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttp.h"
 #include "nsHttpPipeline.h"
 #include "nsHttpHandler.h"
 #include "nsIOService.h"
 #include "nsIRequest.h"
 #include "nsISocketTransport.h"
 #include "nsIStringStream.h"
 #include "nsIPipe.h"
--- a/netwerk/protocol/http/nsHttpRequestHead.cpp
+++ b/netwerk/protocol/http/nsHttpRequestHead.cpp
@@ -1,13 +1,16 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpRequestHead.h"
 
 //-----------------------------------------------------------------------------
 // nsHttpRequestHead
 //-----------------------------------------------------------------------------
 
 void
 nsHttpRequestHead::Flatten(nsACString &buf, bool pruneProxyHeaders)
--- a/netwerk/protocol/http/nsHttpResponseHead.cpp
+++ b/netwerk/protocol/http/nsHttpResponseHead.cpp
@@ -1,15 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include <stdlib.h>
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "nsHttpResponseHead.h"
 #include "nsPrintfCString.h"
 #include "prprf.h"
 #include "prtime.h"
 #include "nsCRT.h"
 #include <algorithm>
 
 //-----------------------------------------------------------------------------
--- a/netwerk/protocol/http/nsHttpResponseHead.h
+++ b/netwerk/protocol/http/nsHttpResponseHead.h
@@ -23,16 +23,18 @@ public:
                          , mContentLength(UINT64_MAX)
                          , mCacheControlNoStore(false)
                          , mCacheControlNoCache(false)
                          , mPragmaNoCache(false) {}
 
     const nsHttpHeaderArray & Headers()   const { return mHeaders; }
     nsHttpHeaderArray    &Headers()             { return mHeaders; }
     nsHttpVersion         Version()       const { return mVersion; }
+// X11's Xlib.h #defines 'Status' to 'int' on some systems!
+#undef Status
     uint16_t              Status()        const { return mStatus; }
     const nsAFlatCString &StatusText()    const { return mStatusText; }
     int64_t               ContentLength() const { return mContentLength; }
     const nsAFlatCString &ContentType()   const { return mContentType; }
     const nsAFlatCString &ContentCharset() const { return mContentCharset; }
     bool                  NoStore() const { return mCacheControlNoStore; }
     bool                  NoCache() const { return (mCacheControlNoCache || mPragmaNoCache); }
     /**
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -1,14 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:set ts=4 sw=4 sts=4 et cin: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+// HttpLog.h should generally be included first
+#include "HttpLog.h"
+
 #include "base/basictypes.h"
 
 #include "nsIOService.h"
 #include "nsHttpHandler.h"
 #include "nsHttpTransaction.h"
 #include "nsHttpConnection.h"
 #include "nsHttpRequestHead.h"
 #include "nsHttpResponseHead.h"
--- a/security/manager/locales/en-US/chrome/pipnss/pipnss.properties
+++ b/security/manager/locales/en-US/chrome/pipnss/pipnss.properties
@@ -333,25 +333,16 @@ CertInfoIssuedFor=Issued to:
 CertInfoIssuedBy=Issued by:
 CertInfoValid=Valid
 CertInfoFrom=from
 CertInfoTo=to
 CertInfoPurposes=Purposes
 CertInfoEmail=Email
 CertInfoStoredIn=Stored in:
 P12DefaultNickname=Imported Certificate
-CrlImportFailure1x=The application cannot import the Certificate Revocation List (CRL).
-CrlImportFailureExpired=A more recent version of this CRL is available.
-CrlImportFailureBadSignature=CRL has an invalid Signature.
-CrlImportFailureInvalid=New CRL has an invalid format.
-CrlImportFailureOld=New CRL is older than the current one.
-CrlImportFailureNotYetValid=The CRL is not yet valid. You might want to check your system clock.
-CrlImportFailureNetworkProblem=Download of the CRL failed due to Network problems.
-CrlImportFailureReasonUnknown=Error Importing CRL to local Database. Error Code: 
-CrlImportFailure2=Please ask your system administrator for assistance.
 NSSInitProblemX=Could not initialize the application's security component. The most likely cause is problems with files in your application's profile directory. Please check that this directory has no read/write restrictions and your hard disk is not full or close to full. It is recommended that you exit the application and fix the problem. If you continue to use this session, you might see incorrect application behaviour when accessing security features.
 VerifyExpired=<Expired>
 VerifyRevoked=<Revoked>
 VerifyNotTrusted=<Not Trusted>
 VerifyIssuerNotTrusted=<Issuer Not Trusted>
 VerifyIssuerUnknown=<Issuer Unknown>
 VerifyInvalidCA=<Invalid CA>
 VerifyDisabledAlgorithm=<Signature Algorithm Not Secure>
--- a/security/manager/locales/en-US/chrome/pippki/pippki.dtd
+++ b/security/manager/locales/en-US/chrome/pippki/pippki.dtd
@@ -71,18 +71,16 @@
 
 <!ENTITY escrowWarn.title "Encryption Key Copy">
 <!ENTITY escrowWarn.message1 "Important: This certificate authority has asked to make a backup of your encryption private key.">
 <!ENTITY escrowWarn.benefit1 "The benefit is that if you lose access to your encryption private key, you can request a copy from this certificate authority.">
 <!ENTITY escrowWarn.message2 "However, your encryption private key will be stored by the certificate authority, and could be used to read your encrypted email or documents without your permission.">
 <!ENTITY examineCert.label "View Certificate">
 <!ENTITY examineCert.accesskey "V">
 
-<!ENTITY serverCrlNextupdate.message "Please ask your system administrator for assistance">
-
 <!-- Strings for the CreateCertInfo dialog  -->
 <!ENTITY createCertInfo.title "Generating A Private Key">
 <!ENTITY createCertInfo.msg1 "Key Generation in progress… This may take a few minutes….">
 <!ENTITY createCertInfo.msg2 "Please wait…">
 
 <!-- Form Signing confirmation prompt -->
 <!ENTITY formSigning.title "Text Signing Request">
 <!ENTITY formSigning.cert "Signing Certificate">
--- a/security/manager/locales/en-US/chrome/pippki/pippki.properties
+++ b/security/manager/locales/en-US/chrome/pippki/pippki.properties
@@ -120,40 +120,18 @@ devinfo_stat_uninitialized=Uninitialized
 devinfo_stat_notloggedin=Not Logged In
 devinfo_stat_loggedin=Logged In
 devinfo_stat_ready=Ready
 enable_fips=Enable FIPS
 disable_fips=Disable FIPS
 fips_nonempty_password_required=FIPS mode requires that you have a Master Password set for each security device. Please set the password before trying to enable FIPS mode.
 unable_to_toggle_fips=Unable to change the FIPS mode for the security device. It is recommended that you exit and restart this application.
 
-# CRL next update.
-crlNextUpdateMsg1=%S cannot establish an encrypted connection with "%S".
-crlNextUpdateMsg2=The certificate revocation list (CRL) from "%S" needs to be updated.
-NoUpdateFailure=None
-lastFetchUrlLabel=URL originally fetched from
-advertisedUrlLabel=URL advertised by the CA
-crlAutoUpdateDayCntError=Number of days before next update must be a number greater than zero.
-crlAutoUpdtaeFreqCntError=Frequency of update must be a number greater than zero.
-disabledStatement=Automatic Update is not enabled for this CRL.
-enabledStatement=Automatic Update is enabled for this CRL.
-crlAutoupdateQuestion1=Would you like to enable automatic update?
-crlAutoupdateQuestion2=Would you like to view the automatic update settings?
-undefinedValStr=<Not Defined>
-undefinedURL=Auto update URL is not defined.
-yesButton=Yes
-noButton=No
 resetPasswordConfirmationTitle=Reset Master Password
 resetPasswordConfirmationMessage=Your password has been reset.
-crlAutoupdateEnabled=Enabled
-crlAutoupdateNotEnabled=Not Enabled
-crlAutoupdateOk=OK
-crlAutoupdateFailed=Failed
-crlImportNewCRLTitle=Import Certificate Revocation List
-crlImportNewCRLLabel=Import the CRL from:
 
 #Import certificate(s) file dialog
 importEmailCertPrompt=Select File containing somebody's Email certificate to import
 importCACertsPrompt=Select File containing CA certificate(s) to import
 importServerCertPrompt=Select File containing Server certificate to import
 file_browse_Certificate_spec=Certificate Files
 
 # Form Signing confirmation prompt
deleted file mode 100644
--- a/security/manager/locales/en-US/chrome/pippki/validation.dtd
+++ /dev/null
@@ -1,34 +0,0 @@
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<!ENTITY  validation.crlmanager.label             "Manage CRLs">
-<!ENTITY  validation.crlmanager.description       "These Certificate Revocation Lists (CRL) are stored in your certificate database:">
-<!ENTITY  validation.crlname.label                "Name">
-<!ENTITY  validation.crllastupdate.label          "Last Update">
-<!ENTITY  validation.crlnextupdate.label          "Next Update">
-<!ENTITY  validation.crlautoupdateenabled.label   "Auto Update">
-<!ENTITY  validation.crlautoupdatestatus.label    "Auto Update Status">
-<!ENTITY  validation.deletecrl.label              "Delete">
-<!ENTITY  validation.deletecrl.accesskey          "D">
-<!ENTITY  validation.updatecrl.label              "Update">
-<!ENTITY  validation.updatecrl.accesskey          "U">
-<!ENTITY  validation.advanced.label               "Settings">
-<!ENTITY  validation.advanced.accesskey           "S">
-
-<!ENTITY  validation.crl.autoupdate.title         "Automatic CRL Update Preferences">
-<!ENTITY  validation.crl.autoupdate.enable.label  "Enable Automatic Update for this CRL">
-<!ENTITY  validation.crl.autoupdate.time.label1   "Update">
-<!ENTITY  validation.crl.autoupdate.time.label2   "Day(s) before Next Update date">
-<!ENTITY  validation.crl.autoupdate.freq.label1   "Update every">
-<!ENTITY  validation.crl.autoupdate.freq.label2   "Day(s)">
-<!ENTITY  validation.crl.autoupdate.url.label     "CRL would be imported From:">
-<!ENTITY  crl.import.status.title                 "CRL Import Status">
-<!ENTITY  crl.import.success.message              "The Certificate Revocation List (CRL) was successfully imported.">
-<!ENTITY  crl.issuer.label                        "CRL Issued By:">
-<!ENTITY  crl.issuer.org.label                    "Organization: ">
-<!ENTITY  crl.issuer.orgunit.label                "Unit: ">
-<!ENTITY  crl.import.nextupdate.label             "Next Update On: ">
-<!ENTITY  crl.autoupdate.fail.cnt.label           "Previous Consecutive Update Failures: ">
-<!ENTITY  crl.autoupdate.fail.reason.label        "Details of Last Update Failure: ">
-<!ENTITY  edit.button                             "Settings">
--- a/security/manager/locales/jar.mn
+++ b/security/manager/locales/jar.mn
@@ -9,9 +9,8 @@
 % locale pippki @AB_CD@ %locale/@AB_CD@/pippki/
   locale/@AB_CD@/pipnss/pipnss.properties     (%chrome/pipnss/pipnss.properties)
   locale/@AB_CD@/pipnss/nsserrors.properties  (%chrome/pipnss/nsserrors.properties)
   locale/@AB_CD@/pipnss/security.properties   (%chrome/pipnss/security.properties)
   locale/@AB_CD@/pippki/pippki.dtd            (%chrome/pippki/pippki.dtd)
   locale/@AB_CD@/pippki/pippki.properties     (%chrome/pippki/pippki.properties)
   locale/@AB_CD@/pippki/certManager.dtd       (%chrome/pippki/certManager.dtd)
   locale/@AB_CD@/pippki/deviceManager.dtd     (%chrome/pippki/deviceManager.dtd)
-  locale/@AB_CD@/pippki/validation.dtd        (%chrome/pippki/validation.dtd)
deleted file mode 100644
--- a/security/manager/pki/resources/content/crlImportDialog.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const nsPKIParamBlock    = "@mozilla.org/security/pkiparamblock;1";
-const nsIPKIParamBlock    = Components.interfaces.nsIPKIParamBlock;
-const nsIX509Cert         = Components.interfaces.nsIX509Cert;
-const nsICRLInfo          = Components.interfaces.nsICRLInfo;
-const nsIPrefService      = Components.interfaces.nsIPrefService
-
-var pkiParams;
-var cert;
-var crl;
-
-function onLoad()
-{
-  pkiParams = window.arguments[0].QueryInterface(nsIPKIParamBlock);  
-  isupport = pkiParams.getISupportAtIndex(1);
-  if (isupport) {
-    crl = isupport.QueryInterface(nsICRLInfo);
-  }
-  var bundle = document.getElementById("pippki_bundle");
-  var yesButton = bundle.getString("yesButton");
-  var noButton = bundle.getString("noButton");
-  document.documentElement.getButton("accept").label = yesButton;
-  document.documentElement.getButton("cancel").label = noButton;
-  
-  var nextUpdateStr;
-  var orgStr;
-  var orgUnitStr;
-
-  if(crl != null) {    
-    nextUpdateStr = crl.nextUpdateLocale;
-    if( (nextUpdateStr == null) || (nextUpdateStr.length == 0) ){
-      nextUpdateStr = bundle.getString("undefinedValStr");
-    }
-    var nextUpdate = document.getElementById("nextUpdate");
-    nextUpdate.setAttribute("value",nextUpdateStr);
-    var org = document.getElementById("orgText");
-    org.setAttribute("value", crl.organization);
-    var orgUnit = document.getElementById("orgUnitText");
-    orgUnit.setAttribute("value", crl.organizationalUnit);
-
-    var autoupdateEnabledString   = "security.crl.autoupdate.enable." + crl.nameInDb;
-    
-    var updateEnabled = false;
-    try {
-      var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefService);
-      var prefBranch = prefService.getBranch(null);
-      updateEnabled = prefBranch.getBoolPref(autoupdateEnabledString);
-      if(updateEnabled) {
-        var autoupdateURLString       = "security.crl.autoupdate.url." + crl.nameInDb;
-        prefBranch.setCharPref(autoupdateURLString, crl.lastFetchURL);
-        prefService.savePrefFile(null);
-      }
-    }catch(exception){}
-
-    var statement = document.getElementById("status");
-    var question = document.getElementById("question");
-    if(updateEnabled) {
-      statement.setAttribute("value", bundle.getString("enabledStatement"));
-      question.setAttribute("value", bundle.getString("crlAutoupdateQuestion2"));
-    } else {
-      statement.setAttribute("value", bundle.getString("disabledStatement"));
-      question.setAttribute("value", bundle.getString("crlAutoupdateQuestion1"));
-    }
-  }  
-}
-
-function onCancel()
-{
-  return true;
-}
-
-
-function onAccept()
-{
-  var params = Components.classes[nsPKIParamBlock].createInstance(nsIPKIParamBlock);
-  params.setISupportAtIndex(1, crl);
-  
-  window.openDialog("chrome://pippki/content/pref-crlupdate.xul","",
-                    "chrome,centerscreen,modal",params);
-  return true;
-}
deleted file mode 100644
--- a/security/manager/pki/resources/content/crlImportDialog.xul
+++ /dev/null
@@ -1,52 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<!DOCTYPE dialog SYSTEM "chrome://pippki/locale/validation.dtd">
-
-<dialog id="crlImportSuccess" 
-  title="&crl.import.status.title;"
-  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" 
-  onload="onLoad();"
-  buttons="accept,cancel"
-  ondialogaccept="return onAccept();"
-  ondialogcancel="return onCancel();">
-
-  <stringbundle id="pippki_bundle" src="chrome://pippki/locale/pippki.properties"/>
-
-  <script type="application/javascript" src="chrome://pippki/content/crlImportDialog.js" />
-  <script type="application/javascript" src="pippki.js" />
-
-  <vbox style="margin: 5px;" flex="1">
-
-    <text value="&crl.import.success.message;" />
-    <separator/>
-  
-    <text class="header" value="&crl.issuer.label;" />
-    <hbox>
-      <text value="&crl.issuer.org.label;" />
-      <text id="orgText" />
-    </hbox>
-    <hbox>
-      <text value="&crl.issuer.orgunit.label;" />
-      <text id="orgUnitText" />
-    </hbox>
-    <separator/>
-
-    <hbox>
-      <text value="&crl.import.nextupdate.label;" />
-      <text id="nextUpdate" />
-    </hbox>
-    <separator/>
-
-    <vbox>
-      <text id="status" />
-      <text id="question" />
-    </vbox>
-
-  </vbox>
-
-</dialog>
deleted file mode 100644
--- a/security/manager/pki/resources/content/crlManager.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const nsICRLManager = Components.interfaces.nsICRLManager;
-const nsCRLManager  = "@mozilla.org/security/crlmanager;1";
-const nsICRLInfo = Components.interfaces.nsICRLInfo;
-const nsISupportsArray = Components.interfaces.nsISupportsArray;
-const nsIPKIParamBlock    = Components.interfaces.nsIPKIParamBlock;
-const nsPKIParamBlock    = "@mozilla.org/security/pkiparamblock;1";
-const nsIPrefService      = Components.interfaces.nsIPrefService;
-
-var crlManager;
-var crls;
-var prefService;
-var prefBranch;
-
-var autoupdateEnabledBaseString   = "security.crl.autoupdate.enable.";
-var autoupdateTimeTypeBaseString  = "security.crl.autoupdate.timingType.";
-var autoupdateTimeBaseString      = "security.crl.autoupdate.nextInstant.";
-var autoupdateURLBaseString       = "security.crl.autoupdate.url.";
-var autoupdateErrCntBaseString    = "security.crl.autoupdate.errCount.";
-var autoupdateErrDetailBaseString = "security.crl.autoupdate.errDetail.";
-var autoupdateDayCntString        = "security.crl.autoupdate.dayCnt.";
-var autoupdateFreqCntString       = "security.crl.autoupdate.freqCnt.";
-
-function onLoad()
-{
-  var crlEntry;
-  var i;
-
-  crlManager = Components.classes[nsCRLManager].getService(nsICRLManager);
-  crls = crlManager.getCrls();
-  prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefService);
-  prefBranch = prefService.getBranch(null);
-  var bundle = document.getElementById("pippki_bundle");
-  var autoupdateEnabledString;
-  var autoupdateErrCntString;
-
-  for (i=0; i<crls.length; i++) {
-    crlEntry = crls.queryElementAt(i, nsICRLInfo);
-    var org = crlEntry.organization;
-    var orgUnit = crlEntry.organizationalUnit;
-    var lastUpdate = crlEntry.lastUpdateLocale;
-    var nextUpdate = crlEntry.nextUpdateLocale;
-    autoupdateEnabledString    = autoupdateEnabledBaseString + crlEntry.nameInDb;
-    autoupdateErrCntString    = autoupdateErrCntBaseString + crlEntry.nameInDb;
-    var enabled = false;
-    var enabledStr = bundle.getString("crlAutoupdateNotEnabled");
-    var status = "";
-    try{
-      enabled = prefBranch.getBoolPref(autoupdateEnabledString)
-      if(enabled){
-        enabledStr = bundle.getString("crlAutoupdateEnabled");
-      }
-      var cnt;
-      cnt = prefBranch.getIntPref(autoupdateErrCntString);
-      if(cnt > 0){
-        status = bundle.getString("crlAutoupdateFailed");
-      } else {
-        status = bundle.getString("crlAutoupdateOk");
-      }
-    }catch(exception){}
-    
-    AddItem("crlList", [org, orgUnit, lastUpdate, nextUpdate, enabledStr, status], "crltree_", i);
-  }
-}
-
-function AddItem(children,cells,prefix,idfier)
-{
-  var kids = document.getElementById(children);
-  var item  = document.createElement("treeitem");
-  var row   = document.createElement("treerow");
-  for(var i = 0; i < cells.length; i++)
-  {
-    var cell  = document.createElement("treecell");
-    cell.setAttribute("class", "propertylist");
-    cell.setAttribute("label", cells[i])
-    row.appendChild(cell);
-  }
-  item.appendChild(row);
-  item.setAttribute("id",prefix + idfier);
-  kids.appendChild(item);
-}
-
-function DeleteCrlSelected() {
-  var crlEntry;
-
-  // delete selected item
-  var crltree = document.getElementById("crltree");
-  var i = crltree.currentIndex;
-  if(i<0){
-    return;
-  }
-  crlEntry = crls.queryElementAt(i, nsICRLInfo);
-    
-  var autoupdateEnabled = false;
-  var autoupdateParamAvailable = false;
-  var id = crlEntry.nameInDb;
-  
-  //First, check if autoupdate was enabled for this crl
-  try {
-    autoupdateEnabled = prefBranch.getBoolPref(autoupdateEnabledBaseString + id);
-    //Note, if the pref is not present, we get an exception right here,
-    //and autoupdateEnabled remains false
-    autoupdateParamAvailable = true;
-    prefBranch.clearUserPref(autoupdateEnabledBaseString + id);
-    prefBranch.clearUserPref(autoupdateTimeTypeBaseString + id);
-    prefBranch.clearUserPref(autoupdateTimeBaseString + id);
-    prefBranch.clearUserPref(autoupdateURLBaseString + id);
-    prefBranch.clearUserPref(autoupdateDayCntString + id);
-    prefBranch.clearUserPref(autoupdateFreqCntString + id);
-    prefBranch.clearUserPref(autoupdateErrCntBaseString + id);
-    prefBranch.clearUserPref(autoupdateErrDetailBaseString + id);
-  } catch(Exception){}
-
-  //Once we have deleted the prefs that can be deleted, we save the 
-  //file if relevant, restart the scheduler, and once we are successful 
-  //in doind that, we try to delete the crl 
-  try{
-    if(autoupdateParamAvailable){
-      prefService.savePrefFile(null);
-    }
-
-    if(autoupdateEnabled){
-      crlManager.rescheduleCRLAutoUpdate();
-    }
-          
-    // Now, try to delete it
-    crlManager.deleteCrl(i);
-    DeleteItemSelected("crltree", "crltree_", "crlList");
-    //To do: If delete fails, we should be able to retrieve the deleted
-    //settings
-    //XXXXXXXXXXXXXXXXXXXXX
-  
-  }catch(exception) {
-    //To Do: Possibly show an error ...
-    //XXXXXXXXXXXX
-  }
-
-  EnableCrlActions();
-}
-
-function EnableCrlActions() {
-  var tree = document.getElementById("crltree");
-  if (tree.view.selection.count) {
-    document.getElementById("deleteCrl").removeAttribute("disabled");
-    document.getElementById("editPrefs").removeAttribute("disabled");
-    document.getElementById("updateCRL").removeAttribute("disabled");
-  } else {
-    document.getElementById("deleteCrl").setAttribute("disabled", "true");
-    document.getElementById("editPrefs").setAttribute("disabled", "true");
-    document.getElementById("updateCRL").setAttribute("disabled", "true");
-  }
-}
-
-function DeleteItemSelected(tree, prefix, kids) {
-  var i;
-  var delnarray = [];
-  var rv = "";
-  var cookietree = document.getElementById(tree);
-  var rangeCount = cookietree.view.selection.getRangeCount();
-  for(i = 0; i < rangeCount; ++i) 
-  { 
-    var start = {}, end = {};
-    cookietree.view.selection.getRangeAt(i, start, end);
-    for (var k = start.value; k <= end.value; ++k) {
-      var item = cookietree.contentView.getItemAtIndex(k);
-      delnarray[i] = document.getElementById(item.id);
-      var itemid = parseInt(item.id.substring(prefix.length, item.id.length));
-      rv += (itemid + ",");
-    }
-  }
-  for(i = 0; i < delnarray.length; i++) 
-  { 
-    document.getElementById(kids).removeChild(delnarray[i]);
-  }
-  return rv;
-}
-
-function EditAutoUpdatePrefs() {
-  var crlEntry;
-
-  // delete selected item
-  var crltree = document.getElementById("crltree");
-  var i = crltree.currentIndex;
-  if(i<0){
-    return;
-  }
-  crlEntry = crls.queryElementAt(i, nsICRLInfo);
-  var params = Components.classes[nsPKIParamBlock].createInstance(nsIPKIParamBlock);
-  params.setISupportAtIndex(1, crlEntry);
-  window.openDialog("chrome://pippki/content/pref-crlupdate.xul","",
-                    "chrome,centerscreen,modal", params);
-}
-
-function UpdateCRL()
-{
-  var crlEntry;
-  var crltree = document.getElementById("crltree");
-  var i = crltree.currentIndex;
-  if(i<0){
-    return;
-  }
-  crlEntry = crls.queryElementAt(i, nsICRLInfo);
-  crlManager.updateCRLFromURL(crlEntry.lastFetchURL, crlEntry.nameInDb);
-}
-
-function ImportCRL()
-{
-  // prompt for the URL to import from
-  var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
-  
-  var CRLLocation = {value:null};
-  var dummy = { value: 0 };
-  var strBundle = document.getElementById('pippki_bundle');
-  var addCRL = promptService.prompt(window, strBundle.getString('crlImportNewCRLTitle'), 
-                                    strBundle.getString('crlImportNewCRLLabel'),  CRLLocation, null, dummy);
-
-  if (addCRL)
-    crlManager.updateCRLFromURL(CRLLocation.value, "");
-}
deleted file mode 100644
--- a/security/manager/pki/resources/content/crlManager.xul
+++ /dev/null
@@ -1,71 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> 
-
-<!DOCTYPE dialog [
-    <!ENTITY % prefValDTD SYSTEM "chrome://pippki/locale/validation.dtd">
-    %prefValDTD;
-    <!ENTITY % prefCertMgrDTD SYSTEM "chrome://pippki/locale/certManager.dtd">
-    %prefCertMgrDTD;
-]>
-
-<dialog id="crlviewer"
-        windowtype="mozilla:crlmanager"
-        title="&validation.crlmanager.label;"
-        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
-        style="width: 65ch;"
-        onload="onLoad();"
-        buttons="accept"
-        buttonlabelaccept="&certmgr.close.label;"
-        persist="screenX screenY width height">
-
-  <stringbundle id="pippki_bundle" src="chrome://pippki/locale/pippki.properties"/>
-
-  <script type="application/javascript" src="chrome://pippki/content/crlManager.js"/>
-
-  <description value="&validation.crlmanager.description;"/>
-  <separator class="thin"/>
-  <tree id="crltree" style="height: 10em;"
-   onselect="EnableCrlActions()" flex="1">
-    <treecols>
-      <treecol id="Col1" flex="3" label="&certmgr.certdetail.o;"/>
-      <splitter class="tree-splitter"/>
-      <treecol id="Col2" flex="5" label="&certmgr.certdetail.ou;"/>
-      <splitter class="tree-splitter"/>
-      <treecol id="Col3" flex="2" label="&validation.crllastupdate.label;"/>
-      <splitter class="tree-splitter"/>
-      <treecol id="Col4" flex="2" label="&validation.crlnextupdate.label;"/>
-      <splitter class="tree-splitter"/>
-      <treecol id="Col5" flex="2" label="&validation.crlautoupdateenabled.label;"/>
-      <splitter class="tree-splitter"/>
-      <treecol id="Col6" flex="3" label="&validation.crlautoupdatestatus.label;"/>
-    </treecols>
-
-    <treechildren id="crlList"/>
-  </tree>
-  <separator class="thin"/>
-
-  <hbox id="dialogButtons">
-    <button id="deleteCrl" disabled="true"
-            label="&validation.deletecrl.label;"
-            accesskey="&validation.deletecrl.accesskey;"
-            oncommand="DeleteCrlSelected();"/>
-    <button id="editPrefs" class="push" disabled="true"
-            label="&validation.advanced.label;"
-            accesskey="&validation.advanced.accesskey;"
-            oncommand="EditAutoUpdatePrefs();"/>
-    <button id="updateCRL" class="push" disabled="true"
-            label="&validation.updatecrl.label;"
-            accesskey="&validation.updatecrl.accesskey;"
-            oncommand="UpdateCRL();"/>
-    <button id="importCRL" class="push"
-            label="&certmgr.restore2.label;"
-            accesskey="&certmgr.restore2.accesskey;"
-            oncommand="ImportCRL();"/>
-    <spacer flex="2"/>
-    <button dlgtype="accept"/>
-  </hbox>
-</dialog>
deleted file mode 100644
--- a/security/manager/pki/resources/content/pref-crlupdate.js
+++ /dev/null
@@ -1,242 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const nsICRLManager = Components.interfaces.nsICRLManager;
-const nsCRLManager  = "@mozilla.org/security/crlmanager;1";
-const nsIPKIParamBlock    = Components.interfaces.nsIPKIParamBlock;
-const nsICRLInfo          = Components.interfaces.nsICRLInfo;
-const nsIPrefService      = Components.interfaces.nsIPrefService;
- 
-var crl;
-var bundle;
-var prefService;
-var prefBranch;
-var updateTypeRadio;
-var enabledCheckBox;
-var timeBasedRadio;
-var freqBasedRadio;
-var crlManager;
-
-var autoupdateEnabledString   = "security.crl.autoupdate.enable.";
-var autoupdateTimeTypeString  = "security.crl.autoupdate.timingType.";
-var autoupdateTimeString      = "security.crl.autoupdate.nextInstant.";
-var autoupdateURLString       = "security.crl.autoupdate.url.";
-var autoupdateErrCntString    = "security.crl.autoupdate.errCount.";
-var autoupdateErrDetailString = "security.crl.autoupdate.errDetail.";
-var autoupdateDayCntString    = "security.crl.autoupdate.dayCnt.";
-var autoupdateFreqCntString   = "security.crl.autoupdate.freqCnt.";
-
-function doPrompt(msg)
-{
-  let prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
-    getService(Components.interfaces.nsIPromptService);
-  prompts.alert(window, null, msg);
-}
-
-function onLoad()
-{
-  crlManager = Components.classes[nsCRLManager].getService(nsICRLManager);
-  var pkiParams = window.arguments[0].QueryInterface(nsIPKIParamBlock);  
-  var isupport = pkiParams.getISupportAtIndex(1);
-  crl = isupport.QueryInterface(nsICRLInfo);
-
-  autoupdateEnabledString    = autoupdateEnabledString + crl.nameInDb;
-  autoupdateTimeTypeString  = autoupdateTimeTypeString + crl.nameInDb;
-  autoupdateTimeString      = autoupdateTimeString + crl.nameInDb;
-  autoupdateDayCntString    = autoupdateDayCntString + crl.nameInDb;
-  autoupdateFreqCntString   = autoupdateFreqCntString + crl.nameInDb;
-  autoupdateURLString       = autoupdateURLString + crl.nameInDb;
-  autoupdateErrCntString    = autoupdateErrCntString + crl.nameInDb;
-  autoupdateErrDetailString = autoupdateErrDetailString + crl.nameInDb;
-
-  bundle = document.getElementById("pippki_bundle");
-  prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefService);
-  prefBranch = prefService.getBranch(null);
-
-  updateTypeRadio = document.getElementById("autoUpdateType");
-  enabledCheckBox = document.getElementById("enableCheckBox");
-  timeBasedRadio = document.getElementById("timeBasedRadio");
-  freqBasedRadio = document.getElementById("freqBasedRadio");
-
-  //Read the existing prefs, if any
-  initializeSelection();
-}
-
-function updateSelectedTimingControls()
-{
-  var freqBox = document.getElementById("nextUpdateFreq");
-  var timeBox = document.getElementById("nextUpdateDay");
-  if(updateTypeRadio.selectedItem.id == "freqBasedRadio"){
-    freqBox.removeAttribute("disabled");
-    timeBox.disabled = true;
-  } else {
-    timeBox.removeAttribute("disabled");
-    freqBox.disabled = true;
-  }
-}
-
-function initializeSelection()
-{
-  var menuItemNode;
-  var hasAdvertisedURL = false;
-  var hasNextUpdate = true;
-
-  var lastFetchMenuNode;
-  var advertisedMenuNode;
-  
-  try {
-    var isEnabled = prefBranch.getBoolPref(autoupdateEnabledString);
-    enabledCheckBox.checked = isEnabled;
-  } catch(exception){
-    enabledCheckBox.checked = false;
-  }
-
-  //Always the last fetch url, for now.
-  var URLDisplayed = document.getElementById("urlName"); 
-  URLDisplayed.value = crl.lastFetchURL;
-  
-  //Decide how many update timing types to be shown
-  //If no next update specified, hide the first choice. Default shows both
-  if(crl.nextUpdateLocale == null || crl.nextUpdateLocale.length == 0) {
-    timeBasedRadio.disabled = true;
-    hasNextUpdate = false;
-  }
-  
-  //Set up the initial selections based on defaults and prefs, if any
-  try{
-    var timingPref = prefBranch.getIntPref(autoupdateTimeTypeString);
-    if(timingPref != null) {
-      if(timingPref == crlManager.TYPE_AUTOUPDATE_TIME_BASED) {
-        if(hasNextUpdate){
-          updateTypeRadio.selectedItem = timeBasedRadio;
-        }
-      } else {
-        updateTypeRadio.selectedItem = freqBasedRadio;
-      }
-    } else {
-      if(hasNextUpdate){
-        updateTypeRadio.selectedItem = timeBasedRadio;
-      } else {
-        updateTypeRadio.selectedItem = freqBasedRadio;
-      }
-    }
-    
-  }catch(exception){
-    if(!hasNextUpdate) {
-      updateTypeRadio.selectedItem = freqBasedRadio;
-    } else {
-      updateTypeRadio.selectedItem = timeBasedRadio;
-    }
-  }
-
-  updateSelectedTimingControls();
-
-  //Now, retrieving the day count
-  var timeBasedBox = document.getElementById("nextUpdateDay");
-  try {
-    var dayCnt = prefBranch.getCharPref(autoupdateDayCntString);
-    //doPrompt(dayCnt);
-    if(dayCnt != null){
-      timeBasedBox.value = dayCnt;
-    } else {
-      timeBasedBox.value = 1; 
-    }
-  } catch(exception) {
-    timeBasedBox.value = 1;
-  }
-
-  var freqBasedBox = document.getElementById("nextUpdateFreq");
-  try {
-    var freqCnt = prefBranch.getCharPref(autoupdateFreqCntString);
-    //doPrompt(freqCnt);
-    if(freqCnt != null){
-      freqBasedBox.value = freqCnt;
-    } else {
-      freqBasedBox.value = 1; 
-    }
-  } catch(exception) {
-    freqBasedBox.value = 1;
-  }
-
-  var errorCountText = document.getElementById("FailureCnt");
-  var errorDetailsText = document.getElementById("FailureDetails");
-  var cnt = 0;
-  var text;
-  try{
-    cnt = prefBranch.getIntPref(autoupdateErrCntString);
-    txt = prefBranch.getCharPref(autoupdateErrDetailString);
-  }catch(exception){}
-
-  if( cnt > 0 ){
-    errorCountText.setAttribute("value",cnt);
-    errorDetailsText.setAttribute("value",txt);
-  } else {
-    errorCountText.setAttribute("value", bundle.getString("NoUpdateFailure"));
-    var reasonBox = document.getElementById("reasonbox");
-    reasonBox.hidden = true;
-  }
-}
-
-function onCancel()
-{
-  // Close dialog by returning true
-  return true;
-}
-
-function onAccept()
-{
-   if(!validatePrefs())
-     return false;
-
-   //set enable pref
-   prefBranch.setBoolPref(autoupdateEnabledString, enabledCheckBox.checked );
-   
-   //set URL TYPE and value prefs - always to last fetch url - till we have anything else available
-   prefBranch.setCharPref(autoupdateURLString, crl.lastFetchURL);
-   
-   var timingTypeId = updateTypeRadio.selectedItem.id;
-   var updateTime;
-   var dayCnt = (document.getElementById("nextUpdateDay")).value;
-   var freqCnt = (document.getElementById("nextUpdateFreq")).value;
-
-   if(timingTypeId == "timeBasedRadio"){
-     prefBranch.setIntPref(autoupdateTimeTypeString, crlManager.TYPE_AUTOUPDATE_TIME_BASED);
-     updateTime = crlManager.computeNextAutoUpdateTime(crl, crlManager.TYPE_AUTOUPDATE_TIME_BASED, dayCnt);
-   } else {
-     prefBranch.setIntPref(autoupdateTimeTypeString, crlManager.TYPE_AUTOUPDATE_FREQ_BASED);
-     updateTime = crlManager.computeNextAutoUpdateTime(crl, crlManager.TYPE_AUTOUPDATE_FREQ_BASED, freqCnt);
-   }
-
-   //doPrompt(updateTime);
-   prefBranch.setCharPref(autoupdateTimeString, updateTime); 
-   prefBranch.setCharPref(autoupdateDayCntString, dayCnt);
-   prefBranch.setCharPref(autoupdateFreqCntString, freqCnt);
-
-   //Save Now
-   prefService.savePrefFile(null);
-   
-   crlManager.rescheduleCRLAutoUpdate();
-   //Close dialog by returning true
-   return true;
-}
-
-function validatePrefs()
-{
-   var dayCnt = (document.getElementById("nextUpdateDay")).value;
-   var freqCnt = (document.getElementById("nextUpdateFreq")).value;
-
-   var tmp = parseFloat(dayCnt);
-   if(!(tmp > 0.0)){
-     doPrompt(bundle.getString("crlAutoUpdateDayCntError"));
-     return false;
-   }
-   
-   tmp = parseFloat(freqCnt);
-   if(!(tmp > 0.0)){
-     doPrompt(bundle.getString("crlAutoUpdtaeFreqCntError"));
-     return false;
-   }
-   
-   return true;
-}
deleted file mode 100644
--- a/security/manager/pki/resources/content/pref-crlupdate.xul
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<!DOCTYPE dialog SYSTEM "chrome://pippki/locale/validation.dtd">
-
-<dialog id="crlUpdatePref" 
-  title="&validation.crl.autoupdate.title;"
-  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" 
-  onload="onLoad();"
-  buttons="accept,cancel"
-  ondialogaccept="return onAccept();"
-  ondialogcancel="return onCancel();">
-
-  <stringbundle id="pippki_bundle" src="chrome://pippki/locale/pippki.properties"/>
-
-  <script type="application/javascript" src="chrome://pippki/content/pippki.js"/>
-  <script type="application/javascript" src="chrome://pippki/content/pref-crlupdate.js" />
-
-  <vbox style="margin: 5px;" flex="1">
-    <checkbox label="&validation.crl.autoupdate.enable.label;" 
-            checked="false" id="enableCheckBox"/>
-    <separator/>
-
-    <vbox>
-      <radiogroup id="autoUpdateType" flex="1" oncommand="updateSelectedTimingControls();" >
-        <hbox align="center" id="timeBasedBox">
-          <radio label="&validation.crl.autoupdate.time.label1;"
-                 id="timeBasedRadio" value="1" group="autoUpdateType"/>
-          <textbox width="20" value="1" id="nextUpdateDay" />
-          <text value="&validation.crl.autoupdate.time.label2;" />
-        </hbox>
-        
-        <hbox align="center" id="freqBasedBox">
-          <radio label="&validation.crl.autoupdate.freq.label1;"
-                 id="freqBasedRadio" value="2" group="autoUpdateType"/>
-          <textbox width="20" value="1" id="nextUpdateFreq" />
-          <text value="&validation.crl.autoupdate.freq.label2;" />
-        </hbox>
-      </radiogroup>
-    </vbox>
-    <separator/>
-
-    <vbox>
-      <text value="&validation.crl.autoupdate.url.label;" />
-      <textbox readonly="true" id="urlName" />
-    </vbox>
-    <separator/>
-
-    <hbox>  
-      <text value="&crl.autoupdate.fail.cnt.label;" />
-      <text id="FailureCnt" />
-    </hbox>
-    <hbox id="reasonbox">  
-      <text value="&crl.autoupdate.fail.reason.label;" />
-      <text id="FailureDetails" />
-    </hbox>
-    
-  </vbox>
-
-</dialog>
deleted file mode 100644
--- a/security/manager/pki/resources/content/serverCrlNextupdate.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-
-const nsIDialogParamBlock = Components.interfaces.nsIDialogParamBlock;
-const nsIPKIParamBlock    = Components.interfaces.nsIPKIParamBlock;
-const nsIX509Cert         = Components.interfaces.nsIX509Cert;
-
-var dialogParams;
-var pkiParams;
-var bundle;
-
-function onLoad()
-{
-  pkiParams    = window.arguments[0].QueryInterface(nsIPKIParamBlock);
-  dialogParams = pkiParams.QueryInterface(nsIDialogParamBlock);
-  var isupport = pkiParams.getISupportAtIndex(1);
-  var cert = isupport.QueryInterface(nsIX509Cert);
-  var connectURL = dialogParams.GetString(1); 
-  var gBundleBrand = document.getElementById("brand_bundle");
-  var brandName = gBundleBrand.getString("brandShortName");
-
-  bundle = document.getElementById("pippki_bundle");
- 
-  var message1 = bundle.getFormattedString("crlNextUpdateMsg1",
-                                           [brandName, connectURL]);
-  var message2 = bundle.getFormattedString("crlNextUpdateMsg2",
-                                           [cert.issuerOrganization]);
-  setText("message1", message1);
-  setText("message2", message2);
-}
deleted file mode 100644
--- a/security/manager/pki/resources/content/serverCrlNextupdate.xul
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<!-- CHANGE THIS WHEN MOVING FILES -->
-<!DOCTYPE dialog [
-    <!ENTITY % pipPkiDTD SYSTEM "chrome://pippki/locale/pippki.dtd">
-    %pipPkiDTD;
-]>
-
-<dialog
-  id="serverCrlNextupdate"
-  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"      
-  style="width: 30em;"
-  buttons="accept"
-  defaultButton="accept"
-  ondialoghelp="openHelp('exp_crl');"
-  onload="onLoad();"
->
-
-<stringbundleset id="stringbundleset">
-  <stringbundle id="pippki_bundle" src="chrome://pippki/locale/pippki.properties"/>
-  <stringbundle id="brand_bundle" src="chrome://branding/locale/brand.properties"/>
-</stringbundleset>
-
-<script type="application/javascript" src="chrome://pippki/content/pippki.js" />
-<script type="application/javascript" src="chrome://pippki/content/serverCrlNextupdate.js" />
-
-  <description id="message1"/>
-  <separator/>
-  <description id="message2"/>
-  <separator/>
-  <label value="&serverCrlNextupdate.message;"/>
-
-</dialog>
--- a/security/manager/pki/resources/jar.mn
+++ b/security/manager/pki/resources/jar.mn
@@ -41,22 +41,14 @@ pippki.jar:
     content/pippki/certDump.xul              (content/certDump.xul)
     content/pippki/device_manager.xul        (content/device_manager.xul)
     content/pippki/device_manager.js         (content/device_manager.js)
     content/pippki/load_device.xul           (content/load_device.xul)
     content/pippki/choosetoken.xul           (content/choosetoken.xul)
     content/pippki/choosetoken.js            (content/choosetoken.js)
     content/pippki/escrowWarn.xul            (content/escrowWarn.xul)
     content/pippki/escrowWarn.js             (content/escrowWarn.js)
-    content/pippki/crlManager.xul            (content/crlManager.xul)
-    content/pippki/crlManager.js             (content/crlManager.js)
-    content/pippki/serverCrlNextupdate.js    (content/serverCrlNextupdate.js)
-    content/pippki/serverCrlNextupdate.xul   (content/serverCrlNextupdate.xul)
     content/pippki/createCertInfo.xul        (content/createCertInfo.xul)
     content/pippki/createCertInfo.js         (content/createCertInfo.js)
-    content/pippki/crlImportDialog.xul       (content/crlImportDialog.xul)
-    content/pippki/crlImportDialog.js        (content/crlImportDialog.js)
-    content/pippki/pref-crlupdate.xul        (content/pref-crlupdate.xul)
-    content/pippki/pref-crlupdate.js         (content/pref-crlupdate.js)
     content/pippki/protectedAuth.xul         (content/protectedAuth.xul)
     content/pippki/protectedAuth.js          (content/protectedAuth.js)
     content/pippki/formsigning.xul           (content/formsigning.xul)
     content/pippki/formsigning.js            (content/formsigning.js)
--- a/security/manager/pki/src/nsNSSDialogs.cpp
+++ b/security/manager/pki/src/nsNSSDialogs.cpp
@@ -26,17 +26,16 @@
 
 #include "nsNSSDialogs.h"
 #include "nsPKIParamBlock.h"
 #include "nsIKeygenThread.h"
 #include "nsIProtectedAuthThread.h"
 #include "nsNSSDialogHelper.h"
 #include "nsIWindowWatcher.h"
 #include "nsIX509CertValidity.h"
-#include "nsICRLInfo.h"
 
 #include "nsEmbedCID.h"
 #include "nsIPromptService.h"
 
 #define PIPSTRING_BUNDLE_URL "chrome://pippki/locale/pippki.properties"
 
 /* ==== */
 
@@ -135,37 +134,16 @@ nsNSSDialogs::GetPassword(nsIInterfaceRe
   if (!*_canceled) {
     // retrieve the password
     rv = block->GetString(2, _password);
   }
   return rv;
 }
 
 NS_IMETHODIMP 
-nsNSSDialogs::CrlImportStatusDialog(nsIInterfaceRequestor *ctx, nsICRLInfo *crl)
-{
-  nsresult rv;
-
-  nsCOMPtr<nsIPKIParamBlock> block =
-           do_CreateInstance(NS_PKIPARAMBLOCK_CONTRACTID,&rv);
-  if (NS_FAILED(rv))
-    return rv;
-  
-  rv = block->SetISupportAtIndex(1, crl);
-  if (NS_FAILED(rv))
-    return rv;
-
-  rv = nsNSSDialogHelper::openDialog(nullptr,
-                             "chrome://pippki/content/crlImportDialog.xul",
-                             block,
-                             false);
-  return NS_OK;
-}
-
-NS_IMETHODIMP 
 nsNSSDialogs::ConfirmDownloadCACert(nsIInterfaceRequestor *ctx, 
                                     nsIX509Cert *cert,
                                     uint32_t *_trust,
                                     bool *_retval)
 {
   nsresult rv;
 
   *_retval = true;
--- a/security/manager/ssl/public/moz.build
+++ b/security/manager/ssl/public/moz.build
@@ -11,18 +11,16 @@ XPIDL_SOURCES += [
     'nsIAssociatedContentSecurity.idl',
     'nsIBadCertListener2.idl',
     'nsICMSDecoder.idl',
     'nsICMSEncoder.idl',
     'nsICMSMessage.idl',
     'nsICMSMessage2.idl',
     'nsICMSMessageErrors.idl',
     'nsICMSSecureMessage.idl',
-    'nsICRLInfo.idl',
-    'nsICRLManager.idl',
     'nsICertOverrideService.idl',
     'nsICertPickDialogs.idl',
     'nsICertificateDialogs.idl',
     'nsICertificatePrincipal.idl',
     'nsIClientAuthDialogs.idl',
     'nsIDOMCryptoDialogs.idl',
     'nsIDataSignatureVerifier.idl',
     'nsIFormSigningDialog.idl',
deleted file mode 100644
--- a/security/manager/ssl/public/nsICRLInfo.idl
+++ /dev/null
@@ -1,58 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsISupports.idl"
-
-/**
- * Information on a Certificate Revocation List (CRL)
- * issued by a Aertificate Authority (CA).
- */
-[scriptable, uuid(c185d920-4a3e-11d5-ba27-00108303b117)]
-interface nsICRLInfo : nsISupports {
-
-  /**
-   *  The issuing CA's organization.
-   */
-  readonly attribute AString organization;
-
-  /**
-   *  The issuing CA's organizational unit.
-   */
-  readonly attribute AString organizationalUnit;
-
-  /**
-   *  The time this CRL was created at.
-   */
-  readonly attribute PRTime  lastUpdate;
-
-  /**
-   *  The time the suggested next update for this CRL.
-   */
-  readonly attribute PRTime  nextUpdate;
-
-  /**
-   *  lastUpdate formatted as a human readable string
-   *  formatted according to the environment locale.
-   */
-  readonly attribute AString lastUpdateLocale;
-
-  /**
-   *  nextUpdate formatted as a human readable string
-   *  formatted according to the environment locale.
-   */
-  readonly attribute AString nextUpdateLocale;
-
-  /**
-   *  The key identifying the CRL in the database.
-   */
-  readonly attribute AString nameInDb;
-
-  /**
-   *  The URL this CRL was last fetched from.
-   */
-  readonly attribute AUTF8String lastFetchURL;
-};
-
deleted file mode 100644
--- a/security/manager/ssl/public/nsICRLManager.idl
+++ /dev/null
@@ -1,78 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsISupports.idl"
-
-interface nsIURI;
-interface nsIArray;
-interface nsICRLInfo;
-
-%{C++
-#define NS_CRLMANAGER_CID { /* 5b256c10-22d8-4109-af92-1253035e9fcb */ \
-    0x5b256c10, \
-    0x22d8, \
-    0x4109, \
-    {0xaf, 0x92, 0x12, 0x53, 0x03, 0x5e, 0x9f, 0xcb} \
-  }
-
-#define NS_CRLMANAGER_CONTRACTID "@mozilla.org/security/crlmanager;1"
-%}
-
-
-
-[scriptable, uuid(486755db-627a-4678-a21b-f6a63bb9c56a)]
-interface nsICRLManager : nsISupports {
-  /*
-   * importCrl
-   *
-   * Import a CRL into the certificate database.
-   */
-  void importCrl([array, size_is(length)] in octet data,
-                 in unsigned long length,
-                 in nsIURI uri,
-                 in unsigned long type,
-                 in boolean doSilentDownload,
-                 in wstring crlKey);
-
-  
-  /*
-   * update crl from url
-   * update an existing crl from the last fetched url. Needed for the update
-   * button in crl manager
-   */
-  boolean updateCRLFromURL(in wstring url, in wstring key);
-
-
-  /*
-   * getCrls
-   *
-   * Get a list of Crl entries in the DB.
-   */
-  nsIArray getCrls();
-
-  /*
-   * deleteCrl
-   *
-   * Delete the crl.
-   */
-  void deleteCrl(in unsigned long crlIndex);
-
-
-  /* This would reschedule the autoupdate of crls with auto update enable.
-   * Most likely to be called when update prefs are changed, or when a crl
-   * is deleted, etc. However, this might not be the most relevant place for
-   * this api, but unless we have a separate crl handler object....
-   */
-  void rescheduleCRLAutoUpdate();
-
-
-  const unsigned long TYPE_AUTOUPDATE_TIME_BASED     = 1;
-  const unsigned long TYPE_AUTOUPDATE_FREQ_BASED     = 2;
-
-  wstring computeNextAutoUpdateTime(in nsICRLInfo info,
-                                    in unsigned long autoUpdateType,
-                                    in double noOfDays);
-};
--- a/security/manager/ssl/public/nsICertificateDialogs.idl
+++ b/security/manager/ssl/public/nsICertificateDialogs.idl
@@ -1,22 +1,21 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
 interface nsIInterfaceRequestor;
 interface nsIX509Cert;
-interface nsICRLInfo;
 
 /**
  * Functions that implement user interface dialogs to manage certificates.
  */
-[scriptable, uuid(a03ca940-09be-11d5-ac5d-000064657374)]
+[scriptable, uuid(da871dab-f69e-4173-ab26-99fcd47b0e85)]
 interface nsICertificateDialogs : nsISupports
 {
   /**
    *  UI shown when a user is asked to download a new CA cert.
    *  Provides user with ability to choose trust settings for the cert.
    *  Asks the user to grant permission to import the certificate.
    *
    *  @param ctx A user interface context.
@@ -75,23 +74,13 @@ interface nsICertificateDialogs : nsISup
    *  The implementation should try to display as many attributes
    *  as possible.
    *
    *  @param ctx A user interface context.
    *  @param cert The certificate to be shown to the user.
    */
   void viewCert(in nsIInterfaceRequestor ctx, 
                 in nsIX509Cert cert);
-
-  /**
-   *  UI shown after a Certificate Revocation List (CRL) has been
-   *  successfully imported.
-   *
-   *  @param ctx A user interface context.
-   *  @param crl Information describing the CRL that was imported.
-   */
-  void crlImportStatusDialog(in nsIInterfaceRequestor ctx, 
-                             in nsICRLInfo crl);
 };
 
 %{C++
 #define NS_CERTIFICATEDIALOGS_CONTRACTID "@mozilla.org/nsCertificateDialogs;1"
 %}
--- a/security/manager/ssl/src/CertVerifier.cpp
+++ b/security/manager/ssl/src/CertVerifier.cpp
@@ -1,14 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "CertVerifier.h"
 #include "nsNSSComponent.h"
+#include "nsServiceManagerUtils.h"
 #include "cert.h"
 #include "secerr.h"
 
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/src/PSMContentDownloader.h
@@ -0,0 +1,303 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef _nsNSSComponent_h_
+#define _nsNSSComponent_h_
+
+#include "mozilla/Mutex.h"
+#include "mozilla/RefPtr.h"
+#include "nsCOMPtr.h"
+#include "nsISignatureVerifier.h"
+#include "nsIURIContentListener.h"
+#include "nsIStreamListener.h"
+#include "nsIEntropyCollector.h"
+#include "nsIStringBundle.h"
+#include "nsIPrefBranch.h"
+#include "nsIObserver.h"
+#include "nsIObserverService.h"
+#include "nsWeakReference.h"
+#ifndef MOZ_DISABLE_CRYPTOLEGACY
+#include "nsIDOMEventTarget.h"
+#endif
+#include "nsINSSErrorsService.h"
+#include "nsNetUtil.h"
+#include "nsNSSCallbacks.h"
+#include "ScopedNSSTypes.h"
+#include "nsNSSHelper.h"
+#include "nsClientAuthRemember.h"
+#include "prerror.h"
+
+class nsIPrompt;
+class SmartCardThreadList;
+
+namespace mozilla { namespace psm {
+
+class CertVerifier;
+
+} } // namespace mozilla::psm
+
+
+#define NS_NSSCOMPONENT_CID \
+{0xa277189c, 0x1dd1, 0x11b2, {0xa8, 0xc9, 0xe4, 0xe8, 0xbf, 0xb1, 0x33, 0x8e}}
+
+#define PSM_COMPONENT_CONTRACTID "@mozilla.org/psm;1"
+
+//Define an interface that we can use to look up from the
+//callbacks passed to NSS.
+
+#define NS_INSSCOMPONENT_IID_STR "6ffbb526-205b-49c5-ae3f-5959c084075e"
+#define NS_INSSCOMPONENT_IID \
+  { 0x6ffbb526, 0x205b, 0x49c5, \
+    { 0xae, 0x3f, 0x59, 0x59, 0xc0, 0x84, 0x7, 0x5e } }
+
+#define NS_PSMCONTENTLISTEN_CID {0xc94f4a30, 0x64d7, 0x11d4, {0x99, 0x60, 0x00, 0xb0, 0xd0, 0x23, 0x54, 0xa0}}
+#define NS_PSMCONTENTLISTEN_CONTRACTID "@mozilla.org/security/psmdownload;1"
+
+enum EnsureNSSOperator
+{
+  nssLoadingComponent = 0,
+  nssInitSucceeded = 1,
+  nssInitFailed = 2,
+  nssShutdown = 3,
+  nssEnsure = 100,
+  nssEnsureOnChromeOnly = 101
+};
+
+extern bool EnsureNSSInitialized(EnsureNSSOperator op);
+
+//--------------------------------------------
+// Now we need a content listener to register 
+//--------------------------------------------
+class PSMContentDownloader : public nsIStreamListener
+{
+public:
+  PSMContentDownloader() {NS_ASSERTION(false, "don't use this constructor."); }
+  PSMContentDownloader(uint32_t type);
+  virtual ~PSMContentDownloader();
+  void setSilentDownload(bool flag);
+
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIREQUESTOBSERVER
+  NS_DECL_NSISTREAMLISTENER
+
+  enum {UNKNOWN_TYPE = 0};
+  enum {X509_CA_CERT  = 1};
+  enum {X509_USER_CERT  = 2};
+  enum {X509_EMAIL_CERT  = 3};
+  enum {X509_SERVER_CERT  = 4};
+
+protected:
+  char* mByteData;
+  int32_t mBufferOffset;
+  int32_t mBufferSize;
+  uint32_t mType;
+  nsCOMPtr<nsIURI> mURI;
+};
+
+class nsNSSComponent;
+
+class NS_NO_VTABLE nsINSSComponent : public nsISupports {
+ public:
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_INSSCOMPONENT_IID)
+
+  NS_IMETHOD ShowAlertFromStringBundle(const char * messageID) = 0;
+
+  NS_IMETHOD GetPIPNSSBundleString(const char *name,
+                                   nsAString &outString) = 0;
+  NS_IMETHOD PIPBundleFormatStringFromName(const char *name,
+                                           const PRUnichar **params,
+                                           uint32_t numParams,
+                                           nsAString &outString) = 0;
+
+  NS_IMETHOD GetNSSBundleString(const char *name,
+                                nsAString &outString) = 0;
+  NS_IMETHOD NSSBundleFormatStringFromName(const char *name,
+                                           const PRUnichar **params,
+                                           uint32_t numParams,
+                                           nsAString &outString) = 0;
+
+  // This method will just disable OCSP in NSS, it will not
+  // alter the respective pref values.
+  NS_IMETHOD SkipOcsp() = 0;
+
+  // This method will set the OCSP value according to the 
+  // values in the preferences.
+  NS_IMETHOD SkipOcspOff() = 0;
+
+  NS_IMETHOD LogoutAuthenticatedPK11() = 0;
+
+#ifndef MOZ_DISABLE_CRYPTOLEGACY
+  NS_IMETHOD LaunchSmartCardThread(SECMODModule *module) = 0;
+
+  NS_IMETHOD ShutdownSmartCardThread(SECMODModule *module) = 0;
+
+  NS_IMETHOD PostEvent(const nsAString &eventType, const nsAString &token) = 0;
+
+  NS_IMETHOD DispatchEvent(const nsAString &eventType, const nsAString &token) = 0;
+#endif
+
+#ifndef NSS_NO_LIBPKIX  
+  NS_IMETHOD EnsureIdentityInfoLoaded() = 0;
+#endif
+
+  NS_IMETHOD IsNSSInitialized(bool *initialized) = 0;
+
+  NS_IMETHOD GetDefaultCertVerifier(
+                  mozilla::RefPtr<mozilla::psm::CertVerifier> &out) = 0;
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(nsINSSComponent, NS_INSSCOMPONENT_IID)
+
+class nsNSSShutDownList;
+class nsCertVerificationThread;
+
+// Implementation of the PSM component interface.
+class nsNSSComponent : public nsISignatureVerifier,
+                       public nsIEntropyCollector,
+                       public nsINSSComponent,
+                       public nsIObserver,
+                       public nsSupportsWeakReference
+{
+  typedef mozilla::Mutex Mutex;
+
+public:
+  NS_DEFINE_STATIC_CID_ACCESSOR( NS_NSSCOMPONENT_CID )
+
+  nsNSSComponent();
+  virtual ~nsNSSComponent();
+
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISIGNATUREVERIFIER
+  NS_DECL_NSIENTROPYCOLLECTOR
+  NS_DECL_NSIOBSERVER
+
+  NS_METHOD Init();
+
+  static nsresult GetNewPrompter(nsIPrompt ** result);
+  static nsresult ShowAlertWithConstructedString(const nsString & message);
+  NS_IMETHOD ShowAlertFromStringBundle(const char * messageID);
+
+  NS_IMETHOD GetPIPNSSBundleString(const char *name,
+                                   nsAString &outString);
+  NS_IMETHOD PIPBundleFormatStringFromName(const char *name,
+                                           const PRUnichar **params,
+                                           uint32_t numParams,
+                                           nsAString &outString);
+  NS_IMETHOD GetNSSBundleString(const char *name,
+                               nsAString &outString);
+  NS_IMETHOD NSSBundleFormatStringFromName(const char *name,
+                                           const PRUnichar **params,
+                                           uint32_t numParams,
+                                           nsAString &outString);
+  NS_IMETHOD SkipOcsp();
+  NS_IMETHOD SkipOcspOff();
+  NS_IMETHOD LogoutAuthenticatedPK11();
+
+#ifndef MOZ_DISABLE_CRYPTOLEGACY
+  NS_IMETHOD LaunchSmartCardThread(SECMODModule *module);
+  NS_IMETHOD ShutdownSmartCardThread(SECMODModule *module);
+  NS_IMETHOD PostEvent(const nsAString &eventType, const nsAString &token);
+  NS_IMETHOD DispatchEvent(const nsAString &eventType, const nsAString &token);
+  void LaunchSmartCardThreads();
+  void ShutdownSmartCardThreads();
+  nsresult DispatchEventToWindow(nsIDOMWindow *domWin, const nsAString &eventType, const nsAString &token);
+#endif
+
+#ifndef NSS_NO_LIBPKIX
+  NS_IMETHOD EnsureIdentityInfoLoaded();
+#endif
+  NS_IMETHOD IsNSSInitialized(bool *initialized);
+
+  NS_IMETHOD GetDefaultCertVerifier(
+                  mozilla::RefPtr<mozilla::psm::CertVerifier> &out);
+private:
+
+  nsresult InitializeNSS(bool showWarningBox);
+  void ShutdownNSS();
+
+  void InstallLoadableRoots();
+  void UnloadLoadableRoots();
+  void CleanupIdentityInfo();
+  void setValidationOptions(nsIPrefBranch * pref);
+  nsresult setEnabledTLSVersions(nsIPrefBranch * pref);
+  nsresult InitializePIPNSSBundle();
+  nsresult ConfigureInternalPKCS11Token();
+  nsresult RegisterPSMContentListener();
+  nsresult RegisterObservers();
+  nsresult DeregisterObservers();
+
+  // Methods that we use to handle the profile change notifications (and to
+  // synthesize a full profile change when we're just doing a profile startup):
+  void DoProfileChangeNetTeardown();
+  void DoProfileChangeTeardown(nsISupports* aSubject);
+  void DoProfileBeforeChange(nsISupports* aSubject);
+  void DoProfileChangeNetRestore();
+  
+  Mutex mutex;
+  
+  nsCOMPtr<nsIStringBundle> mPIPNSSBundle;
+  nsCOMPtr<nsIStringBundle> mNSSErrorsBundle;
+  nsCOMPtr<nsIURIContentListener> mPSMContentListener;
+  nsCOMPtr<nsIPrefBranch> mPrefBranch;
+  bool mNSSInitialized;
+  bool mObserversRegistered;
+  static int mInstanceCount;
+  nsNSSShutDownList *mShutdownObjectList;
+#ifndef MOZ_DISABLE_CRYPTOLEGACY
+  SmartCardThreadList *mThreadList;
+#endif
+  bool mIsNetworkDown;
+
+  void deleteBackgroundThreads();
+  void createBackgroundThreads();
+  nsCertVerificationThread *mCertVerificationThread;
+
+  nsNSSHttpInterface mHttpForNSS;
+  mozilla::RefPtr<mozilla::psm::CertVerifier> mDefaultCertVerifier;
+
+
+  static PRStatus IdentityInfoInit(void);
+  PRCallOnceType mIdentityInfoCallOnce;
+
+public:
+  static bool globalConstFlagUsePKIXVerification;
+};
+
+class PSMContentListener : public nsIURIContentListener,
+                            public nsSupportsWeakReference {
+public:
+  PSMContentListener();
+  virtual ~PSMContentListener();
+  nsresult init();
+
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIURICONTENTLISTENER
+private:
+  nsCOMPtr<nsISupports> mLoadCookie;
+  nsCOMPtr<nsIURIContentListener> mParentContentListener;
+};
+
+class nsNSSErrors
+{
+public:
+  static const char *getDefaultErrorStringName(PRErrorCode err);
+  static const char *getOverrideErrorStringName(PRErrorCode aErrorCode);
+  static nsresult getErrorMessageFromCode(PRErrorCode err,
+                                          nsINSSComponent *component,
+                                          nsString &returnedMessage);
+};
+
+class nsPSMInitPanic
+{
+private:
+  static bool isPanic;
+public:
+  static void SetPanic() {isPanic = true;}
+  static bool GetPanic() {return isPanic;}
+};
+
+#endif // _nsNSSComponent_h_
+
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/src/PSMContentListener.cpp
@@ -0,0 +1,320 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifdef MOZ_LOGGING
+#define FORCE_PR_LOG 1
+#endif
+
+#include "PSMContentListener.h"
+
+#include "nsIStreamListener.h"
+#include "nsIX509CertDB.h"
+
+#include "mozilla/Services.h"
+
+#include "nsCRT.h"
+#include "nsNetUtil.h"
+#include "nsNSSHelper.h"
+#include "nsNSSShutDown.h"
+
+#include "prlog.h"
+
+#ifdef MOZ_LOGGING
+extern PRLogModuleInfo* gPIPNSSLog;
+#endif
+
+namespace mozilla { namespace psm {
+
+namespace {
+
+class PSMContentDownloader : public nsIStreamListener
+{
+public:
+  PSMContentDownloader() {NS_ASSERTION(false, "don't use this constructor."); }
+  PSMContentDownloader(uint32_t type);
+  virtual ~PSMContentDownloader();
+  void setSilentDownload(bool flag);
+
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIREQUESTOBSERVER
+  NS_DECL_NSISTREAMLISTENER
+
+  enum {UNKNOWN_TYPE = 0};
+  enum {X509_CA_CERT  = 1};
+  enum {X509_USER_CERT  = 2};
+  enum {X509_EMAIL_CERT  = 3};
+  enum {X509_SERVER_CERT  = 4};
+
+protected:
+  char* mByteData;
+  int32_t mBufferOffset;
+  int32_t mBufferSize;
+  uint32_t mType;
+  nsCOMPtr<nsIURI> mURI;
+};
+
+PSMContentDownloader::PSMContentDownloader(uint32_t type)
+  : mByteData(nullptr),
+    mType(type)
+{
+}
+
+PSMContentDownloader::~PSMContentDownloader()
+{
+  if (mByteData)
+    nsMemory::Free(mByteData);
+}
+
+NS_IMPL_ISUPPORTS2(PSMContentDownloader, nsIStreamListener, nsIRequestObserver)
+
+const int32_t kDefaultCertAllocLength = 2048;
+
+NS_IMETHODIMP
+PSMContentDownloader::OnStartRequest(nsIRequest* request, nsISupports* context)
+{
+  nsresult rv;
+  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnStartRequest\n"));
+  nsCOMPtr<nsIChannel> channel(do_QueryInterface(request));
+  if (!channel) return NS_ERROR_FAILURE;
+
+  // Get the URI //
+  channel->GetURI(getter_AddRefs(mURI));
+
+  int64_t contentLength;
+  rv = channel->GetContentLength(&contentLength);
+  if (NS_FAILED(rv) || contentLength <= 0)
+    contentLength = kDefaultCertAllocLength;
+  if (contentLength > INT32_MAX)
+    return NS_ERROR_OUT_OF_MEMORY;
+  
+  mBufferOffset = 0;
+  mBufferSize = 0;
+  mByteData = (char*) nsMemory::Alloc(contentLength);
+  if (!mByteData)
+    return NS_ERROR_OUT_OF_MEMORY;
+  
+  mBufferSize = int32_t(contentLength);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentDownloader::OnDataAvailable(nsIRequest* request,
+                                nsISupports* context,
+                                nsIInputStream *aIStream,
+                                uint64_t aSourceOffset,
+                                uint32_t aLength)
+{
+  if (!mByteData)
+    return NS_ERROR_OUT_OF_MEMORY;
+  
+  uint32_t amt;
+  nsresult err;
+  //Do a check to see if we need to allocate more memory.
+  if ((mBufferOffset + (int32_t)aLength) > mBufferSize) {
+      size_t newSize = (mBufferOffset + aLength) *2; // grow some more than needed
+      char *newBuffer;
+      newBuffer = (char*)nsMemory::Realloc(mByteData, newSize);
+      if (!newBuffer) {
+        return NS_ERROR_OUT_OF_MEMORY;
+      }
+      mByteData = newBuffer;
+      mBufferSize = newSize;
+  }
+  
+  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnDataAvailable\n"));
+  do {
+    err = aIStream->Read(mByteData+mBufferOffset,
+                         aLength, &amt);
+    if (NS_FAILED(err)) return err;
+    if (amt == 0) break;
+    
+    aLength -= amt;
+    mBufferOffset += amt;
+    
+  } while (aLength > 0);
+  
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentDownloader::OnStopRequest(nsIRequest* request,
+                              nsISupports* context,
+                              nsresult aStatus)
+{
+  nsNSSShutDownPreventionLock locker;
+  //Check if the download succeeded - it might have failed due to
+  //network issues, etc.
+  if (NS_FAILED(aStatus)){
+    return aStatus;
+  }
+
+  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnStopRequest\n"));
+
+  nsCOMPtr<nsIX509CertDB> certdb;
+
+  nsresult rv;
+  nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
+
+  switch (mType) {
+  case PSMContentDownloader::X509_CA_CERT:
+  case PSMContentDownloader::X509_USER_CERT:
+  case PSMContentDownloader::X509_EMAIL_CERT:
+    certdb = do_GetService(NS_X509CERTDB_CONTRACTID);
+    break;
+
+  default:
+    break;
+  }
+
+  switch (mType) {
+  case PSMContentDownloader::X509_CA_CERT:
+    return certdb->ImportCertificates((uint8_t*)mByteData, mBufferOffset, mType, ctx); 
+  case PSMContentDownloader::X509_USER_CERT:
+    return certdb->ImportUserCertificate((uint8_t*)mByteData, mBufferOffset, ctx);
+  case PSMContentDownloader::X509_EMAIL_CERT:
+    return certdb->ImportEmailCertificate((uint8_t*)mByteData, mBufferOffset, ctx); 
+  default:
+    rv = NS_ERROR_FAILURE;
+    break;
+  }
+  
+  return rv;
+}
+
+/* other mime types that we should handle sometime:
+   
+   application/x-pkcs7-mime
+   application/pkcs7-signature
+   application/pre-encrypted
+   
+*/
+
+uint32_t
+getPSMContentType(const char * aContentType)
+{ 
+  // Don't forget to update the registration of content listeners in nsNSSModule.cpp 
+  // for every supported content type.
+  
+  if (!nsCRT::strcasecmp(aContentType, "application/x-x509-ca-cert"))
+    return PSMContentDownloader::X509_CA_CERT;
+  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-server-cert"))
+    return PSMContentDownloader::X509_SERVER_CERT;
+  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-user-cert"))
+    return PSMContentDownloader::X509_USER_CERT;
+  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-email-cert"))
+    return PSMContentDownloader::X509_EMAIL_CERT;
+
+  return PSMContentDownloader::UNKNOWN_TYPE;
+}
+
+} // unnamed namespace
+
+NS_IMPL_ISUPPORTS2(PSMContentListener,
+                   nsIURIContentListener,
+                   nsISupportsWeakReference) 
+
+PSMContentListener::PSMContentListener()
+{
+  mLoadCookie = nullptr;
+  mParentContentListener = nullptr;
+}
+
+PSMContentListener::~PSMContentListener()
+{
+}
+
+nsresult
+PSMContentListener::init()
+{
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::OnStartURIOpen(nsIURI *aURI, bool *aAbortOpen)
+{
+  //if we don't want to handle the URI, return true in
+  //*aAbortOpen
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::IsPreferred(const char * aContentType,
+                                 char ** aDesiredContentType,
+                                 bool * aCanHandleContent)
+{
+  return CanHandleContent(aContentType, true,
+                          aDesiredContentType, aCanHandleContent);
+}
+
+NS_IMETHODIMP
+PSMContentListener::CanHandleContent(const char * aContentType,
+                                      bool aIsContentPreferred,
+                                      char ** aDesiredContentType,
+                                      bool * aCanHandleContent)
+{
+  uint32_t type;
+  type = getPSMContentType(aContentType);
+  if (type == PSMContentDownloader::UNKNOWN_TYPE) {
+    *aCanHandleContent = false;
+  } else {
+    *aCanHandleContent = true;
+  }
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::DoContent(const char * aContentType,
+                               bool aIsContentPreferred,
+                               nsIRequest * aRequest,
+                               nsIStreamListener ** aContentHandler,
+                               bool * aAbortProcess)
+{
+  PSMContentDownloader *downLoader;
+  uint32_t type;
+  type = getPSMContentType(aContentType);
+  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PSMContentListener::DoContent\n"));
+  if (type != PSMContentDownloader::UNKNOWN_TYPE) {
+    downLoader = new PSMContentDownloader(type);
+    if (downLoader) {
+      downLoader->QueryInterface(NS_GET_IID(nsIStreamListener), 
+                                            (void **)aContentHandler);
+      return NS_OK;
+    }
+  }
+  return NS_ERROR_FAILURE;
+}
+
+NS_IMETHODIMP
+PSMContentListener::GetLoadCookie(nsISupports * *aLoadCookie)
+{
+  *aLoadCookie = mLoadCookie;
+  NS_IF_ADDREF(*aLoadCookie);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::SetLoadCookie(nsISupports * aLoadCookie)
+{
+  mLoadCookie = aLoadCookie;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::GetParentContentListener(nsIURIContentListener ** aContentListener)
+{
+  *aContentListener = mParentContentListener;
+  NS_IF_ADDREF(*aContentListener);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+PSMContentListener::SetParentContentListener(nsIURIContentListener * aContentListener)
+{
+  mParentContentListener = aContentListener;
+  return NS_OK;
+}
+
+} } // namespace mozilla::psm
new file mode 100644
--- /dev/null
+++ b/security/manager/ssl/src/PSMContentListener.h
@@ -0,0 +1,35 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_psm_PSMCOntentListener_h_
+#define mozilla_psm_PSMCOntentListener_h_
+
+#include "nsCOMPtr.h"
+#include "nsIURIContentListener.h"
+#include "nsWeakReference.h"
+
+#define NS_PSMCONTENTLISTEN_CID {0xc94f4a30, 0x64d7, 0x11d4, {0x99, 0x60, 0x00, 0xb0, 0xd0, 0x23, 0x54, 0xa0}}
+#define NS_PSMCONTENTLISTEN_CONTRACTID "@mozilla.org/security/psmdownload;1"
+
+namespace mozilla { namespace psm {
+
+class PSMContentListener : public nsIURIContentListener,
+                            public nsSupportsWeakReference {
+public:
+  PSMContentListener();
+  virtual ~PSMContentListener();
+  nsresult init();
+
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSIURICONTENTLISTENER
+private:
+  nsCOMPtr<nsISupports> mLoadCookie;
+  nsCOMPtr<nsIURIContentListener> mParentContentListener;
+};
+
+} } // namespace mozilla::psm
+
+#endif // mozilla_psm_PSMCOntentListener_h
--- a/security/manager/ssl/src/SSLServerCertVerification.cpp
+++ b/security/manager/ssl/src/SSLServerCertVerification.cpp
@@ -104,16 +104,17 @@
 #include "nsRecentBadCerts.h"
 #include "nsNSSIOLayer.h"
 #include "nsNSSShutDown.h"
 
 #include "mozilla/Assertions.h"
 #include "mozilla/Mutex.h"
 #include "mozilla/Telemetry.h"
 #include "nsIThreadPool.h"
+#include "nsNetUtil.h"
 #include "nsXPCOMCIDInternal.h"
 #include "nsComponentManagerUtils.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIConsoleService.h"
 #include "PSMRunnable.h"
 #include "SharedSSLState.h"
 
 #include "ssl.h"
--- a/security/manager/ssl/src/TransportSecurityInfo.cpp
+++ b/security/manager/ssl/src/TransportSecurityInfo.cpp
@@ -12,16 +12,18 @@
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
 #include "nsICertOverrideService.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "nsNSSCertHelper.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsIArray.h"
+#include "nsComponentManagerUtils.h"
+#include "nsServiceManagerUtils.h"
 #include "PSMRunnable.h"
 #include "ScopedNSSTypes.h"
 
 #include "secerr.h"
 
 //#define DEBUG_SSL_VERBOSE //Enable this define to get minimal 
                             //reports when doing SSL read/write
                             
--- a/security/manager/ssl/src/moz.build
+++ b/security/manager/ssl/src/moz.build
@@ -23,18 +23,16 @@ CPP_SOURCES += [
     'JARSignatureVerification.cpp',
     'nsCertificatePrincipal.cpp',
     'nsCertOverrideService.cpp',
     'nsCertPicker.cpp',
     'nsCertVerificationThread.cpp',
     'nsClientAuthRemember.cpp',
     'nsCMS.cpp',
     'nsCMSSecureMessage.cpp',
-    'nsCRLInfo.cpp',
-    'nsCRLManager.cpp',
     'nsCrypto.cpp',
     'nsCryptoHash.cpp',
     'nsDataSignatureVerifier.cpp',
     'nsIdentityChecking.cpp',
     'nsKeygenHandler.cpp',
     'nsKeygenThread.cpp',
     'nsKeyModule.cpp',
     'nsNSSASN1Object.cpp',
@@ -63,16 +61,17 @@ CPP_SOURCES += [
     'nsRecentBadCerts.cpp',
     'nsSDR.cpp',
     'NSSErrorsService.cpp',
     'nsSSLSocketProvider.cpp',
     'nsSSLStatus.cpp',
     'nsStreamCipher.cpp',
     'nsTLSSocketProvider.cpp',
     'nsUsageArrayHelper.cpp',
+	'PSMContentListener.cpp',
     'PSMRunnable.cpp',
     'SharedSSLState.cpp',
     'SSLServerCertVerification.cpp',
     'TransportSecurityInfo.cpp',
 ]
 
 if not CONFIG['MOZ_DISABLE_CRYPTOLEGACY']:
     CPP_SOURCES += [
deleted file mode 100644
--- a/security/manager/ssl/src/nsCRLInfo.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "prerror.h"
-#include "prprf.h"
-
-#include "nsCRLInfo.h"
-#include "nsIDateTimeFormat.h"
-#include "nsDateTimeFormatCID.h"
-#include "nsCOMPtr.h"
-#include "nsComponentManagerUtils.h"
-#include "nsReadableUtils.h"
-#include "nsNSSShutDown.h"
-
-#include "nspr.h"
-#include "pk11func.h"
-#include "certdb.h"
-#include "cert.h"
-#include "secerr.h"
-#include "nssb64.h"
-#include "secasn1.h"
-#include "secder.h"
-
-NS_IMPL_ISUPPORTS1(nsCRLInfo, nsICRLInfo)
-
-nsCRLInfo::nsCRLInfo()
-{
-  /* member initializers and constructor code */
-}
-
-nsCRLInfo::nsCRLInfo(CERTSignedCrl *signedCrl)
-{
-  nsNSSShutDownPreventionLock locker;
-  CERTCrl *crl = &(signedCrl->crl);
-  nsAutoString org;
-  nsAutoString orgUnit;
-  nsAutoString nameInDb;
-  nsAutoString nextUpdateLocale;
-  nsAutoString lastUpdateLocale;
-  nsAutoCString lastFetchURL;
-  PRTime lastUpdate = 0;
-  PRTime nextUpdate = 0;
-  SECStatus sec_rv;
-  
-  // Get the information we need here //
-  char * o = CERT_GetOrgName(&(crl->name));
-  if (o) {
-    org = NS_ConvertASCIItoUTF16(o);
-    PORT_Free(o);
-  }
-
-  char * ou = CERT_GetOrgUnitName(&(crl->name));
-  if (ou) {
-    orgUnit = NS_ConvertASCIItoUTF16(ou);
-    //At present, the ou is being used as the unique key - but this
-    //would change, one support for delta crls come in.
-    nameInDb =  orgUnit;
-    PORT_Free(ou);
-  }
-  
-  nsCOMPtr<nsIDateTimeFormat> dateFormatter = do_CreateInstance(NS_DATETIMEFORMAT_CONTRACTID);
-  
-  // Last Update time
-  if (crl->lastUpdate.len) {
-    sec_rv = DER_UTCTimeToTime(&lastUpdate, &(crl->lastUpdate));
-    if (sec_rv == SECSuccess && dateFormatter) {
-      dateFormatter->FormatPRTime(nullptr, kDateFormatShort, kTimeFormatNone,
-                            lastUpdate, lastUpdateLocale);
-    }
-  }
-
-  if (crl->nextUpdate.len) {
-    // Next update time
-    sec_rv = DER_UTCTimeToTime(&nextUpdate, &(crl->nextUpdate));
-    if (sec_rv == SECSuccess && dateFormatter) {
-      dateFormatter->FormatPRTime(nullptr, kDateFormatShort, kTimeFormatNone,
-                            nextUpdate, nextUpdateLocale);
-    }
-  }
-
-  char * url = signedCrl->url;
-  if(url) {
-    lastFetchURL =  url;
-  }
-
-  mOrg.Assign(org.get());
-  mOrgUnit.Assign(orgUnit.get());
-  mLastUpdateLocale.Assign(lastUpdateLocale.get());
-  mNextUpdateLocale.Assign(nextUpdateLocale.get());
-  mLastUpdate = lastUpdate;
-  mNextUpdate = nextUpdate;
-  mNameInDb.Assign(nameInDb.get());
-  mLastFetchURL = lastFetchURL;
-}
-
-nsCRLInfo::~nsCRLInfo()
-{
-  /* destructor code */
-}
-
-/* readonly attribute */
-NS_IMETHODIMP nsCRLInfo::GetOrganization(nsAString & aOrg)
-{
-  aOrg = mOrg;
-  return NS_OK;
-}
-
-/* readonly attribute */
-NS_IMETHODIMP nsCRLInfo::GetOrganizationalUnit(nsAString & aOrgUnit)
-{
-  aOrgUnit = mOrgUnit;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetLastUpdateLocale(nsAString & aLastUpdateLocale)
-{
-  aLastUpdateLocale = mLastUpdateLocale;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetNextUpdateLocale(nsAString & aNextUpdateLocale)
-{
-  aNextUpdateLocale = mNextUpdateLocale;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetLastUpdate(PRTime* aLastUpdate)
-{
-  NS_ENSURE_ARG(aLastUpdate);
-  *aLastUpdate = mLastUpdate;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetNextUpdate(PRTime* aNextUpdate)
-{
-  NS_ENSURE_ARG(aNextUpdate);
-  *aNextUpdate = mNextUpdate;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetNameInDb(nsAString & aNameInDb)
-{
-  aNameInDb = mNameInDb;
-  return NS_OK;
-}
-
-NS_IMETHODIMP nsCRLInfo::GetLastFetchURL(nsACString & aLastFetchURL)
-{
-  aLastFetchURL = mLastFetchURL;
-  return NS_OK;
-}
deleted file mode 100644
--- a/security/manager/ssl/src/nsCRLInfo.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef _NSCLRLINFO_H_
-#define _NSCRLINFO_H_
-
-#include "nsICRLInfo.h"
-
-#include "certt.h"
-#include "nsString.h"
-	  
-#define CRL_AUTOUPDATE_TIMIINGTYPE_PREF "security.crl.autoupdate.timingType"
-#define CRL_AUTOUPDATE_TIME_PREF "security.crl.autoupdate.nextInstant"
-#define CRL_AUTOUPDATE_URL_PREF "security.crl.autoupdate.url"
-#define CRL_AUTOUPDATE_DAYCNT_PREF "security.crl.autoupdate.dayCnt"
-#define CRL_AUTOUPDATE_FREQCNT_PREF "security.crl.autoupdate.freqCnt"
-#define CRL_AUTOUPDATE_ERRCNT_PREF "security.crl.autoupdate.errCount"
-#define CRL_AUTOUPDATE_ERRDETAIL_PREF "security.crl.autoupdate.errDetail"
-#define CRL_AUTOUPDATE_ENABLED_PREF "security.crl.autoupdate.enable."
-#define CRL_AUTOUPDATE_DEFAULT_DELAY 30000UL
-
-class nsCRLInfo : public nsICRLInfo
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSICRLINFO
-
-  nsCRLInfo();
-  nsCRLInfo(CERTSignedCrl *);
-  virtual ~nsCRLInfo();
-  /* additional members */
-private:
-  nsString mOrg;
-  nsString mOrgUnit;
-  nsString mLastUpdateLocale;
-  nsString mNextUpdateLocale;
-  PRTime mLastUpdate;
-  PRTime mNextUpdate;
-  nsString mNameInDb;
-  nsCString mLastFetchURL;
-  nsString mNextAutoUpdateDate;
-};
-
-#endif
deleted file mode 100644
--- a/security/manager/ssl/src/nsCRLManager.cpp
+++ /dev/null
@@ -1,441 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsCRLManager.h"
-#include "nsCRLInfo.h"
-
-#include "nsCOMPtr.h"
-#include "nsComponentManagerUtils.h"
-#include "nsReadableUtils.h"
-#include "nsNSSComponent.h"
-#include "nsCOMPtr.h"
-#include "nsICertificateDialogs.h"
-#include "nsIMutableArray.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
-#include "nsNSSShutDown.h"
-#include "nsThreadUtils.h"
-
-#include "nspr.h"
-#include "pk11func.h"
-#include "certdb.h"
-#include "cert.h"
-#include "secerr.h"
-#include "nssb64.h"
-#include "secasn1.h"
-#include "secder.h"
-#include "ssl.h"
-#include "ocsp.h"
-#include "plbase64.h"
-
-static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
-
-NS_IMPL_ISUPPORTS1(nsCRLManager, nsICRLManager)
-
-nsCRLManager::nsCRLManager()
-{
-}
-
-nsCRLManager::~nsCRLManager()
-{
-}
-
-NS_IMETHODIMP 
-nsCRLManager::ImportCrl (uint8_t *aData, uint32_t aLength, nsIURI * aURI, uint32_t aType, bool doSilentDownload, const PRUnichar* crlKey)
-{
-  if (!NS_IsMainThread()) {
-    NS_ERROR("nsCRLManager::ImportCrl called off the main thread");
-    return NS_ERROR_NOT_SAME_THREAD;
-  }
-  
-  nsNSSShutDownPreventionLock locker;
-  nsresult rv;
-  PLArenaPool *arena = nullptr;
-  CERTCertificate *caCert;
-  SECItem derName = { siBuffer, nullptr, 0 };
-  SECItem derCrl;
-  CERTSignedData sd;
-  SECStatus sec_rv;
-  CERTSignedCrl *crl;
-  nsAutoCString url;
-  nsCOMPtr<nsICRLInfo> crlData;
-  bool importSuccessful;
-  int32_t errorCode;
-  nsString errorMessage;
-  
-  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if (NS_FAILED(rv)) return rv;
-	         
-  aURI->GetSpec(url);
-  arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-  if (!arena) {
-    goto loser;
-  }
-  memset(&sd, 0, sizeof(sd));
-
-  derCrl.data = (unsigned char*)aData;
-  derCrl.len = aLength;
-  sec_rv = CERT_KeyFromDERCrl(arena, &derCrl, &derName);
-  if (sec_rv != SECSuccess) {
-    goto loser;
-  }
-
-  caCert = CERT_FindCertByName(CERT_GetDefaultCertDB(), &derName);
-  if (!caCert) {
-    if (aType == SEC_KRL_TYPE){
-      goto loser;
-    }
-  } else {
-    sec_rv = SEC_ASN1DecodeItem(arena,
-                            &sd, SEC_ASN1_GET(CERT_SignedDataTemplate), 
-                            &derCrl);
-    if (sec_rv != SECSuccess) {
-      goto loser;
-    }
-    sec_rv = CERT_VerifySignedData(&sd, caCert, PR_Now(),
-                               nullptr);
-    if (sec_rv != SECSuccess) {
-      goto loser;
-    }
-  }
-  
-  crl = SEC_NewCrl(CERT_GetDefaultCertDB(), const_cast<char*>(url.get()), &derCrl,
-                   aType);
-  
-  if (!crl) {
-    goto loser;
-  }
-
-  crlData = new nsCRLInfo(crl);
-  SSL_ClearSessionCache();
-  SEC_DestroyCrl(crl);
-  
-  importSuccessful = true;
-  goto done;
-
-loser:
-  importSuccessful = false;
-  errorCode = PR_GetError();
-  switch (errorCode) {
-    case SEC_ERROR_CRL_EXPIRED:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureExpired", errorMessage);
-      break;
-
-	case SEC_ERROR_CRL_BAD_SIGNATURE:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureBadSignature", errorMessage);
-      break;
-
-	case SEC_ERROR_CRL_INVALID:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureInvalid", errorMessage);
-      break;
-
-	case SEC_ERROR_OLD_CRL:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureOld", errorMessage);
-      break;
-
-	case SEC_ERROR_CRL_NOT_YET_VALID:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureNotYetValid", errorMessage);
-      break;
-
-    default:
-      nssComponent->GetPIPNSSBundleString("CrlImportFailureReasonUnknown", errorMessage);
-      errorMessage.AppendInt(errorCode,16);
-      break;
-  }
-
-done:
-          
-  if(!doSilentDownload){
-    if (!importSuccessful){
-      nsString message;
-      nsString temp;
-      nssComponent->GetPIPNSSBundleString("CrlImportFailure1x", message);
-      message.Append(NS_LITERAL_STRING("\n").get());
-      message.Append(errorMessage);
-      nssComponent->GetPIPNSSBundleString("CrlImportFailure2", temp);
-      message.Append(NS_LITERAL_STRING("\n").get());
-      message.Append(temp);
-
-      nsNSSComponent::ShowAlertWithConstructedString(message);
-    } else {
-      nsCOMPtr<nsICertificateDialogs> certDialogs;
-      // Not being able to display the success dialog should not
-      // be a fatal error, so don't return a failure code.
-      {
-        nsPSMUITracker tracker;
-        if (tracker.isUIForbidden()) {
-          rv = NS_ERROR_NOT_AVAILABLE;
-        }
-        else {
-          rv = ::getNSSDialogs(getter_AddRefs(certDialogs),
-            NS_GET_IID(nsICertificateDialogs), NS_CERTIFICATEDIALOGS_CONTRACTID);
-        }
-      }
-      if (NS_SUCCEEDED(rv)) {
-        nsCOMPtr<nsIInterfaceRequestor> cxt = new PipUIContext();
-        certDialogs->CrlImportStatusDialog(cxt, crlData);
-      }
-    }
-  } else {
-    if (!crlKey) {
-      return NS_ERROR_FAILURE;
-    }
-    nsCOMPtr<nsIPrefService> prefSvc = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
-    nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
-    if (NS_FAILED(rv)){
-      return rv;
-    }
-    
-    nsAutoCString updateErrCntPrefStr(CRL_AUTOUPDATE_ERRCNT_PREF);
-    LossyAppendUTF16toASCII(crlKey, updateErrCntPrefStr);
-    if(importSuccessful){
-      PRUnichar *updateTime;
-      nsAutoCString updateTimeStr;
-      nsCString updateURL;
-      int32_t timingTypePref;
-      double dayCnt;
-      char *dayCntStr;
-      nsAutoCString updateTypePrefStr(CRL_AUTOUPDATE_TIMIINGTYPE_PREF);
-      nsAutoCString updateTimePrefStr(CRL_AUTOUPDATE_TIME_PREF);
-      nsAutoCString updateUrlPrefStr(CRL_AUTOUPDATE_URL_PREF);
-      nsAutoCString updateDayCntPrefStr(CRL_AUTOUPDATE_DAYCNT_PREF);
-      nsAutoCString updateFreqCntPrefStr(CRL_AUTOUPDATE_FREQCNT_PREF);
-      LossyAppendUTF16toASCII(crlKey, updateTypePrefStr);
-      LossyAppendUTF16toASCII(crlKey, updateTimePrefStr);
-      LossyAppendUTF16toASCII(crlKey, updateUrlPrefStr);
-      LossyAppendUTF16toASCII(crlKey, updateDayCntPrefStr);
-      LossyAppendUTF16toASCII(crlKey, updateFreqCntPrefStr);
-
-      pref->GetIntPref(updateTypePrefStr.get(),&timingTypePref);
-      
-      //Compute and update the next download instant
-      if(timingTypePref == TYPE_AUTOUPDATE_TIME_BASED){
-        pref->GetCharPref(updateDayCntPrefStr.get(),&dayCntStr);
-      }else{
-        pref->GetCharPref(updateFreqCntPrefStr.get(),&dayCntStr);
-      }
-      dayCnt = atof(dayCntStr);
-      nsMemory::Free(dayCntStr);
-
-      bool toBeRescheduled = false;
-      if(NS_SUCCEEDED(ComputeNextAutoUpdateTime(crlData, timingTypePref, dayCnt, &updateTime))){
-        updateTimeStr.AssignWithConversion(updateTime);
-        pref->SetCharPref(updateTimePrefStr.get(),updateTimeStr.get());
-        //Now, check if this update time is already in the past. This would
-        //imply we have downloaded the same crl, or there is something wrong
-        //with the next update date. We will not reschedule this crl in this
-        //session anymore - or else, we land into a loop. It would anyway be
-        //imported once the browser is restarted.
-        if(int64_t(updateTime) > int64_t(PR_Now())){
-          toBeRescheduled = true;
-        }
-        nsMemory::Free(updateTime);
-      }
-      
-      //Update the url to download from, next time
-      crlData->GetLastFetchURL(updateURL);
-      pref->SetCharPref(updateUrlPrefStr.get(),updateURL.get());
-      
-      pref->SetIntPref(updateErrCntPrefStr.get(),0);
-      
-      if (toBeRescheduled) {
-        nsAutoString hashKey(crlKey);
-        nssComponent->RemoveCrlFromList(hashKey);
-        nssComponent->DefineNextTimer();
-      }
-
-    } else{
-      int32_t errCnt;
-      nsAutoCString errMsg;
-      nsAutoCString updateErrDetailPrefStr(CRL_AUTOUPDATE_ERRDETAIL_PREF);
-      LossyAppendUTF16toASCII(crlKey, updateErrDetailPrefStr);
-      errMsg.AssignWithConversion(errorMessage.get());
-      rv = pref->GetIntPref(updateErrCntPrefStr.get(),&errCnt);
-      if(NS_FAILED(rv))
-        errCnt = 0;
-
-      pref->SetIntPref(updateErrCntPrefStr.get(),errCnt+1);
-      pref->SetCharPref(updateErrDetailPrefStr.get(),errMsg.get());
-    }
-    prefSvc->SavePrefFile(nullptr);
-  }
-
-  return rv;
-}
-
-NS_IMETHODIMP 
-nsCRLManager::UpdateCRLFromURL( const PRUnichar *url, const PRUnichar* key, bool *res)
-{
-  nsresult rv;
-  nsAutoString downloadUrl(url);
-  nsAutoString dbKey(key);
-  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if(NS_FAILED(rv)){
-    *res = false;
-    return rv;
-  }
-
-  rv = nssComponent->DownloadCRLDirectly(downloadUrl, dbKey);
-  if(NS_FAILED(rv)){
-    *res = false;
-  } else {
-    *res = true;
-  }
-  return NS_OK;
-
-}
-
-NS_IMETHODIMP 
-nsCRLManager::RescheduleCRLAutoUpdate(void)
-{
-  nsresult rv;
-  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if(NS_FAILED(rv)){
-    return rv;
-  }
-  rv = nssComponent->DefineNextTimer();
-  return rv;
-}
-
-/**
- * getCRLs
- *
- * Export a set of certs and keys from the database to a PKCS#12 file.
- */
-NS_IMETHODIMP 
-nsCRLManager::GetCrls(nsIArray ** aCrls)
-{
-  nsNSSShutDownPreventionLock locker;
-  SECStatus sec_rv;
-  CERTCrlHeadNode *head = nullptr;
-  CERTCrlNode *node = nullptr;
-  nsresult rv;
-  nsCOMPtr<nsIMutableArray> crlsArray =
-    do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
-  if (NS_FAILED(rv)) {
-    return rv;
-  }
-
-  // Get the list of certs //
-  sec_rv = SEC_LookupCrls(CERT_GetDefaultCertDB(), &head, -1);
-  if (sec_rv != SECSuccess) {
-    return NS_ERROR_FAILURE;
-  }
-
-  if (head) {
-    for (node=head->first; node; node = node->next) {
-
-      nsCOMPtr<nsICRLInfo> entry = new nsCRLInfo((node->crl));
-      crlsArray->AppendElement(entry, false);
-    }
-    PORT_FreeArena(head->arena, false);
-  }
-
-  *aCrls = crlsArray;
-  NS_IF_ADDREF(*aCrls);
-  return NS_OK;
-}
-
-/**
- * deleteCrl
- *
- * Delete a Crl entry from the cert db.
- */
-NS_IMETHODIMP 
-nsCRLManager::DeleteCrl(uint32_t aCrlIndex)
-{
-  nsNSSShutDownPreventionLock locker;
-  CERTSignedCrl *realCrl = nullptr;
-  CERTCrlHeadNode *head = nullptr;
-  CERTCrlNode *node = nullptr;
-  SECStatus sec_rv;
-  uint32_t i;
-
-  // Get the list of certs //
-  sec_rv = SEC_LookupCrls(CERT_GetDefaultCertDB(), &head, -1);
-  if (sec_rv != SECSuccess) {
-    return NS_ERROR_FAILURE;
-  }
-
-  if (head) {
-    for (i = 0, node=head->first; node; i++, node = node->next) {
-      if (i != aCrlIndex) {
-        continue;
-      }
-      realCrl = SEC_FindCrlByName(CERT_GetDefaultCertDB(), &(node->crl->crl.derName), node->type);
-      SEC_DeletePermCRL(realCrl);
-      SEC_DestroyCrl(realCrl);
-      SSL_ClearSessionCache();
-    }
-    PORT_FreeArena(head->arena, false);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsCRLManager::ComputeNextAutoUpdateTime(nsICRLInfo *info, 
-  uint32_t autoUpdateType, double dayCnt, PRUnichar **nextAutoUpdate)
-{
-  if (!info)
-    return NS_ERROR_FAILURE;
-  NS_ENSURE_ARG_POINTER(nextAutoUpdate);
-
-  PRTime microsecInDayCnt;
-  PRTime now = PR_Now();
-  PRTime tempTime;
-  int64_t diff = 0;
-  int64_t secsInDay = 86400UL;
-  int64_t temp;
-  int64_t cycleCnt = 0;
-  double tmpData = double(secsInDay);
-  tmpData *= dayCnt;
-  microsecInDayCnt = int64_t(tmpData) * PR_USEC_PER_SEC;
-
-  PRTime lastUpdate;
-  PRTime nextUpdate;
-
-  nsresult rv;
-
-  rv = info->GetLastUpdate(&lastUpdate);
-  if (NS_FAILED(rv))
-    return rv;
-
-  rv = info->GetNextUpdate(&nextUpdate);
-  if (NS_FAILED(rv))
-    return rv;
-
-  switch (autoUpdateType) {
-  case TYPE_AUTOUPDATE_FREQ_BASED:
-    diff = now - lastUpdate;                    //diff is the no of micro sec between now and last update
-    cycleCnt = diff / microsecInDayCnt;       //temp is the number of full cycles from lst update
-    temp = diff % microsecInDayCnt;
-    if(temp != 0) {
-      ++cycleCnt;            //no of complete cycles till next autoupdate instant
-    }
-    temp = cycleCnt * microsecInDayCnt;    //micro secs from last update
-    tempTime = lastUpdate + temp;
-    break;  
-  case TYPE_AUTOUPDATE_TIME_BASED:
-    tempTime = nextUpdate - microsecInDayCnt;
-    break;
-  default:
-    return NS_ERROR_NOT_IMPLEMENTED;
-  }
-
-  //Now, a basic constraing is that the next auto update date can never be after
-  //next update, if one is defined
-  if(nextUpdate > 0) {
-    if(tempTime > nextUpdate) {
-      tempTime = nextUpdate;
-    }
-  }
-
-  // Return value as string; no pref type for Int64/PRTime
-  char *tempTimeStr = PR_smprintf("%lli", tempTime);
-  *nextAutoUpdate = ToNewUnicode(nsDependentCString(tempTimeStr));
-  PR_smprintf_free(tempTimeStr);
-
-  return NS_OK;
-}
-
deleted file mode 100644
--- a/security/manager/ssl/src/nsCRLManager.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef _NSCRLMANAGER_H_
-#define _NSCRLMANAGER_H_
-
-#include "nsICRLManager.h"
-
-class nsCRLManager : public nsICRLManager
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSICRLMANAGER
-  
-  nsCRLManager();
-  virtual ~nsCRLManager();
-};
-
-#endif
--- a/security/manager/ssl/src/nsCrypto.cpp
+++ b/security/manager/ssl/src/nsCrypto.cpp
@@ -7,19 +7,19 @@
 #include "nsNSSComponent.h"
 #include "secmod.h"
 
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
 #include "nsXPIDLString.h"
 #include "nsISaveAsCharset.h"
 #include "nsNativeCharsetUtils.h"
+#include "nsServiceManagerUtils.h"
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
-#include "nsNSSComponent.h"
 #include "nsKeygenHandler.h"
 #include "nsKeygenThread.h"
 #include "nsNSSCertificate.h"
 #include "nsNSSCertificateDB.h"
 #include "nsPKCS12Blob.h"
 #include "nsPK11TokenDB.h"
 #include "nsThreadUtils.h"
 #include "nsIServiceManager.h"
--- a/security/manager/ssl/src/nsNSSCallbacks.cpp
+++ b/security/manager/ssl/src/nsNSSCallbacks.cpp
@@ -18,16 +18,17 @@
 #include "nsThreadUtils.h"
 #include "nsIPrompt.h"
 #include "nsProxyRelease.h"
 #include "PSMRunnable.h"
 #include "ScopedNSSTypes.h"
 #include "nsIConsoleService.h"
 #include "nsIHttpChannelInternal.h"
 #include "nsCRT.h"
+#include "nsNetUtil.h"
 #include "SharedSSLState.h"
 
 #include "ssl.h"
 #include "sslproto.h"
 #include "ocsp.h"
 #include "nssb64.h"
 
 using namespace mozilla;
--- a/security/manager/ssl/src/nsNSSCertHelper.cpp
+++ b/security/manager/ssl/src/nsNSSCertHelper.cpp
@@ -5,22 +5,24 @@
 #include "prerror.h"
 #include "prprf.h"
 
 #include "ScopedNSSTypes.h"
 #include "nsNSSCertHelper.h"
 #include "nsCOMPtr.h"
 #include "nsNSSCertificate.h"
 #include "secder.h"
+#include "nsComponentManagerUtils.h"
 #include "nsNSSCertValidity.h"
 #include "nsNSSASN1Object.h"
 #include "nsNSSComponent.h"
 #include "nsNSSCertTrust.h"
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
+#include "nsServiceManagerUtils.h"
 #include <algorithm>
 
 using namespace mozilla;
  
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
 
 /* Object Identifier constants */
 #define CONST_OID static const unsigned char
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -6,38 +6,22 @@
 
 #ifdef MOZ_LOGGING
 #define FORCE_PR_LOG 1
 #endif
 
 #include "nsNSSComponent.h"
 
 #include "CertVerifier.h"
-#include "nsNSSCallbacks.h"
-#include "nsNSSIOLayer.h"
 #include "nsCertVerificationThread.h"
-
-#include "nsNetUtil.h"
 #include "nsAppDirectoryServiceDefs.h"
-#include "nsDirectoryService.h"
-#include "nsIStreamListener.h"
-#include "nsIStringBundle.h"
-#include "nsIDirectoryService.h"
-#include "nsCURILoader.h"
+#include "nsComponentManagerUtils.h"
 #include "nsDirectoryServiceDefs.h"
-#include "nsIX509Cert.h"
-#include "nsIX509CertDB.h"
-#include "nsNSSCertificate.h"
-#include "nsNSSHelper.h"
-#include "prlog.h"
+#include "nsICertOverrideService.h"
 #include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
-#include "nsIDateTimeFormat.h"
-#include "nsDateTimeFormatCID.h"
-#include "nsThreadUtils.h"
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
 #include "nsIDOMNode.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIDocument.h"
@@ -45,55 +29,44 @@
 #include "nsSmartCardMonitor.h"
 #include "nsIDOMCryptoLegacy.h"
 #include "nsIPrincipal.h"
 #else
 #include "nsIDOMCrypto.h"
 #endif
 
 #include "nsCRT.h"
-#include "nsCRLInfo.h"
-#include "nsCertOverrideService.h"
 #include "nsNTLMAuthModule.h"
-
+#include "nsIFile.h"
+#include "nsIProperties.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPrompt.h"
 #include "nsCertificatePrincipal.h"
-#include "nsReadableUtils.h"
-#include "nsIDateTimeFormat.h"
-#include "prtypes.h"
-#include "nsIEntropyCollector.h"
 #include "nsIBufEntropyCollector.h"
-#include "nsIServiceManager.h"
-#include "nsIFile.h"
 #include "nsITokenPasswordDialogs.h"
-#include "nsICRLManager.h"
+#include "nsServiceManagerUtils.h"
 #include "nsNSSShutDown.h"
 #include "GeneratedEvents.h"
 #include "SharedSSLState.h"
 
 #include "nss.h"
 #include "ssl.h"
 #include "sslproto.h"
 #include "secmod.h"
 #include "secmime.h"
 #include "ocsp.h"
-#include "nssckbi.h"
-#include "base64.h"
 #include "secerr.h"
 #include "sslerr.h"
 
 #include "nsXULAppAPI.h"
-#include <algorithm>
 
 #ifdef XP_WIN
 #include "nsILocalFileWin.h"
 #endif
 
-#include "pkcs12.h"
 #include "p12plcy.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::psm;
 
 #ifdef MOZ_LOGGING
 PRLogModuleInfo* gPIPNSSLog = nullptr;
@@ -108,45 +81,16 @@ bool nsNSSComponent::globalConstFlagUseP
 #endif
 
 // XXX tmp callback for slot password
 extern char* pk11PasswordPrompt(PK11SlotInfo *slot, PRBool retry, void *arg);
 
 #define PIPNSS_STRBUNDLE_URL "chrome://pipnss/locale/pipnss.properties"
 #define NSSERR_STRBUNDLE_URL "chrome://pipnss/locale/nsserrors.properties"
 
-class CRLDownloadEvent : public nsRunnable {
-public:
-  CRLDownloadEvent(const nsCSubstring &urlString, nsIStreamListener *listener)
-    : mURLString(urlString)
-    , mListener(listener)
-  {}
-
-  // Note that nsNSSComponent is a singleton object across all threads, 
-  // and automatic downloads are always scheduled sequentially - that is, 
-  // once one crl download is complete, the next one is scheduled
-  NS_IMETHOD Run()
-  {
-    if (!mListener || mURLString.IsEmpty())
-      return NS_OK;
-
-    nsCOMPtr<nsIURI> uri;
-    nsresult rv = NS_NewURI(getter_AddRefs(uri), mURLString);
-    if (NS_SUCCEEDED(rv)){
-      NS_OpenURI(mListener, nullptr, uri);
-    }
-
-    return NS_OK;
-  }
-
-private:
-  nsCString mURLString;
-  nsCOMPtr<nsIStreamListener> mListener;
-};
-
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
 //This class is used to run the callback code
 //passed to the event handlers for smart card notification
 class nsTokenEventRunnable : public nsIRunnable {
 public:
   nsTokenEventRunnable(const nsAString &aType, const nsAString &aTokenName);
   virtual ~nsTokenEventRunnable();
 
@@ -259,31 +203,26 @@ bool EnsureNSSInitialized(EnsureNSSOpera
     NS_ASSERTION(false, "Bad operator to EnsureNSSInitialized");
     return false;
   }
 }
 
 nsNSSComponent::nsNSSComponent()
   :mutex("nsNSSComponent.mutex"),
    mNSSInitialized(false),
-   mCrlTimerLock("nsNSSComponent.mCrlTimerLock"),
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
    mThreadList(nullptr),
 #endif
    mCertVerificationThread(nullptr)
 {
 #ifdef PR_LOGGING
   if (!gPIPNSSLog)
     gPIPNSSLog = PR_NewLogModule("pipnss");
 #endif
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::ctor\n"));
-  mUpdateTimerInitialized = false;
-  crlDownloadTimerOn = false;
-  crlsScheduledForDownload = nullptr;
-  mTimer = nullptr;
   mObserversRegistered = false;
 
 #ifndef NSS_NO_LIBPKIX
   // In order to keep startup time lower, we delay loading and 
   // registering all identity data until first needed.
   memset(&mIdentityInfoCallOnce, 0, sizeof(PRCallOnceType));
 #endif
 
@@ -321,32 +260,16 @@ nsNSSComponent::createBackgroundThreads(
 }
 
 nsNSSComponent::~nsNSSComponent()
 {
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::dtor\n"));
 
   deleteBackgroundThreads();
 
-  if (mUpdateTimerInitialized) {
-    {
-      MutexAutoLock lock(mCrlTimerLock);
-      if (crlDownloadTimerOn) {
-        mTimer->Cancel();
-      }
-      crlDownloadTimerOn = false;
-    }
-    if (crlsScheduledForDownload) {
-      crlsScheduledForDownload->Reset();
-      delete crlsScheduledForDownload;
-    }
-
-    mUpdateTimerInitialized = false;
-  }
-
   // All cleanup code requiring services needs to happen in xpcom_shutdown
 
   ShutdownNSS();
   SharedSSLState::GlobalCleanup();
   RememberCertErrorsTable::Cleanup();
   --mInstanceCount;
   delete mShutdownObjectList;
 
@@ -893,32 +816,16 @@ nsNSSComponent::InitializePIPNSSBundle()
   bundleService->CreateBundle(NSSERR_STRBUNDLE_URL,
                               getter_AddRefs(mNSSErrorsBundle));
   if (!mNSSErrorsBundle)
     rv = NS_ERROR_FAILURE;
 
   return rv;
 }
 
-nsresult
-nsNSSComponent::RegisterPSMContentListener()
-{
-  // Called during init only, no mutex required.
-
-  nsresult rv = NS_OK;
-  if (!mPSMContentListener) {
-    nsCOMPtr<nsIURILoader> dispatcher(do_GetService(NS_URI_LOADER_CONTRACTID));
-    if (dispatcher) {
-      mPSMContentListener = do_CreateInstance(NS_PSMCONTENTLISTEN_CONTRACTID);
-      rv = dispatcher->RegisterContentListener(mPSMContentListener);
-    }
-  }
-  return rv;
-}
-
 /* Table of pref names and SSL cipher ID */
 typedef struct {
   const char* pref;
   long id;
 } CipherPref;
 
 static CipherPref CipherPrefs[] = {
  /* SSL3/TLS cipher suites*/
@@ -1106,295 +1013,16 @@ nsNSSComponent::SkipOcspOff()
   setNonPkixOcspEnabled(ocspEnabled, mPrefBranch);
 
   if (ocspEnabled)
     SSL_ClearSessionCache();
 
   return NS_OK;
 }
 
-nsresult
-nsNSSComponent::PostCRLImportEvent(const nsCSubstring &urlString,
-                                   nsIStreamListener *listener)
-{
-  //Create the event
-  nsCOMPtr<nsIRunnable> event = new CRLDownloadEvent(urlString, listener);
-
-  //Get a handle to the ui thread
-  return NS_DispatchToMainThread(event);
-}
-
-nsresult
-nsNSSComponent::DownloadCRLDirectly(nsAutoString url, nsAutoString key)
-{
-  //This api is meant to support direct interactive update of crl from the crl manager
-  //or other such ui.
-  nsCOMPtr<nsIStreamListener> listener =
-      new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL);
-  
-  NS_ConvertUTF16toUTF8 url8(url);
-  return PostCRLImportEvent(url8, listener);
-}
-
-nsresult nsNSSComponent::DownloadCrlSilently()
-{
-  //Add this attempt to the hashtable
-  nsStringKey hashKey(mCrlUpdateKey.get());
-  crlsScheduledForDownload->Put(&hashKey,(void *)nullptr);
-    
-  //Set up the download handler
-  RefPtr<PSMContentDownloader> psmDownloader(
-      new PSMContentDownloader(PSMContentDownloader::PKCS7_CRL));
-  psmDownloader->setSilentDownload(true);
-  psmDownloader->setCrlAutodownloadKey(mCrlUpdateKey);
-  
-  //Now get the url string
-  NS_ConvertUTF16toUTF8 url8(mDownloadURL);
-  return PostCRLImportEvent(url8, psmDownloader);
-}
-
-nsresult nsNSSComponent::getParamsForNextCrlToDownload(nsAutoString *url, PRTime *time, nsAutoString *key)
-{
-  const char *updateEnabledPref = CRL_AUTOUPDATE_ENABLED_PREF;
-  const char *updateTimePref = CRL_AUTOUPDATE_TIME_PREF;
-  const char *updateURLPref = CRL_AUTOUPDATE_URL_PREF;
-  char **allCrlsToBeUpdated;
-  uint32_t noOfCrls;
-  PRTime nearestUpdateTime = 0;
-  nsAutoString crlKey;
-  char *tempUrl;
-  nsresult rv;
-  
-  nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
-  if(NS_FAILED(rv)){
-    return rv;
-  }
-
-  rv = pref->GetChildList(updateEnabledPref, &noOfCrls, &allCrlsToBeUpdated);
-  if ( (NS_FAILED(rv)) || (noOfCrls==0) ){
-    return NS_ERROR_FAILURE;
-  }
-
-  for(uint32_t i=0;i<noOfCrls;i++) {
-    //First check if update pref is enabled for this crl
-    bool autoUpdateEnabled = false;
-    rv = pref->GetBoolPref(*(allCrlsToBeUpdated+i), &autoUpdateEnabled);
-    if (NS_FAILED(rv) || !autoUpdateEnabled) {
-      continue;
-    }
-
-    nsAutoString tempCrlKey;
-
-    //Now, generate the crl key. Same key would be used as hashkey as well
-    nsAutoCString enabledPrefCString(*(allCrlsToBeUpdated+i));
-    enabledPrefCString.ReplaceSubstring(updateEnabledPref,".");
-    tempCrlKey.AssignWithConversion(enabledPrefCString.get());
-      
-    //Check if this crl has already been scheduled. Its presence in the hashtable
-    //implies that it has been scheduled already this client session, and
-    //is either in the process of being downloaded, or its download failed
-    //for some reason. In the second case, we will not retry in the current client session
-    nsStringKey hashKey(tempCrlKey.get());
-    if(crlsScheduledForDownload->Exists(&hashKey)){
-      continue;
-    }
-
-    char *tempTimeString;
-    PRTime tempTime;
-    nsAutoCString timingPrefCString(updateTimePref);
-    LossyAppendUTF16toASCII(tempCrlKey, timingPrefCString);
-    // No PRTime/Int64 type in prefs; stored as string; parsed here as int64_t
-    rv = pref->GetCharPref(timingPrefCString.get(), &tempTimeString);
-    if (NS_FAILED(rv)){
-      // Assume corrupted. Force download. Pref should be reset after download.
-      tempTime = PR_Now();
-      PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
-             ("get %s failed: forcing download\n", timingPrefCString.get()));
-    } else {
-      tempTime = (PRTime)nsCRT::atoll(tempTimeString);
-      nsMemory::Free(tempTimeString);
-      // nsCRT::atoll parses the first token in the string; three possibilities
-      //  -1- Alpha char: returns 0; change to PR_Now() and force update.
-      //  -2- Number (between epoch and PR_Now(), e.g. 0 - 1332280017 for
-      //      Tue Mar 20, 2012, 2:46pm approx): includes formatted date 
-      //      values (previous method of storing update date, e.g year, month 
-      //      or day, 2012, 1-31, 1-12 etc). Less than PR_Now() forces 
-      //      autoupdate.
-      //  -3- Number (larger than PR_Now()): no forced autoupdate
-      // Note: corrupt values within range of -2- will have an implicit 
-      // unflagged recovery. Corrupt values in range of -3- will be unflagged
-      // and unrecovered by this code.
-      if (tempTime == 0)
-        tempTime = PR_Now();
-#ifdef PR_LOGGING
-      PRExplodedTime explodedTime;
-      PR_ExplodeTime(tempTime, PR_GMTParameters, &explodedTime);
-      // Note: tm_month starts from 0 = Jan, hence +1
-      PR_LOG(gPIPNSSLog, PR_LOG_DEBUG,
-             ("%s tempTime(%lli) "
-              "(m/d/y h:m:s = %02d/%02d/%d %02d:%02d:%02d GMT\n",
-              timingPrefCString.get(), tempTime,
-              explodedTime.tm_month+1, explodedTime.tm_mday,
-              explodedTime.tm_year, explodedTime.tm_hour,
-              explodedTime.tm_min, explodedTime.tm_sec));
-#endif
-    }
-
-    if(nearestUpdateTime == 0 || tempTime < nearestUpdateTime){
-      nsAutoCString urlPrefCString(updateURLPref);
-      LossyAppendUTF16toASCII(tempCrlKey, urlPrefCString);
-      rv = pref->GetCharPref(urlPrefCString.get(), &tempUrl);
-      if (NS_FAILED(rv) || (!tempUrl)){
-        continue;
-      }
-      nearestUpdateTime = tempTime;
-      crlKey = tempCrlKey;
-    }
-  }
-
-  if(noOfCrls > 0)
-    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(noOfCrls, allCrlsToBeUpdated);
-
-  if(nearestUpdateTime > 0){
-    *time = nearestUpdateTime;
-    url->AssignWithConversion((const char *)tempUrl);
-    nsMemory::Free(tempUrl);
-    *key = crlKey;
-    rv = NS_OK;
-  } else{
-    rv = NS_ERROR_FAILURE;
-  }
-
-  return rv;
-}
-
-NS_IMETHODIMP
-nsNSSComponent::Notify(nsITimer *timer)
-{
-  //Timer has fired. So set the flag accordingly
-  {
-    MutexAutoLock lock(mCrlTimerLock);
-    crlDownloadTimerOn = false;
-  }
-
-  //First, handle this download
-  DownloadCrlSilently();
-
-  //Dont Worry if successful or not
-  //Set the next timer
-  DefineNextTimer();
-  return NS_OK;
-}
-
-nsresult
-nsNSSComponent::RemoveCrlFromList(nsAutoString key)
-{
-  nsStringKey hashKey(key.get());
-  if(crlsScheduledForDownload->Exists(&hashKey)){
-    crlsScheduledForDownload->Remove(&hashKey);
-  }
-  return NS_OK;
-}
-
-nsresult
-nsNSSComponent::DefineNextTimer()
-{
-  PRTime nextFiring;
-  PRTime now = PR_Now();
-  uint32_t interval;
-  uint32_t primaryDelay = CRL_AUTOUPDATE_DEFAULT_DELAY;
-  nsresult rv;
-
-  if(!mTimer){
-    mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if(NS_FAILED(rv))
-      return rv;
-  }
-
-  //If some timer is already running, cancel it. Thus, the request that came last,
-  //wins. This would ensure that in no way we end up setting two different timers
-  //This part should be synchronized because this function might be called from separate
-  //threads
-
-  MutexAutoLock lock(mCrlTimerLock);
-
-  if (crlDownloadTimerOn) {
-    mTimer->Cancel();
-  }
-
-  rv = getParamsForNextCrlToDownload(&mDownloadURL, &nextFiring, &mCrlUpdateKey);
-  //If there are no more crls to be updated any time in future
-  if(NS_FAILED(rv)){
-    // Return - no error - just implies nothing to schedule
-    return NS_OK;
-  }
-     
-  //Define the firing interval, from NOW
-  if ( now < nextFiring) {
-    interval = uint32_t(nextFiring - now);
-    //Now, we are doing 32 operations - so, don't need LL_ functions...
-    interval = interval/PR_USEC_PER_MSEC;
-  }else {
-    interval = primaryDelay;
-  }
-  
-  mTimer->InitWithCallback(static_cast<nsITimerCallback*>(this), 
-                           interval,
-                           nsITimer::TYPE_ONE_SHOT);
-  crlDownloadTimerOn = true;
-
-  return NS_OK;
-}
-
-//Note that the StopCRLUpdateTimer and InitializeCRLUpdateTimer functions should never be called
-//simultaneously from diff threads - they are NOT threadsafe. But, since there is no chance of 
-//that happening, there is not much benefit it trying to make it so at this point
-nsresult
-nsNSSComponent::StopCRLUpdateTimer()
-{
-  
-  //If it is at all running. 
-  if (mUpdateTimerInitialized) {
-    if (crlsScheduledForDownload) {
-      crlsScheduledForDownload->Reset();
-      delete crlsScheduledForDownload;
-      crlsScheduledForDownload = nullptr;
-    }
-    {
-      MutexAutoLock lock(mCrlTimerLock);
-      if (crlDownloadTimerOn) {
-        mTimer->Cancel();
-      }
-      crlDownloadTimerOn = false;
-    }
-    mUpdateTimerInitialized = false;
-  }
-
-  return NS_OK;
-}
-
-nsresult
-nsNSSComponent::InitializeCRLUpdateTimer()
-{
-  nsresult rv;
-    
-  //First check if this is already initialized. Then we stop it.
-  if (!mUpdateTimerInitialized) {
-    mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
-    if(NS_FAILED(rv)){
-      return rv;
-    }
-    crlsScheduledForDownload = new nsHashtable(16, true);
-    DefineNextTimer();
-    mUpdateTimerInitialized = true;  
-  } 
-
-  return NS_OK;
-}
-
 static void configureMD5(bool enabled)
 {
   if (enabled) { // set flags
     NSS_SetAlgorithmPolicy(SEC_OID_MD5, 
         NSS_USE_ALG_IN_CERT_SIGNATURE | NSS_USE_ALG_IN_CMS_SIGNATURE, 0);
     NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
         NSS_USE_ALG_IN_CERT_SIGNATURE | NSS_USE_ALG_IN_CMS_SIGNATURE, 0);
     NSS_SetAlgorithmPolicy(SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC,
@@ -1749,19 +1377,16 @@ nsNSSComponent::Init()
   {
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("NSS init, could not create threads\n"));
 
     DeregisterObservers();
     mPIPNSSBundle = nullptr;
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
-  InitializeCRLUpdateTimer();
-  RegisterPSMContentListener();
-
   nsCOMPtr<nsIEntropyCollector> ec
       = do_GetService(NS_ENTROPYCOLLECTOR_CONTRACTID);
 
   nsCOMPtr<nsIBufEntropyCollector> bec;
 
   if (ec) {
     bec = do_QueryInterface(ec);
   }
@@ -1771,23 +1396,22 @@ nsNSSComponent::Init()
   if (bec) {
     bec->ForwardTo(this);
   }
 
   return rv;
 }
 
 /* nsISupports Implementation for the class */
-NS_IMPL_THREADSAFE_ISUPPORTS6(nsNSSComponent,
+NS_IMPL_THREADSAFE_ISUPPORTS5(nsNSSComponent,
                               nsISignatureVerifier,
                               nsIEntropyCollector,
                               nsINSSComponent,
                               nsIObserver,
-                              nsISupportsWeakReference,
-                              nsITimerCallback)
+                              nsISupportsWeakReference)
 
 
 /* Callback functions for decoder. For now, use empty/default functions. */
 static void ContentCallback(void *arg, 
                                            const char *buf,
                                            unsigned long len)
 {
 }
@@ -1975,33 +1599,23 @@ nsNSSComponent::Observe(nsISupports *aSu
       }
     }
     
     if (needsInit) {
       if (NS_FAILED(InitializeNSS(false))) { // do not show a warning box on failure
         PR_LOG(gPIPNSSLog, PR_LOG_ERROR, ("Unable to Initialize NSS after profile switch.\n"));
       }
     }
-
-    InitializeCRLUpdateTimer();
   }
   else if (nsCRT::strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
 
     PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent: XPCom shutdown observed\n"));
 
     // Cleanup code that requires services, it's too late in destructor.
 
-    if (mPSMContentListener) {
-      nsCOMPtr<nsIURILoader> dispatcher(do_GetService(NS_URI_LOADER_CONTRACTID));
-      if (dispatcher) {
-        dispatcher->UnRegisterContentListener(mPSMContentListener);
-      }
-      mPSMContentListener = nullptr;
-    }
-
     nsCOMPtr<nsIEntropyCollector> ec
         = do_GetService(NS_ENTROPYCOLLECTOR_CONTRACTID);
 
     if (ec) {
       nsCOMPtr<nsIBufEntropyCollector> bec
         = do_QueryInterface(ec);
       if (bec) {
         bec->DontForward();
@@ -2222,18 +1836,16 @@ nsNSSComponent::DoProfileBeforeChange(ns
     if (!mNSSInitialized) {
       // Make sure we don't try to cleanup if we have already done so.
       // This makes sure we behave safely, in case we are notified
       // multiple times.
       needsCleanup = false;
     }
   }
     
-  StopCRLUpdateTimer();
-
   if (needsCleanup) {
     ShutdownNSS();
   }
   mShutdownObjectList->allowUI();
 }
 
 void
 nsNSSComponent::DoProfileChangeNetRestore()
@@ -2343,359 +1955,8 @@ setPassword(PK11SlotInfo *slot, nsIInter
     NS_RELEASE(dialogs);
     if (NS_FAILED(rv)) goto loser;
 
     if (canceled) { rv = NS_ERROR_NOT_AVAILABLE; goto loser; }
   }
  loser:
   return rv;
 }
-
-
-PSMContentDownloader::PSMContentDownloader(uint32_t type)
-  : mByteData(nullptr),
-    mType(type),
-    mDoSilentDownload(false)
-{
-}
-
-PSMContentDownloader::~PSMContentDownloader()
-{
-  if (mByteData)
-    nsMemory::Free(mByteData);
-}
-
-NS_IMPL_ISUPPORTS2(PSMContentDownloader, nsIStreamListener, nsIRequestObserver)
-
-const int32_t kDefaultCertAllocLength = 2048;
-
-NS_IMETHODIMP
-PSMContentDownloader::OnStartRequest(nsIRequest* request, nsISupports* context)
-{
-  nsresult rv;
-  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnStartRequest\n"));
-  nsCOMPtr<nsIChannel> channel(do_QueryInterface(request));
-  if (!channel) return NS_ERROR_FAILURE;
-
-  // Get the URI //
-  channel->GetURI(getter_AddRefs(mURI));
-
-  int64_t contentLength;
-  rv = channel->GetContentLength(&contentLength);
-  if (NS_FAILED(rv) || contentLength <= 0)
-    contentLength = kDefaultCertAllocLength;
-  if (contentLength > INT32_MAX)
-    return NS_ERROR_OUT_OF_MEMORY;
-  
-  mBufferOffset = 0;
-  mBufferSize = 0;
-  mByteData = (char*) nsMemory::Alloc(contentLength);
-  if (!mByteData)
-    return NS_ERROR_OUT_OF_MEMORY;
-  
-  mBufferSize = int32_t(contentLength);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentDownloader::OnDataAvailable(nsIRequest* request,
-                                nsISupports* context,
-                                nsIInputStream *aIStream,
-                                uint64_t aSourceOffset,
-                                uint32_t aLength)
-{
-  if (!mByteData)
-    return NS_ERROR_OUT_OF_MEMORY;
-  
-  uint32_t amt;
-  nsresult err;
-  //Do a check to see if we need to allocate more memory.
-  if ((mBufferOffset + (int32_t)aLength) > mBufferSize) {
-      size_t newSize = (mBufferOffset + aLength) *2; // grow some more than needed
-      char *newBuffer;
-      newBuffer = (char*)nsMemory::Realloc(mByteData, newSize);
-      if (!newBuffer) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-      mByteData = newBuffer;
-      mBufferSize = newSize;
-  }
-  
-  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnDataAvailable\n"));
-  do {
-    err = aIStream->Read(mByteData+mBufferOffset,
-                         aLength, &amt);
-    if (NS_FAILED(err)) return err;
-    if (amt == 0) break;
-    
-    aLength -= amt;
-    mBufferOffset += amt;
-    
-  } while (aLength > 0);
-  
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentDownloader::OnStopRequest(nsIRequest* request,
-                              nsISupports* context,
-                              nsresult aStatus)
-{
-  nsNSSShutDownPreventionLock locker;
-  //Check if the download succeeded - it might have failed due to
-  //network issues, etc.
-  if (NS_FAILED(aStatus)){
-    handleContentDownloadError(aStatus);
-    return aStatus;
-  }
-
-  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CertDownloader::OnStopRequest\n"));
-
-  nsCOMPtr<nsIX509CertDB> certdb;
-  nsCOMPtr<nsICRLManager> crlManager;
-
-  nsresult rv;
-  nsCOMPtr<nsIInterfaceRequestor> ctx = new PipUIContext();
-
-  switch (mType) {
-  case PSMContentDownloader::X509_CA_CERT:
-  case PSMContentDownloader::X509_USER_CERT:
-  case PSMContentDownloader::X509_EMAIL_CERT:
-    certdb = do_GetService(NS_X509CERTDB_CONTRACTID);
-    break;
-
-  case PSMContentDownloader::PKCS7_CRL:
-    crlManager = do_GetService(NS_CRLMANAGER_CONTRACTID);
-
-  default:
-    break;
-  }
-
-  switch (mType) {
-  case PSMContentDownloader::X509_CA_CERT:
-    return certdb->ImportCertificates((uint8_t*)mByteData, mBufferOffset, mType, ctx); 
-  case PSMContentDownloader::X509_USER_CERT:
-    return certdb->ImportUserCertificate((uint8_t*)mByteData, mBufferOffset, ctx);
-  case PSMContentDownloader::X509_EMAIL_CERT:
-    return certdb->ImportEmailCertificate((uint8_t*)mByteData, mBufferOffset, ctx); 
-  case PSMContentDownloader::PKCS7_CRL:
-    return crlManager->ImportCrl((uint8_t*)mByteData, mBufferOffset, mURI, SEC_CRL_TYPE, mDoSilentDownload, mCrlAutoDownloadKey.get());
-  default:
-    rv = NS_ERROR_FAILURE;
-    break;
-  }
-  
-  return rv;
-}
-
-
-nsresult
-PSMContentDownloader::handleContentDownloadError(nsresult errCode)
-{
-  nsString tmpMessage;
-  nsresult rv;
-  nsCOMPtr<nsINSSComponent> nssComponent(do_GetService(kNSSComponentCID, &rv));
-  if(NS_FAILED(rv)){
-    return rv;
-  }
-      
-  //Handling errors for crl download only, for now.
-  switch (mType){
-  case PSMContentDownloader::PKCS7_CRL:
-
-    //TO DO: Handle network errors in details
-    //XXXXXXXXXXXXXXXXXX
-    nssComponent->GetPIPNSSBundleString("CrlImportFailureNetworkProblem", tmpMessage);
-      
-    if (mDoSilentDownload) {
-      //This is the case for automatic download. Update failure history
-      nsAutoCString updateErrCntPrefStr(CRL_AUTOUPDATE_ERRCNT_PREF);
-      nsAutoCString updateErrDetailPrefStr(CRL_AUTOUPDATE_ERRDETAIL_PREF);
-      nsCString errMsg;
-      int32_t errCnt;
-
-      nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID,&rv);
-      if(NS_FAILED(rv)){
-        return rv;
-      }
-      
-      LossyAppendUTF16toASCII(mCrlAutoDownloadKey, updateErrCntPrefStr);
-      LossyAppendUTF16toASCII(mCrlAutoDownloadKey, updateErrDetailPrefStr);
-      errMsg.AssignWithConversion(tmpMessage.get());
-      
-      rv = pref->GetIntPref(updateErrCntPrefStr.get(),&errCnt);
-      if( (NS_FAILED(rv)) || (errCnt == 0) ){
-        pref->SetIntPref(updateErrCntPrefStr.get(),1);
-      }else{
-        pref->SetIntPref(updateErrCntPrefStr.get(),errCnt+1);
-      }
-      pref->SetCharPref(updateErrDetailPrefStr.get(),errMsg.get());
-      nsCOMPtr<nsIPrefService> prefSvc(do_QueryInterface(pref));
-      prefSvc->SavePrefFile(nullptr);
-    }else{
-      nsString message;
-      nssComponent->GetPIPNSSBundleString("CrlImportFailure1x", message);
-      message.Append(NS_LITERAL_STRING("\n").get());
-      message.Append(tmpMessage);
-      nssComponent->GetPIPNSSBundleString("CrlImportFailure2", tmpMessage);
-      message.Append(NS_LITERAL_STRING("\n").get());
-      message.Append(tmpMessage);
-      nsNSSComponent::ShowAlertWithConstructedString(message);
-    }
-    break;
-  default:
-    break;
-  }
-
-  return NS_OK;
-
-}
-
-void 
-PSMContentDownloader::setSilentDownload(bool flag)
-{
-  mDoSilentDownload = flag;
-}
-
-void
-PSMContentDownloader::setCrlAutodownloadKey(nsAutoString key)
-{
-  mCrlAutoDownloadKey = key;
-}
-
-
-/* other mime types that we should handle sometime:
-   
-   application/x-pkcs7-crl
-   application/x-pkcs7-mime
-   application/pkcs7-signature
-   application/pre-encrypted
-   
-*/
-
-uint32_t
-getPSMContentType(const char * aContentType)
-{ 
-  // Don't forget to update RegisterPSMContentListeners in nsNSSModule.cpp 
-  // for every supported content type.
-  
-  if (!nsCRT::strcasecmp(aContentType, "application/x-x509-ca-cert"))
-    return PSMContentDownloader::X509_CA_CERT;
-  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-server-cert"))
-    return PSMContentDownloader::X509_SERVER_CERT;
-  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-user-cert"))
-    return PSMContentDownloader::X509_USER_CERT;
-  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-email-cert"))
-    return PSMContentDownloader::X509_EMAIL_CERT;
-  else if (!nsCRT::strcasecmp(aContentType, "application/x-pkcs7-crl"))
-    return PSMContentDownloader::PKCS7_CRL;
-  else if (!nsCRT::strcasecmp(aContentType, "application/x-x509-crl"))
-    return PSMContentDownloader::PKCS7_CRL;
-  else if (!nsCRT::strcasecmp(aContentType, "application/pkix-crl"))
-    return PSMContentDownloader::PKCS7_CRL;
-  return PSMContentDownloader::UNKNOWN_TYPE;
-}
-
-
-NS_IMPL_ISUPPORTS2(PSMContentListener,
-                   nsIURIContentListener,
-                   nsISupportsWeakReference) 
-
-PSMContentListener::PSMContentListener()
-{
-  mLoadCookie = nullptr;
-  mParentContentListener = nullptr;
-}
-
-PSMContentListener::~PSMContentListener()
-{
-}
-
-nsresult
-PSMContentListener::init()
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::OnStartURIOpen(nsIURI *aURI, bool *aAbortOpen)
-{
-  //if we don't want to handle the URI, return true in
-  //*aAbortOpen
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::IsPreferred(const char * aContentType,
-                                 char ** aDesiredContentType,
-                                 bool * aCanHandleContent)
-{
-  return CanHandleContent(aContentType, true,
-                          aDesiredContentType, aCanHandleContent);
-}
-
-NS_IMETHODIMP
-PSMContentListener::CanHandleContent(const char * aContentType,
-                                      bool aIsContentPreferred,
-                                      char ** aDesiredContentType,
-                                      bool * aCanHandleContent)
-{
-  uint32_t type;
-  type = getPSMContentType(aContentType);
-  if (type == PSMContentDownloader::UNKNOWN_TYPE) {
-    *aCanHandleContent = false;
-  } else {
-    *aCanHandleContent = true;
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::DoContent(const char * aContentType,
-                               bool aIsContentPreferred,
-                               nsIRequest * aRequest,
-                               nsIStreamListener ** aContentHandler,
-                               bool * aAbortProcess)
-{
-  PSMContentDownloader *downLoader;
-  uint32_t type;
-  type = getPSMContentType(aContentType);
-  PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("PSMContentListener::DoContent\n"));
-  if (type != PSMContentDownloader::UNKNOWN_TYPE) {
-    downLoader = new PSMContentDownloader(type);
-    if (downLoader) {
-      downLoader->QueryInterface(NS_GET_IID(nsIStreamListener), 
-                                            (void **)aContentHandler);
-      return NS_OK;
-    }
-  }
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-PSMContentListener::GetLoadCookie(nsISupports * *aLoadCookie)
-{
-  *aLoadCookie = mLoadCookie;
-  NS_IF_ADDREF(*aLoadCookie);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::SetLoadCookie(nsISupports * aLoadCookie)
-{
-  mLoadCookie = aLoadCookie;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::GetParentContentListener(nsIURIContentListener ** aContentListener)
-{
-  *aContentListener = mParentContentListener;
-  NS_IF_ADDREF(*aContentListener);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-PSMContentListener::SetParentContentListener(nsIURIContentListener * aContentListener)
-{
-  mParentContentListener = aContentListener;
-  return NS_OK;
-}
--- a/security/manager/ssl/src/nsNSSComponent.h
+++ b/security/manager/ssl/src/nsNSSComponent.h
@@ -6,38 +6,33 @@
 
 #ifndef _nsNSSComponent_h_
 #define _nsNSSComponent_h_
 
 #include "mozilla/Mutex.h"
 #include "mozilla/RefPtr.h"
 #include "nsCOMPtr.h"
 #include "nsISignatureVerifier.h"
-#include "nsIURIContentListener.h"
-#include "nsIStreamListener.h"
 #include "nsIEntropyCollector.h"
-#include "nsString.h"
 #include "nsIStringBundle.h"
 #include "nsIPrefBranch.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
-#include "nsWeakReference.h"
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
 #include "nsIDOMEventTarget.h"
-#include "nsSmartCardMonitor.h"
 #endif
 #include "nsINSSErrorsService.h"
-#include "nsITimer.h"
-#include "nsNetUtil.h"
-#include "nsHashtable.h"
 #include "nsNSSCallbacks.h"
-#include "nsNSSShutDown.h"
-
+#include "ScopedNSSTypes.h"
 #include "nsNSSHelper.h"
 #include "nsClientAuthRemember.h"
+#include "prerror.h"
+
+class nsIPrompt;
+class SmartCardThreadList;
 
 namespace mozilla { namespace psm {
 
 class CertVerifier;
 
 } } // namespace mozilla::psm
 
 
@@ -49,65 +44,28 @@ class CertVerifier;
 //Define an interface that we can use to look up from the
 //callbacks passed to NSS.
 
 #define NS_INSSCOMPONENT_IID_STR "6ffbb526-205b-49c5-ae3f-5959c084075e"
 #define NS_INSSCOMPONENT_IID \
   { 0x6ffbb526, 0x205b, 0x49c5, \
     { 0xae, 0x3f, 0x59, 0x59, 0xc0, 0x84, 0x7, 0x5e } }
 
-#define NS_PSMCONTENTLISTEN_CID {0xc94f4a30, 0x64d7, 0x11d4, {0x99, 0x60, 0x00, 0xb0, 0xd0, 0x23, 0x54, 0xa0}}
-#define NS_PSMCONTENTLISTEN_CONTRACTID "@mozilla.org/security/psmdownload;1"
-
 enum EnsureNSSOperator
 {
   nssLoadingComponent = 0,
   nssInitSucceeded = 1,
   nssInitFailed = 2,
   nssShutdown = 3,
   nssEnsure = 100,
   nssEnsureOnChromeOnly = 101
 };
 
 extern bool EnsureNSSInitialized(EnsureNSSOperator op);
 
-//--------------------------------------------
-// Now we need a content listener to register 
-//--------------------------------------------
-class PSMContentDownloader : public nsIStreamListener
-{
-public:
-  PSMContentDownloader() {NS_ASSERTION(false, "don't use this constructor."); }
-  PSMContentDownloader(uint32_t type);
-  virtual ~PSMContentDownloader();
-  void setSilentDownload(bool flag);
-  void setCrlAutodownloadKey(nsAutoString key);
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIREQUESTOBSERVER
-  NS_DECL_NSISTREAMLISTENER
-
-  enum {UNKNOWN_TYPE = 0};
-  enum {X509_CA_CERT  = 1};
-  enum {X509_USER_CERT  = 2};
-  enum {X509_EMAIL_CERT  = 3};
-  enum {X509_SERVER_CERT  = 4};
-  enum {PKCS7_CRL = 5};
-
-protected:
-  char* mByteData;
-  int32_t mBufferOffset;
-  int32_t mBufferSize;
-  uint32_t mType;
-  bool mDoSilentDownload;
-  nsString mCrlAutoDownloadKey;
-  nsCOMPtr<nsIURI> mURI;
-  nsresult handleContentDownloadError(nsresult errCode);
-};
-
 class nsNSSComponent;
 
 class NS_NO_VTABLE nsINSSComponent : public nsISupports {
  public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_INSSCOMPONENT_IID)
 
   NS_IMETHOD ShowAlertFromStringBundle(const char * messageID) = 0;
 
@@ -128,22 +86,16 @@ class NS_NO_VTABLE nsINSSComponent : pub
   // This method will just disable OCSP in NSS, it will not
   // alter the respective pref values.
   NS_IMETHOD SkipOcsp() = 0;
 
   // This method will set the OCSP value according to the 
   // values in the preferences.
   NS_IMETHOD SkipOcspOff() = 0;
 
-  NS_IMETHOD RemoveCrlFromList(nsAutoString) = 0;
-
-  NS_IMETHOD DefineNextTimer() = 0;
-
-  NS_IMETHOD DownloadCRLDirectly(nsAutoString, nsAutoString) = 0;
-  
   NS_IMETHOD LogoutAuthenticatedPK11() = 0;
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   NS_IMETHOD LaunchSmartCardThread(SECMODModule *module) = 0;
 
   NS_IMETHOD ShutdownSmartCardThread(SECMODModule *module) = 0;
 
   NS_IMETHOD PostEvent(const nsAString &eventType, const nsAString &token) = 0;
@@ -166,32 +118,30 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsINSSComp
 class nsNSSShutDownList;
 class nsCertVerificationThread;
 
 // Implementation of the PSM component interface.
 class nsNSSComponent : public nsISignatureVerifier,
                        public nsIEntropyCollector,
                        public nsINSSComponent,
                        public nsIObserver,
-                       public nsSupportsWeakReference,
-                       public nsITimerCallback
+                       public nsSupportsWeakReference
 {
   typedef mozilla::Mutex Mutex;
 
 public:
   NS_DEFINE_STATIC_CID_ACCESSOR( NS_NSSCOMPONENT_CID )
 
   nsNSSComponent();
   virtual ~nsNSSComponent();
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISIGNATUREVERIFIER
   NS_DECL_NSIENTROPYCOLLECTOR
   NS_DECL_NSIOBSERVER
-  NS_DECL_NSITIMERCALLBACK
 
   NS_METHOD Init();
 
   static nsresult GetNewPrompter(nsIPrompt ** result);
   static nsresult ShowAlertWithConstructedString(const nsString & message);
   NS_IMETHOD ShowAlertFromStringBundle(const char * messageID);
 
   NS_IMETHOD GetPIPNSSBundleString(const char *name,
@@ -203,22 +153,17 @@ public:
   NS_IMETHOD GetNSSBundleString(const char *name,
                                nsAString &outString);
   NS_IMETHOD NSSBundleFormatStringFromName(const char *name,
                                            const PRUnichar **params,
                                            uint32_t numParams,
                                            nsAString &outString);
   NS_IMETHOD SkipOcsp();
   NS_IMETHOD SkipOcspOff();
-  nsresult InitializeCRLUpdateTimer();
-  nsresult StopCRLUpdateTimer();
-  NS_IMETHOD RemoveCrlFromList(nsAutoString);
-  NS_IMETHOD DefineNextTimer();
   NS_IMETHOD LogoutAuthenticatedPK11();
-  NS_IMETHOD DownloadCRLDirectly(nsAutoString, nsAutoString);
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   NS_IMETHOD LaunchSmartCardThread(SECMODModule *module);
   NS_IMETHOD ShutdownSmartCardThread(SECMODModule *module);
   NS_IMETHOD PostEvent(const nsAString &eventType, const nsAString &token);
   NS_IMETHOD DispatchEvent(const nsAString &eventType, const nsAString &token);
   void LaunchSmartCardThreads();
   void ShutdownSmartCardThreads();
@@ -239,45 +184,33 @@ private:
 
   void InstallLoadableRoots();
   void UnloadLoadableRoots();
   void CleanupIdentityInfo();
   void setValidationOptions(nsIPrefBranch * pref);
   nsresult setEnabledTLSVersions(nsIPrefBranch * pref);
   nsresult InitializePIPNSSBundle();
   nsresult ConfigureInternalPKCS11Token();
-  nsresult RegisterPSMContentListener();
   nsresult RegisterObservers();
   nsresult DeregisterObservers();
-  nsresult DownloadCrlSilently();
-  nsresult PostCRLImportEvent(const nsCSubstring &urlString, nsIStreamListener *psmDownloader);
-  nsresult getParamsForNextCrlToDownload(nsAutoString *url, PRTime *time, nsAutoString *key);
 
   // Methods that we use to handle the profile change notifications (and to
   // synthesize a full profile change when we're just doing a profile startup):
   void DoProfileChangeNetTeardown();
   void DoProfileChangeTeardown(nsISupports* aSubject);
   void DoProfileBeforeChange(nsISupports* aSubject);
   void DoProfileChangeNetRestore();
   
   Mutex mutex;
   
   nsCOMPtr<nsIStringBundle> mPIPNSSBundle;
   nsCOMPtr<nsIStringBundle> mNSSErrorsBundle;
-  nsCOMPtr<nsIURIContentListener> mPSMContentListener;
   nsCOMPtr<nsIPrefBranch> mPrefBranch;
-  nsCOMPtr<nsITimer> mTimer;
   bool mNSSInitialized;
   bool mObserversRegistered;
-  nsAutoString mDownloadURL;
-  nsAutoString mCrlUpdateKey;
-  Mutex mCrlTimerLock;
-  nsHashtable *crlsScheduledForDownload;
-  bool crlDownloadTimerOn;
-  bool mUpdateTimerInitialized;
   static int mInstanceCount;
   nsNSSShutDownList *mShutdownObjectList;
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   SmartCardThreadList *mThreadList;
 #endif
   bool mIsNetworkDown;
 
   void deleteBackgroundThreads();
@@ -290,30 +223,16 @@ private:
 
   static PRStatus IdentityInfoInit(void);
   PRCallOnceType mIdentityInfoCallOnce;
 
 public:
   static bool globalConstFlagUsePKIXVerification;
 };
 
-class PSMContentListener : public nsIURIContentListener,
-                            public nsSupportsWeakReference {
-public:
-  PSMContentListener();
-  virtual ~PSMContentListener();
-  nsresult init();
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIURICONTENTLISTENER
-private:
-  nsCOMPtr<nsISupports> mLoadCookie;
-  nsCOMPtr<nsIURIContentListener> mParentContentListener;
-};
-
 class nsNSSErrors
 {
 public:
   static const char *getDefaultErrorStringName(PRErrorCode err);
   static const char *getOverrideErrorStringName(PRErrorCode aErrorCode);
   static nsresult getErrorMessageFromCode(PRErrorCode err,
                                           nsINSSComponent *component,
                                           nsString &returnedMessage);
--- a/security/manager/ssl/src/nsNSSIOLayer.cpp
+++ b/security/manager/ssl/src/nsNSSIOLayer.cpp
@@ -11,16 +11,17 @@
 
 #include "prlog.h"
 #include "prnetdb.h"
 #include "nsIPrefService.h"
 #include "nsIClientAuthDialogs.h"
 #include "nsClientAuthRemember.h"
 #include "nsISSLErrorListener.h"
 
+#include "nsNetUtil.h"
 #include "nsPrintfCString.h"
 #include "SSLServerCertVerification.h"
 #include "nsNSSCertHelper.h"
 #include "nsNSSCleaner.h"
 
 #ifndef NSS_NO_LIBPKIX
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
--- a/security/manager/ssl/src/nsNSSModule.cpp
+++ b/security/manager/ssl/src/nsNSSModule.cpp
@@ -22,34 +22,36 @@
 #include "nsCMS.h"
 #ifdef MOZ_XUL
 #include "nsCertTree.h"
 #endif
 #include "nsCrypto.h"
 #include "nsCryptoHash.h"
 //For the NS_CRYPTO_CONTRACTID define
 #include "nsDOMCID.h"
-
+#include "nsNetCID.h"
 #include "nsCMSSecureMessage.h"
 #include "nsCertPicker.h"
 #include "nsCURILoader.h"
 #include "nsICategoryManager.h"
-#include "nsCRLManager.h"
 #include "nsNTLMAuthModule.h"
 #include "nsStreamCipher.h"
 #include "nsKeyModule.h"
 #include "nsDataSignatureVerifier.h"
 #include "nsCertOverrideService.h"
 #include "nsRandomGenerator.h"
 #include "nsSSLStatus.h"
 #include "TransportSecurityInfo.h"
 #include "NSSErrorsService.h"
 #include "nsNSSVersion.h"
 
 #include "nsXULAppAPI.h"
+
+#include "PSMContentListener.h"
+
 #define NS_IS_PROCESS_DEFAULT                                                 \
     (GeckoProcessType_Default == XRE_GetProcessType())
 
 #define NS_NSS_INSTANTIATE(ensureOperator, _InstanceClass)                    \
     PR_BEGIN_MACRO                                                            \
         _InstanceClass * inst;                                                \
         inst = new _InstanceClass();                                          \
         NS_ADDREF(inst);                                                      \
@@ -191,17 +193,16 @@ NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEn
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCrypto)
 #endif
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsPkcs11)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCMSSecureMessage)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCMSDecoder)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCMSEncoder)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCMSMessage)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCertPicker)
-NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCRLManager)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nssEnsure, nsNTLMAuthModule, InitTest)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCryptoHash)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsCryptoHMAC)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsStreamCipher)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsKeyObject)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsKeyObjectFactory)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR(nssEnsure, nsDataSignatureVerifier)
 NS_NSS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nssEnsure, nsCertOverrideService, Init)
@@ -233,17 +234,16 @@ NS_DEFINE_NAMED_CID(NS_CRYPTO_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_CMSSECUREMESSAGE_CID);
 NS_DEFINE_NAMED_CID(NS_CMSDECODER_CID);
 NS_DEFINE_NAMED_CID(NS_CMSENCODER_CID);
 NS_DEFINE_NAMED_CID(NS_CMSMESSAGE_CID);
 NS_DEFINE_NAMED_CID(NS_CRYPTO_HASH_CID);
 NS_DEFINE_NAMED_CID(NS_CRYPTO_HMAC_CID);
 NS_DEFINE_NAMED_CID(NS_CERT_PICKER_CID);
-NS_DEFINE_NAMED_CID(NS_CRLMANAGER_CID);
 NS_DEFINE_NAMED_CID(NS_NTLMAUTHMODULE_CID);
 NS_DEFINE_NAMED_CID(NS_STREAMCIPHER_CID);
 NS_DEFINE_NAMED_CID(NS_KEYMODULEOBJECT_CID);
 NS_DEFINE_NAMED_CID(NS_KEYMODULEOBJECTFACTORY_CID);
 NS_DEFINE_NAMED_CID(NS_DATASIGNATUREVERIFIER_CID);
 NS_DEFINE_NAMED_CID(NS_CERTOVERRIDE_CID);
 NS_DEFINE_NAMED_CID(NS_RANDOMGENERATOR_CID);
 NS_DEFINE_NAMED_CID(NS_SSLSTATUS_CID);
@@ -272,17 +272,16 @@ static const mozilla::Module::CIDEntry k
 #endif
   { &kNS_CMSSECUREMESSAGE_CID, false, nullptr, nsCMSSecureMessageConstructor },
   { &kNS_CMSDECODER_CID, false, nullptr, nsCMSDecoderConstructor },
   { &kNS_CMSENCODER_CID, false, nullptr, nsCMSEncoderConstructor },
   { &kNS_CMSMESSAGE_CID, false, nullptr, nsCMSMessageConstructor },
   { &kNS_CRYPTO_HASH_CID, false, nullptr, nsCryptoHashConstructor },
   { &kNS_CRYPTO_HMAC_CID, false, nullptr, nsCryptoHMACConstructor },
   { &kNS_CERT_PICKER_CID, false, nullptr, nsCertPickerConstructor },
-  { &kNS_CRLMANAGER_CID, false, nullptr, nsCRLManagerConstructor },
   { &kNS_NTLMAUTHMODULE_CID, false, nullptr, nsNTLMAuthModuleConstructor },
   { &kNS_STREAMCIPHER_CID, false, nullptr, nsStreamCipherConstructor },
   { &kNS_KEYMODULEOBJECT_CID, false, nullptr, nsKeyObjectConstructor },
   { &kNS_KEYMODULEOBJECTFACTORY_CID, false, nullptr, nsKeyObjectFactoryConstructor },
   { &kNS_DATASIGNATUREVERIFIER_CID, false, nullptr, nsDataSignatureVerifierConstructor },
   { &kNS_CERTOVERRIDE_CID, false, nullptr, nsCertOverrideServiceConstructor },
   { &kNS_RANDOMGENERATOR_CID, false, nullptr, nsRandomGeneratorConstructor },
   { &kNS_SSLSTATUS_CID, false, nullptr, nsSSLStatusConstructor },
@@ -315,36 +314,32 @@ static const mozilla::Module::ContractID
   { NS_CMSSECUREMESSAGE_CONTRACTID, &kNS_CMSSECUREMESSAGE_CID },
   { NS_CMSDECODER_CONTRACTID, &kNS_CMSDECODER_CID },
   { NS_CMSENCODER_CONTRACTID, &kNS_CMSENCODER_CID },
   { NS_CMSMESSAGE_CONTRACTID, &kNS_CMSMESSAGE_CID },
   { NS_CRYPTO_HASH_CONTRACTID, &kNS_CRYPTO_HASH_CID },
   { NS_CRYPTO_HMAC_CONTRACTID, &kNS_CRYPTO_HMAC_CID },
   { NS_CERT_PICKER_CONTRACTID, &kNS_CERT_PICKER_CID },
   { "@mozilla.org/uriloader/psm-external-content-listener;1", &kNS_PSMCONTENTLISTEN_CID },
-  { NS_CRLMANAGER_CONTRACTID, &kNS_CRLMANAGER_CID },
   { NS_CRYPTO_FIPSINFO_SERVICE_CONTRACTID, &kNS_PKCS11MODULEDB_CID },
   { NS_NTLMAUTHMODULE_CONTRACTID, &kNS_NTLMAUTHMODULE_CID },
   { NS_STREAMCIPHER_CONTRACTID, &kNS_STREAMCIPHER_CID },
   { NS_KEYMODULEOBJECT_CONTRACTID, &kNS_KEYMODULEOBJECT_CID },
   { NS_KEYMODULEOBJECTFACTORY_CONTRACTID, &kNS_KEYMODULEOBJECTFACTORY_CID },
   { NS_DATASIGNATUREVERIFIER_CONTRACTID, &kNS_DATASIGNATUREVERIFIER_CID },
   { NS_CERTOVERRIDE_CONTRACTID, &kNS_CERTOVERRIDE_CID },
   { NS_RANDOMGENERATOR_CONTRACTID, &kNS_RANDOMGENERATOR_CID },
   { nullptr }
 };
 
 static const mozilla::Module::CategoryEntry kNSSCategories[] = {
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-ca-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-server-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-user-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-email-cert", "@mozilla.org/uriloader/psm-external-content-listener;1" },
-  { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-pkcs7-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
-  { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/x-x509-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
-  { NS_CONTENT_LISTENER_CATEGORYMANAGER_ENTRY, "application/pkix-crl", "@mozilla.org/uriloader/psm-external-content-listener;1" },
   { nullptr }
 };
 
 static const mozilla::Module kNSSModule = {
   mozilla::Module::kVersion,
   kNSSCIDs,
   kNSSContracts,
   kNSSCategories
--- a/security/manager/ssl/src/nsPK11TokenDB.cpp
+++ b/security/manager/ssl/src/nsPK11TokenDB.cpp
@@ -5,16 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "nsISupports.h"
 #include "nsISupportsArray.h"
 #include "nsIPK11TokenDB.h"
 #include "prerror.h"
 #include "secerr.h"
 #include "nsReadableUtils.h"
 #include "nsNSSComponent.h"
+#include "nsServiceManagerUtils.h"
 
 #include "nsPK11TokenDB.h"
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
 static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
--- a/security/manager/ssl/src/nsSDR.cpp
+++ b/security/manager/ssl/src/nsSDR.cpp
@@ -3,26 +3,28 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "stdlib.h"
 #include "plstr.h"
 #include "plbase64.h"
 
+#include "mozilla/Services.h"
 #include "nsMemory.h"
 #include "nsString.h"
 #include "nsCOMPtr.h"
 #include "nsThreadUtils.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIServiceManager.h"
 #include "nsITokenPasswordDialogs.h"
 
 #include "nsISecretDecoderRing.h"
+#include "nsCRT.h"
 #include "nsSDR.h"
 #include "nsNSSComponent.h"
 #include "nsNSSShutDown.h"
 #include "ScopedNSSTypes.h"
 
 #include "pk11func.h"
 #include "pk11sdr.h" // For PK11SDR_Encrypt, PK11SDR_Decrypt
 
--- a/security/manager/ssl/src/nsSmartCardMonitor.cpp
+++ b/security/manager/ssl/src/nsSmartCardMonitor.cpp
@@ -2,16 +2,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #include "nspr.h"
 
 #include "pk11func.h"
 #include "nsNSSComponent.h"
 #include "nsSmartCardMonitor.h"
 #include "nsIDOMSmartCardEvent.h"
+#include "nsServiceManagerUtils.h"
 #include "mozilla/unused.h"
 
 using namespace mozilla;
 
 //
 // The SmartCard monitoring thread should start up for each module we load
 // that has removable tokens. This code calls an NSS function which waits
 // until there is a change in the token state. NSS uses the 
--- a/security/manager/ssl/src/nsUsageArrayHelper.cpp
+++ b/security/manager/ssl/src/nsUsageArrayHelper.cpp
@@ -6,16 +6,17 @@
 
 #include "mozilla/Assertions.h"
 #include "nsCOMPtr.h"
 #include "nsIDateTimeFormat.h"
 #include "nsDateTimeFormatCID.h"
 #include "nsComponentManagerUtils.h"
 #include "nsReadableUtils.h"
 #include "nsNSSCertificate.h"
+#include "nsServiceManagerUtils.h"
 
 #include "nspr.h"
 #include "secerr.h"
 
 using namespace mozilla;
 using namespace mozilla::psm;
 
 #ifdef PR_LOGGING
--- a/toolkit/locales/en-US/chrome/mozapps/update/updates.dtd
+++ b/toolkit/locales/en-US/chrome/mozapps/update/updates.dtd
@@ -20,16 +20,22 @@
 <!ENTITY  manualUpdate.desc               "A recommended security and stability update is available, but you do
                                            not have the system permissions required to install it. Please contact your
                                            system administrator, or try again from an account that has permission to
                                            install software on this computer.">
 <!ENTITY  manualUpdate.space.desc         "A recommended security and stability update is available, but you do
                                            not have enough space to install it.">
 <!ENTITY  manualUpdateGetMsg.label        "You can always get the latest version of &brandShortName; at:">
 
+<!ENTITY  unsupported.title               "System Unsupported">
+<!ENTITY  unsupported.label               "Your &brandShortName; is out of date, but the latest version is not
+                                           supported on your system. Please upgrade your system, then try again.
+                                           You will not see this notice again, but you can">
+<!ENTITY  unsupportedLink.label           "learn more.">
+
 <!ENTITY  incompatibleCheck.title         "Checking Add-on Compatibility">
 <!ENTITY  incompatibleCheck.label         "Looking for newer versions of your add-ons…">
 
 <!ENTITY  clickHere.label                 "View more information about this update">
 
 <!ENTITY  evangelism.desc                 "It is strongly recommended that you apply this 
                                            update for &brandShortName; as soon as possible.">
 
--- a/toolkit/mozapps/update/content/updates.js
+++ b/toolkit/mozapps/update/content/updates.js
@@ -8,29 +8,30 @@ Components.utils.import("resource://gre/
 Components.utils.import("resource://gre/modules/Services.jsm");
 
 // Firefox's macBrowserOverlay.xul includes scripts that define Cc, Ci, and Cr
 // so we have to use different names.
 const CoC = Components.classes;
 const CoI = Components.interfaces;
 const CoR = Components.results;
 
-const XMLNS_XUL               = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+const XMLNS_XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 
-const PREF_APP_UPDATE_BACKGROUNDERRORS   = "app.update.backgroundErrors";
-const PREF_APP_UPDATE_BILLBOARD_TEST_URL = "app.update.billboard.test_url";
-const PREF_APP_UPDATE_CERT_ERRORS        = "app.update.cert.errors";
-const PREF_APP_UPDATE_ENABLED            = "app.update.enabled";
-const PREF_APP_UPDATE_LOG                = "app.update.log";
-const PREF_APP_UPDATE_MANUAL_URL         = "app.update.url.manual";
-const PREF_APP_UPDATE_NEVER_BRANCH       = "app.update.never.";
-const PREF_APP_UPDATE_TEST_LOOP          = "app.update.test.loop";
-const PREF_PLUGINS_UPDATEURL             = "plugins.update.url";
+const PREF_APP_UPDATE_BACKGROUNDERRORS    = "app.update.backgroundErrors";
+const PREF_APP_UPDATE_BILLBOARD_TEST_URL  = "app.update.billboard.test_url";
+const PREF_APP_UPDATE_CERT_ERRORS         = "app.update.cert.errors";
+const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
+const PREF_APP_UPDATE_LOG                 = "app.update.log";
+const PREF_APP_UPDATE_MANUAL_URL          = "app.update.url.manual";
+const PREF_APP_UPDATE_NEVER_BRANCH        = "app.update.never.";
+const PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED = "app.update.notifiedUnsupported";
+const PREF_APP_UPDATE_TEST_LOOP           = "app.update.test.loop";
+const PREF_PLUGINS_UPDATEURL              = "plugins.update.url";
 
-const PREF_EM_HOTFIX_ID                  = "extensions.hotfix.id";
+const PREF_EM_HOTFIX_ID                   = "extensions.hotfix.id";
 
 const UPDATE_TEST_LOOP_INTERVAL     = 2000;
 
 const URI_UPDATES_PROPERTIES  = "chrome://mozapps/locale/update/updates.properties";
 
 const STATE_DOWNLOADING       = "downloading";
 const STATE_PENDING           = "pending";
 const STATE_PENDING_SVC       = "pending-service";
@@ -377,16 +378,21 @@ var gUpdates = {
         this.setUpdate(arg0);
         if (this.update.errorCode == CERT_ATTR_CHECK_FAILED_NO_UPDATE ||
             this.update.errorCode == CERT_ATTR_CHECK_FAILED_HAS_UPDATE ||
             this.update.errorCode == BACKGROUNDCHECK_MULTIPLE_FAILURES) {
           aCallback("errorextra");
           return;
         }
 
+        if (this.update.unsupported) {
+          aCallback("unsupported");
+          return;
+        }
+
         var p = this.update.selectedPatch;
         if (p) {
           var state = p.state;
           var patchFailed;
           try {
             patchFailed = this.update.getProperty("patchingFailed");
           }
           catch (e) {
@@ -589,16 +595,21 @@ var gCheckingPage = {
     // notifications will never happen.
     Services.prefs.deleteBranch(PREF_APP_UPDATE_NEVER_BRANCH);
 
     // The user will be notified if there is an error so clear the background
     // check error count.
     if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_BACKGROUNDERRORS))
       Services.prefs.clearUserPref(PREF_APP_UPDATE_BACKGROUNDERRORS);
 
+    // The preference will be set back to true if the system is still
+    // unsupported.
+    if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED))
+      Services.prefs.clearUserPref(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED);
+
     this._checker = CoC["@mozilla.org/updates/update-checker;1"].
                     createInstance(CoI.nsIUpdateChecker);
     this._checker.checkForUpdates(this.updateListener, true);
   },
 
   /**
    * The user has closed the window, either by pressing cancel or using a Window
    * Manager control, so stop checking for updates.
@@ -616,16 +627,21 @@ var gCheckingPage = {
      * See nsIUpdateCheckListener
      */
     onCheckComplete: function(request, updates, updateCount) {
       var aus = CoC["@mozilla.org/updates/update-service;1"].
                 getService(CoI.nsIApplicationUpdateService);
       gUpdates.setUpdate(aus.selectUpdate(updates, updates.length));
       if (gUpdates.update) {
         LOG("gCheckingPage", "onCheckComplete - update found");
+        if (gUpdates.update.unsupported) {
+          gUpdates.wiz.goTo("unsupported");
+          return;
+        }
+
         if (!aus.canApplyUpdates) {
           // Prevent multiple notifications for the same update when the user is
           // unable to apply updates.
           gUpdates.never();
           gUpdates.wiz.goTo("manualUpdate");
           return;
         }
 
@@ -864,16 +880,33 @@ var gManualUpdatePage = {
     manualUpdateLinkLabel.setAttribute("url", manualURL);
 
     gUpdates.setButtons(null, null, "okButton", true);
     gUpdates.wiz.getButton("finish").focus();
   }
 };
 
 /**
+ * The "System Unsupported" page. Provides the user with information about their
+ * system no longer being supported and an url for more information.
+ */
+var gUnsupportedPage = {
+  onPageShow: function() {
+    Services.prefs.setBoolPref(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED, true);
+    if (gUpdates.update.detailsURL) {
+      let unsupportedLinkLabel = document.getElementById("unsupportedLinkLabel");
+      unsupportedLinkLabel.setAttribute("url", gUpdates.update.detailsURL);
+    }
+
+    gUpdates.setButtons(null, null, "okButton", true);
+    gUpdates.wiz.getButton("finish").focus();
+  }
+};
+
+/**
  * The "Updates Are Available" page. Provides the user information about the
  * available update.
  */
 var gUpdatesFoundBasicPage = {
   /**
    * Initialize
    */
   onPageShow: function() {
--- a/toolkit/mozapps/update/content/updates.xul
+++ b/toolkit/mozapps/update/content/updates.xul
@@ -77,16 +77,29 @@
       <label>&manualUpdateGetMsg.label;</label>
       <hbox>
         <label class="text-link" id="manualUpdateLinkLabel" value=""
                onclick="openUpdateURL(event);"/>
       </hbox>
     </vbox>
   </wizardpage>
 
+  <wizardpage id="unsupported" pageid="unsupported"
+              object="gUnsupportedPage"
+              onpageshow="gUnsupportedPage.onPageShow();">
+    <updateheader label="&unsupported.title;"/>
+    <vbox class="update-content" flex="1">
+      <description flex="1">&unsupported.label;
+        <label id="unsupportedLinkLabel" class="text-link inline-link" onclick="openUpdateURL(event);">
+          &unsupportedLink.label;
+        </label>
+      </description>
+    </vbox>
+  </wizardpage>
+
   <wizardpage id="incompatibleCheck" pageid="incompatibleCheck"
               next="updatesfoundbasic" object="gIncompatibleCheckPage"
               onpageshow="gIncompatibleCheckPage.onPageShow();">
     <updateheader label="&incompatibleCheck.title;"/>
     <vbox class="update-content" flex="1">
       <label>&incompatibleCheck.label;</label>
       <separator class="thin"/>
       <progressmeter id="incompatibleCheckProgress" mode="undetermined"/>
--- a/toolkit/mozapps/update/nsIUpdateService.idl
+++ b/toolkit/mozapps/update/nsIUpdateService.idl
@@ -82,17 +82,17 @@ interface nsIUpdatePatch : nsISupports
  * the current application - this update may have several available patches
  * from which one must be selected to download and install, for example we
  * might select a binary difference patch first and attempt to apply that,
  * then if the application process fails fall back to downloading a complete
  * file-replace patch. This object also contains information about the update
  * that the front end and other application services can use to learn more
  * about what is going on.
  */
-[scriptable, uuid(8f7185a7-056a-45a8-985c-1cb39cf7b7a8)]
+[scriptable, uuid(6b0b7721-6746-443d-8cb0-c6199d7f28a6)]
 interface nsIUpdate : nsISupports
 {
   /**
    * The type of update:
    *   "major"  A major new version of the Application
    *   "minor"  A minor update to the Application (e.g. security update)
    */
   attribute AString type;
@@ -173,20 +173,19 @@ interface nsIUpdate : nsISupports
   /**
    * Whether to show the "No Thanks" button in the update prompt. This allows
    * the user to never receive a notification for that specific update version
    * again.
    */
   attribute boolean showNeverForVersion;
 
   /**
-   * Whether to show the survey link in the update prompt. The url must also be
-   * present in the app.update.surveyURL preference.
+   * Whether the update is no longer supported on this system.
    */
-  attribute boolean showSurvey;
+  attribute boolean unsupported;
   
   /**
    * Allows overriding the default amount of time in seconds before prompting the
    * user to apply an update. If not specified, the value of
    * app.update.promptWaitTime will be used.
    */
   attribute long long promptWaitTime;
 
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -39,16 +39,17 @@ const PREF_APP_UPDATE_INTERVAL          
 const PREF_APP_UPDATE_LOG                 = "app.update.log";
 const PREF_APP_UPDATE_MODE                = "app.update.mode";
 const PREF_APP_UPDATE_NEVER_BRANCH        = "app.update.never.";
 const PREF_APP_UPDATE_POSTUPDATE          = "app.update.postupdate";
 const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
 const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
 const PREF_APP_UPDATE_SILENT              = "app.update.silent";
 const PREF_APP_UPDATE_STAGING_ENABLED     = "app.update.staging.enabled";
+const PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED = "app.update.notifiedUnsupported";
 const PREF_APP_UPDATE_URL                 = "app.update.url";
 const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
 const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
 const PREF_APP_UPDATE_SERVICE_ENABLED     = "app.update.service.enabled";
 const PREF_APP_UPDATE_SERVICE_ERRORS      = "app.update.service.errors";
 const PREF_APP_UPDATE_SERVICE_MAX_ERRORS  = "app.update.service.maxErrors";
 const PREF_APP_UPDATE_SOCKET_ERRORS       = "app.update.socket.maxErrors";
 const PREF_APP_UPDATE_RETRY_TIMEOUT       = "app.update.socket.retryTimeout";
@@ -176,16 +177,17 @@ const DEFAULT_SERVICE_MAX_ERRORS = 10;
 // The number of consecutive socket errors to allow before falling back to
 // downloading a different MAR file or failing if already downloading the full.
 const DEFAULT_SOCKET_MAX_ERRORS = 10;
 
 // The number of milliseconds to wait before retrying a connection error.
 const DEFAULT_UPDATE_RETRY_TIMEOUT = 2000;
 
 var gLocale     = null;
+
 #ifdef MOZ_B2G
 var gVolumeMountLock = null;
 XPCOMUtils.defineLazyGetter(this, "gExtStorage", function aus_gExtStorage() {
     return Services.env.get("EXTERNAL_STORAGE");
 });
 
 var gSDCardMountLock = null;
 #endif
@@ -1555,18 +1557,18 @@ UpdatePatch.prototype = {
  * @constructor
  */
 function Update(update) {
   this._properties = {};
   this._patches = [];
   this.isCompleteUpdate = false;
   this.isOSUpdate = false;
   this.showPrompt = false;
-  this.showSurvey = false;
   this.showNeverForVersion = false;
+  this.unsupported = false;
   this.channel = "default";
   this.promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);
 
   // Null <update>, assume this is a message container and do no
   // further initialization
   if (!update)
     return;
 
@@ -1581,17 +1583,17 @@ function Update(update) {
     try {
       var patch = new UpdatePatch(patchElement);
     } catch (e) {
       continue;
     }
     this._patches.push(patch);
   }
 
-  if (0 == this._patches.length)
+  if (this._patches.length == 0 && !update.hasAttribute("unsupported"))
     throw Cr.NS_ERROR_ILLEGAL_VALUE;
 
   // Fallback to the behavior prior to bug 530872 if the update does not have an
   // appVersion attribute.
   if (!update.hasAttribute("appVersion")) {
     if (update.getAttribute("type") == "major") {
       if (update.hasAttribute("detailsURL")) {
         this.billboardURL = update.getAttribute("detailsURL");
@@ -1626,18 +1628,18 @@ function Update(update) {
       this.showNeverForVersion = attr.value == "true";
     else if (attr.name == "showPrompt")
       this.showPrompt = attr.value == "true";
     else if (attr.name == "promptWaitTime")
     {
       if(!isNaN(attr.value))
         this.promptWaitTime = parseInt(attr.value);
     }
-    else if (attr.name == "showSurvey")
-      this.showSurvey = attr.value == "true";
+    else if (attr.name == "unsupported")
+      this.unsupported = attr.value == "true";
     else if (attr.name == "version") {
       // Prevent version from replacing displayVersion if displayVersion is
       // present in the update xml.
       if (!this.displayVersion)
         this.displayVersion = attr.value;
     }
     else {
       this[attr.name] = attr.value;
@@ -1766,17 +1768,16 @@ Update.prototype = {
     update.setAttribute("installDate", this.installDate);
     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
     update.setAttribute("isOSUpdate", this.isOSUpdate);
     update.setAttribute("name", this.name);
     update.setAttribute("serviceURL", this.serviceURL);
     update.setAttribute("showNeverForVersion", this.showNeverForVersion);
     update.setAttribute("showPrompt", this.showPrompt);
     update.setAttribute("promptWaitTime", this.promptWaitTime);
-    update.setAttribute("showSurvey", this.showSurvey);
     update.setAttribute("type", this.type);
     // for backwards compatibility in case the user downgrades
     update.setAttribute("version", this.displayVersion);
 
     // Optional attributes
     if (this.billboardURL)
       update.setAttribute("billboardURL", this.billboardURL);
     if (this.detailsURL)
@@ -1784,16 +1785,18 @@ Update.prototype = {
     if (this.licenseURL)
       update.setAttribute("licenseURL", this.licenseURL);
     if (this.platformVersion)
       update.setAttribute("platformVersion", this.platformVersion);
     if (this.previousAppVersion)
       update.setAttribute("previousAppVersion", this.previousAppVersion);
     if (this.statusText)
       update.setAttribute("statusText", this.statusText);
+    if (this.unsupported)
+      update.setAttribute("unsupported", this.unsupported);
     updates.documentElement.appendChild(update);
 
     for (var p in this._properties) {
       if (this._properties[p].present)
         update.setAttribute(p, this._properties[p].data);
     }
 
     for (var i = 0; i < this.patchCount; ++i)
@@ -2371,16 +2374,19 @@ UpdateService.prototype = {
    * @param   updates
    *          An array of available nsIUpdate items
    * @return  The nsIUpdate to offer.
    */
   selectUpdate: function AUS_selectUpdate(updates) {
     if (updates.length == 0)
       return null;
 
+    if (updates.length == 1 && updates[0].unsupported)
+      return updates[0];
+
     // Choose the newest of the available minor and major updates.
     var majorUpdate = null;
     var minorUpdate = null;
     var vc = Services.vc;
 
     updates.forEach(function(aUpdate) {
       // Ignore updates for older versions of the application and updates for
       // the same version of the application with the same build ID.
@@ -2448,31 +2454,43 @@ UpdateService.prototype = {
 #ifdef MOZ_WIDGET_GONK
       // For gonk, the user isn't necessarily aware of the update, so we need
       // to show the prompt to make sure.
       this._showPrompt(um.activeUpdate);
 #endif
       return;
     }
 
-    var update = this.selectUpdate(updates, updates.length);
-    if (!update)
-      return;
-
     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
     if (!updateEnabled) {
       LOG("UpdateService:_selectAndInstallUpdate - not prompting because " +
           "update is disabled");
       return;
     }
 
     if (!gMetroUpdatesEnabled) {
       return;
     }
 
+    var update = this.selectUpdate(updates, updates.length);
+    if (!update) {
+      return;
+    }
+
+    if (update.unsupported) {
+      LOG("UpdateService:_selectAndInstallUpdate - update not supported for " +
+          "this system");
+      if (!getPref("getBoolPref", PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED, false)) {
+        LOG("UpdateService:_selectAndInstallUpdate - notifying that the " +
+            "update is not supported for this system");
+        this._showPrompt(update);
+      }
+      return;
+    }
+
     if (!gCanApplyUpdates) {
       LOG("UpdateService:_selectAndInstallUpdate - the user is unable to " +
           "apply updates... prompting");
       this._showPrompt(update);
       return;
     }
 
     /**
@@ -3296,34 +3314,34 @@ Checker.prototype = {
   get _updates() {
     var updatesElement = this._request.responseXML.documentElement;
     if (!updatesElement) {
       LOG("Checker:_updates get - empty updates document?!");
       return [];
     }
 
     if (updatesElement.nodeName != "updates") {
-      LOG("Checker:updates get - unexpected node name!");
+      LOG("Checker:_updates get - unexpected node name!");
       throw new Error("Unexpected node name, expected: updates, got: " +
                       updatesElement.nodeName);
     }
 
     const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
     var updates = [];
     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
       var updateElement = updatesElement.childNodes.item(i);
       if (updateElement.nodeType != ELEMENT_NODE ||
           updateElement.localName != "update")
         continue;
 
       updateElement.QueryInterface(Ci.nsIDOMElement);
       try {
         var update = new Update(updateElement);
       } catch (e) {
-        LOG("Checker:updates get - invalid <update/>, ignoring...");
+        LOG("Checker:_updates get - invalid <update/>, ignoring...");
         continue;
       }
       update.serviceURL = this.getUpdateURL(this._forced);
       update.channel = UpdateChannel.get();
       updates.push(update);
     }
 
     return updates;
@@ -3373,17 +3391,17 @@ Checker.prototype = {
       gCertUtils.checkCert(this._request.channel, allowNonBuiltIn, certs);
 
       if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_CERT_ERRORS))
         Services.prefs.clearUserPref(PREF_APP_UPDATE_CERT_ERRORS);
 
       if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_BACKGROUNDERRORS))
         Services.prefs.clearUserPref(PREF_APP_UPDATE_BACKGROUNDERRORS);
 
-      // Tell the Update Service about the updates
+      // Tell the callback about the updates
       this._callback.onCheckComplete(event.target, updates, updates.length);
     }
     catch (e) {
       LOG("Checker:onLoad - there was a problem checking for updates. " +
           "Exception: " + e);
       var request = event.target;
       var status = this._getChannelStatus(request);
       LOG("Checker:onLoad - request.status: " + status);
--- a/toolkit/mozapps/update/nsUpdateTimerManager.js
+++ b/toolkit/mozapps/update/nsUpdateTimerManager.js
@@ -77,18 +77,18 @@ TimerManager.prototype = {
    * The set of registered timers.
    */
   _timers: { },
 
   /**
    * See nsIObserver.idl
    */
   observe: function TM_observe(aSubject, aTopic, aData) {
-    // Prevent setting the timer interval to a value of less than 60 seconds.
-    var minInterval = 60000;
+    // Prevent setting the timer interval to a value of less than 30 seconds.
+    var minInterval = 30000;
     // Prevent setting the first timer interval to a value of less than 10
     // seconds.
     var minFirstInterval = 10000;
     switch (aTopic) {
     case "utm-test-init":
       // Enforce a minimum timer interval of 500 ms for tests and fall through
       // to profile-after-change to initialize the timer.
       minInterval = 500;
--- a/toolkit/mozapps/update/test/chrome/Makefile.in
+++ b/toolkit/mozapps/update/test/chrome/Makefile.in
@@ -76,16 +76,18 @@ MOCHITEST_CHROME_FILES += \
   test_0121_check_requireBuiltinCert.xul \
   test_0122_check_allowNonBuiltinCert_validCertAttrs.xul \
   test_0123_check_allowNonBuiltinCert_noCertAttrsCheck.xul \
   test_0131_check_invalidCertAttrs_noUpdate.xul \
   test_0132_check_invalidCertAttrs_hasUpdate.xul \
   test_0141_notify_invalidCertAttrs_noUpdate.xul \
   test_0142_notify_invalidCertAttrs_hasUpdate.xul \
   test_0151_notify_backgroundCheckError.xul \
+  test_0161_check_unsupported.xul \
+  test_0162_notify_unsupported.xul \
   test_0900_deprecatedUpdateFormat_minor.xul \
   test_0901_deprecatedUpdateFormat_major.xul \
   test_9999_cleanup.xul \
   $(NULL)
 
 
 include $(topsrcdir)/config/rules.mk
 
new file mode 100644
--- /dev/null
+++ b/toolkit/mozapps/update/test/chrome/test_0161_check_unsupported.xul
@@ -0,0 +1,50 @@
+<?xml version="1.0"?>
+<!--
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+-->
+
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
+
+<window title="Test checking for updates when system is no longer supported (bug 843497)"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        onload="runTestDefault();">
+<script type="application/javascript"
+        src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+<script type="application/javascript"
+        src="utils.js"/>
+
+<script type="application/javascript">
+<![CDATA[
+
+const TESTS = [ {
+  pageid: PAGEID_CHECKING
+}, {
+  pageid: PAGEID_UNSUPPORTED,
+  buttonClick: "finish"
+} ];
+
+function runTest() {
+  debugDump("entering");
+
+  // When checking manually the unsupported page should still be shown even if
+  // it was shown previously.
+  Services.prefs.setBoolPref(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED, true);
+
+  let url = URL_UPDATE + "?unsupported=1";
+  setUpdateURLOverride(url);
+
+  gUP.checkForUpdates();
+}
+
+]]>
+</script>
+
+<body xmlns="http://www.w3.org/1999/xhtml">
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test"></pre>
+</body>
+</window>
new file mode 100644
--- /dev/null
+++ b/toolkit/mozapps/update/test/chrome/test_0162_notify_unsupported.xul
@@ -0,0 +1,44 @@
+<?xml version="1.0"?>
+<!--
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+-->
+
+<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
+<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
+
+<window title="Test notification of updates when system is no longer supported (bug 843497)"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        onload="runTestDefault();">
+<script type="application/javascript"
+        src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+<script type="application/javascript"
+        src="utils.js"/>
+
+<script type="application/javascript">
+<![CDATA[
+
+const TESTS = [ {
+  pageid: PAGEID_UNSUPPORTED,
+  buttonClick: "finish"
+} ];
+
+function runTest() {
+  debugDump("entering");
+
+  let url = URL_UPDATE + "?unsupported=1";
+  setUpdateURLOverride(url);
+
+  gAUS.notify(null);
+}
+
+]]>
+</script>
+
+<body xmlns="http://www.w3.org/1999/xhtml">
+  <p id="display"></p>
+  <div id="content" style="display: none"></div>
+  <pre id="test"></pre>
+</body>
+</window>
--- a/toolkit/mozapps/update/test/chrome/update.sjs
+++ b/toolkit/mozapps/update/test/chrome/update.sjs
@@ -82,16 +82,24 @@ function handleRequest(aRequest, aRespon
     return;
   }
 
   if (params.noUpdates) {
     aResponse.write(getRemoteUpdatesXMLString(""));
     return;
   }
 
+  if (params.unsupported) {
+    aResponse.write(getRemoteUpdatesXMLString("  <update type=\"major\" " +
+                                              "unsupported=\"true\" " +
+                                              "detailsURL=\"" + URL_HOST +
+                                              "\"></update>\n"));
+    return;
+  }
+
   var hash;
   var patches = "";
   if (!params.partialPatchOnly) {
     hash = SHA512_HASH_SIMPLE_MAR + (params.invalidCompleteHash ? "e" : "");
     patches += getRemotePatchString("complete", SERVICE_URL, "SHA512",
                                     hash, SIZE_SIMPLE_MAR);
   }
 
--- a/toolkit/mozapps/update/test/chrome/utils.js
+++ b/toolkit/mozapps/update/test/chrome/utils.js
@@ -118,16 +118,17 @@ Components.utils.import("resource://gre/
 
 // The tests have to use the pageid instead of the pageIndex due to the
 // app update wizard's access method being random.
 const PAGEID_DUMMY            = "dummy";                 // Done
 const PAGEID_CHECKING         = "checking";              // Done
 const PAGEID_PLUGIN_UPDATES   = "pluginupdatesfound";
 const PAGEID_NO_UPDATES_FOUND = "noupdatesfound";        // Done
 const PAGEID_MANUAL_UPDATE    = "manualUpdate"; // Tested on license load failure
+const PAGEID_UNSUPPORTED      = "unsupported";           // Done
 const PAGEID_INCOMPAT_CHECK   = "incompatibleCheck";     // Done
 const PAGEID_FOUND_BASIC      = "updatesfoundbasic";     // Done
 const PAGEID_FOUND_BILLBOARD  = "updatesfoundbillboard"; // Done
 const PAGEID_LICENSE          = "license";               // Done
 const PAGEID_INCOMPAT_LIST    = "incompatibleList";      // Done
 const PAGEID_DOWNLOADING      = "downloading";           // Done
 const PAGEID_ERRORS           = "errors";                // Done
 const PAGEID_ERROR_EXTRA      = "errorextra";            // Done
@@ -548,16 +549,17 @@ function getExpectedButtonStates() {
                next  : { disabled: false, hidden: false } };
     case PAGEID_INCOMPAT_LIST:
       return { extra1: { disabled: false, hidden: false },
                next  : { disabled: false, hidden: false } };
     case PAGEID_DOWNLOADING:
       return { extra1: { disabled: false, hidden: false } };
     case PAGEID_NO_UPDATES_FOUND:
     case PAGEID_MANUAL_UPDATE:
+    case PAGEID_UNSUPPORTED:
     case PAGEID_ERRORS:
     case PAGEID_ERROR_EXTRA:
     case PAGEID_INSTALLED:
       return { finish: { disabled: false, hidden: false } };
     case PAGEID_ERROR_PATCHING:
       return { next  : { disabled: false, hidden: false } };
     case PAGEID_FINISHED:
     case PAGEID_FINISHED_BKGRD:
@@ -957,16 +959,20 @@ function resetPrefs() {
   if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_URL_DETAILS)) {
     Services.prefs.clearUserPref(PREF_APP_UPDATE_URL_DETAILS);
   }
 
   if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_SHOW_INSTALLED_UI)) {
     Services.prefs.clearUserPref(PREF_APP_UPDATE_SHOW_INSTALLED_UI);
   }
 
+  if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED)) {
+    Services.prefs.clearUserPref(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED);
+  }
+
   if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_LOG)) {
     Services.prefs.clearUserPref(PREF_APP_UPDATE_LOG);
   }
 
   if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_CERT_ERRORS)) {
     Services.prefs.clearUserPref(PREF_APP_UPDATE_CERT_ERRORS);
   }
 
--- a/toolkit/mozapps/update/test/shared.js
+++ b/toolkit/mozapps/update/test/shared.js
@@ -21,16 +21,17 @@ const PREF_APP_UPDATE_CERT_ERRORS       
 const PREF_APP_UPDATE_CERT_MAXERRORS      = "app.update.cert.maxErrors";
 const PREF_APP_UPDATE_CERT_REQUIREBUILTIN = "app.update.cert.requireBuiltIn";
 const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
 const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
 const PREF_APP_UPDATE_METRO_ENABLED       = "app.update.metro.enabled";
 const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
 const PREF_APP_UPDATE_LOG                 = "app.update.log";
 const PREF_APP_UPDATE_NEVER_BRANCH        = "app.update.never.";
+const PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED = "app.update.notifiedUnsupported";
 const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
 const PREF_APP_UPDATE_SERVICE_ENABLED     = "app.update.service.enabled";
 const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
 const PREF_APP_UPDATE_SILENT              = "app.update.silent";
 const PREF_APP_UPDATE_STAGING_ENABLED     = "app.update.staging.enabled";
 const PREF_APP_UPDATE_URL                 = "app.update.url";
 const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
 const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
--- a/toolkit/mozapps/update/test/sharedUpdateXML.js
+++ b/toolkit/mozapps/update/test/sharedUpdateXML.js
@@ -310,33 +310,31 @@ function getUpdateString(aType, aName, a
   let licenseURL = aLicenseURL ? "licenseURL=\"" + aLicenseURL + "\" " : "";
   let showPrompt = aShowPrompt ? "showPrompt=\"" + aShowPrompt + "\" " : "";
   let showNeverForVersion = aShowNeverForVersion ? "showNeverForVersion=\"" +
                                                    aShowNeverForVersion + "\" "
                                                  : "";
   let promptWaitTime = aPromptWaitTime ? "promptWaitTime=\"" + aPromptWaitTime +
                                          "\" "
                                        : "";
-  let showSurvey = aShowSurvey ? "showSurvey=\"" + aShowSurvey + "\" " : "";
   let custom1 = aCustom1 ? aCustom1 + " " : "";
   let custom2 = aCustom2 ? aCustom2 + " " : "";
   return "  <update type=\"" + type + "\" " +
                    "name=\"" + name + "\" " +
                     displayVersion +
                     version +
                     appVersion +
                     extensionVersion +
                     platformVersion +
                     detailsURL +
                     billboardURL +
                     licenseURL +
                     showPrompt +
                     showNeverForVersion +
                     promptWaitTime +
-                    showSurvey +
                     custom1 +
                     custom2 +
                    "buildID=\"" + buildID + "\"";
 }
 
 /**
  * Constructs a string representing a patch element for an update xml file.
  *
--- a/toolkit/mozapps/update/test/unit/test_0020_general.js
+++ b/toolkit/mozapps/update/test/unit/test_0020_general.js
@@ -114,17 +114,16 @@ function check_test_pt02() {
   do_check_eq(bestUpdate.platformVersion, "3.1a1pre");
   do_check_eq(bestUpdate.buildID, "20080811053724");
   do_check_eq(bestUpdate.detailsURL, "http://details/");
   do_check_eq(bestUpdate.billboardURL, "http://billboard/");
   do_check_eq(bestUpdate.licenseURL, "http://license/");
   do_check_true(bestUpdate.showPrompt);
   do_check_true(bestUpdate.showNeverForVersion);
   do_check_eq(bestUpdate.promptWaitTime, "345600");
-  do_check_true(bestUpdate.showSurvey);
   do_check_eq(bestUpdate.serviceURL, URL_HOST + "update.xml?force=1");
   do_check_eq(bestUpdate.channel, "test_channel");
   do_check_false(bestUpdate.isCompleteUpdate);
   do_check_false(bestUpdate.isSecurityUpdate);
   // Check that installDate is within 10 seconds of the current date.
   do_check_true((Date.now() - bestUpdate.installDate) < 10000);
   do_check_eq(bestUpdate.statusText, null);
   // nsIUpdate:state returns an empty string when no action has been performed
@@ -195,17 +194,16 @@ function check_test_pt03() {
   do_check_eq(bestUpdate.platformVersion, "5.1a1pre");
   do_check_eq(bestUpdate.buildID, "20080811053724");
   do_check_eq(bestUpdate.detailsURL, "http://details/");
   do_check_eq(bestUpdate.billboardURL, "http://details/");
   do_check_eq(bestUpdate.licenseURL, null);
   do_check_true(bestUpdate.showPrompt);
   do_check_true(bestUpdate.showNeverForVersion);
   do_check_eq(bestUpdate.promptWaitTime, "691200");
-  do_check_false(bestUpdate.showSurvey);
   do_check_eq(bestUpdate.serviceURL, URL_HOST + "update.xml?force=1");
   do_check_eq(bestUpdate.channel, "test_channel");
   do_check_false(bestUpdate.isCompleteUpdate);
   do_check_false(bestUpdate.isSecurityUpdate);
   // Check that installDate is within 10 seconds of the current date.
   do_check_true((Date.now() - bestUpdate.installDate) < 10000);
   do_check_eq(bestUpdate.statusText, null);
   // nsIUpdate:state returns an empty string when no action has been performed
--- a/toolkit/mozapps/update/test/unit/test_0030_general.js
+++ b/toolkit/mozapps/update/test/unit/test_0030_general.js
@@ -238,23 +238,23 @@ var newFactory = {
   },
   QueryInterface: XPCOMUtils.generateQI([AUS_Ci.nsIFactory])
 };
 
 function initMockIncrementalDownload() {
   var registrar = AUS_Cm.QueryInterface(AUS_Ci.nsIComponentRegistrar);
   gIncrementalDownloadClassID = registrar.contractIDToCID(INC_CONTRACT_ID);
   gIncOldFactory = AUS_Cm.getClassObject(AUS_Cc[INC_CONTRACT_ID],
-                                     AUS_Ci.nsIFactory);
+                                         AUS_Ci.nsIFactory);
   registrar.unregisterFactory(gIncrementalDownloadClassID, gIncOldFactory);
   var components = [IncrementalDownload];
   registrar.registerFactory(gIncrementalDownloadClassID, "",
                             INC_CONTRACT_ID, newFactory);
   gIncOldFactory = AUS_Cm.getClassObject(AUS_Cc[INC_CONTRACT_ID],
-                                     AUS_Ci.nsIFactory);
+                                         AUS_Ci.nsIFactory);
 }
 
 function cleanupMockIncrementalDownload() {
   if (gIncOldFactory) {
     var registrar = AUS_Cm.QueryInterface(AUS_Ci.nsIComponentRegistrar);
     registrar.unregisterFactory(gIncrementalDownloadClassID, newFactory);
     registrar.registerFactory(gIncrementalDownloadClassID, "",
                               INC_CONTRACT_ID, gIncOldFactory);
--- a/toolkit/mozapps/update/test/unit/test_0060_manager.js
+++ b/toolkit/mozapps/update/test/unit/test_0060_manager.js
@@ -66,17 +66,16 @@ function run_test() {
   do_check_eq(update.installDate, "1238441300314");
   // statusText is updated
   do_check_eq(update.statusText, getString("installSuccess"));
   do_check_false(update.isCompleteUpdate);
   do_check_eq(update.channel, "test_channel");
   do_check_true(update.showPrompt);
   do_check_true(update.showNeverForVersion);
   do_check_eq(update.promptWaitTime, "345600");
-  do_check_true(update.showSurvey);
   do_check_eq(update.previousAppVersion, "3.0");
   // Custom attributes
   do_check_eq(update.getProperty("custom1_attr"), "custom1 value");
   do_check_eq(update.getProperty("custom2_attr"), "custom2 value");
 
   patch = update.selectedPatch;
   do_check_eq(patch.type, "partial");
   do_check_eq(patch.URL, "http://partial/");
@@ -100,17 +99,16 @@ function run_test() {
   do_check_eq(update.installDate, "1238441400314");
   do_check_eq(update.statusText, getString("patchApplyFailure"));
   do_check_eq(update.buildID, "20080811053724");
   do_check_true(update.isCompleteUpdate);
   do_check_eq(update.channel, "test_channel");
   do_check_true(update.showPrompt);
   do_check_true(update.showNeverForVersion);
   do_check_eq(update.promptWaitTime, "691200");
-  do_check_false(update.showSurvey);
   do_check_eq(update.previousAppVersion, null);
   // Custom attributes
   do_check_eq(update.getProperty("custom3_attr"), "custom3 value");
   do_check_eq(update.getProperty("custom4_attr"), "custom4 value");
 
   patch = update.selectedPatch;
   do_check_eq(patch.type, "complete");
   do_check_eq(patch.URL, "http://complete/");
@@ -167,17 +165,16 @@ function run_test() {
   do_check_eq(update.installDate, "1238441400314");
   do_check_eq(update.statusText, getString("installSuccess"));
   do_check_eq(update.buildID, "20080811053724");
   do_check_true(update.isCompleteUpdate);
   do_check_eq(update.channel, "test_channel");
   do_check_true(update.showPrompt);
   do_check_true(update.showNeverForVersion);
   do_check_eq(update.promptWaitTime, "100");
-  do_check_true(update.showSurvey);
   do_check_eq(update.previousAppVersion, "3.0");
 
   patch = update.selectedPatch;
   do_check_eq(patch.type, "complete");
   do_check_eq(patch.URL, URL_HOST + URL_PATH + "/" + FILE_SIMPLE_MAR);
   do_check_eq(patch.hashFunction, "MD5");
   do_check_eq(patch.hashValue, MD5_HASH_SIMPLE_MAR);
   do_check_eq(patch.size, SIZE_SIMPLE_MAR);
@@ -198,17 +195,16 @@ function run_test() {
   do_check_eq(update.installDate, "1238441400314");
   do_check_eq(update.statusText, getString("patchApplyFailure"));
   do_check_eq(update.buildID, "20080811053724");
   do_check_true(update.isCompleteUpdate);
   do_check_eq(update.channel, "test_channel");
   do_check_false(update.showPrompt);
   do_check_false(update.showNeverForVersion);
   do_check_eq(update.promptWaitTime, "200");
-  do_check_false(update.showSurvey);
   do_check_eq(update.previousAppVersion, null);
 
   patch = update.selectedPatch;
   do_check_eq(patch.type, "complete");
   do_check_eq(patch.URL, URL_HOST + URL_PATH + "/" + FILE_SIMPLE_MAR);
   do_check_eq(patch.hashFunction, "MD5");
   do_check_eq(patch.hashValue, MD5_HASH_SIMPLE_MAR);
   do_check_eq(patch.size, SIZE_SIMPLE_MAR);
new file mode 100644
--- /dev/null
+++ b/toolkit/mozapps/update/test/unit/test_0082_prompt_unsupportAlreadyNotified.js
@@ -0,0 +1,129 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+/**
+ * Test that nsIUpdatePrompt doesn't display UI for showUpdateAvailable for an
+ * unsupported system update when it has already been shown (bug 843497).
+ */
+
+function run_test() {
+  do_test_pending();
+  do_register_cleanup(end_test);
+  removeUpdateDirsAndFiles();
+  setUpdateURLOverride();
+  // The mock XMLHttpRequest is MUCH faster
+  overrideXHR(callHandleEvent);
+  standardInit();
+  // The HTTP server is only used for the mar file downloads which is slow
+  start_httpserver(URL_PATH);
+
+  let registrar = Components.manager.QueryInterface(AUS_Ci.nsIComponentRegistrar);
+  registrar.registerFactory(Components.ID("{1dfeb90a-2193-45d5-9cb8-864928b2af55}"),
+                            "Fake Window Watcher",
+                            "@mozilla.org/embedcomp/window-watcher;1",
+                            WindowWatcherFactory);
+  registrar.registerFactory(Components.ID("{1dfeb90a-2193-45d5-9cb8-864928b2af56}"),
+                            "Fake Window Mediator",
+                            "@mozilla.org/appshell/window-mediator;1",
+                            WindowMediatorFactory);
+
+  logTestInfo("testing nsIUpdatePrompt notifications should not be seen for " +
+              "an unsupported system update when it has already been shown");
+
+  Services.prefs.setBoolPref(PREF_APP_UPDATE_SILENT, false);
+  Services.prefs.setBoolPref(PREF_APP_UPDATE_NOTIFIEDUNSUPPORTED, true);
+  // This preference is used to determine when the background update check has
+  // completed since a successful check will clear the preference.
+  Services.prefs.setIntPref(PREF_APP_UPDATE_BACKGROUNDERRORS, 1);
+
+  gResponseBody = getRemoteUpdatesXMLString("  <update type=\"major\" " +
+                                            "name=\"Unsupported Update\" " +
+                                            "unsupported=\"true\" " +
+                                            "detailsURL=\"" + URL_HOST +
+                                            "\"></update>\n");
+  gAUS.notify(null);
+  do_execute_soon(check_test);
+}
+
+function check_test() {
+  if (Services.prefs.prefHasUserValue(PREF_APP_UPDATE_BACKGROUNDERRORS)) {
+    do_execute_soon(check_test);
+    return;
+  }
+  do_check_true(true);
+  do_test_finished();
+}
+
+function end_test() {
+  let registrar = Components.manager.QueryInterface(AUS_Ci.nsIComponentRegistrar);
+  registrar.unregisterFactory(Components.ID("{1dfeb90a-2193-45d5-9cb8-864928b2af55}"),
+                              WindowWatcherFactory);
+  registrar.unregisterFactory(Components.ID("{1dfeb90a-2193-45d5-9cb8-864928b2af56}"),
+                              WindowMediatorFactory);
+  cleanUp();
+}
+
+// Callback function used by the custom XMLHttpRequest implementation to
+// call the nsIDOMEventListener's handleEvent method for onload.
+function callHandleEvent() {
+  gXHR.status = 400;
+  gXHR.responseText = gResponseBody;
+  try {
+    var parser = AUS_Cc["@mozilla.org/xmlextras/domparser;1"].
+                 createInstance(AUS_Ci.nsIDOMParser);
+    gXHR.responseXML = parser.parseFromString(gResponseBody, "application/xml");
+  }
+  catch(e) {
+  }
+  var e = { target: gXHR };
+  gXHR.onload(e);
+}
+
+function check_showUpdateAvailable() {
+  do_throw("showUpdateAvailable should not have called openWindow!");
+}
+
+var WindowWatcher = {
+  openWindow: function(aParent, aUrl, aName, aFeatures, aArgs) {
+    check_showUpdateAvailable();
+  },
+
+  QueryInterface: function(aIID) {
+    if (aIID.equals(AUS_Ci.nsIWindowWatcher) ||
+        aIID.equals(AUS_Ci.nsISupports))
+      return this;
+
+    throw AUS_Cr.NS_ERROR_NO_INTERFACE;
+  }
+}
+
+var WindowWatcherFactory = {
+  createInstance: function createInstance(aOuter, aIID) {
+    if (aOuter != null)
+      throw AUS_Cr.NS_ERROR_NO_AGGREGATION;
+    return WindowWatcher.QueryInterface(aIID);
+  }
+};
+
+var WindowMediator = {
+  getMostRecentWindow: function(aWindowType) {
+    return null;
+  },
+
+  QueryInterface: function(aIID) {
+    if (aIID.equals(AUS_Ci.nsIWindowMediator) ||
+        aIID.equals(AUS_Ci.nsISupports))
+      return this;
+
+    throw AUS_Cr.NS_ERROR_NO_INTERFACE;
+  }
+}
+
+var WindowMediatorFactory = {
+  createInstance: function createInstance(aOuter, aIID) {
+    if (aOuter != null)
+      throw AUS_Cr.NS_ERROR_NO_AGGREGATION;
+    return WindowMediator.QueryInterface(aIID);
+  }
+};
--- a/toolkit/mozapps/update/test/unit/xpcshell.ini
+++ b/toolkit/mozapps/update/test/unit/xpcshell.ini
@@ -15,16 +15,19 @@ tail =
 [test_0070_update_dir_cleanup.js]
 [test_0071_update_dir_cleanup.js]
 [test_0072_update_dir_cleanup.js]
 [test_0073_update_dir_cleanup.js]
 [test_0080_prompt_silent.js]
 [test_0081_prompt_uiAlreadyOpen.js]
 skip-if = toolkit == "gonk"
 reason = custom nsIUpdatePrompt
+[test_0082_prompt_unsupportAlreadyNotified.js]
+skip-if = toolkit == "gonk"
+reason = custom nsIUpdatePrompt
 ; Tests that require the updater binary
 [include:xpcshell_updater.ini]
 skip-if = os == 'android'
 [include:xpcshell_updater_windows.ini]
 run-if = os == 'win'
 [include:xpcshell_updater_xp_unix.ini]
 run-if = os == 'linux' || os == 'mac' || os == 'sunos'
 [test_0160_appInUse_complete.js]
--- a/toolkit/themes/linux/mozapps/update/updates.css
+++ b/toolkit/themes/linux/mozapps/update/updates.css
@@ -41,16 +41,31 @@ wizardpage {
   margin-top: 0 !important;
 }
 
 #licenseContent, #incompatibleListbox {
   -moz-margin-start: 6px;
   -moz-margin-end: 6px;
 }
 
+.inline-link {
+  color: -moz-nativehyperlinktext;
+  text-decoration: none;
+}
+
+.inline-link:hover {
+  text-decoration: underline;
+}
+
+/* Unsupported Page */
+#unsupportedLabel, #unsupportedLinkLabel {
+  -moz-margin-start: 0;
+  -moz-padding-start: 0;
+}
+
 /* Update Found Basic Page */
 #updateName, #updateFinishedName {
   font-weight: bold;
   font-size: larger;
 }
 
 /* License Page */
 #licenseContent {
--- a/toolkit/themes/osx/mozapps/update/updates.css
+++ b/toolkit/themes/osx/mozapps/update/updates.css
@@ -66,16 +66,31 @@ wizardpage {
   margin-bottom: 6px;
 }
 
 #licenseContent, #incompatibleListbox {
   -moz-margin-start: 6px;
   -moz-margin-end: 6px;
 }
 
+.inline-link {
+  color: -moz-nativehyperlinktext;
+  text-decoration: none;
+}
+
+.inline-link:hover {
+  text-decoration: underline;
+}
+
+/* Unsupported Page */
+#unsupportedLabel, #unsupportedLinkLabel {
+  -moz-margin-start: 0;
+  -moz-padding-start: 0;
+}
+
 /* Update Found Basic Page */
 #updateName, #updateFinishedName {
   font-weight: bold;
   font-size: larger;
 }
 
 /* License Page */
 #licenseContent {
--- a/toolkit/themes/windows/mozapps/update/updates.css
+++ b/toolkit/themes/windows/mozapps/update/updates.css
@@ -41,16 +41,31 @@ wizardpage {
   margin-top: 0 !important;
 }
 
 #licenseContent, #incompatibleListbox {
   -moz-margin-start: 6px;
   -moz-margin-end: 6px;
 }
 
+.inline-link {
+  color: -moz-nativehyperlinktext;
+  text-decoration: none;
+}
+
+.inline-link:hover {
+  text-decoration: underline;
+}
+
+/* Unsupported Page */
+#unsupportedLabel, #unsupportedLinkLabel {
+  -moz-margin-start: 0;
+  -moz-padding-start: 0;
+}
+
 /* Update Found Basic Page */
 #updateName, #updateFinishedName {
   font-weight: bold;
   font-size: larger;
 }
 
 /* License Page */
 #licenseContent {