[tor-commits] [torbutton/master] Fix components and modules, and minor style changes

gk at torproject.org gk at torproject.org
Wed Aug 7 19:21:07 UTC 2019


commit 18e7226776301a82bb2c5715739b25f9c2b281ad
Author: Alex Catarineu <acat at torproject.org>
Date:   Thu May 9 19:48:10 2019 +0200

    Fix components and modules, and minor style changes
---
 src/chrome/content/preferences-mobile.js  |  10 +-
 src/chrome/content/tor-circuit-display.js |  18 +--
 src/chrome/content/torbutton.js           | 230 +++++++++++++-----------------
 src/chrome/content/torbutton_util.js      |  14 +-
 src/components/aboutTor.js                |  21 +--
 src/components/cookie-jar-selector.js     | 131 +++++------------
 src/components/domain-isolator.js         |  19 ++-
 src/components/dragDropFilter.js          |  16 +--
 src/components/external-app-blocker.js    |  13 +-
 src/components/torCheckService.js         |  27 +---
 src/components/torbutton-logger.js        |  38 ++---
 src/modules/default-prefs.js              |   2 +-
 src/modules/noscript-control.js           |  50 ++++---
 src/modules/security-prefs.js             |   9 +-
 src/modules/tor-control-port.js           |  10 +-
 src/modules/utils.js                      |  16 +--
 16 files changed, 243 insertions(+), 381 deletions(-)

diff --git a/src/chrome/content/preferences-mobile.js b/src/chrome/content/preferences-mobile.js
index e2da9b88..fa79dce8 100644
--- a/src/chrome/content/preferences-mobile.js
+++ b/src/chrome/content/preferences-mobile.js
@@ -1,12 +1,12 @@
 // # Security Settings User Interface for Mobile
 
 // Utilities
-let { utils: Cu } = Components;
-let { getBoolPref, getIntPref, setBoolPref, setIntPref, getCharPref } =
-    Cu.import("resource://gre/modules/Services.jsm", {}).Services.prefs;
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { getBoolPref, getIntPref, setBoolPref, setIntPref, getCharPref }
+  = Services.prefs;
 
 let { getLocale, show_torbrowser_manual } =
-    Cu.import("resource://torbutton/modules/utils.js", {});
+    ChromeUtils.import("resource://torbutton/modules/utils.js", {});
 
 // Description elements have the follow names.
 const descNames =
@@ -64,7 +64,7 @@ function torbutton_set_learn_more_links() {
     locale = getLocale();
   }
   let links = linkNames.map(name => document.getElementById(name));
-  links.forEach(link => {;
+  links.forEach(link => {
     if (show_manual && locale != "") {
       link.href= "https:/tb-manual.torproject.org/" + locale +
         "/security-slider.html";
diff --git a/src/chrome/content/tor-circuit-display.js b/src/chrome/content/tor-circuit-display.js
index 5ecbe7d7..05dc14de 100644
--- a/src/chrome/content/tor-circuit-display.js
+++ b/src/chrome/content/tor-circuit-display.js
@@ -26,18 +26,17 @@ let createTorCircuitDisplay = (function () {
 "use strict";
 
 // Mozilla utilities
-const { Cu : utils , Ci : interfaces } = Components.utils;
-Cu.import("resource://gre/modules/Services.jsm");
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // Import the controller code.
-let { controller } = Cu.import("resource://torbutton/modules/tor-control-port.js", {});
+let { controller } = ChromeUtils.import("resource://torbutton/modules/tor-control-port.js", {});
 
 // Utility functions
-let { bindPrefAndInit, observe, getLocale, getDomainForBrowser } = Cu.import("resource://torbutton/modules/utils.js", {});
+let { bindPrefAndInit, observe, getLocale, getDomainForBrowser } = ChromeUtils.import("resource://torbutton/modules/utils.js", {});
 
 // Make the TorButton logger available.
 let logger = Cc["@torproject.org/torbutton-logger;1"]
-               .getService(Components.interfaces.nsISupports).wrappedJSObject;
+               .getService(Ci.nsISupports).wrappedJSObject;
 
 // ## Circuit/stream credentials and node monitoring
 
@@ -209,18 +208,13 @@ let uiString = function (shortName) {
   return torbuttonBundle.GetStringFromName("torbutton.circuit_display." + shortName);
 };
 
-// __regionBundle__.
-// A list of localized region (country) names.
-let regionBundle = Services.strings.createBundle(
-                     "chrome://global/locale/regionNames.properties");
-
 // __localizedCountryNameFromCode(countryCode)__.
 // Convert a country code to a localized country name.
 // Example: `'de'` -> `'Deutschland'` in German locale.
 let localizedCountryNameFromCode = function (countryCode) {
   if (!countryCode) return uiString("unknown_country");
   try {
-    return regionBundle.GetStringFromName(countryCode.toLowerCase());
+    return Services.intl.getRegionDisplayNames(undefined, [countryCode])[0];
   } catch (e) {
     return countryCode.toUpperCase();
   }
@@ -363,7 +357,7 @@ let setupGuardNote = function () {
              ["div", {},
               noteBefore, ["span", {class: "circuit-guard-name"}, name],
               noteAfter, " ",
-              ["span", {onclick: `gBrowser.selectedTab = gBrowser.addTab('https://support.torproject.org/${localeCode}/tbb/tbb-2/');`,
+              ["span", {onclick: `gBrowser.selectedTab = gBrowser.addTab('https://support.torproject.org/${localeCode}/tbb/tbb-2/', {triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()});`,
                         class: "circuit-link"},
                learnMoreString]]);
 };
diff --git a/src/chrome/content/torbutton.js b/src/chrome/content/torbutton.js
index a7bd4f8c..d73ddf73 100644
--- a/src/chrome/content/torbutton.js
+++ b/src/chrome/content/torbutton.js
@@ -7,16 +7,20 @@
 // TODO: Double-check there are no strange exploits to defeat:
 //       http://kb.mozillazine.org/Links_to_local_pages_don%27t_work
 
-let { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
-const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
+/* global torbutton_log, gBrowser, torbutton_safelog, CustomizableUI,
+   createTorCircuitDisplay, torbutton_get_property_string, gFindBarInitialized,
+   gFindBar, OpenBrowserWindow, PrivateBrowsingUtils, torbutton_get_stringbundle,
+   Services, AppConstants
+ */
+
 let {
   showDialog,
   show_torbrowser_manual,
   unescapeTorString,
   bindPrefAndInit,
   getDomainForBrowser,
-} = Cu.import("resource://torbutton/modules/utils.js", {});
-let SecurityPrefs = Cu.import("resource://torbutton/modules/security-prefs.js", {});
+} = ChromeUtils.import("resource://torbutton/modules/utils.js", {});
+let SecurityPrefs = ChromeUtils.import("resource://torbutton/modules/security-prefs.js", {});
 
 const k_tb_last_browser_version_pref = "extensions.torbutton.lastBrowserVersion";
 const k_tb_browser_update_needed_pref = "extensions.torbutton.updateNeeded";
@@ -44,8 +48,7 @@ var m_tb_control_host = null;        // Set if using TCP.
 var m_tb_control_pass = null;
 var m_tb_control_desc = null;        // For logging.
 
-var m_tb_domWindowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor).
-                          getInterface(Ci.nsIDOMWindowUtils);
+var m_tb_domWindowUtils = window.windowUtils;
 
 // Bug 1506 P1: This object is only for updating the UI for toggling and style
 var torbutton_window_pref_observer =
@@ -91,9 +94,8 @@ var torbutton_unique_pref_observer =
         m_tb_prefs.addObserver("privacy.resistFingerprinting", this, false);
 
         // We observe xpcom-category-entry-added for plugins w/ Gecko-Content-Viewers
-        var observerService = Cc["@mozilla.org/observer-service;1"].
-            getService(Ci.nsIObserverService);
-        observerService.addObserver(this, "xpcom-category-entry-added", false);
+        var observerService = Services.obs;
+        observerService.addObserver(this, "xpcom-category-entry-added");
     },
 
     unregister: function()
@@ -106,8 +108,7 @@ var torbutton_unique_pref_observer =
         m_tb_prefs.removeObserver("privacy.firstparty.isolate", this);
         m_tb_prefs.removeObserver("privacy.resistFingerprinting", this);
 
-        var observerService = Cc["@mozilla.org/observer-service;1"].
-            getService(Ci.nsIObserverService);
+        var observerService = Services.obs;
         observerService.removeObserver(this, "xpcom-category-entry-added");
     },
 
@@ -165,11 +166,9 @@ var torbutton_unique_pref_observer =
 }
 
 var torbutton_tor_check_observer = {
-    register: function()
-    {
-        this._obsSvc = Cc["@mozilla.org/observer-service;1"]
-                         .getService(Ci.nsIObserverService);
-        this._obsSvc.addObserver(this, k_tb_tor_check_failed_topic, false);
+    register() {
+        this._obsSvc = Services.obs;
+        this._obsSvc.addObserver(this, k_tb_tor_check_failed_topic);
     },
 
     unregister: function()
@@ -189,22 +188,24 @@ var torbutton_tor_check_observer = {
 
         // If the user does not have an about:tor tab open in the front most
         // window, open one.
-        var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
-              .getService(Components.interfaces.nsIWindowMediator);
+        var wm = Services.wm;
         var win = wm.getMostRecentWindow("navigator:browser");
         if (win == window) {
           let foundTab = false;
-          let tabBrowser = top.getBrowser();
+          let tabBrowser = top.gBrowser;
           for (let i = 0; !foundTab && (i < tabBrowser.browsers.length); ++i) {
             let b = tabBrowser.getBrowserAtIndex(i);
             foundTab = (b.currentURI.spec.toLowerCase() == "about:tor");
           }
 
-          if (!foundTab)
-            gBrowser.selectedTab = gBrowser.addTab("about:tor");
+          if (!foundTab) {
+            gBrowser.selectedTab = gBrowser.addTab("about:tor", {
+              triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
+            });
+          }
         }
       }
-    }
+    },
 };
 
 function torbutton_init_toolbutton()
@@ -268,8 +269,8 @@ function torbutton_init() {
     } catch(e) {}
 
     // Bug 1506 P4: These vars are very important for New Identity
-    var environ = Components.classes["@mozilla.org/process/environment;1"]
-                   .getService(Components.interfaces.nsIEnvironment);
+    var environ = Cc["@mozilla.org/process/environment;1"]
+                   .getService(Ci.nsIEnvironment);
 
     if (environ.exists("TOR_CONTROL_PASSWD")) {
         m_tb_control_pass = environ.get("TOR_CONTROL_PASSWD");
@@ -282,10 +283,12 @@ function torbutton_init() {
         } catch(e) {
             torbutton_log(4, 'unable to read authentication cookie');
         }
-    } else try {
+    } else {
+      try {
         // Try to get password from Tor Launcher.
         m_tb_control_pass = tlps.TorGetPassword(false);
-    } catch(e) {}
+      } catch (e) {}
+    }
 
     // Try to get the control port IPC file (an nsIFile) from Tor Launcher,
     // since Tor Launcher knows how to handle its own preferences and how to
@@ -341,9 +344,8 @@ function torbutton_init() {
         // This works only by setting the pref to `true` otherwise we get an
         // exception and nothing is happening.
         m_tb_prefs.setBoolPref("dom.quotaManager.testing", true);
-        Cc["@mozilla.org/dom/quota-manager-service;1"]
-          .getService(Ci.nsIQuotaManagerService).clear();
-      } catch(e) {
+        Services.qms.clear();
+      } catch (e) {
       } finally {
         m_tb_prefs.setBoolPref("dom.quotaManager.testing", orig_quota_test);
       }
@@ -503,8 +505,7 @@ function torbutton_confirm_plugins() {
 
   torbutton_log(3, "Confirming plugin usage.");
 
-  var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
-      .getService(Components.interfaces.nsIPromptService);
+  var prompts = Services.prompt;
 
   // Display two buttons, both with string titles.
   var flags = prompts.STD_YES_NO_BUTTONS + prompts.BUTTON_DELAY_ENABLE;
@@ -513,8 +514,7 @@ function torbutton_confirm_plugins() {
   var askAgainText = torbutton_get_property_string("torbutton.popup.never_ask_again");
   var askAgain = {value: false};
 
-  var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
-             .getService(Components.interfaces.nsIWindowMediator);
+  var wm = Services.wm;
   var win = wm.getMostRecentWindow("navigator:browser");
   var no_plugins = (prompts.confirmEx(win, "", message, flags, null, null, null,
       askAgainText, askAgain) == 1);
@@ -531,8 +531,6 @@ function torbutton_confirm_plugins() {
 
   // Now, if any tabs were open to about:addons, reload them. Our popup
   // messed up that page.
-  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
-                     .getService(Components.interfaces.nsIWindowMediator);
   var browserEnumerator = wm.getEnumerator("navigator:browser");
 
   // Check each browser instance for our URL
@@ -553,15 +551,13 @@ function torbutton_confirm_plugins() {
 }
 
 function torbutton_inform_about_tbb() {
-  var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
-      .getService(Components.interfaces.nsIPromptService);
+  var prompts = Services.prompt;
 
   var message = torbutton_get_property_string("torbutton.popup.prompt_torbrowser");
   var title = torbutton_get_property_string("torbutton.title.prompt_torbrowser");
   var checkbox = {value: false};
 
-  var sb = Components.classes["@mozilla.org/intl/stringbundle;1"]
-      .getService(Components.interfaces.nsIStringBundleService);
+  var sb = Services.strings;
   var browserstrings = sb.createBundle("chrome://browser/locale/browser.properties");
 
   var askagain = browserstrings.GetStringFromName("privateBrowsingNeverAsk");
@@ -761,14 +757,14 @@ function torbutton_socket_readline(input) {
 
 // Bug 1506 P4: Control port interaction. Needed for New Identity.
 function torbutton_read_authentication_cookie(path) {
-  var file = Components.classes['@mozilla.org/file/local;1']
-             .createInstance(Components.interfaces.nsIFile);
+  var file = Cc["@mozilla.org/file/local;1"]
+             .createInstance(Ci.nsIFile);
   file.initWithPath(path);
-  var fileStream = Components.classes['@mozilla.org/network/file-input-stream;1']
-                   .createInstance(Components.interfaces.nsIFileInputStream);
+  var fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
+                   .createInstance(Ci.nsIFileInputStream);
   fileStream.init(file, 1, 0, false);
-  var binaryStream = Components.classes['@mozilla.org/binaryinputstream;1']
-                     .createInstance(Components.interfaces.nsIBinaryInputStream);
+  var binaryStream = Cc["@mozilla.org/binaryinputstream;1"]
+                     .createInstance(Ci.nsIBinaryInputStream);
   binaryStream.setInputStream(fileStream);
   var array = binaryStream.readByteArray(fileStream.available());
   binaryStream.close();
@@ -795,8 +791,7 @@ function torbutton_send_ctrl_cmd(command) {
   // suppressing/unsuppressing user initiated events in a window's document to
   // be sure that these events are not interfering with processing events being
   // in the event queue.
-  var thread = Cc["@mozilla.org/thread-manager;1"].
-               getService(Ci.nsIThreadManager).currentThread;
+  var thread = Services.tm.currentThread;
   m_tb_domWindowUtils.suppressEventHandling(true);
   while (thread.processNextEvent(false)) {}
   m_tb_domWindowUtils.suppressEventHandling(false);
@@ -871,15 +866,14 @@ function torbutton_new_identity() {
     // conditions leading to failures (see bug 11783 for an example).
     // TODO: Remove the Torbutton menu entry again once we have done our
     // security control redesign.
-    document.getElementById("torbutton-new-identity").disabled = true;
+    // document.getElementById("torbutton-new-identity").disabled = true;
     document.getElementById("menu_newIdentity").disabled = true;
     document.getElementById("appMenuNewIdentity").disabled = true;
 
     let shouldConfirm =  m_tb_prefs.getBoolPref("extensions.torbutton.confirm_newnym");
 
     if (shouldConfirm) {
-      let prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"]
-                      .getService(Ci.nsIPromptService);
+      let prompts = Services.prompt;
 
       // Display two buttons, both with string titles.
       let flags = prompts.STD_YES_NO_BUTTONS;
@@ -898,7 +892,7 @@ function torbutton_new_identity() {
       } else {
         // TODO: Remove the Torbutton menu entry again once we have done our
         // security control redesign.
-        document.getElementById("torbutton-new-identity").disabled = false;
+        // document.getElementById("torbutton-new-identity").disabled = false;
         document.getElementById("menu_newIdentity").disabled = false;
         document.getElementById("appMenuNewIdentity").disabled = false;
       }
@@ -910,11 +904,11 @@ function torbutton_new_identity() {
     // enabled (again).
     // TODO: Remove the Torbutton menu entry again once we have done our
     // security control redesign.
-    document.getElementById("torbutton-new-identity").disabled = false;
+    torbutton_log(5, "Unexpected error on new identity: " + e);
+    window.alert("Torbutton: Unexpected error on new identity: " + e);
+    // document.getElementById("torbutton-new-identity").disabled = false;
     document.getElementById("menu_newIdentity").disabled = false;
     document.getElementById("appMenuNewIdentity").disabled = false;
-    torbutton_log(5, "Unexpected error on new identity: "+e);
-    window.alert("Torbutton: Unexpected error on new identity: "+e);
   }
 }
 
@@ -941,7 +935,7 @@ function torbutton_new_identity() {
  */
 // Bug 1506 P4: Needed for New Identity.
 function torbutton_do_new_identity() {
-  var obsSvc = Components.classes["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
+  var obsSvc = Services.obs;
   torbutton_log(3, "New Identity: Disabling JS");
   torbutton_disable_all_js();
 
@@ -995,9 +989,9 @@ function torbutton_do_new_identity() {
 
   torbutton_log(3, "New Identity: Clearing HTTP Auth");
 
-  if(m_tb_prefs.getBoolPref('extensions.torbutton.clear_http_auth')) {
-      var auth = Components.classes["@mozilla.org/network/http-auth-manager;1"].
-          getService(Components.interfaces.nsIHttpAuthManager);
+  if (m_tb_prefs.getBoolPref("extensions.torbutton.clear_http_auth")) {
+      var auth = Cc["@mozilla.org/network/http-auth-manager;1"].
+          getService(Ci.nsIHttpAuthManager);
       auth.clearAll();
   }
 
@@ -1006,8 +1000,8 @@ function torbutton_do_new_identity() {
   // Clear all crypto auth tokens. This includes calls to PK11_LogoutAll(),
   // nsNSSComponent::LogoutAuthenticatedPK11() and clearing the SSL session
   // cache.
-  let sdr = Components.classes["@mozilla.org/security/sdr;1"].
-                       getService(Components.interfaces.nsISecretDecoderRing);
+  let sdr = Cc["@mozilla.org/security/sdr;1"].
+                       getService(Ci.nsISecretDecoderRing);
   sdr.logoutAndTeardown();
 
   // This clears the OCSP cache.
@@ -1047,8 +1041,7 @@ function torbutton_do_new_identity() {
   torbutton_log(3, "New Identity: Clearing Offline Cache");
 
   try {
-    const LoadContextInfo = Cc["@mozilla.org/load-context-info-factory;1"]
-      .getService(Ci.nsILoadContextInfoFactory);
+    const LoadContextInfo = Services.loadContextInfo;
 
     for (let contextInfo of [LoadContextInfo.default, LoadContextInfo.private]) {
       let appCacheStorage = Services.cache2.appCacheStorage(contextInfo, null);
@@ -1089,19 +1082,18 @@ function torbutton_do_new_identity() {
       // This works only by setting the pref to `true` otherwise we get an
       // exception and nothing is happening.
       m_tb_prefs.setBoolPref("dom.quotaManager.testing", true);
-      Cc["@mozilla.org/dom/quota-manager-service;1"]
-          .getService(Ci.nsIQuotaManagerService).clear();
-  } catch(e) {
-      torbutton_log(5, "Exception on storage clearing: "+e);
+      Services.qms.clear();
+  } catch (e) {
+      torbutton_log(5, "Exception on storage clearing: " + e);
   } finally {
       m_tb_prefs.setBoolPref("dom.quotaManager.testing", orig_quota_test);
   }
 
   torbutton_log(3, "New Identity: Clearing Cookies and DOM Storage");
 
-  if (m_tb_prefs.getBoolPref('extensions.torbutton.cookie_protections')) {
-    var selector = Components.classes["@torproject.org/cookie-jar-selector;1"]
-                    .getService(Components.interfaces.nsISupports)
+  if (m_tb_prefs.getBoolPref("extensions.torbutton.cookie_protections")) {
+    var selector = Cc["@torproject.org/cookie-jar-selector;1"]
+                    .getService(Ci.nsISupports)
                     .wrappedJSObject;
     // This emits "cookie-changed", "cleared", which kills DOM storage
     // and the safe browsing API key
@@ -1119,18 +1111,12 @@ function torbutton_do_new_identity() {
 
   // XXX: This may not clear zoom site-specific
   // browser.content.full-zoom
-  if (Ci.nsIContentPrefService2) {   // Firefox >= 20
-    XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
-                            "resource://gre/modules/PrivateBrowsingUtils.jsm");
-    var pbCtxt = PrivateBrowsingUtils.privacyContextFromWindow(window);
-    var cps = Cc["@mozilla.org/content-pref/service;1"]
-                .getService(Ci.nsIContentPrefService2);
-    cps.removeAllDomains(pbCtxt);
-  } else {                           // Firefox < 20
-    var cps = Cc["@mozilla.org/content-pref/service;1"].
-        createInstance(Ci.nsIContentPrefService);
-    cps.removeGroupedPrefs();
-  }
+  ChromeUtils.defineModuleGetter(this, "PrivateBrowsingUtils",
+                          "resource://gre/modules/PrivateBrowsingUtils.jsm");
+  var pbCtxt = PrivateBrowsingUtils.privacyContextFromWindow(window);
+  var cps = Cc["@mozilla.org/content-pref/service;1"]
+              .getService(Ci.nsIContentPrefService2);
+  cps.removeAllDomains(pbCtxt);
 
   torbutton_log(3, "New Identity: Syncing prefs");
 
@@ -1139,8 +1125,7 @@ function torbutton_do_new_identity() {
 
   torbutton_log(3, "New Identity: Clearing permissions");
 
-  let pm = Cc["@mozilla.org/permissionmanager;1"].
-           getService(Ci.nsIPermissionManager);
+  let pm = Services.perms;
   pm.removeAll();
 
   // Clear the domain isolation state.
@@ -1234,8 +1219,7 @@ function torbutton_clear_image_caches()
       // Try to clear the private browsing cache.  To do so, we must locate
       // a content document that is contained within a private browsing window.
       let didClearPBCache = false;
-      let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
-                 .getService(Ci.nsIWindowMediator);
+      let wm = Services.wm;
       let enumerator = wm.getEnumerator("navigator:browser");
       while (!didClearPBCache && enumerator.hasMoreElements()) {
         let win = enumerator.getNext();
@@ -1243,7 +1227,7 @@ function torbutton_clear_image_caches()
         if (!browserDoc.hasAttribute("privatebrowsingmode"))
           continue;
 
-        let tabbrowser = win.getBrowser();
+        let tabbrowser = win.gBrowser;
         if (!tabbrowser)
           continue;
 
@@ -1372,8 +1356,7 @@ function torbutton_local_tor_check()
   if (socksAddr && socksAddr.startsWith("file:")) {
     // Convert the file URL to a file path.
     try {
-      let ioService = Cc["@mozilla.org/network/io-service;1"]
-                        .getService(Ci.nsIIOService);
+      let ioService = Services.io;
       let fph = ioService.getProtocolHandler("file")
                          .QueryInterface(Ci.nsIFileProtocolHandler);
       socksIPCPath = fph.getFileFromURLSpec(socksAddr).path;
@@ -1440,11 +1423,8 @@ function torbutton_local_tor_check()
 } // torbutton_local_tor_check
 
 
-function torbutton_initiate_remote_tor_check()
-{
-  let obsSvc = Cc["@mozilla.org/observer-service;1"]
-                 .getService(Ci.nsIObserverService);
-
+function torbutton_initiate_remote_tor_check() {
+  let obsSvc = Services.obs;
   try {
       let checkSvc = Cc["@torproject.org/torbutton-torCheckService;1"]
                        .getService(Ci.nsISupports).wrappedJSObject;
@@ -1573,13 +1553,12 @@ function torbutton_close_tabs_on_new_identity() {
 
   // TODO: muck around with browser.tabs.warnOnClose.. maybe..
   torbutton_log(3, "Closing tabs...");
-  let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
-             .getService(Ci.nsIWindowMediator);
+  let wm = Services.wm;
   let enumerator = wm.getEnumerator("navigator:browser");
-  let windowsToClose = new Array();
+  let windowsToClose = [];
   while (enumerator.hasMoreElements()) {
     let win = enumerator.getNext();
-    let browser = win.getBrowser();
+    let browser = win.gBrowser;
     if (!browser) {
       torbutton_log(5, "No browser for possible closed window");
       continue;
@@ -1598,7 +1577,9 @@ function torbutton_close_tabs_on_new_identity() {
     }
 
     if (win == window) {
-      browser.addTab("about:blank");
+      browser.addTab("about:blank", {
+        triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
+      });
     } else {
       // It is a bad idea to alter the window list while iterating
       // over it, so add this window to an array and close it later.
@@ -1672,9 +1653,8 @@ function torbutton_open_cookie_dialog() {
 // Bug 1506 P4: Used by New Identity if cookie protections are
 // not in use.
 function torbutton_clear_cookies() {
-    torbutton_log(2, 'called torbutton_clear_cookies');
-    var cm = Components.classes["@mozilla.org/cookiemanager;1"]
-                    .getService(Components.interfaces.nsICookieManager);
+    torbutton_log(2, "called torbutton_clear_cookies");
+    var cm = Services.cookies;
 
     cm.removeAll();
 }
@@ -1692,7 +1672,7 @@ function torbutton_disable_browser_js(browser) {
             torbutton_log(3, "No content window to disable JS events.");
         else
             eventSuppressor = browser.contentWindow.
-                QueryInterface(Components.interfaces.nsIInterfaceRequestor).
+                QueryInterface(Ci.nsIInterfaceRequestor).
                        getInterface(Ci.nsIDOMWindowUtils);
     } catch(e) {
         torbutton_log(4, "Failed to disable JS events: "+e)
@@ -1718,8 +1698,8 @@ function torbutton_disable_browser_js(browser) {
 // Bug 1506 P3: The JS-killing bits of this are used by
 // New Identity as a defense-in-depth measure.
 function torbutton_disable_window_js(win) {
-    var browser = win.getBrowser();
-    if(!browser) {
+    var browser = win.gBrowser;
+    if (!browser) {
       torbutton_log(5, "No browser for plugin window...");
       return;
     }
@@ -1760,8 +1740,7 @@ function torbutton_disable_window_js(win) {
 // This is an ugly beast.. But unfortunately it has to be so..
 // Looping over all tabs twice is not somethign we wanna do..
 function torbutton_disable_all_js() {
-    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
-                       .getService(Components.interfaces.nsIWindowMediator);
+    var wm = Services.wm;
     var enumerator = wm.getEnumerator("navigator:browser");
     while(enumerator.hasMoreElements()) {
         var win = enumerator.getNext();
@@ -1817,8 +1796,8 @@ function torbutton_do_startup()
 {
     if(m_tb_prefs.getBoolPref("extensions.torbutton.startup")) {
         // Bug 1506: Still want to do this
-        torbutton_toggle_plugins(
-                m_tb_prefs.getBoolPref("plugin.disable"));
+        // torbutton_toggle_plugins(
+        //         m_tb_prefs.getBoolPref("plugin.disable"));
 
         // Bug 1506: Should probably be moved to an XPCOM component
         torbutton_do_main_window_startup();
@@ -1839,7 +1818,7 @@ function torbutton_do_startup()
         if (!m_tb_tbb && m_tb_prefs.getBoolPref("extensions.torbutton.prompt_torbrowser")) {
           var warning = torbutton_get_property_string("torbutton.popup.short_torbrowser");
           var title = torbutton_get_property_string("torbutton.title.prompt_torbrowser");
-          var prompts = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
+          var prompts = Services.prompt;
           prompts.alert(null, title, warning);
         }
 
@@ -1867,8 +1846,8 @@ function torbutton_new_tab(event)
 function torbutton_is_windowed(wind) {
     torbutton_log(3, "Window: (" + wind.outerWidth + "," + wind.outerHeight + ") ?= ("
                      + wind.screen.availWidth + "," + wind.screen.availHeight + ")");
-    if(wind.windowState == Components.interfaces.nsIDOMChromeWindow.STATE_MINIMIZED
-      || wind.windowState == Components.interfaces.nsIDOMChromeWindow.STATE_MAXIMIZED) {
+    if (wind.windowState == Ci.nsIDOMChromeWindow.STATE_MINIMIZED
+      || wind.windowState == Ci.nsIDOMChromeWindow.STATE_MAXIMIZED) {
         torbutton_log(2, "Window is minimized/maximized");
         return false;
     }
@@ -1904,8 +1883,9 @@ function showSecurityPreferencesPanel(chromeWindow) {
   if (settingsTab === null) {
       // Open up the settings panel in a new tab.
       tabBrowser.addTab(SECURITY_PREFERENCES_URI, {
-          'selected': true,
-          'parentId': tabBrowser.selectedTab.id
+          "selected": true,
+          "parentId": tabBrowser.selectedTab.id,
+          triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
       });
   } else {
       // Activate an existing settings panel tab.
@@ -1984,8 +1964,7 @@ function torbutton_close_window(event) {
     // But that is a major overhaul..
     if (m_tb_is_main_window) {
         torbutton_log(3, "Original window closed. Searching for another");
-        var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
-            .getService(Components.interfaces.nsIWindowMediator);
+        var wm = Services.wm;
         var enumerator = wm.getEnumerator("navigator:browser");
         while(enumerator.hasMoreElements()) {
             var win = enumerator.getNext();
@@ -2016,9 +1995,8 @@ function torbutton_close_window(event) {
 
 
 function torbutton_open_network_settings() {
-  var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
-                .getService(Ci.nsIObserverService);
-  obsSvc.notifyObservers(this, "TorOpenNetworkSettings", null);
+  var obsSvc = Services.obs;
+  obsSvc.notifyObservers(this, "TorOpenNetworkSettings");
 }
 
 
@@ -2032,14 +2010,7 @@ var m_tb_resize_date = null;
 // probably not for android.
 var torbutton_resizelistener =
 {
-  QueryInterface: function(aIID)
-  {
-   if (aIID.equals(Ci.nsIWebProgressListener) ||
-       aIID.equals(Ci.nsISupportsWeakReference) ||
-       aIID.equals(Ci.nsISupports))
-     return this;
-   throw Cr.NS_NOINTERFACE;
-  },
+  QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener", "nsISupportsWeakReference"]),
 
   onLocationChange: function(aProgress, aRequest, aURI) {},
   onStateChange: function(aProgress, aRequest, aFlag, aStatus) {
@@ -2072,10 +2043,8 @@ var torbutton_resizelistener =
               m_tb_resize_date = Date.now();
             }
 
-            let sb = torbutton_get_stringbundle();
             // No need to get "OK" translated again.
-            let sbSvc = Cc["@mozilla.org/intl/stringbundle;1"].
-              getService(Ci.nsIStringBundleService);
+            let sbSvc = Services.strings;
             let bundle = sbSvc.
               createBundle("chrome://global/locale/commonDialogs.properties");
             let button_label = bundle.GetStringFromName("OK");
@@ -2141,8 +2110,7 @@ var torbutton_resizelistener =
 function torbutton_get_current_accept_language_value(aURI)
 {
   try {
-    let ioService = Cc["@mozilla.org/network/io-service;1"]
-                      .getService(Ci.nsIIOService);
+    let ioService = Services.io;
     let channel = ioService.newChannelFromURI(aURI);
     let httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);
     return httpChannel.getRequestHeader("Accept-Language");
diff --git a/src/chrome/content/torbutton_util.js b/src/chrome/content/torbutton_util.js
index e6de7681..c7116a09 100644
--- a/src/chrome/content/torbutton_util.js
+++ b/src/chrome/content/torbutton_util.js
@@ -3,8 +3,9 @@
 // code directly. I don't see any of them as essential for 1506,
 // really.
 
-var m_tb_torlog = Components.classes["@torproject.org/torbutton-logger;1"]
-.getService(Components.interfaces.nsISupports).wrappedJSObject;
+// let { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm", {});
+var m_tb_torlog = Cc["@torproject.org/torbutton-logger;1"]
+.getService(Ci.nsISupports).wrappedJSObject;
 
 var m_tb_string_bundle = torbutton_get_stringbundle();
 
@@ -28,10 +29,8 @@ function torbutton_get_prefbranch(branch_name) {
     var o_branch = false;
 
     torbutton_log(1, "called get_prefbranch()");
-    o_prefs = Components.classes["@mozilla.org/preferences-service;1"]
-                        .getService(Components.interfaces.nsIPrefService);
-    if (!o_prefs)
-    {
+    o_prefs = Services.prefs;
+    if (!o_prefs) {
         torbutton_log(5, "Failed to get preferences-service!");
         return false;
     }
@@ -52,8 +51,7 @@ function torbutton_get_stringbundle()
     var o_stringbundle = false;
 
     try {
-        var oBundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
-                                .getService(Components.interfaces.nsIStringBundleService);
+        var oBundle = Services.strings;
         o_stringbundle = oBundle.createBundle("chrome://torbutton/locale/torbutton.properties");
     } catch(err) {
         o_stringbundle = false;
diff --git a/src/components/aboutTor.js b/src/components/aboutTor.js
index e3ee03d6..ec48d668 100644
--- a/src/components/aboutTor.js
+++ b/src/components/aboutTor.js
@@ -14,20 +14,15 @@ const kMODULE_CID = Components.ID("84d47da6-79c3-4661-aa9f-8049476f7bf5");
 
 const kAboutTorURL = "chrome://torbutton/content/aboutTor/aboutTor.xhtml";
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-function AboutTor()
-{
-}
+function AboutTor() {}
 
 
 AboutTor.prototype =
 {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
+  QueryInterface: ChromeUtils.generateQI([Ci.nsIAboutModule]),
 
   // nsIClassInfo implementation:
   classDescription: kMODULE_NAME,
@@ -35,11 +30,9 @@ AboutTor.prototype =
   contractID: kMODULE_CONTRACTID,
 
   // nsIAboutModule implementation:
-  newChannel: function(aURI, aLoadInfo)
-  {
-    let ioSvc = Cc["@mozilla.org/network/io-service;1"]
-                  .getService(Ci.nsIIOService);
-    let uri = ioSvc.newURI(kAboutTorURL, null, null);
+  newChannel(aURI, aLoadInfo) {
+    let ioSvc = Services.io;
+    let uri = ioSvc.newURI(kAboutTorURL);
     let channel = ioSvc.newChannelFromURIWithLoadInfo(uri, aLoadInfo);
     channel.originalURI = aURI;
 
diff --git a/src/components/cookie-jar-selector.js b/src/components/cookie-jar-selector.js
index 8456da3b..b3eeda53 100644
--- a/src/components/cookie-jar-selector.js
+++ b/src/components/cookie-jar-selector.js
@@ -18,12 +18,11 @@ const kMODULE_NAME = "Cookie Jar Selector";
 const kMODULE_CONTRACTID = "@torproject.org/cookie-jar-selector;1";
 const kMODULE_CID = Components.ID("e6204253-b690-4159-bfe8-d4eedab6b3be");
 
-const Cr = Components.results;
-const Cu = Components.utils;
-
-Cu.import("resource://torbutton/modules/default-prefs.js", {})
+ChromeUtils.import("resource://torbutton/modules/default-prefs.js", {})
   .ensureDefaultPrefs();
 
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
 // XXX: Must match the definition in torcookie.js :/
 function Cookie(number,name,value,isDomain,host,rawHost,HttpOnly,path,isSecure,isSession,
                 expires,isProtected) {
@@ -42,73 +41,32 @@ function Cookie(number,name,value,isDomain,host,rawHost,HttpOnly,path,isSecure,i
 }
 
 function CookieJarSelector() {
-  var Cc = Components.classes;
-  var Ci = Components.interfaces;
-
-  this.logger = Components.classes["@torproject.org/torbutton-logger;1"]
-      .getService(Components.interfaces.nsISupports).wrappedJSObject;
+  this.logger = Cc["@torproject.org/torbutton-logger;1"]
+      .getService(Ci.nsISupports).wrappedJSObject;
 
-  this.logger.log(3, "Component Load 5: New CookieJarSelector "+kMODULE_CONTRACTID);
+  this.logger.log(3, "Component Load 5: New CookieJarSelector " + kMODULE_CONTRACTID);
 
-  this.prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
+  this.prefs = Services.prefs;
 
   var getProfileFile = function(filename) {
-    var loc = "ProfD";  // profile directory
-    var file = 
-      Cc["@mozilla.org/file/directory_service;1"]
-      .getService(Ci.nsIProperties)
+    var loc = "ProfD"; // profile directory
+    var file = Services.dirsvc
       .get(loc, Ci.nsIFile)
       .clone();
     file.append(filename); 
     return file;
   };
 
-  var copyProfileFile = function(src, dest) {
-    var srcfile = getProfileFile(src);    
-    var destfile = getProfileFile(dest);
-    if (srcfile.exists()) {
-      // XXX: Permissions issue with Vista roaming profiles? 
-      // Maybe file locking?
-      try {
-          if (destfile.exists()) {
-              destfile.remove(false);
-          }
-      } catch(e) {
-          this.logger.log(4, "Cookie file deletion exception: "+e);
-      }
-      try {
-          srcfile.copyTo(null, dest);
-      } catch(e) {
-          this.logger.log(5, "Cookie file copy exception: "+e);
-      }
-    }
-  };
-
-  var moveProfileFile = function(src, dest) { // FIXME: Why does this not work?
-    var srcfile = getProfileFile(src);    
-    var destfile = getProfileFile(dest);
-    if (srcfile.exists()) {
-      if (destfile.exists()) {
-        destfile.remove(false);
-      }
-      srcfile.moveTo(null, dest);
-    }
-  };
-
   this.clearCookies = function() {
     try {
-        Cc["@mozilla.org/cookiemanager;1"]
-            .getService(Ci.nsICookieManager)
-            .removeAll();
-    } catch(e) {
-        this.logger.log(4, "Cookie clearing exception: "+e);
+        Services.cookies.removeAll();
+    } catch (e) {
+        this.logger.log(4, "Cookie clearing exception: " + e);
     }
   };
 
   this._cookiesToJS = function(getSession) {
-    var cookieManager =
-      Cc["@mozilla.org/cookiemanager;1"]
-      .getService(Ci.nsICookieManager);
+    var cookieManager = Services.cookies;
     var cookiesEnum = cookieManager.enumerator;
     var cookiesAsJS = [];
     var count = 0;
@@ -353,7 +311,7 @@ function CookieJarSelector() {
         var nextCookie = enumerator.getNext();
         if (!nextCookie) break;
 
-        nextCookie = nextCookie.QueryInterface(Components.interfaces.nsICookie);
+        nextCookie = nextCookie.QueryInterface(Ci.nsICookie);
         for (var i = 0; i < protCookies.length; i++) {
           protcookie = protcookie || (nextCookie.host == protCookies[i].host &&
                                       nextCookie.name == protCookies[i].name &&
@@ -371,7 +329,7 @@ function CookieJarSelector() {
       }
       // Emit cookie-changed event. This instructs other components to clear their identifiers
       // (Specifically DOM storage and safe browsing, but possibly others)
-      var obsSvc = Components.classes["@mozilla.org/observer-service;1"].getService(nsIObserverService);
+      var obsSvc = Cc["@mozilla.org/observer-service;1"].getService(nsIObserverService);
       obsSvc.notifyObservers(this, "cookie-changed", "cleared");
     } catch (e) {
       this.logger.log(5, "Error deleting unprotected cookies: " + e);
@@ -410,10 +368,8 @@ function CookieJarSelector() {
   };
 
   // Check firefox version to know filename
-  var appInfo = Components.classes["@mozilla.org/xre/app-info;1"]
-      .getService(Components.interfaces.nsIXULAppInfo);
-  var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
-      .getService(Components.interfaces.nsIVersionComparator);
+  // var appInfo = Services.appinfo;
+  // var versionChecker = Services.vc;
 
   // This JSObject is exported directly to chrome
   this.wrappedJSObject = this;
@@ -424,15 +380,8 @@ function CookieJarSelector() {
   this.timerCallback = {
     cookie_changed: false,
 
-    QueryInterface: function(iid) {
-       if (!iid.equals(Component.interfaces.nsISupports) &&
-           !iid.equals(Component.interfaces.nsITimer)) {
-         Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
-         return null;
-       }
-       return this;
-    },
-    notify: function() {
+    QueryInterface: ChromeUtils.generateQI(["nsITimer"]),
+    notify() {
        // this refers to timerCallback object. use jarThis to reference
        // CookieJarSelector object.
        if(!this.cookie_changed) {
@@ -450,27 +399,18 @@ function CookieJarSelector() {
 
 }
 
-const nsISupports = Components.interfaces.nsISupports;
-const nsIClassInfo = Components.interfaces.nsIClassInfo;
-const nsIObserver = Components.interfaces.nsIObserver;
-const nsITimer = Components.interfaces.nsITimer;
-const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
-const nsIObserverService = Components.interfaces.nsIObserverService;
-const nsICategoryManager = Components.interfaces.nsICategoryManager;
+const nsISupports = Ci.nsISupports;
+const nsIClassInfo = Ci.nsIClassInfo;
+const nsIObserver = Ci.nsIObserver;
+const nsITimer = Ci.nsITimer;
+const nsIComponentRegistrar = Ci.nsIComponentRegistrar;
+const nsIObserverService = Ci.nsIObserverService;
+const nsICategoryManager = Ci.nsICategoryManager;
 
 // Start1506: You may or may not care about this:
 CookieJarSelector.prototype =
 {
-  QueryInterface: function(iid)
-  {
-    if (!iid.equals(nsIClassInfo) &&
-        !iid.equals(nsIObserver) &&
-        !iid.equals(nsISupports)) {
-      Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
-      return null;
-    }
-    return this;
-  },
+  QueryInterface: ChromeUtils.generateQI(["nsIClassInfo", "nsIObserver"]),
 
   wrappedJSObject: null,  // Initialized by constructor
 
@@ -496,19 +436,18 @@ CookieJarSelector.prototype =
   observe : function(aSubject, aTopic, aData) {
        switch(aTopic) { 
         case "cookie-changed":
-            var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);          
+            var prefs = Services.prefs;
             this.timerCallback.cookie_changed = true;
-    
+
             if (aData == "added"
                 && prefs.getBoolPref("extensions.torbutton.cookie_auto_protect")
-                && !prefs.getBoolPref("extensions.torbutton.tor_memory_jar"))
-            {
-              this.addProtectedCookie(aSubject.QueryInterface(Components.interfaces.nsICookie2));//protect the new cookie!    
+                && !prefs.getBoolPref("extensions.torbutton.tor_memory_jar")) {
+              this.addProtectedCookie(aSubject.QueryInterface(Ci.nsICookie2));// protect the new cookie!
             }
             break;
         case "profile-after-change":
-            var obsSvc = Components.classes["@mozilla.org/observer-service;1"].getService(nsIObserverService);
-            obsSvc.addObserver(this, "cookie-changed", false);
+            var obsSvc = Cc["@mozilla.org/observer-service;1"].getService(nsIObserverService);
+            obsSvc.addObserver(this, "cookie-changed");
             // after profil loading, initialize a timer to call timerCallback
             // at a specified interval
             this.timer.initWithCallback(this.timerCallback, 60 * 1000, nsITimer.TYPE_REPEATING_SLACK); // 1 minute
@@ -517,7 +456,7 @@ CookieJarSelector.prototype =
        }
   },
 
-  timer:  Components.classes["@mozilla.org/timer;1"].createInstance(nsITimer),
+  timer:  Cc["@mozilla.org/timer;1"].createInstance(nsITimer),
 
 }
 
@@ -525,7 +464,7 @@ CookieJarSelector.prototype =
 * XPCOMUtils.generateNSGetFactory was introduced in Mozilla 2 (Firefox 4).
 * XPCOMUtils.generateNSGetModule is for Mozilla 1.9.2 (Firefox 3.6).
 */
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 if (XPCOMUtils.generateNSGetFactory)
     var NSGetFactory = XPCOMUtils.generateNSGetFactory([CookieJarSelector]);
 else
diff --git a/src/components/domain-isolator.js b/src/components/domain-isolator.js
index fc28703f..e04005a5 100644
--- a/src/components/domain-isolator.js
+++ b/src/components/domain-isolator.js
@@ -6,21 +6,19 @@
 // call earlier functions). The code file can be processed
 // with docco.js to provide clear documentation.
 
-/* jshint esversion: 6 */
-/* global Components, console, XPCOMUtils */
-
 // ### Abbreviations
-const Cc = Components.classes, Ci = Components.interfaces, Cu = Components.utils;
+
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // Make the logger available.
 let logger = Cc["@torproject.org/torbutton-logger;1"]
-               .getService(Components.interfaces.nsISupports).wrappedJSObject;
+               .getService(Ci.nsISupports).wrappedJSObject;
 
-let { ensureDefaultPrefs } = Cu.import("resource://torbutton/modules/default-prefs.js", {});
+let { ensureDefaultPrefs } = ChromeUtils.import("resource://torbutton/modules/default-prefs.js", {});
 ensureDefaultPrefs();
 
 // Import Services object
-Cu.import("resource://gre/modules/Services.jsm");
+ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // Import crypto object (FF 37+).
 Cu.importGlobalProperties(["crypto"]);
@@ -82,6 +80,8 @@ tor.socksProxyCredentials = function (originalProxy, domain) {
                           proxy.port,
                           domain, // username
                           tor.noncesForDomains[domain], // password
+                          "", // aProxyAuthorizationHeader
+                          "", // aConnectionIsolationKey
                           proxy.flags,
                           proxy.failoverTimeout,
                           proxy.failoverProxy);
@@ -138,7 +138,6 @@ tor.isolateCircuitsByDomain = function () {
     }
     try {
       let channel = aChannel.QueryInterface(Ci.nsIChannel),
-          proxy = aProxy.QueryInterface(Ci.nsIProxyInfo),
           firstPartyDomain = channel.loadInfo.originAttributes.firstPartyDomain;
       if (firstPartyDomain === "") {
         firstPartyDomain = "--unknown--";
@@ -165,7 +164,7 @@ const kMODULE_CONTRACTID = "@torproject.org/domain-isolator;1";
 const kMODULE_CID = Components.ID("e33fd6d4-270f-475f-a96f-ff3140279f68");
 
 // Import XPCOMUtils object.
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 // DomainIsolator object.
 function DomainIsolator() {
@@ -174,7 +173,7 @@ function DomainIsolator() {
 
 // Firefox component requirements
 DomainIsolator.prototype = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
+  QueryInterface: ChromeUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
   classDescription: kMODULE_NAME,
   classID: kMODULE_CID,
   contractID: kMODULE_CONTRACTID,
diff --git a/src/components/dragDropFilter.js b/src/components/dragDropFilter.js
index 916b835f..4465187e 100644
--- a/src/components/dragDropFilter.js
+++ b/src/components/dragDropFilter.js
@@ -5,13 +5,11 @@
  * access to URLs (a potential proxy bypass vector).
  *************************************************************************/
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
 
-Cu.import("resource://torbutton/modules/default-prefs.js", {}).ensureDefaultPrefs();
+ChromeUtils.import("resource://torbutton/modules/default-prefs.js", {}).ensureDefaultPrefs();
 
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // Module specific constants
 const kMODULE_NAME = "Torbutton Drag and Drop Handler";
@@ -26,17 +24,15 @@ function DragDropFilter() {
   this.logger.log(3, "Component Load 0: New DragDropFilter.");
 
   try {
-    var observerService = Cc["@mozilla.org/observer-service;1"].
-        getService(Ci.nsIObserverService);
-    observerService.addObserver(this, "on-datatransfer-available", false);
-  } catch(e) {
+    Services.obs.addObserver(this, "on-datatransfer-available");
+  } catch (e) {
     this.logger.log(5, "Failed to register drag observer");
   }
 }
 
 DragDropFilter.prototype =
 {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
+  QueryInterface: ChromeUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]),
 
   // make this an nsIClassInfo object
   flags: Ci.nsIClassInfo.DOM_OBJECT,
diff --git a/src/components/external-app-blocker.js b/src/components/external-app-blocker.js
index 1f88fc78..747824d1 100644
--- a/src/components/external-app-blocker.js
+++ b/src/components/external-app-blocker.js
@@ -12,14 +12,9 @@
  * handle an URL (e.g., when the user clicks on a mailto: URL).
  *************************************************************************/
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cr = Components.results;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/SharedPromptUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const {PromptUtils} = ChromeUtils.import("resource://gre/modules/SharedPromptUtils.jsm");
 
 // Module specific constants
 const kMODULE_NAME = "Torbutton External App Handler";
@@ -38,7 +33,7 @@ ExternalAppBlocker.prototype =
 {
   _helperAppLauncher: undefined,
 
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver,
+  QueryInterface: ChromeUtils.generateQI([Ci.nsISupports, Ci.nsIObserver,
                                          Ci.nsIHelperAppWarningDialog]),
 
   // make this an nsIClassInfo object
diff --git a/src/components/torCheckService.js b/src/components/torCheckService.js
index 19e13f49..4f79bef4 100644
--- a/src/components/torCheckService.js
+++ b/src/components/torCheckService.js
@@ -7,16 +7,13 @@
  * Tor check service
  *************************************************************************/
 
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
 // Module specific constants
 const kMODULE_NAME = "Torbutton Tor Check Service";
 const kMODULE_CONTRACTID = "@torproject.org/torbutton-torCheckService;1";
 const kMODULE_CID = Components.ID("5d57312b-5d8c-4169-b4af-e80d6a28a72e");
 
-const Cr = Components.results;
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
 function TBTorCheckService() {
   this._logger = Cc["@torproject.org/torbutton-logger;1"]
                    .getService(Ci.nsISupports).wrappedJSObject;
@@ -28,15 +25,7 @@ function TBTorCheckService() {
 
 TBTorCheckService.prototype =
 {
-  QueryInterface: function(iid) {
-    if (!iid.equals(Ci.nsIClassInfo) &&
-        !iid.equals(Ci.nsISupports)) {
-      Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
-      return null;
-    }
-
-    return this;
-  },
+  QueryInterface: ChromeUtils.generateQI([Ci.nsISupports, Ci.nsIClassInfo]),
 
   kCheckNotInitiated: 0, // Possible values for statusOfTorCheck.
   kCheckSuccessful: 1,
@@ -79,10 +68,8 @@ TBTorCheckService.prototype =
   {
     Cu.importGlobalProperties(["XMLHttpRequest"]);
     let req = new XMLHttpRequest();
-    let prefs =  Cc["@mozilla.org/preferences-service;1"]
-                   .getService(Ci.nsIPrefBranch);
-    let url = prefs.getCharPref("extensions.torbutton.test_url");
-    req.open('GET', url, aAsync);
+    let url = Services.prefs.getCharPref("extensions.torbutton.test_url");
+    req.open("GET", url, aAsync);
     req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
     req.overrideMimeType("text/xml");
     req.timeout = 120000;  // Wait at most two minutes for a response.
@@ -140,8 +127,8 @@ TBTorCheckService.prototype =
       }
 
     return ret;
-  }
+  },
 };
 
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 var NSGetFactory = XPCOMUtils.generateNSGetFactory([TBTorCheckService]);
diff --git a/src/components/torbutton-logger.js b/src/components/torbutton-logger.js
index fdf7bb7d..ce4ba70b 100644
--- a/src/components/torbutton-logger.js
+++ b/src/components/torbutton-logger.js
@@ -13,31 +13,25 @@ const kMODULE_NAME = "Torbutton Logger";
 const kMODULE_CONTRACTID = "@torproject.org/torbutton-logger;1";
 const kMODULE_CID = Components.ID("f36d72c9-9718-4134-b550-e109638331d7");
 
-const Cr = Components.results;
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
+ChromeUtils.import("resource://torbutton/modules/default-prefs.js", {}).ensureDefaultPrefs();
 
-Cu.import("resource://torbutton/modules/default-prefs.js", {}).ensureDefaultPrefs();
-
-Cu.import("resource://gre/modules/Services.jsm");
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 function TorbuttonLogger() {
     // Register observer
-    Services.prefs.addObserver("extensions.torbutton", this, false);
+    Services.prefs.addObserver("extensions.torbutton", this);
 
     this.loglevel = Services.prefs.getIntPref("extensions.torbutton.loglevel");
     this.logmethod = Services.prefs.getIntPref("extensions.torbutton.logmethod");
 
     try {
-        var logMngr = Components.classes["@mozmonkey.com/debuglogger/manager;1"]
-            .getService(Components.interfaces.nsIDebugLoggerManager); 
+        var logMngr = Cc["@mozmonkey.com/debuglogger/manager;1"]
+            .getService(Ci.nsIDebugLoggerManager);
         this._debuglog = logMngr.registerLogger("torbutton");
     } catch (exErr) {
         this._debuglog = false;
     }
-    this._console = Components.classes["@mozilla.org/consoleservice;1"]
-        .getService(Components.interfaces.nsIConsoleService);
+    this._console = Services.console;
 
     // This JSObject is exported directly to chrome
     this.wrappedJSObject = this;
@@ -50,10 +44,10 @@ function TorbuttonLogger() {
  * Everything below is boring boilerplate and can probably be ignored.
  */
 
-const nsISupports = Components.interfaces.nsISupports;
-const nsIClassInfo = Components.interfaces.nsIClassInfo;
-const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
-const nsIObserverService = Components.interfaces.nsIObserverService;
+const nsISupports = Ci.nsISupports;
+const nsIClassInfo = Ci.nsIClassInfo;
+const nsIComponentRegistrar = Ci.nsIComponentRegistrar;
+const nsIObserverService = Ci.nsIObserverService;
 
 const logString = { 1:"VERB", 2:"DBUG", 3: "INFO", 4:"NOTE", 5:"WARN" };
 
@@ -64,15 +58,7 @@ function padInt(i)
 
 TorbuttonLogger.prototype =
 {
-  QueryInterface: function(iid)
-  {
-    if (!iid.equals(nsIClassInfo) &&
-        !iid.equals(nsISupports)) {
-      Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
-      return null;
-    }
-    return this;
-  },
+  QueryInterface: ChromeUtils.generateQI([Ci.nsISupports, Ci.nsIClassInfo]),
 
   wrappedJSObject: null,  // Initialized by constructor
 
@@ -176,7 +162,7 @@ TorbuttonLogger.prototype =
 * XPCOMUtils.generateNSGetFactory was introduced in Mozilla 2 (Firefox 4).
 * XPCOMUtils.generateNSGetModule is for Mozilla 1.9.2 (Firefox 3.6).
 */
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 if (XPCOMUtils.generateNSGetFactory)
     var NSGetFactory = XPCOMUtils.generateNSGetFactory([TorbuttonLogger]);
 else
diff --git a/src/modules/default-prefs.js b/src/modules/default-prefs.js
index 6a2bd86c..5ea549f4 100644
--- a/src/modules/default-prefs.js
+++ b/src/modules/default-prefs.js
@@ -4,7 +4,7 @@ function ensureDefaultPrefs () {
   if (loaded) {
     return;
   }
-  Components.utils.import("resource://gre/modules/Services.jsm");
+  const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
   const kDefaultPreferences = "resource://torbutton/defaults/preferences/preferences.js";
   const defaultPrefBranch = Services.prefs.getDefaultBranch(null);
 
diff --git a/src/modules/noscript-control.js b/src/modules/noscript-control.js
index 4513dce8..0daf15e1 100644
--- a/src/modules/noscript-control.js
+++ b/src/modules/noscript-control.js
@@ -1,17 +1,16 @@
 // # NoScript settings control (for binding to Security Slider)
 
-/* jshint esversion:6 */
-
 // ## Utilities
 
-const { utils: Cu } = Components;
-const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
-const { LegacyExtensionContext } =
-      Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {});
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm", {});
 const { bindPref } =
-      Cu.import("resource://torbutton/modules/utils.js", {});
-let logger = Components.classes["@torproject.org/torbutton-logger;1"]
-    .getService(Components.interfaces.nsISupports).wrappedJSObject;
+      ChromeUtils.import("resource://torbutton/modules/utils.js", {});
+
+const { ExtensionUtils } = ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm");
+const { MessageChannel } = ChromeUtils.import("resource://gre/modules/MessageChannel.jsm");
+
+let logger = Cc["@torproject.org/torbutton-logger;1"]
+    .getService(Ci.nsISupports).wrappedJSObject;
 let log = (level, msg) => logger.log(level, msg);
 
 // ## NoScript settings
@@ -100,20 +99,28 @@ var initialize = () => {
   initialized = true;
 
   try {
-    // A mock extension object that can communicate with another extension
-    // via the WebExtensions sendMessage/onMessage mechanism.
-    let extensionContext = new LegacyExtensionContext({ id : noscriptID });
+    // LegacyExtensionContext is not there anymore. Using raw
+    // Services.mm.broadcastAsyncMessage mecanism to communicate with
+    // NoScript.
 
     // The component that handles WebExtensions' sendMessage.
-    let messageManager = extensionContext.messenger.messageManagers[0];
 
     // __setNoScriptSettings(settings)__.
     // NoScript listens for internal settings with onMessage. We can send
     // a new settings JSON object according to NoScript's
     // protocol and these are accepted! See the use of
     // `browser.runtime.onMessage.addListener(...)` in NoScript's bg/main.js.
+
+    // TODO: Is there a better way?
     let sendNoScriptSettings = settings =>
-        extensionContext.messenger.sendMessage(messageManager, settings, noscriptID);
+      Services.mm.broadcastAsyncMessage("MessageChannel:Messages", [{
+        messageName: "Extension:Message",
+        sender: { id: noscriptID, extensionId: noscriptID },
+        recipient: { extensionId: noscriptID },
+        data: new StructuredCloneHolder(settings),
+        channelId: ExtensionUtils.getUniqueId(),
+        responseType: MessageChannel.RESPONSE_NONE,
+      }]);
 
     // __setNoScriptSafetyLevel(safetyLevel)__.
     // Set NoScript settings according to a particular safety level
@@ -129,13 +136,20 @@ var initialize = () => {
 
     // Wait for the first message from NoScript to arrive, and then
     // bind the security_slider pref to the NoScript settings.
-    let messageListener = (a,b,c) => {
+    const listener = ({ data }) => {
+      for (const msg of data) {
+        if (msg.recipient.extensionId === noscriptID) {
+          messageListener(msg.data.deserialize({}), msg.sender);
+        }
+      }
+    };
+    let messageListener = (a, b, c) => {
       try {
-        log(3, `Message received from NoScript: ${JSON.stringify([a,b,c])}`);
+        log(3, `Message received from NoScript: ${JSON.stringify([a, b, c])}`);
         if (!["started", "pageshow"].includes(a.__meta.name)) {
           return;
         }
-        extensionContext.api.browser.runtime.onMessage.removeListener(messageListener);
+        Services.mm.removeMessageListener("MessageChannel:Messages", listener);
         let noscriptPersist = Services.prefs.getBoolPref("extensions.torbutton.noscript_persist", false);
         let noscriptInited = Services.prefs.getBoolPref("extensions.torbutton.noscript_inited", false);
         // Set the noscript safety level once if we have never run noscript
@@ -153,7 +167,7 @@ var initialize = () => {
         log(5, e.message);
       }
     };
-    extensionContext.api.browser.runtime.onMessage.addListener(messageListener);
+    Services.mm.addMessageListener("MessageChannel:Messages", listener);
     log(3, "Listening for message from NoScript.");
   } catch (e) {
     log(5, e.message);
diff --git a/src/modules/security-prefs.js b/src/modules/security-prefs.js
index fa97b70d..ffc5ee39 100644
--- a/src/modules/security-prefs.js
+++ b/src/modules/security-prefs.js
@@ -2,13 +2,12 @@
 
 // ### Utilities
 
-let {classes: Cc, utils: Cu } = Components;
 let { getBoolPref, setBoolPref, getIntPref, setIntPref } =
-    Cu.import("resource://gre/modules/Services.jsm", {}).Services.prefs;
+    ChromeUtils.import("resource://gre/modules/Services.jsm", {}).Services.prefs;
 let { bindPref, bindPrefAndInit } =
-    Cu.import("resource://torbutton/modules/utils.js", {});
-let logger = Components.classes["@torproject.org/torbutton-logger;1"]
-    .getService(Components.interfaces.nsISupports).wrappedJSObject;
+    ChromeUtils.import("resource://torbutton/modules/utils.js", {});
+let logger = Cc["@torproject.org/torbutton-logger;1"]
+    .getService(Ci.nsISupports).wrappedJSObject;
 let log = (level, msg) => logger.log(level, msg);
 
 // ### Constants
diff --git a/src/modules/tor-control-port.js b/src/modules/tor-control-port.js
index 2c399367..f1d9ed14 100644
--- a/src/modules/tor-control-port.js
+++ b/src/modules/tor-control-port.js
@@ -19,15 +19,15 @@
 "use strict";
 
 // ### Mozilla Abbreviations
-let {classes: Cc, interfaces: Ci, results: Cr, Constructor: CC, utils: Cu } = Components;
+let { Constructor: CC } = Components;
 
 // ### Import Mozilla Services
-Cu.import("resource://gre/modules/Services.jsm");
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // __log__.
 // Logging function
 let logger = Cc["@torproject.org/torbutton-logger;1"]
-               .getService(Components.interfaces.nsISupports).wrappedJSObject;
+               .getService(Ci.nsISupports).wrappedJSObject;
 let log = x => logger.eclog(3, x.trimRight().replace(/\r\n/g, "\n"));
 
 // ### announce this file
@@ -42,8 +42,8 @@ let io = {};
 // given ipcFile or host and port.
 io.asyncSocketStreams = function (ipcFile, host, port) {
   let sts = Cc["@mozilla.org/network/socket-transport-service;1"]
-              .getService(Components.interfaces.nsISocketTransportService),
-	  UNBUFFERED = Ci.nsITransport.OPEN_UNBUFFERED;
+              .getService(Ci.nsISocketTransportService),
+      UNBUFFERED = Ci.nsITransport.OPEN_UNBUFFERED;
 
   // Create an instance of a socket transport.
   let socketTransport;
diff --git a/src/modules/utils.js b/src/modules/utils.js
index d7baca6e..7b81819d 100644
--- a/src/modules/utils.js
+++ b/src/modules/utils.js
@@ -1,14 +1,8 @@
 // # Utils.js
 // Various helpful utility functions.
 
-// ### Shortcut
-const { Cu: utils, Cr: results } = Components;
-
 // ### Import Mozilla Services
-Cu.import("resource://gre/modules/Services.jsm");
-
-// ### Import global URL
-Cu.importGlobalProperties(["URL"]);
+const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
 
 // ### About firstPartyDomain literal
 const k_tb_about_uri_first_party_domain = "about.ef2a7dd5-93bc-417f-a698-142c3116864f.mozilla";
@@ -76,8 +70,8 @@ var observe = function (topic, callback) {
 
 // __env__.
 // Provides access to process environment variables.
-let env = Components.classes["@mozilla.org/process/environment;1"]
-            .getService(Components.interfaces.nsIEnvironment);
+let env = Cc["@mozilla.org/process/environment;1"]
+            .getService(Ci.nsIEnvironment);
 
 // __getEnv(name)__.
 // Reads the environment variable of the given name.
@@ -88,8 +82,8 @@ var getEnv = function (name) {
 // __getLocale
 // Reads the browser locale, the default locale is en-US.
 var getLocale = function() {
-  return Services.locale.getRequestedLocale() || "en-US";
-}
+  return Services.locale.requestedLocale || "en-US";
+};
 
 // ## Windows
 





More information about the tor-commits mailing list