lists.torproject.org
Sign In Sign Up
Manage this list Sign In Sign Up

Keyboard Shortcuts

Thread View

  • j: Next unread message
  • k: Previous unread message
  • j a: Jump to all threads
  • j l: Jump to MailingList overview

tbb-commits

Thread Start a new thread
Threads by month
  • ----- 2026 -----
  • March
  • February
  • January
  • ----- 2025 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2024 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2023 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2022 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2021 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2020 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2019 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2018 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2017 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2016 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2015 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2014 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
tbb-commits@lists.torproject.org

  • 1 participants
  • 20078 discussions
[Git][tpo/applications/firefox-android][firefox-android-115.2.1-13.0-1] fixup! Bug 42074: 2023 year end campaign for tor browser HomeFragment
by Pier Angelo Vendrame (@pierov) 19 Sep '23

19 Sep '23
Pier Angelo Vendrame pushed to branch firefox-android-115.2.1-13.0-1 at The Tor Project / Applications / firefox-android Commits: ec2162be by henry at 2023-09-18T16:12:37+01:00 fixup! Bug 42074: 2023 year end campaign for tor browser HomeFragment - - - - - 1 changed file: - fenix/app/src/main/res/values/torbrowser_strings.xml Changes: ===================================== fenix/app/src/main/res/values/torbrowser_strings.xml ===================================== @@ -81,12 +81,8 @@ <!-- Large introduction text. --> <string name="yec_2023_introduction">Right now, Tor Browser for Android is protecting your privacy!</string> <!-- 2023 year-end-campaign. --> - <!-- The first part of yec_2023_pleas_donate_full. Split out from the full string to bring some styling attention to this part. Follows directly below yec_2023_introduction. --> - <string name="yec_2023_please_donate_beginning">This is possible because of donations from our community.</string> - <!-- 2023 year-end-campaign. --> <!-- Full donation message. Follows directly below yec_2023_introduction. --> - <!-- %s will be replaced with the translated string of yec_2023_please_donate_beginning with some visual styling. --> - <string name="yec_2023_please_donate_full">%s If you value the privacy that Tor Browser for Android offers yourself and others, please make a donation today.</string> + <string name="yec_2023_please_donate">This is possible because of donations from our community. If you value the privacy that Tor Browser for Android offers yourself and others, please make a donation today.</string> <!-- 2023 year-end-campaign. --> <!-- Shown only during a period where donations will be matched. The end date should match the end of the year. --> <!-- %s will be replaced with the donation limit. This will be a whole-number and will be automatically pre-formatted according to the language/locale: using the language's numeral symbols and thousand-separators. --> View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/ec2… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/ec2… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-build][main] Update ublock-origin to 1.52.0
by boklm (@boklm) 19 Sep '23

19 Sep '23
boklm pushed to branch main at The Tor Project / Applications / tor-browser-build Commits: aab7b2d6 by Richard Pospesel at 2023-09-18T22:04:13+00:00 Update ublock-origin to 1.52.0 - - - - - 1 changed file: - projects/browser/config Changes: ===================================== projects/browser/config ===================================== @@ -87,9 +87,9 @@ input_files: - URL: https://addons.mozilla.org/firefox/downloads/file/4164985/noscript-11.4.27.… name: noscript sha256sum: 6b57d9afce663f801177b7492fe7f00967ee3e66b6351b2cf3ff2a6c3ca99637 - - URL: https://addons.mozilla.org/firefox/downloads/file/4141256/ublock_origin-1.5… + - URL: https://addons.mozilla.org/firefox/downloads/file/4164949/ublock_origin-1.5… name: ublock-origin - sha256sum: 8b73468bc233a11dd2895219466381783d19123857dd0b6fd16a01820fca4834 + sha256sum: 3932506ce4df306e4da7527d93d60fe0421cf15045c2f4ea73589d9a0902266b enable: '[% c("var/mullvad-browser") %]' - URL: https://github.com/mullvad/browser-extension/releases/download/v0.8.3-firef… name: mullvad-extension View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/a… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/a… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Firefox preference overrides.
by Pier Angelo Vendrame (@pierov) 19 Sep '23

19 Sep '23
Pier Angelo Vendrame pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 6a043750 by Richard Pospesel at 2023-09-19T07:46:09+00:00 fixup! Firefox preference overrides. Bug 42094: Explicitly disable media.aboutwebrtc.hist.enabled - - - - - 1 changed file: - browser/app/profile/001-base-profile.js Changes: ===================================== browser/app/profile/001-base-profile.js ===================================== @@ -49,6 +49,7 @@ pref("browser.cache.disk.enable", false); pref("permissions.memory_only", true); pref("network.cookie.lifetimePolicy", 2); pref("security.nocertdb", true); +pref("media.aboutwebrtc.hist.enabled", false); // Disk Activity View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/6a04375… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/6a04375… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][base-browser-115.2.1esr-13.0-1] Bug 41995: Generated headers on Windows are not reproducible
by richard (@richard) 19 Sep '23

19 Sep '23
richard pushed to branch base-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 0a1a48fd by Pier Angelo Vendrame at 2023-09-19T01:34:03+00:00 Bug 41995: Generated headers on Windows are not reproducible The flags optionally passed as a third parameter to DLL_BLOCKLIST_ENTRY are stored in a set, so they are not ordered. Sorting them before outputting them makes the creation of the headers deterministic. - - - - - 1 changed file: - toolkit/xre/dllservices/mozglue/gen_dll_blocklist_defs.py Changes: ===================================== toolkit/xre/dllservices/mozglue/gen_dll_blocklist_defs.py ===================================== @@ -570,7 +570,7 @@ class DllBlocklistEntry(object): flags_str = "" - flags = self.get_flags_list() + flags = sorted(self.get_flags_list()) if flags: flags_str = ", " + " | ".join(map(self.get_flag_string, flags)) View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0a1a48f… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0a1a48f… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] Bug 41995: Generated headers on Windows are not reproducible
by richard (@richard) 19 Sep '23

19 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 43f9dbcb by Pier Angelo Vendrame at 2023-09-19T01:29:25+00:00 Bug 41995: Generated headers on Windows are not reproducible The flags optionally passed as a third parameter to DLL_BLOCKLIST_ENTRY are stored in a set, so they are not ordered. Sorting them before outputting them makes the creation of the headers deterministic. - - - - - 1 changed file: - toolkit/xre/dllservices/mozglue/gen_dll_blocklist_defs.py Changes: ===================================== toolkit/xre/dllservices/mozglue/gen_dll_blocklist_defs.py ===================================== @@ -570,7 +570,7 @@ class DllBlocklistEntry(object): flags_str = "" - flags = self.get_flags_list() + flags = sorted(self.get_flags_list()) if flags: flags_str = ", " + " | ".join(map(self.get_flag_string, flags)) View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/43f9dbc… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/43f9dbc… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] 6 commits: fixup! Bug 30237: Add v3 onion services client authentication prompt
by richard (@richard) 19 Sep '23

19 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: de6b3303 by Henry Wilkes at 2023-09-19T01:24:50+00:00 fixup! Bug 30237: Add v3 onion services client authentication prompt Bug 42091: Tidy up authPrompt.jsm. Stop importing modules to the global scope and remove authUtil.jsm. Refactor the description string handling. - - - - - 1a422b66 by Henry Wilkes at 2023-09-19T01:24:50+00:00 fixup! Add TorStrings module for localization Bug 42091: Remove authPrompt &quot;Learn More&quot; href from TorStrings. - - - - - 7c864096 by Henry Wilkes at 2023-09-19T01:24:50+00:00 Bug 42110: Add TorUIUtils module for common tor component methods. - - - - - 6662e2dd by Henry Wilkes at 2023-09-19T01:24:50+00:00 fixup! Bug 41600: Add a tor circuit display panel. Bug 42091: Use TorUIUtils to shorten the onion address. - - - - - d66b44eb by Henry Wilkes at 2023-09-19T01:24:50+00:00 fixup! Bug 30237: Add v3 onion services client authentication prompt Bug 42091: Shorten the shown onion address in the auth prompt. - - - - - 6f0199ab by Henry Wilkes at 2023-09-19T01:24:50+00:00 fixup! Bug 23247: Communicating security expectations for .onion Bug 42091: Shorten onion address in site identity panel to be consistent with the circuit display. - - - - - 10 changed files: - browser/base/content/browser-siteIdentity.js - browser/base/content/browser.js - browser/components/onionservices/content/authPreferences.js - browser/components/onionservices/content/authPrompt.js - − browser/components/onionservices/content/authUtil.jsm - browser/components/onionservices/jar.mn - browser/components/torcircuit/content/torCircuitPanel.js - browser/modules/TorStrings.jsm - + browser/modules/TorUIUtils.sys.mjs - browser/modules/moz.build Changes: ===================================== browser/base/content/browser-siteIdentity.js ===================================== @@ -729,7 +729,15 @@ var gIdentityHandler = { host = this._uri.specIgnoringRef; } - return host; + // For tor browser we want to shorten onion addresses for the site identity + // panel (gIdentityHandler) to match the circuit display and the onion + // authorization panel. + // See tor-browser#42091 and tor-browser#41600. + // This will also shorten addresses for other consumers of this method, + // which includes the permissions panel (gPermissionPanel) and the + // protections panel (gProtectionsHandler), although the latter is hidden in + // tor browser. + return TorUIUtils.shortenOnionAddress(host); }, /** ===================================== browser/base/content/browser.js ===================================== @@ -67,6 +67,7 @@ ChromeUtils.defineESModuleGetters(this, { "resource:///modules/firefox-view-tabs-setup-manager.sys.mjs", TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.sys.mjs", TorDomainIsolator: "resource://gre/modules/TorDomainIsolator.sys.mjs", + TorUIUtils: "resource:///modules/TorUIUtils.sys.mjs", TranslationsParent: "resource://gre/actors/TranslationsParent.sys.mjs", UITour: "resource:///modules/UITour.sys.mjs", UpdateUtils: "resource://gre/modules/UpdateUtils.sys.mjs", ===================================== browser/components/onionservices/content/authPreferences.js ===================================== @@ -42,10 +42,11 @@ const OnionServicesAuthPreferences = { elem = groupbox.querySelector(this.selector.learnMore); elem.setAttribute("value", TorStrings.onionServices.learnMore); - elem.setAttribute("href", TorStrings.onionServices.learnMoreURL); - if (TorStrings.onionServices.learnMoreURL.startsWith("about:")) { - elem.setAttribute("useoriginprincipal", "true"); - } + elem.setAttribute( + "href", + "about:manual#onion-services_onion-service-authentication" + ); + elem.setAttribute("useoriginprincipal", "true"); elem = groupbox.querySelector(this.selector.savedKeysButton); elem.setAttribute( ===================================== browser/components/onionservices/content/authPrompt.js ===================================== @@ -1,20 +1,19 @@ -// Copyright (c) 2020, The Tor Project, Inc. +/* eslint-env mozilla/browser-window */ "use strict"; -/* globals gBrowser, PopupNotifications, Services, XPCOMUtils */ - -ChromeUtils.defineESModuleGetters(this, { - TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs", -}); - -XPCOMUtils.defineLazyModuleGetters(this, { - OnionAuthUtil: "chrome://browser/content/onionservices/authUtil.jsm", - CommonUtils: "resource://services-common/utils.js", - TorStrings: "resource:///modules/TorStrings.jsm", -}); - const OnionAuthPrompt = (function () { + // Only import to our internal scope, rather than the global scope of + // browser.xhtml. + const lazy = {}; + ChromeUtils.defineESModuleGetters(lazy, { + TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs", + CommonUtils: "resource://services-common/utils.sys.mjs", + }); + XPCOMUtils.defineLazyModuleGetters(lazy, { + TorStrings: "resource:///modules/TorStrings.jsm", + }); + // OnionServicesAuthPrompt objects run within the main/chrome process. // aReason is the topic passed within the observer notification that is // causing this auth prompt to be displayed. @@ -25,11 +24,16 @@ const OnionAuthPrompt = (function () { this._onionHostname = aOnionName; } + const topics = { + clientAuthMissing: "tor-onion-services-clientauth-missing", + clientAuthIncorrect: "tor-onion-services-clientauth-incorrect", + }; + OnionServicesAuthPrompt.prototype = { show(aWarningMessage) { let mainAction = { - label: TorStrings.onionServices.authPrompt.done, - accessKey: TorStrings.onionServices.authPrompt.doneAccessKey, + label: lazy.TorStrings.onionServices.authPrompt.done, + accessKey: lazy.TorStrings.onionServices.authPrompt.doneAccessKey, leaveOpen: true, // Callback is responsible for closing the notification. callback: this._onDone.bind(this), }; @@ -68,9 +72,9 @@ const OnionAuthPrompt = (function () { this._prompt = PopupNotifications.show( this._browser, - OnionAuthUtil.domid.notification, + "tor-clientauth", "", - OnionAuthUtil.domid.anchor, + "tor-clientauth-notification-icon", mainAction, [cancelAction], options @@ -79,52 +83,38 @@ const OnionAuthPrompt = (function () { _onPromptShowing(aWarningMessage) { let xulDoc = this._browser.ownerDocument; - let descElem = xulDoc.getElementById(OnionAuthUtil.domid.description); + let descElem = xulDoc.getElementById("tor-clientauth-notification-desc"); if (descElem) { // Handle replacement of the onion name within the localized // string ourselves so we can show the onion name as bold text. // We do this by splitting the localized string and creating // several HTML <span> elements. - while (descElem.firstChild) { - descElem.firstChild.remove(); - } + const fmtString = lazy.TorStrings.onionServices.authPrompt.description; + const [prefix, suffix] = fmtString.split("%S"); - let fmtString = TorStrings.onionServices.authPrompt.description; - let prefix = ""; - let suffix = ""; - const kToReplace = "%S"; - let idx = fmtString.indexOf(kToReplace); - if (idx < 0) { - prefix = fmtString; - } else { - prefix = fmtString.substring(0, idx); - suffix = fmtString.substring(idx + kToReplace.length); - } + const domainEl = xulDoc.createElement("span"); + domainEl.id = "tor-clientauth-notification-onionname"; + domainEl.textContent = TorUIUtils.shortenOnionAddress( + this._onionHostname + ); - const kHTMLNS = "http://www.w3.org/1999/xhtml"; - let span = xulDoc.createElementNS(kHTMLNS, "span"); - span.textContent = prefix; - descElem.appendChild(span); - span = xulDoc.createElementNS(kHTMLNS, "span"); - span.id = OnionAuthUtil.domid.onionNameSpan; - span.textContent = this._onionHostname; - descElem.appendChild(span); - span = xulDoc.createElementNS(kHTMLNS, "span"); - span.textContent = suffix; - descElem.appendChild(span); + descElem.replaceChildren(prefix, domainEl, suffix); } // Set "Learn More" label and href. - let learnMoreElem = xulDoc.getElementById(OnionAuthUtil.domid.learnMore); + let learnMoreElem = xulDoc.getElementById( + "tor-clientauth-notification-learnmore" + ); if (learnMoreElem) { - learnMoreElem.setAttribute("value", TorStrings.onionServices.learnMore); + learnMoreElem.setAttribute( + "value", + lazy.TorStrings.onionServices.learnMore + ); learnMoreElem.setAttribute( "href", - TorStrings.onionServices.learnMoreURL + "about:manual#onion-services_onion-service-authentication" ); - if (TorStrings.onionServices.learnMoreURL.startsWith("about:")) { - learnMoreElem.setAttribute("useoriginprincipal", "true"); - } + learnMoreElem.setAttribute("useoriginprincipal", "true"); } this._showWarning(aWarningMessage); @@ -139,7 +129,7 @@ const OnionAuthPrompt = (function () { if (keyElem) { keyElem.setAttribute( "placeholder", - TorStrings.onionServices.authPrompt.keyPlaceholder + lazy.TorStrings.onionServices.authPrompt.keyPlaceholder ); this._boundOnKeyFieldKeyPress = this._onKeyFieldKeyPress.bind(this); this._boundOnKeyFieldInput = this._onKeyFieldInput.bind(this); @@ -186,14 +176,14 @@ const OnionAuthPrompt = (function () { const base64key = this._keyToBase64(keyElem.value); if (!base64key) { - this._showWarning(TorStrings.onionServices.authPrompt.invalidKey); + this._showWarning(lazy.TorStrings.onionServices.authPrompt.invalidKey); return; } this._prompt.remove(); const controllerFailureMsg = - TorStrings.onionServices.authPrompt.failedToSetKey; + lazy.TorStrings.onionServices.authPrompt.failedToSetKey; try { // ^(subdomain.)*onionserviceid.onion$ (case-insensitive) const onionServiceIdRegExp = @@ -205,7 +195,7 @@ const OnionAuthPrompt = (function () { const checkboxElem = this._getCheckboxElement(); const isPermanent = checkboxElem && checkboxElem.checked; - const provider = await TorProviderBuilder.build(); + const provider = await lazy.TorProviderBuilder.build(); await provider.onionAuthAdd(onionServiceId, base64key, isPermanent); // Success! Reload the page. this._browser.sendMessageToActor("Browser:Reload", {}, "BrowserTab"); @@ -227,7 +217,7 @@ const OnionAuthPrompt = (function () { // this authentication prompt. const failedURI = this._failedURI.spec; const errorCode = - this._reasonForPrompt === OnionAuthUtil.topic.clientAuthMissing + this._reasonForPrompt === topics.clientAuthMissing ? Cr.NS_ERROR_TOR_ONION_SVC_MISSING_CLIENT_AUTH : Cr.NS_ERROR_TOR_ONION_SVC_BAD_CLIENT_AUTH; const io = @@ -245,19 +235,17 @@ const OnionAuthPrompt = (function () { _getKeyElement() { let xulDoc = this._browser.ownerDocument; - return xulDoc.getElementById(OnionAuthUtil.domid.keyElement); + return xulDoc.getElementById("tor-clientauth-notification-key"); }, _getCheckboxElement() { let xulDoc = this._browser.ownerDocument; - return xulDoc.getElementById(OnionAuthUtil.domid.checkboxElement); + return xulDoc.getElementById("tor-clientauth-persistkey-checkbox"); }, _showWarning(aWarningMessage) { let xulDoc = this._browser.ownerDocument; - let warningElem = xulDoc.getElementById( - OnionAuthUtil.domid.warningElement - ); + let warningElem = xulDoc.getElementById("tor-clientauth-warning"); let keyElem = this._getKeyElement(); if (warningElem) { if (aWarningMessage) { @@ -289,7 +277,7 @@ const OnionAuthPrompt = (function () { // a tor onion-auth file (which uses lowercase). let rawKey; try { - rawKey = CommonUtils.decodeBase32(aKeyString.toUpperCase()); + rawKey = lazy.CommonUtils.decodeBase32(aKeyString.toUpperCase()); } catch (e) {} if (rawKey) { @@ -313,24 +301,21 @@ const OnionAuthPrompt = (function () { let retval = { init() { - Services.obs.addObserver(this, OnionAuthUtil.topic.clientAuthMissing); - Services.obs.addObserver(this, OnionAuthUtil.topic.clientAuthIncorrect); + Services.obs.addObserver(this, topics.clientAuthMissing); + Services.obs.addObserver(this, topics.clientAuthIncorrect); }, uninit() { - Services.obs.removeObserver(this, OnionAuthUtil.topic.clientAuthMissing); - Services.obs.removeObserver( - this, - OnionAuthUtil.topic.clientAuthIncorrect - ); + Services.obs.removeObserver(this, topics.clientAuthMissing); + Services.obs.removeObserver(this, topics.clientAuthIncorrect); }, // aSubject is the DOM Window or browser where the prompt should be shown. // aData contains the .onion name. observe(aSubject, aTopic, aData) { if ( - aTopic != OnionAuthUtil.topic.clientAuthMissing && - aTopic != OnionAuthUtil.topic.clientAuthIncorrect + aTopic != topics.clientAuthMissing && + aTopic != topics.clientAuthIncorrect ) { return; } ===================================== browser/components/onionservices/content/authUtil.jsm deleted ===================================== @@ -1,25 +0,0 @@ -// Copyright (c) 2020, The Tor Project, Inc. - -"use strict"; - -var EXPORTED_SYMBOLS = ["OnionAuthUtil"]; - -const OnionAuthUtil = { - topic: { - clientAuthMissing: "tor-onion-services-clientauth-missing", - clientAuthIncorrect: "tor-onion-services-clientauth-incorrect", - }, - message: { - authPromptCanceled: "Tor:OnionServicesAuthPromptCanceled", - }, - domid: { - anchor: "tor-clientauth-notification-icon", - notification: "tor-clientauth", - description: "tor-clientauth-notification-desc", - learnMore: "tor-clientauth-notification-learnmore", - onionNameSpan: "tor-clientauth-notification-onionname", - keyElement: "tor-clientauth-notification-key", - warningElement: "tor-clientauth-warning", - checkboxElement: "tor-clientauth-persistkey-checkbox", - }, -}; ===================================== browser/components/onionservices/jar.mn ===================================== @@ -2,7 +2,6 @@ browser.jar: content/browser/onionservices/authPreferences.css (content/authPreferences.css) content/browser/onionservices/authPreferences.js (content/authPreferences.js) content/browser/onionservices/authPrompt.js (content/authPrompt.js) - content/browser/onionservices/authUtil.jsm (content/authUtil.jsm) content/browser/onionservices/netError/ (content/netError/*) content/browser/onionservices/onionservices.css (content/onionservices.css) content/browser/onionservices/savedKeysDialog.js (content/savedKeysDialog.js) ===================================== browser/components/torcircuit/content/torCircuitPanel.js ===================================== @@ -408,21 +408,6 @@ var gTorCircuitPanel = { return this._fallbackStringBundle.formatStringFromName(name, args); }, - /** - * Shorten the given address if it is an onion address. - * - * @param {string} address - The address to shorten. - * - * @returns {string} The shortened form of the address, or the address itself - * if it was not shortened. - */ - _shortenOnionAddress(address) { - if (!address.endsWith(".onion") || address.length <= 22) { - return address; - } - return `${address.slice(0, 7)}…${address.slice(-12)}`; - }, - /** * Updates the circuit display in the panel to show the current browser data. */ @@ -465,12 +450,12 @@ var gTorCircuitPanel = { this._panelElements.heading.textContent = this._getString( "torbutton.circuit_display.heading", // Only shorten the onion domain if it has no alias. - [onionAlias ? domain : this._shortenOnionAddress(domain)] + [TorUIUtils.shortenOnionAddress(domain)] ); if (onionAlias) { this._panelElements.aliasLink.textContent = - this._shortenOnionAddress(onionAlias); + TorUIUtils.shortenOnionAddress(onionAlias); if (scheme === "http" || scheme === "https") { // We assume the same scheme as the current page for the alias, which we // expect to be either http or https. @@ -521,7 +506,8 @@ var gTorCircuitPanel = { ); // Set the address that we want to copy. - this._panelElements.endItem.textContent = this._shortenOnionAddress(domain); + this._panelElements.endItem.textContent = + TorUIUtils.shortenOnionAddress(domain); // Button description text, depending on whether our first node was a // bridge, or otherwise a guard. ===================================== browser/modules/TorStrings.jsm ===================================== @@ -300,7 +300,6 @@ const Loader = { const retval = { learnMore: getString("learnMore", "Learn more"), - learnMoreURL: "about:manual#onion-services_onion-service-authentication", errorPage: { browser: getString("errorPage.browser", "Browser"), network: getString("errorPage.network", "Network"), ===================================== browser/modules/TorUIUtils.sys.mjs ===================================== @@ -0,0 +1,26 @@ +/** + * Common methods for tor UI components. + */ +export const TorUIUtils = { + /** + * Shorten the given address if it is an onion address. + * + * @param {string} address - The address to shorten. + * + * @returns {string} The shortened form of the address, or the address itself + * if it was not shortened. + */ + shortenOnionAddress(address) { + if ( + // Only shorten ".onion" addresses. + !address.endsWith(".onion") || + // That are not "onion" aliases. + address.endsWith(".tor.onion") || + // And are long. + address.length <= 21 + ) { + return address; + } + return `${address.slice(0, 6)}…${address.slice(-12)}`; + }, +}; ===================================== browser/modules/moz.build ===================================== @@ -152,6 +152,7 @@ EXTRA_JS_MODULES += [ "TorConnect.sys.mjs", "TorSettings.sys.mjs", "TorStrings.jsm", + "TorUIUtils.sys.mjs", "TransientPrefs.jsm", "URILoadingHelper.sys.mjs", "webrtcUI.jsm", View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/2760a7… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/2760a7… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 2176: Rebrand Firefox to TorBrowser
by Pier Angelo Vendrame (@pierov) 18 Sep '23

18 Sep '23
Pier Angelo Vendrame pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 2760a7b8 by Henry Wilkes at 2023-09-18T17:00:13+01:00 fixup! Bug 2176: Rebrand Firefox to TorBrowser Bug 41957: Use full tor browser icon for site identity button for internal pages. Also remove colors in tor-styles.css. - - - - - 11 changed files: - − browser/branding/tb-alpha/content/identity-icons-brand.svg - browser/branding/tb-alpha/content/jar.mn - − browser/branding/tb-alpha/content/tor-styles.css - − browser/branding/tb-nightly/content/identity-icons-brand.svg - browser/branding/tb-nightly/content/jar.mn - − browser/branding/tb-nightly/content/tor-styles.css - − browser/branding/tb-release/content/identity-icons-brand.svg - browser/branding/tb-release/content/jar.mn - − browser/branding/tb-release/content/tor-styles.css - browser/themes/shared/browser-shared.css - browser/themes/shared/identity-block/identity-block.css Changes: ===================================== browser/branding/tb-alpha/content/identity-icons-brand.svg deleted ===================================== @@ -1,8 +0,0 @@ -<svg fill="context-fill" fill-opacity="context-fill-opacity" viewBox="0 0 16 16" width="16" height="16" xmlns="http://www.w3.org/2000/svg"> - <g clip-rule="evenodd" fill-rule="evenodd"> - <path d="m11 8c0 1.65686-1.34314 3-3 3-1.65685 0-3-1.34314-3-3 0-1.65685 1.34315-3 3-3 1.65686 0 3 1.34315 3 3zm-1.17187 0c0 1.00965-.81848 1.82813-1.82813 1.82813-1.00964 0-1.82812-.81848-1.82812-1.82813 0-1.00964.81848-1.82812 1.82812-1.82812 1.00965 0 1.82813.81848 1.82813 1.82812z"/> - <path d="m7.99999 13.25c2.89951 0 5.25001-2.3505 5.25001-5.25001 0-2.89949-2.3505-5.25-5.25001-5.25-2.89949 0-5.25 2.35051-5.25 5.25 0 2.89951 2.35051 5.25001 5.25 5.25001zm0-1.1719c2.25231 0 4.07811-1.8258 4.07811-4.07811 0-2.25228-1.8258-4.07812-4.07811-4.07812-2.25228 0-4.07812 1.82584-4.07812 4.07812 0 2.25231 1.82584 4.07811 4.07812 4.07811z"/> - <path d="m8 15.5c4.1421 0 7.5-3.3579 7.5-7.5 0-4.14214-3.3579-7.5-7.5-7.5-4.14214 0-7.5 3.35786-7.5 7.5 0 4.1421 3.35786 7.5 7.5 7.5zm0-1.1719c3.4949 0 6.3281-2.8332 6.3281-6.3281 0-3.49493-2.8332-6.32812-6.3281-6.32812-3.49493 0-6.32812 2.83319-6.32812 6.32812 0 3.4949 2.83319 6.3281 6.32812 6.3281z"/> - </g> - <path d="m.5 8c0 4.1421 3.35786 7.5 7.5 7.5v-15c-4.14214 0-7.5 3.35786-7.5 7.5z"/> -</svg> \ No newline at end of file ===================================== browser/branding/tb-alpha/content/jar.mn ===================================== @@ -16,7 +16,5 @@ browser.jar: content/branding/icon64.png (../default64.png) content/branding/icon128.png (../default128.png) content/branding/icon256.png (../default256.png) - content/branding/identity-icons-brand.svg content/branding/aboutDialog.css content/branding/tor-browser-logo.svg - content/branding/tor-styles.css ===================================== browser/branding/tb-alpha/content/tor-styles.css deleted ===================================== @@ -1,11 +0,0 @@ -/* default theme*/ -:root { - --tor-branding-color: var(--teal-70); -} - -/* dark theme */ -@media (prefers-color-scheme: dark) { - :root { - --tor-branding-color: var(--teal-60); - } -} ===================================== browser/branding/tb-nightly/content/identity-icons-brand.svg deleted ===================================== @@ -1,8 +0,0 @@ -<svg fill="context-fill" fill-opacity="context-fill-opacity" viewBox="0 0 16 16" width="16" height="16" xmlns="http://www.w3.org/2000/svg"> - <g clip-rule="evenodd" fill-rule="evenodd"> - <path d="m11 8c0 1.65686-1.34314 3-3 3-1.65685 0-3-1.34314-3-3 0-1.65685 1.34315-3 3-3 1.65686 0 3 1.34315 3 3zm-1.17187 0c0 1.00965-.81848 1.82813-1.82813 1.82813-1.00964 0-1.82812-.81848-1.82812-1.82813 0-1.00964.81848-1.82812 1.82812-1.82812 1.00965 0 1.82813.81848 1.82813 1.82812z"/> - <path d="m7.99999 13.25c2.89951 0 5.25001-2.3505 5.25001-5.25001 0-2.89949-2.3505-5.25-5.25001-5.25-2.89949 0-5.25 2.35051-5.25 5.25 0 2.89951 2.35051 5.25001 5.25 5.25001zm0-1.1719c2.25231 0 4.07811-1.8258 4.07811-4.07811 0-2.25228-1.8258-4.07812-4.07811-4.07812-2.25228 0-4.07812 1.82584-4.07812 4.07812 0 2.25231 1.82584 4.07811 4.07812 4.07811z"/> - <path d="m8 15.5c4.1421 0 7.5-3.3579 7.5-7.5 0-4.14214-3.3579-7.5-7.5-7.5-4.14214 0-7.5 3.35786-7.5 7.5 0 4.1421 3.35786 7.5 7.5 7.5zm0-1.1719c3.4949 0 6.3281-2.8332 6.3281-6.3281 0-3.49493-2.8332-6.32812-6.3281-6.32812-3.49493 0-6.32812 2.83319-6.32812 6.32812 0 3.4949 2.83319 6.3281 6.32812 6.3281z"/> - </g> - <path d="m.5 8c0 4.1421 3.35786 7.5 7.5 7.5v-15c-4.14214 0-7.5 3.35786-7.5 7.5z"/> -</svg> \ No newline at end of file ===================================== browser/branding/tb-nightly/content/jar.mn ===================================== @@ -16,7 +16,5 @@ browser.jar: content/branding/icon64.png (../default64.png) content/branding/icon128.png (../default128.png) content/branding/icon256.png (../default256.png) - content/branding/identity-icons-brand.svg content/branding/aboutDialog.css content/branding/tor-browser-logo.svg - content/branding/tor-styles.css ===================================== browser/branding/tb-nightly/content/tor-styles.css deleted ===================================== @@ -1,11 +0,0 @@ -/* default theme*/ -:root { - --tor-branding-color: var(--blue-60); -} - -/* dark theme */ -@media (prefers-color-scheme: dark) { - :root { - --tor-branding-color: var(--blue-40); - } -} ===================================== browser/branding/tb-release/content/identity-icons-brand.svg deleted ===================================== @@ -1,8 +0,0 @@ -<svg fill="context-fill" fill-opacity="context-fill-opacity" viewBox="0 0 16 16" width="16" height="16" xmlns="http://www.w3.org/2000/svg"> - <g clip-rule="evenodd" fill-rule="evenodd"> - <path d="m11 8c0 1.65686-1.34314 3-3 3-1.65685 0-3-1.34314-3-3 0-1.65685 1.34315-3 3-3 1.65686 0 3 1.34315 3 3zm-1.17187 0c0 1.00965-.81848 1.82813-1.82813 1.82813-1.00964 0-1.82812-.81848-1.82812-1.82813 0-1.00964.81848-1.82812 1.82812-1.82812 1.00965 0 1.82813.81848 1.82813 1.82812z"/> - <path d="m7.99999 13.25c2.89951 0 5.25001-2.3505 5.25001-5.25001 0-2.89949-2.3505-5.25-5.25001-5.25-2.89949 0-5.25 2.35051-5.25 5.25 0 2.89951 2.35051 5.25001 5.25 5.25001zm0-1.1719c2.25231 0 4.07811-1.8258 4.07811-4.07811 0-2.25228-1.8258-4.07812-4.07811-4.07812-2.25228 0-4.07812 1.82584-4.07812 4.07812 0 2.25231 1.82584 4.07811 4.07812 4.07811z"/> - <path d="m8 15.5c4.1421 0 7.5-3.3579 7.5-7.5 0-4.14214-3.3579-7.5-7.5-7.5-4.14214 0-7.5 3.35786-7.5 7.5 0 4.1421 3.35786 7.5 7.5 7.5zm0-1.1719c3.4949 0 6.3281-2.8332 6.3281-6.3281 0-3.49493-2.8332-6.32812-6.3281-6.32812-3.49493 0-6.32812 2.83319-6.32812 6.32812 0 3.4949 2.83319 6.3281 6.32812 6.3281z"/> - </g> - <path d="m.5 8c0 4.1421 3.35786 7.5 7.5 7.5v-15c-4.14214 0-7.5 3.35786-7.5 7.5z"/> -</svg> \ No newline at end of file ===================================== browser/branding/tb-release/content/jar.mn ===================================== @@ -16,7 +16,5 @@ browser.jar: content/branding/icon64.png (../default64.png) content/branding/icon128.png (../default128.png) content/branding/icon256.png (../default256.png) - content/branding/identity-icons-brand.svg content/branding/aboutDialog.css content/branding/tor-browser-logo.svg - content/branding/tor-styles.css ===================================== browser/branding/tb-release/content/tor-styles.css deleted ===================================== @@ -1,11 +0,0 @@ -/* default theme*/ -:root { - --tor-branding-color: var(--purple-60); -} - -/* dark theme */ -@media (prefers-color-scheme: dark) { - :root { - --tor-branding-color: var(--purple-30); - } -} ===================================== browser/themes/shared/browser-shared.css ===================================== @@ -23,7 +23,6 @@ @import url("chrome://browser/skin/customizableui/customizeMode.css"); @import url("chrome://browser/skin/UITour.css"); @import url("chrome://browser/skin/browser-colors.css"); -@import url("chrome://branding/content/tor-styles.css"); @import url("chrome://browser/skin/tor-urlbar-button.css"); @import url("chrome://browser/skin/onionlocation.css"); ===================================== browser/themes/shared/identity-block/identity-block.css ===================================== @@ -53,10 +53,6 @@ border-radius: var(--urlbar-icon-border-radius); } -#identity-box[pageproxystate="valid"].chromeUI #identity-icon-label { - color: var(--tor-branding-color); -} - #identity-icon-label { padding-inline-start: 4px; } @@ -151,9 +147,12 @@ } #identity-box[pageproxystate="valid"].chromeUI #identity-icon { - list-style-image: url(chrome://branding/content/identity-icons-brand.svg); - fill: var(--tor-branding-color); - fill-opacity: 1; + list-style-image: url(chrome://branding/content/icon16.png); +} +@media (min-resolution: 1.1dppx) { + #identity-box[pageproxystate="valid"].chromeUI #identity-icon { + list-style-image: url(chrome://branding/content/icon32.png); + } } #identity-box[pageproxystate="valid"].localResource #identity-icon { View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/2760a7b… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/2760a7b… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] squash! Bug 2176: Rebrand Firefox to TorBrowser
by Pier Angelo Vendrame (@pierov) 18 Sep '23

18 Sep '23
Pier Angelo Vendrame pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: dec788d1 by Henry Wilkes at 2023-09-18T15:48:48+01:00 squash! Bug 2176: Rebrand Firefox to TorBrowser Bug 42088: New application icons (used in-app and on linux). - - - - - 30 changed files: - browser/branding/tb-alpha/content/tor-browser-logo.svg - browser/branding/tb-alpha/default128.png - browser/branding/tb-alpha/default16.png - browser/branding/tb-alpha/default22.png - browser/branding/tb-alpha/default24.png - browser/branding/tb-alpha/default256.png - browser/branding/tb-alpha/default32.png - browser/branding/tb-alpha/default48.png - browser/branding/tb-alpha/default64.png - − browser/branding/tb-alpha/firefox.svg - browser/branding/tb-nightly/content/tor-browser-logo.svg - browser/branding/tb-nightly/default128.png - browser/branding/tb-nightly/default16.png - browser/branding/tb-nightly/default22.png - browser/branding/tb-nightly/default24.png - browser/branding/tb-nightly/default256.png - browser/branding/tb-nightly/default32.png - browser/branding/tb-nightly/default48.png - browser/branding/tb-nightly/default64.png - − browser/branding/tb-nightly/firefox.svg - browser/branding/tb-release/content/tor-browser-logo.svg - browser/branding/tb-release/default128.png - browser/branding/tb-release/default16.png - browser/branding/tb-release/default22.png - browser/branding/tb-release/default24.png - browser/branding/tb-release/default256.png - browser/branding/tb-release/default32.png - browser/branding/tb-release/default48.png - browser/branding/tb-release/default64.png - − browser/branding/tb-release/firefox.svg The diff was not included because it is too large. View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/dec788d… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/dec788d… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-build][main] Update rbm for rbm#40061
by boklm (@boklm) 18 Sep '23

18 Sep '23
boklm pushed to branch main at The Tor Project / Applications / tor-browser-build Commits: 0e729d3f by Nicolas Vigier at 2023-09-18T16:50:16+02:00 Update rbm for rbm#40061 - - - - - 1 changed file: - rbm Changes: ===================================== rbm ===================================== @@ -1 +1 @@ -Subproject commit c4c1716dcbffa58c102daa8a5f3e188acdaf823a +Subproject commit fb51b232ea9281032762df30211400139ff80275 View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/0… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/0… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/rbm][main] Bug 40061: Log copy of input_files when the RBM_VERBOSE_LOG environment variable is set
by boklm (@boklm) 18 Sep '23

18 Sep '23
boklm pushed to branch main at The Tor Project / Applications / RBM Commits: fb51b232 by Nicolas Vigier at 2023-09-18T08:30:49+02:00 Bug 40061: Log copy of input_files when the RBM_VERBOSE_LOG environment variable is set - - - - - 1 changed file: - lib/RBM.pm Changes: ===================================== lib/RBM.pm ===================================== @@ -1229,6 +1229,10 @@ sub build_run { exec_name => 'put', exec_as_root => 0, }); + if ($ENV{RBM_VERBOSE_LOG}) { + my $now = localtime; + path($build_log)->append_utf8("[$now] Copying file $file\n"); + } if (run_script($project, $cmd, sub { system(@_) }) != 0) { $error = "Error uploading $file"; goto EXIT; View it on GitLab: https://gitlab.torproject.org/tpo/applications/rbm/-/commit/fb51b232ea92810… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/rbm/-/commit/fb51b232ea92810… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 31740: Remove some unnecessary RemoteSettings instances
by Pier Angelo Vendrame (@pierov) 18 Sep '23

18 Sep '23
Pier Angelo Vendrame pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 5d6218da by Pier Angelo Vendrame at 2023-09-18T11:16:31+02:00 fixup! Bug 31740: Remove some unnecessary RemoteSettings instances Bug 42083: RemoteSecuritySettings.init throws error in console - - - - - 1 changed file: - security/manager/ssl/RemoteSecuritySettings.sys.mjs Changes: ===================================== security/manager/ssl/RemoteSecuritySettings.sys.mjs ===================================== @@ -529,6 +529,10 @@ class CRLiteFilters { } async cleanAttachmentCache() { + if (!this.client) { + return; + } + // Bug 1795710 - misuse of Remote Settings `downloadToDisk` caused us to // keep filters and stashes on disk indefinitely. We're no longer caching // these downloads, so if there are any filters still in the cache they can View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/5d6218d… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/5d6218d… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/firefox-android][firefox-android-115.2.1-13.0-1] Bug 42074: 2023 year end campaign for tor browser HomeFragment
by Pier Angelo Vendrame (@pierov) 18 Sep '23

18 Sep '23
Pier Angelo Vendrame pushed to branch firefox-android-115.2.1-13.0-1 at The Tor Project / Applications / firefox-android Commits: 2ebfc4b7 by clairehurst at 2023-09-18T08:49:21+00:00 Bug 42074: 2023 year end campaign for tor browser HomeFragment - - - - - 1 changed file: - fenix/app/src/main/res/values/torbrowser_strings.xml Changes: ===================================== fenix/app/src/main/res/values/torbrowser_strings.xml ===================================== @@ -75,4 +75,30 @@ <!-- Onion location --> <string name="preferences_tor_prioritize_onions">Prioritize .onion sites</string> + + <!-- 2023 year-end-campaign. --> + + <!-- Large introduction text. --> + <string name="yec_2023_introduction">Right now, Tor Browser for Android is protecting your privacy!</string> + <!-- 2023 year-end-campaign. --> + <!-- The first part of yec_2023_pleas_donate_full. Split out from the full string to bring some styling attention to this part. Follows directly below yec_2023_introduction. --> + <string name="yec_2023_please_donate_beginning">This is possible because of donations from our community.</string> + <!-- 2023 year-end-campaign. --> + <!-- Full donation message. Follows directly below yec_2023_introduction. --> + <!-- %s will be replaced with the translated string of yec_2023_please_donate_beginning with some visual styling. --> + <string name="yec_2023_please_donate_full">%s If you value the privacy that Tor Browser for Android offers yourself and others, please make a donation today.</string> + <!-- 2023 year-end-campaign. --> + <!-- Shown only during a period where donations will be matched. The end date should match the end of the year. --> + <!-- %s will be replaced with the donation limit. This will be a whole-number and will be automatically pre-formatted according to the language/locale: using the language's numeral symbols and thousand-separators. --> + <!-- NOTE: The amount should be shown as USD (United States dollar) currency. In the original English string, the leading "$" is the literal USD currency symbol, and this can be changed or removed when translating to whatever is most appropriate for USD currency in the locale. The ending "!" is also the literal exclamation point and can be similarly changed. --> + <!-- For example, "$%s" for English would eventually be shown as "$5,000", whilst "%s US$" for Arabic would be shown as "٥٬٠٠٠ US$". --> + <!-- Translators: If you need any help or clarification, feel free to ask a question on weblate or in IRC (#tor-l10n). --> + <string name="yec_2023_matched_donation">From now until December 31, donations to the Tor Project will be matched one-to-one, up to $%s!</string> + <!-- 2023 year-end-campaign. --> + <string name="yec_2023_close_button">Close</string> + <!-- 2023 year-end-campaign. --> + <string name="yec_2023_donate_button">Donate now</string> + <!-- 2023 year-end-campaign. --> + <string name="yec_2023_free_to_use">Tor Browser for Android will always be free to use—no donation is required to use this app.</string> + </resources> View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/2eb… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/2eb… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 7494: Create local home page for TBB.
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 5813d89a by Henry Wilkes at 2023-09-15T20:18:20+00:00 fixup! Bug 7494: Create local home page for TBB. Bug 42073: Add onion pattern to about:tor background. - - - - - 3 changed files: - browser/components/abouttor/content/aboutTor.css - + browser/components/abouttor/content/onion-pattern.svg - browser/components/abouttor/jar.mn Changes: ===================================== browser/components/abouttor/content/aboutTor.css ===================================== @@ -20,6 +20,11 @@ body { / 1fr minmax(max-content, 600px) 1fr; justify-items: center; padding-inline: 20px; + background: + local + url("chrome://browser/content/abouttor/onion-pattern.svg") + center bottom + repeat-x; } h1 { ===================================== browser/components/abouttor/content/onion-pattern.svg ===================================== @@ -0,0 +1,27 @@ +<svg fill="none" height="150" viewBox="0 0 1200 150" width="1200" xmlns="http://www.w3.org/2000/svg"> + <path clip-rule="evenodd" d="m75 145c38.66 0 70-31.34 70-70 0-38.6599-31.34-70-70-70-38.6599 0-70 31.3401-70 70 0 38.66 31.3401 70 70 70zm0 5c41.421 0 75-33.579 75-75 0-41.4214-33.579-75-75-75-41.4214 0-75 33.5786-75 75 0 41.421 33.5786 75 75 75z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m75 126.25c28.305 0 51.25-22.945 51.25-51.25 0-28.3046-22.945-51.25-51.25-51.25-28.3046 0-51.25 22.9454-51.25 51.25 0 28.305 22.9454 51.25 51.25 51.25zm0 5c31.066 0 56.25-25.184 56.25-56.25s-25.184-56.25-56.25-56.25-56.25 25.184-56.25 56.25 25.184 56.25 56.25 56.25z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m75 107.5c17.9493 0 32.5-14.5507 32.5-32.5s-14.5507-32.5-32.5-32.5-32.5 14.5507-32.5 32.5 14.5507 32.5 32.5 32.5zm0 5c20.7107 0 37.5-16.7893 37.5-37.5s-16.7893-37.5-37.5-37.5-37.5 16.7893-37.5 37.5 16.7893 37.5 37.5 37.5z" fill="#3e0663" fill-rule="evenodd"/> + + <path clip-rule="evenodd" d="m75 88.75c7.5939 0 13.75-6.1561 13.75-13.75s-6.1561-13.75-13.75-13.75-13.75 6.1561-13.75 13.75 6.1561 13.75 13.75 13.75zm0 5c10.3553 0 18.75-8.3947 18.75-18.75s-8.3947-18.75-18.75-18.75-18.75 8.3947-18.75 18.75 8.3947 18.75 18.75 18.75z" fill="#3e0663" fill-rule="evenodd"/> + <path d="m294.846 0c2.762 0 5.017 2.24554 4.836 5.001-2.573 39.0897-35.095 69.999-74.836 69.999s-72.262-30.9093-74.836-69.999c-.181-2.75546 2.075-5.001 4.836-5.001z" fill="#3e0663"/> + <path d="m294.846 75c2.762 0 5.017 2.2455 4.836 5.001-2.573 39.09-35.095 69.999-74.836 69.999s-72.262-30.909-74.836-69.999c-.181-2.7555 2.075-5.001 4.836-5.001z" fill="#350556"/> + <path clip-rule="evenodd" d="m374.692 145c38.66 0 70-31.34 70-70 0-38.6599-31.34-70-70-70s-70 31.3401-70 70c0 38.66 31.34 70 70 70zm0 5c41.422 0 75-33.579 75-75 0-41.4214-33.578-75-75-75-41.421 0-75 33.5786-75 75 0 41.421 33.579 75 75 75z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m374.692 126.25c28.305 0 51.25-22.945 51.25-51.25 0-28.3046-22.945-51.25-51.25-51.25-28.304 0-51.25 22.9454-51.25 51.25 0 28.305 22.946 51.25 51.25 51.25zm0 5c31.066 0 56.25-25.184 56.25-56.25s-25.184-56.25-56.25-56.25-56.25 25.184-56.25 56.25 25.184 56.25 56.25 56.25z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m374.692 107.5c17.95 0 32.5-14.5507 32.5-32.5s-14.55-32.5-32.5-32.5c-17.949 0-32.5 14.5507-32.5 32.5s14.551 32.5 32.5 32.5zm0 5c20.711 0 37.5-16.7893 37.5-37.5s-16.789-37.5-37.5-37.5c-20.71 0-37.5 16.7893-37.5 37.5s16.79 37.5 37.5 37.5z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m374.692 88.75c7.594 0 13.75-6.1561 13.75-13.75s-6.156-13.75-13.75-13.75-13.75 6.1561-13.75 13.75 6.156 13.75 13.75 13.75zm0 5c10.356 0 18.75-8.3947 18.75-18.75s-8.394-18.75-18.75-18.75c-10.355 0-18.75 8.3947-18.75 18.75s8.395 18.75 18.75 18.75z" fill="#3e0663" fill-rule="evenodd"/> + <path d="m449.692 4.99998c0-2.76142 2.246-5.0173044 5.001-4.835902 39.09 2.573422 69.999 35.095022 69.999 74.835922 0 39.741-30.909 72.262-69.999 74.836-2.755.181-5.001-2.075-5.001-4.836z" fill="#3e0663"/> + <path d="m524.692 4.99998c0-2.76142 2.246-5.0173044 5.001-4.835902 39.09 2.573422 69.999 35.095022 69.999 74.835922 0 39.741-30.909 72.262-69.999 74.836-2.755.181-5.001-2.075-5.001-4.836z" fill="#350556"/> + <path clip-rule="evenodd" d="m674.692 145c38.66 0 70-31.34 70-70 0-38.6599-31.34-70-70-70s-70 31.3401-70 70c0 38.66 31.34 70 70 70zm0 5c41.422 0 75-33.579 75-75 0-41.4214-33.578-75-75-75-41.421 0-75 33.5786-75 75 0 41.421 33.579 75 75 75z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m674.692 126.25c28.305 0 51.25-22.945 51.25-51.25 0-28.3046-22.945-51.25-51.25-51.25-28.304 0-51.25 22.9454-51.25 51.25 0 28.305 22.946 51.25 51.25 51.25zm0 5c31.066 0 56.25-25.184 56.25-56.25s-25.184-56.25-56.25-56.25-56.25 25.184-56.25 56.25 25.184 56.25 56.25 56.25z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m674.692 107.5c17.95 0 32.5-14.5507 32.5-32.5s-14.55-32.5-32.5-32.5c-17.949 0-32.5 14.5507-32.5 32.5s14.551 32.5 32.5 32.5zm0 5c20.711 0 37.5-16.7893 37.5-37.5s-16.789-37.5-37.5-37.5c-20.71 0-37.5 16.7893-37.5 37.5s16.79 37.5 37.5 37.5z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m674.692 88.75c7.594 0 13.75-6.1561 13.75-13.75s-6.156-13.75-13.75-13.75-13.75 6.1561-13.75 13.75 6.156 13.75 13.75 13.75zm0 5c10.356 0 18.75-8.3947 18.75-18.75s-8.394-18.75-18.75-18.75c-10.355 0-18.75 8.3947-18.75 18.75s8.395 18.75 18.75 18.75z" fill="#3e0663" fill-rule="evenodd"/> + <path d="m894.538 0c2.762 0 5.018 2.24554 4.836 5.001-2.573 39.0897-35.095 69.999-74.836 69.999-39.74 0-72.262-30.9093-74.836-69.999-.181-2.75546 2.075-5.001 4.836-5.001z" fill="#3e0663"/> + <path d="m894.538 75c2.762 0 5.018 2.2455 4.836 5.001-2.573 39.09-35.095 69.999-74.836 69.999-39.74 0-72.262-30.909-74.836-69.999-.181-2.7555 2.075-5.001 4.836-5.001z" fill="#350556"/> + <path clip-rule="evenodd" d="m974.385 145c38.655 0 69.995-31.34 69.995-70 0-38.6599-31.34-70-69.995-70-38.66 0-70 31.3401-70 70 0 38.66 31.34 70 70 70zm0 5c41.425 0 74.995-33.579 74.995-75 0-41.4214-33.57-75-74.995-75-41.422 0-75 33.5786-75 75 0 41.421 33.578 75 75 75z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m974.385 126.25c28.305 0 51.245-22.945 51.245-51.25 0-28.3046-22.94-51.25-51.245-51.25s-51.25 22.9454-51.25 51.25c0 28.305 22.945 51.25 51.25 51.25zm0 5c31.065 0 56.245-25.184 56.245-56.25s-25.18-56.25-56.245-56.25c-31.066 0-56.25 25.184-56.25 56.25s25.184 56.25 56.25 56.25z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m974.385 107.5c17.949 0 32.495-14.5507 32.495-32.5s-14.546-32.5-32.495-32.5c-17.95 0-32.5 14.5507-32.5 32.5s14.55 32.5 32.5 32.5zm0 5c20.71 0 37.495-16.7893 37.495-37.5s-16.785-37.5-37.495-37.5c-20.711 0-37.5 16.7893-37.5 37.5s16.789 37.5 37.5 37.5z" fill="#3e0663" fill-rule="evenodd"/> + <path clip-rule="evenodd" d="m974.385 88.75c7.593 0 13.75-6.1561 13.75-13.75s-6.157-13.75-13.75-13.75c-7.594 0-13.75 6.1561-13.75 13.75s6.156 13.75 13.75 13.75zm0 5c10.355 0 18.75-8.3947 18.75-18.75s-8.395-18.75-18.75-18.75c-10.356 0-18.75 8.3947-18.75 18.75s8.394 18.75 18.75 18.75z" fill="#3e0663" fill-rule="evenodd"/> + <path d="m1199.38 145c0 2.761-2.24 5.017-5 4.836-39.09-2.573-70-35.095-70-74.836 0-39.7409 30.91-72.26248 70-74.835903 2.76-.1814017 5 2.074493 5 4.835913z" fill="#3e0663"/> + <path d="m1124.38 145c0 2.761-2.24 5.017-5 4.836-39.09-2.573-70-35.095-70-74.836 0-39.7409 30.91-72.26248 70-74.835903 2.76-.1814017 5 2.074493 5 4.835913z" fill="#350556"/> +</svg> ===================================== browser/components/abouttor/jar.mn ===================================== @@ -7,3 +7,4 @@ browser.jar: content/browser/abouttor/26a1-high-voltage.svg (content/26a1-high-voltage.svg) content/browser/abouttor/2728-sparkles.svg (content/2728-sparkles.svg) content/browser/abouttor/2764-red-heart.svg (content/2764-red-heart.svg) + content/browser/abouttor/onion-pattern.svg (content/onion-pattern.svg) View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/5813d89… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/5813d89… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 30237: Add v3 onion services client authentication prompt
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 0ce95033 by Henry Wilkes at 2023-09-15T20:11:51+00:00 fixup! Bug 30237: Add v3 onion services client authentication prompt Bug 42092: Fix layout styling of saved onion keys dialog. - - - - - 3 changed files: - browser/components/onionservices/content/authPreferences.css - browser/components/onionservices/content/savedKeysDialog.js - browser/components/onionservices/content/savedKeysDialog.xhtml Changes: ===================================== browser/components/onionservices/content/authPreferences.css ===================================== @@ -3,7 +3,11 @@ @import url("chrome://browser/skin/browser-colors.css"); #torOnionServiceKeys-overview-container { - margin-right: 30px; + margin-inline-end: 30px; +} + +#onionservices-savedkeys-dialog { + min-width: 45em; } #onionservices-savedkeys-tree treechildren::-moz-tree-cell-text { @@ -11,14 +15,17 @@ } #onionservices-savedkeys-errorContainer { - margin-top: 4px; + margin-block-start: 4px; min-height: 3em; } +#onionservices-savedkeys-errorContainer:not(.show-error) { + visibility: hidden; +} + #onionservices-savedkeys-errorIcon { - margin-right: 4px; + margin-inline-end: 4px; list-style-image: url("chrome://global/skin/icons/warning.svg"); -moz-context-properties: fill; fill: var(--warning-color); - visibility: hidden; } ===================================== browser/components/onionservices/content/savedKeysDialog.js ===================================== @@ -189,10 +189,10 @@ var gOnionServicesSavedKeysDialog = { }, _showError(aMessage) { - const dialog = document.querySelector(this.selector.dialog); - const errorIcon = dialog.querySelector(this.selector.errorIcon); - errorIcon.style.visibility = aMessage ? "visible" : "hidden"; - const errorDesc = dialog.querySelector(this.selector.errorMessage); + document + .getElementById("onionservices-savedkeys-errorContainer") + .classList.toggle("show-error", !!aMessage); + const errorDesc = document.querySelector(this.selector.errorMessage); errorDesc.textContent = aMessage ? aMessage : ""; }, ===================================== browser/components/onionservices/content/savedKeysDialog.xhtml ===================================== @@ -9,7 +9,6 @@ id="onionservices-savedkeys-dialog" windowtype="OnionServices:SavedKeys" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - style="width: 45em" > <script src="chrome://browser/content/onionservices/savedKeysDialog.js" /> @@ -23,8 +22,6 @@ id="onionservices-savedkeys-tree" flex="1" hidecolumnpicker="true" - width="750" - style="height: 20em" onselect="gOnionServicesSavedKeysDialog.updateButtonsState();" > <treecols> @@ -38,7 +35,7 @@ </treecols> <treechildren /> </tree> - <hbox id="onionservices-savedkeys-errorContainer" align="baseline" flex="1"> + <hbox id="onionservices-savedkeys-errorContainer" align="center"> <image id="onionservices-savedkeys-errorIcon" /> <description id="onionservices-savedkeys-errorMessage" flex="1" /> </hbox> View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0ce9503… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0ce9503… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 27476: Implement about:torconnect captive portal within Tor Browser
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 3d4edb72 by Henry Wilkes at 2023-09-15T18:51:48+00:00 fixup! Bug 27476: Implement about:torconnect captive portal within Tor Browser Bug 42079: Support moving out of the TorConnectState.Bootsrapped state for gTorConnectTitlebarStatus and gTorConnectUrlbarButton. - - - - - 2 changed files: - browser/components/torconnect/content/torConnectTitlebarStatus.js - browser/components/torconnect/content/torConnectUrlbarButton.js Changes: ===================================== browser/components/torconnect/content/torConnectTitlebarStatus.js ===================================== @@ -72,7 +72,6 @@ var gTorConnectTitlebarStatus = { this.node.hidden = true; return; case TorConnectState.Bootstrapped: - this._startHiding(); textId = "titlebarStatusConnected"; connected = true; break; @@ -114,6 +113,14 @@ var gTorConnectTitlebarStatus = { ); this.node.classList.toggle("tor-connect-status-connected", connected); this.connected = connected; + if (connected) { + this._startHiding(); + } else { + // We can leave the connected state when we are no longer Bootstrapped + // because the underlying tor process exited early and needs a + // restart. In this case we want to re-show the status. + this._stopHiding(); + } } this.node.classList.toggle( "tor-connect-status-potentially-blocked", @@ -125,8 +132,23 @@ var gTorConnectTitlebarStatus = { * Mark the component to be hidden after some delay. */ _startHiding() { - setTimeout(() => { + if (this._hidingTimeout) { + // Already hiding. + return; + } + this._hidingTimeout = setTimeout(() => { this.node.hidden = true; }, 5000); }, + + /** + * Re-show the component immediately. + */ + _stopHiding() { + if (this._hidingTimeout) { + clearTimeout(this._hidingTimeout); + this._hidingTimeout = 0; + } + this.node.hidden = false; + }, }; ===================================== browser/components/torconnect/content/torConnectUrlbarButton.js ===================================== @@ -112,10 +112,10 @@ var gTorConnectUrlbarButton = { * Callback for when the TorConnect state changes. */ _torConnectStateChanged() { - if ( - TorConnect.state === TorConnectState.Bootstrapped || - TorConnect.state === TorConnectState.Disabled - ) { + if (TorConnect.state === TorConnectState.Disabled) { + // NOTE: We do not uninit early when we reach the + // TorConnectState.Bootstrapped state because we can still leave the + // Bootstrapped state if the tor process exists early and needs a restart. this.uninit(); return; } View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/3d4edb7… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/3d4edb7… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Bug 40933: Add tor-launcher functionality
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: a4ff8505 by Pier Angelo Vendrame at 2023-09-15T18:31:31+00:00 fixup! Bug 40933: Add tor-launcher functionality Bug 42102: Fix checkPort in TorProcess - - - - - 2 changed files: - toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs - toolkit/components/tor-launcher/TorProcess.sys.mjs Changes: ===================================== toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs ===================================== @@ -8,7 +8,7 @@ const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { - FileUtils: "resource://gre/modules/FileUtils.sys.jsm", + FileUtils: "resource://gre/modules/FileUtils.sys.mjs", }); const kPropBundleURI = "chrome://torbutton/locale/torlauncher.properties"; @@ -565,7 +565,7 @@ export const TorLauncherUtil = Object.freeze({ } if (useIPC === undefined) { - socksPortInfo.useIPC = + useIPC = !this.isWindows && Services.prefs.getBoolPref( "extensions.torlauncher.socks_port_use_ipc", @@ -574,7 +574,7 @@ export const TorLauncherUtil = Object.freeze({ } // Fill in missing SOCKS info from prefs. - if (socksPortInfo.useIPC) { + if (useIPC) { if (!socksPortInfo.ipcFile) { socksPortInfo.ipcFile = TorLauncherUtil.getTorFile("socks_ipc", false); } @@ -611,7 +611,7 @@ export const TorLauncherUtil = Object.freeze({ return; } - if (socksPortInfo.useIPC) { + if (socksPortInfo.ipcFile) { const fph = Services.io .getProtocolHandler("file") .QueryInterface(Ci.nsIFileProtocolHandler); ===================================== toolkit/components/tor-launcher/TorProcess.sys.mjs ===================================== @@ -49,9 +49,7 @@ export class TorProcess { const checkPort = port => port === undefined || - (Number.isInteger(controlSettings.port) && - controlSettings.port > 0 && - controlSettings.port < 65535); + (Number.isInteger(port) && port > 0 && port < 65535); if (!checkPort(controlSettings?.port)) { throw new Error("Invalid control port"); } View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a4ff850… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a4ff850… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] 2 commits: fixup! Bug 41649: Create rebase and security backport gitlab issue templates
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: 0a8b54dc by Pier Angelo Vendrame at 2023-09-15T17:39:33+00:00 fixup! Bug 41649: Create rebase and security backport gitlab issue templates Add a step to make the default branch and add how to find a tag when it does not exist yet. - - - - - bbfe9bf0 by Pier Angelo Vendrame at 2023-09-15T17:39:33+00:00 fixup! Adding issue and merge request templates Do not assign to new issue to nah anymore - - - - - 2 changed files: - .gitlab/issue_templates/Rebase Browser - Alpha.md - − .gitlab/issue_templates/UXBug.md Changes: ===================================== .gitlab/issue_templates/Rebase Browser - Alpha.md ===================================== @@ -39,10 +39,21 @@ - **Allowed to merge**: `Maintainers` - **Allowed to push and merge**: `Maintainers` - **Allowed to force push**: `false` + - If you copied and pasted from old rules, double check you didn't add spaces at the end, as GitLab will not trim them! ### **Create New Branches** -- [ ] Create new alpha `base-browser` branch from Firefox mercurial tag (found during the stable rebase) +- [ ] Find the Firefox mercurial tag `$(ESR_TAG)` + - If `$(BROWSER_MINOR)` is 5, the tag should already exist from the stable release + - Otherwise: + - [ ] Go to `https://hg.mozilla.org/releases/mozilla-esr$(ESR_MAJOR)/tags` + - [ ] Find and inspect the commit tagged with `$(ESR_TAG)` + - Tags are in yellow in the Mercurial web UI + - [ ] Find the equivalent commit in `https://github.com/mozilla/gecko-dev/commits/esr$(ESR_MAJOR)` + - The tag should be very close to `HEAD` (usually the second, before a `No bug - Tagging $(HG_HASH) with $(ESR_TAG)`) + - **Notice**: GitHub sorts commits by time, you might want to use `git log gecko-dev/esr$(ESR_MAJOR)` locally, instead + - [ ] Sign/Tag the `gecko-dev` commit: `git tag -as $(ESR_TAG) $(GIT_HASH) -m "Hg tag $(ESR_TAG)"` +- [ ] Create new alpha `base-browser` branch from Firefox mercurial tag - Branch name in the form: `base-browser-$(ESR_VERSION)esr-$(BROWSER_MAJOR).$(BROWSER_MINOR)-1` - **Example**: `base-browser-102.8.0esr-12.5-1` - [ ] Create new alpha `tor-browser` branch from Firefox mercurial tag @@ -111,6 +122,11 @@ - Update and push `base-browser` branch - [ ] Reset the new `base-browser` branch to the appropriate commit in this new `tor-browser` branch - [ ] Push these commits to `upstream` +- [ ] Set `$(TOR_BROWSER_BRANCH)` as the default GitLab branch + - [ ] Go to [Repository Settings](https://gitlab.torproject.org/tpo/applications/tor-browser/-/sett… + - [ ] Expand `Branch defaults` + - [ ] Set the branch and leave the `Auto-close` checkbox unchecked + - [ ] Save changes ### **Sign and Tag** ===================================== .gitlab/issue_templates/UXBug.md deleted ===================================== @@ -1,29 +0,0 @@ -<!-- -* Use this issue template for reporting a new UX bug. ---> - -### Summary -**Summarize the bug encountered concisely.** - - -### Steps to reproduce: -**How one can reproduce the issue - this is very important.** - -1. Step 1 -2. Step 2 -3. ... - -### What is the current bug behavior? -**What actually happens.** - - -### What is the expected behavior? -**What you want to see instead** - - - -## Relevant logs and/or screenshots -**Do you have screenshots? Attach them to this ticket please.** - -/label ~tor-ux ~needs-investigation ~bug -/assign @nah View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/cd0362… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/cd0362… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/firefox-android][firefox-android-115.2.1-13.0-1] fixup! Adding gitlab merge request template
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch firefox-android-115.2.1-13.0-1 at The Tor Project / Applications / firefox-android Commits: 985b6697 by Richard Pospesel at 2023-09-15T17:36:58+00:00 fixup! Adding gitlab merge request template moved misc/other to the endof the list as a fallback - - - - - 1 changed file: - .gitlab/merge_request_templates/default.md Changes: ===================================== .gitlab/merge_request_templates/default.md ===================================== @@ -41,12 +41,12 @@ - **frontend (review)** : donuts, richard - **localization** : henry, pierov - **macos** : clairehurst, dan - - **misc/other** : pierov, richard - **nightly builds** : boklm - **rebases/release-prep** : dan, ma1, pierov, richard - **security** : ma1 - **signing** : boklm, richard - **updater** : pierov + - **misc/other** : pierov, richard #### Change Description View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/985… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/firefox-android/-/commit/985… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-build][main] fixup! Updated default merge request template
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch main at The Tor Project / Applications / tor-browser-build Commits: d850df4e by Richard Pospesel at 2023-09-15T17:31:51+00:00 fixup! Updated default merge request template moved misc/other back to bottom since its meant as a fallback - - - - - 1 changed file: - .gitlab/merge_request_templates/default.md Changes: ===================================== .gitlab/merge_request_templates/default.md ===================================== @@ -42,12 +42,12 @@ - **frontend (review)** : donuts, richard - **localization** : henry, pierov - **macos** : clairehurst, dan - - **misc/other** : pierov, richard - **nightly builds** : boklm - **rebases/release-prep** : dan, ma1, pierov, richard - **security** : ma1 - **signing** : boklm, richard - **updater** : pierov + - **misc/other** : pierov, richard #### Change Description View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/d… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/d… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][base-browser-115.2.1esr-13.0-1] fixup! Adding issue and merge request templates
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch base-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: a4da2726 by Richard Pospesel at 2023-09-15T17:29:19+00:00 fixup! Adding issue and merge request templates - - - - - 1 changed file: - .gitlab/merge_request_templates/default.md Changes: ===================================== .gitlab/merge_request_templates/default.md ===================================== @@ -38,7 +38,7 @@ - [ ] Request review from an applications developer depending on modified system: - **NOTE**: if the MR modifies multiple areas, please `/cc` all the relevant reviewers (since gitlab only allows 1 reviewer) - **accessibility** : henry - - **android** : dan + - **android** : clairehurst, dan - **build system** : boklm - **extensions** : ma1 - **firefox internals (XUL/JS/XPCOM)** : ma1 @@ -46,8 +46,9 @@ - **frontend (implementation)** : henry - **frontend (review)** : donuts, richard - **localization** : henry, pierov + - **macos** : clairehurst, dan - **nightly builds** : boklm - - **rebases/release-prep** : dan_b, ma1, pierov, richard + - **rebases/release-prep** : dan, ma1, pierov, richard - **security** : ma1 - **signing** : boklm, richard - **updater** : pierov @@ -56,3 +57,7 @@ #### Change Description <!-- Whatever context the reviewer needs to effectively review the patchset; if the patch includes UX updates be sure to include screenshots/video of how any new behaviour --> + +#### How Tested + +<!-- Description of steps taken to verify the change --> \ No newline at end of file View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a4da272… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/a4da272… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] fixup! Adding issue and merge request templates
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: cd03624c by Richard Pospesel at 2023-09-15T17:27:18+00:00 fixup! Adding issue and merge request templates - - - - - 1 changed file: - .gitlab/merge_request_templates/default.md Changes: ===================================== .gitlab/merge_request_templates/default.md ===================================== @@ -38,7 +38,7 @@ - [ ] Request review from an applications developer depending on modified system: - **NOTE**: if the MR modifies multiple areas, please `/cc` all the relevant reviewers (since gitlab only allows 1 reviewer) - **accessibility** : henry - - **android** : dan + - **android** : clairehurst, dan - **build system** : boklm - **extensions** : ma1 - **firefox internals (XUL/JS/XPCOM)** : ma1 @@ -46,8 +46,9 @@ - **frontend (implementation)** : henry - **frontend (review)** : donuts, richard - **localization** : henry, pierov + - **macos** : clairehurst, dan - **nightly builds** : boklm - - **rebases/release-prep** : dan_b, ma1, pierov, richard + - **rebases/release-prep** : dan, ma1, pierov, richard - **security** : ma1 - **signing** : boklm, richard - **updater** : pierov @@ -56,3 +57,7 @@ #### Change Description <!-- Whatever context the reviewer needs to effectively review the patchset; if the patch includes UX updates be sure to include screenshots/video of how any new behaviour --> + +#### How Tested + +<!-- Description of steps taken to verify the change --> \ No newline at end of file View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/cd03624… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/cd03624… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-build][main] Updated default merge request template
by richard (@richard) 15 Sep '23

15 Sep '23
richard pushed to branch main at The Tor Project / Applications / tor-browser-build Commits: f544324a by Richard Pospesel at 2023-09-15T17:07:38+00:00 Updated default merge request template - - - - - 1 changed file: - .gitlab/merge_request_templates/default.md Changes: ===================================== .gitlab/merge_request_templates/default.md ===================================== @@ -33,7 +33,7 @@ - [ ] Request review from an applications developer depending on modified system: - **NOTE**: if the MR modifies multiple areas, please `/cc` all the relevant reviewers (since gitlab only allows 1 reviewer) - **accessibility** : henry - - **android** : dan + - **android** : clairehurst, dan - **build system** : boklm - **extensions** : ma1 - **firefox internals (XUL/JS/XPCOM)** : ma1 @@ -41,13 +41,18 @@ - **frontend (implementation)** : henry - **frontend (review)** : donuts, richard - **localization** : henry, pierov + - **macos** : clairehurst, dan + - **misc/other** : pierov, richard - **nightly builds** : boklm - - **rebases/release-prep** : dan_b, ma1, pierov, richard + - **rebases/release-prep** : dan, ma1, pierov, richard - **security** : ma1 - **signing** : boklm, richard - **updater** : pierov - - **misc/other** : pierov, richard #### Change Description <!-- Whatever context the reviewer needs to effectively review the patchset; if the patch includes UX updates be sure to include screenshots/video of how any new behaviour --> + +#### How Tested + +<!-- Description of steps taken to verify the change --> \ No newline at end of file View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/f… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/f… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser][tor-browser-115.2.1esr-13.0-1] 25 commits: fixup! Bug 40933: Add tor-launcher functionality
by Pier Angelo Vendrame (@pierov) 14 Sep '23

14 Sep '23
Pier Angelo Vendrame pushed to branch tor-browser-115.2.1esr-13.0-1 at The Tor Project / Applications / Tor Browser Commits: acebcc4c by Pier Angelo Vendrame at 2023-09-14T19:11:10+02:00 fixup! Bug 40933: Add tor-launcher functionality Deleted old stuff, unified TorController with ControlSocket, simplified everything (e.g., do not use the dispatcher anymore, just call stuff directly or use a much simpler map). - - - - - 96edc001 by Pier Angelo Vendrame at 2023-09-14T19:11:11+02:00 fixup! Bug 40933: Add tor-launcher functionality Use `#` instead of `_` for private things here and there, to make reviewing the changes easier. - - - - - a2eebe17 by Pier Angelo Vendrame at 2023-09-14T19:11:12+02:00 fixup! Bug 40933: Add tor-launcher functionality Shuffle code here and there, so that it&#39;s feasible to check that nothing actually changed with `git diff --color-moved`. - - - - - 545ab0f1 by Pier Angelo Vendrame at 2023-09-14T19:11:12+02:00 fixup! Bug 40933: Add tor-launcher functionality Further refactors/improvements. - - - - - fb7bb380 by Pier Angelo Vendrame at 2023-09-14T19:11:13+02:00 fixup! Bug 40597: Implement TorSettings module Workaround for a race condition. - - - - - ae07f248 by Pier Angelo Vendrame at 2023-09-14T19:11:13+02:00 fixup! Bug 40933: Add tor-launcher functionality Refactored the settings reading, the first connection and events setup. - - - - - dc538277 by Pier Angelo Vendrame at 2023-09-14T19:11:14+02:00 fixup! Bug 27476: Implement about:torconnect captive portal within Tor Browser Fixed another race condition and moved to ES modules while I was touching this code. - - - - - 52144e2b by Pier Angelo Vendrame at 2023-09-14T19:11:14+02:00 fixup! Bug 40933: Add tor-launcher functionality Moved the control port parsing for asynchronous events from TorProvider to TorControlPort. - - - - - d5c6fb9e by Pier Angelo Vendrame at 2023-09-14T19:11:15+02:00 fixup! Bug 40933: Add tor-launcher functionality Bug 41986: Fix the control port password handling - - - - - f28fe46a by Pier Angelo Vendrame at 2023-09-14T19:11:15+02:00 fixup! Bug 40933: Add tor-launcher functionality - - - - - 5dd564d5 by Pier Angelo Vendrame at 2023-09-14T19:11:16+02:00 fixup! Bug 40933: Add tor-launcher functionality Second chunk of changes requested during the review. - - - - - ebd23167 by Pier Angelo Vendrame at 2023-09-14T19:11:16+02:00 fixup! Add TorStrings module for localization Marked tor_controlconn_failed as a 12.5-only - - - - - 44347a46 by Pier Angelo Vendrame at 2023-09-14T19:11:17+02:00 fixup! Bug 40933: Add tor-launcher functionality Change the provider buidler to make build async and other fixes. - - - - - 700bbaba by Pier Angelo Vendrame at 2023-09-14T19:11:17+02:00 fixup! Bug 40597: Implement TorSettings module The provider building is now async. - - - - - d8c5d36e by Pier Angelo Vendrame at 2023-09-14T19:11:17+02:00 fixup! Bug 30237: Add v3 onion services client authentication prompt The provider building is now async. - - - - - 47a17382 by Pier Angelo Vendrame at 2023-09-14T19:11:18+02:00 fixup! Bug 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection The provider building is now async. - - - - - 8d5ec618 by Pier Angelo Vendrame at 2023-09-14T19:11:18+02:00 fixup! Bug 3455: Add DomainIsolator, for isolating circuit by domain. The provider building is now async. - - - - - 11e651cc by Pier Angelo Vendrame at 2023-09-14T19:11:19+02:00 fixup! Bug 41668: Tweaks to the Base Browser updater for Tor Browser The provider building is now async. - - - - - 7019179e by Pier Angelo Vendrame at 2023-09-14T19:11:19+02:00 fixup! Bug 30237: Add v3 onion services client authentication prompt Fix possible race conditions on the busy state. - - - - - 491b730b by Pier Angelo Vendrame at 2023-09-14T19:11:20+02:00 fixup! Bug 40933: Add tor-launcher functionality Make the restart case stronger. - - - - - a4f54a1d by Pier Angelo Vendrame at 2023-09-14T19:11:20+02:00 fixup! Bug 40933: Add tor-launcher functionality Move the restart to the ProviderBuilder. - - - - - f291f9b4 by Pier Angelo Vendrame at 2023-09-14T19:11:21+02:00 fixup! Bug 40597: Implement TorSettings module Set the state back to Configure when the tor process exits, and disable qiuckstart. We should also show the &quot;Not Connected&quot; pill again. - - - - - 255fd5d3 by henry at 2023-09-14T19:11:21+02:00 fixup! Bug 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection Added some error handling for the cases in which the Tor provider failed to build. - - - - - 725d46c1 by Pier Angelo Vendrame at 2023-09-14T19:11:22+02:00 fixup! Bug 30237: Add v3 onion services client authentication prompt Re-build the provider every time we need it, since it might change now. - - - - - 00986a07 by Pier Angelo Vendrame at 2023-09-14T19:11:22+02:00 fixup! Bug 40933: Add tor-launcher functionality Addressed more requests from the review, and added documentation. - - - - - 23 changed files: - browser/components/BrowserGlue.sys.mjs - browser/components/onionservices/content/authPrompt.js - browser/components/onionservices/content/savedKeysDialog.js - − browser/components/torconnect/TorConnectChild.jsm - + browser/components/torconnect/TorConnectChild.sys.mjs - browser/components/torconnect/TorConnectParent.jsm → browser/components/torconnect/TorConnectParent.sys.mjs - browser/components/torconnect/moz.build - browser/components/torpreferences/content/connectionPane.js - browser/components/torpreferences/content/torLogDialog.jsm - browser/modules/Moat.sys.mjs - browser/modules/TorConnect.sys.mjs - browser/modules/TorSettings.sys.mjs - toolkit/components/tor-launcher/TorBootstrapRequest.sys.mjs - toolkit/components/tor-launcher/TorControlPort.sys.mjs - toolkit/components/tor-launcher/TorDomainIsolator.sys.mjs - toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs - toolkit/components/tor-launcher/TorParsers.sys.mjs - toolkit/components/tor-launcher/TorProcess.sys.mjs - toolkit/components/tor-launcher/TorProvider.sys.mjs - toolkit/components/tor-launcher/TorProviderBuilder.sys.mjs - toolkit/components/tor-launcher/TorStartupService.sys.mjs - toolkit/mozapps/update/UpdateService.sys.mjs - toolkit/torbutton/chrome/locale/en-US/torlauncher.properties Changes: ===================================== browser/components/BrowserGlue.sys.mjs ===================================== @@ -67,6 +67,7 @@ ChromeUtils.defineESModuleGetters(lazy, { "resource://messaging-system/lib/SpecialMessageActions.sys.mjs", TRRRacer: "resource:///modules/TRRPerformance.sys.mjs", TelemetryUtils: "resource://gre/modules/TelemetryUtils.sys.mjs", + TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs", UIState: "resource://services-sync/UIState.sys.mjs", UrlbarPrefs: "resource:///modules/UrlbarPrefs.sys.mjs", WebChannel: "resource://gre/modules/WebChannel.sys.mjs", @@ -772,10 +773,10 @@ let JSWINDOWACTORS = { TorConnect: { parent: { - moduleURI: "resource:///modules/TorConnectParent.jsm", + esModuleURI: "resource:///actors/TorConnectParent.sys.mjs", }, child: { - moduleURI: "resource:///modules/TorConnectChild.jsm", + esModuleURI: "resource:///actors/TorConnectChild.sys.mjs", events: { DOMWindowCreated: {}, }, @@ -1750,6 +1751,8 @@ BrowserGlue.prototype = { lazy.DragDropFilter.init(); + lazy.TorProviderBuilder.firstWindowLoaded(); + this._firstWindowTelemetry(aWindow); this._firstWindowLoaded(); ===================================== browser/components/onionservices/content/authPrompt.js ===================================== @@ -179,12 +179,12 @@ const OnionAuthPrompt = (function () { }, async _onDone() { - let keyElem = this._getKeyElement(); + const keyElem = this._getKeyElement(); if (!keyElem) { return; } - let base64key = this._keyToBase64(keyElem.value); + const base64key = this._keyToBase64(keyElem.value); if (!base64key) { this._showWarning(TorStrings.onionServices.authPrompt.invalidKey); return; @@ -192,8 +192,7 @@ const OnionAuthPrompt = (function () { this._prompt.remove(); - // Use Torbutton's controller module to add the private key to Tor. - let controllerFailureMsg = + const controllerFailureMsg = TorStrings.onionServices.authPrompt.failedToSetKey; try { // ^(subdomain.)*onionserviceid.onion$ (case-insensitive) @@ -204,29 +203,19 @@ const OnionAuthPrompt = (function () { .match(onionServiceIdRegExp) .groups.onionServiceId.toLowerCase(); - let checkboxElem = this._getCheckboxElement(); - let isPermanent = checkboxElem && checkboxElem.checked; - TorProviderBuilder.build() - .onionAuthAdd(onionServiceId, base64key, isPermanent) - .then(aResponse => { - // Success! Reload the page. - this._browser.sendMessageToActor( - "Browser:Reload", - {}, - "BrowserTab" - ); - }) - .catch(aError => { - if (aError.torMessage) { - this.show(aError.torMessage); - } else { - console.error(controllerFailureMsg, aError); - this.show(controllerFailureMsg); - } - }); + const checkboxElem = this._getCheckboxElement(); + const isPermanent = checkboxElem && checkboxElem.checked; + const provider = await TorProviderBuilder.build(); + await provider.onionAuthAdd(onionServiceId, base64key, isPermanent); + // Success! Reload the page. + this._browser.sendMessageToActor("Browser:Reload", {}, "BrowserTab"); } catch (e) { - console.error(controllerFailureMsg, e); - this.show(controllerFailureMsg); + if (e.torMessage) { + this.show(e.torMessage); + } else { + console.error(controllerFailureMsg, e); + this.show(controllerFailureMsg); + } } }, ===================================== browser/components/onionservices/content/savedKeysDialog.js ===================================== @@ -26,42 +26,46 @@ var gOnionServicesSavedKeysDialog = { }, _tree: undefined, - _isBusy: false, // true when loading data, deleting a key, etc. + _busyCount: 0, + get _isBusy() { + // true when loading data, deleting a key, etc. + return this._busyCount > 0; + }, // Public functions (called from outside this file). async deleteSelectedKeys() { - this._setBusyState(true); - - const indexesToDelete = []; - const count = this._tree.view.selection.getRangeCount(); - for (let i = 0; i < count; ++i) { - const minObj = {}; - const maxObj = {}; - this._tree.view.selection.getRangeAt(i, minObj, maxObj); - for (let idx = minObj.value; idx <= maxObj.value; ++idx) { - indexesToDelete.push(idx); + this._withBusy(async () => { + const indexesToDelete = []; + const count = this._tree.view.selection.getRangeCount(); + for (let i = 0; i < count; ++i) { + const minObj = {}; + const maxObj = {}; + this._tree.view.selection.getRangeAt(i, minObj, maxObj); + for (let idx = minObj.value; idx <= maxObj.value; ++idx) { + indexesToDelete.push(idx); + } } - } - if (indexesToDelete.length) { - const controllerFailureMsg = - TorStrings.onionServices.authPreferences.failedToRemoveKey; - try { - // Remove in reverse index order to avoid issues caused by index changes. - for (let i = indexesToDelete.length - 1; i >= 0; --i) { - await this._deleteOneKey(indexesToDelete[i]); - } - } catch (e) { - console.error("Removing a saved key failed", e); - if (e.torMessage) { - this._showError(e.torMessage); - } else { - this._showError(controllerFailureMsg); + if (indexesToDelete.length) { + const controllerFailureMsg = + TorStrings.onionServices.authPreferences.failedToRemoveKey; + const provider = await TorProviderBuilder.build(); + try { + // Remove in reverse index order to avoid issues caused by index + // changes. + for (let i = indexesToDelete.length - 1; i >= 0; --i) { + await this._deleteOneKey(provider, indexesToDelete[i]); + } + } catch (e) { + console.error("Removing a saved key failed", e); + if (e.torMessage) { + this._showError(e.torMessage); + } else { + this._showError(controllerFailureMsg); + } } } - } - - this._setBusyState(false); + }); }, async deleteAllKeys() { @@ -84,16 +88,12 @@ var gOnionServicesSavedKeysDialog = { }, async _init() { - await this._populateXUL(); - + this._populateXUL(); window.addEventListener("keypress", this._onWindowKeyPress.bind(this)); - - // We don't use await here because we want _loadSavedKeys() to run - // in the background and not block loading of this dialog. this._loadSavedKeys(); }, - async _populateXUL() { + _populateXUL() { const dialog = document.querySelector(this.selector.dialog); const authPrefStrings = TorStrings.onionServices.authPreferences; dialog.setAttribute("title", authPrefStrings.dialogTitle); @@ -119,56 +119,68 @@ var gOnionServicesSavedKeysDialog = { async _loadSavedKeys() { const controllerFailureMsg = TorStrings.onionServices.authPreferences.failedToGetKeys; - this._setBusyState(true); - - try { - this._tree.view = this; - - const keyInfoList = await TorProviderBuilder.build().onionAuthViewKeys(); - if (keyInfoList) { - // Filter out temporary keys. - this._keyInfoList = keyInfoList.filter(aKeyInfo => - aKeyInfo.flags?.includes("Permanent") - ); - // Sort by the .onion address. - this._keyInfoList.sort((aObj1, aObj2) => { - const hsAddr1 = aObj1.address.toLowerCase(); - const hsAddr2 = aObj2.address.toLowerCase(); - if (hsAddr1 < hsAddr2) { - return -1; - } - return hsAddr1 > hsAddr2 ? 1 : 0; - }); - } + this._withBusy(async () => { + try { + this._tree.view = this; + + const provider = await TorProviderBuilder.build(); + const keyInfoList = await provider.onionAuthViewKeys(); + if (keyInfoList) { + // Filter out temporary keys. + this._keyInfoList = keyInfoList.filter(aKeyInfo => + aKeyInfo.flags?.includes("Permanent") + ); + // Sort by the .onion address. + this._keyInfoList.sort((aObj1, aObj2) => { + const hsAddr1 = aObj1.address.toLowerCase(); + const hsAddr2 = aObj2.address.toLowerCase(); + if (hsAddr1 < hsAddr2) { + return -1; + } + return hsAddr1 > hsAddr2 ? 1 : 0; + }); + } - // Render the tree content. - this._tree.rowCountChanged(0, this.rowCount); - } catch (e) { - if (e.torMessage) { - this._showError(e.torMessage); - } else { - this._showError(controllerFailureMsg); + // Render the tree content. + this._tree.rowCountChanged(0, this.rowCount); + } catch (e) { + if (e.torMessage) { + this._showError(e.torMessage); + } else { + this._showError(controllerFailureMsg); + } } - } - - this._setBusyState(false); + }); }, // This method may throw; callers should catch errors. - async _deleteOneKey(aIndex) { + async _deleteOneKey(provider, aIndex) { const keyInfoObj = this._keyInfoList[aIndex]; - await TorProviderBuilder.build().onionAuthRemove(keyInfoObj.address); + await provider.onionAuthRemove(keyInfoObj.address); this._tree.view.selection.clearRange(aIndex, aIndex); this._keyInfoList.splice(aIndex, 1); this._tree.rowCountChanged(aIndex + 1, -1); }, - _setBusyState(aIsBusy) { - this._isBusy = aIsBusy; - this.updateButtonsState(); + async _withBusy(func) { + this._busyCount++; + if (this._busyCount === 1) { + this.updateButtonsState(); + } + try { + await func(); + } finally { + this._busyCount--; + if (this._busyCount === 0) { + this.updateButtonsState(); + } + } }, _onWindowKeyPress(event) { + if (this._isBusy) { + return; + } if (event.keyCode === KeyEvent.DOM_VK_ESCAPE) { window.close(); } else if (event.keyCode === KeyEvent.DOM_VK_DELETE) { ===================================== browser/components/torconnect/TorConnectChild.jsm deleted ===================================== @@ -1,9 +0,0 @@ -// Copyright (c) 2021, The Tor Project, Inc. - -var EXPORTED_SYMBOLS = ["TorConnectChild"]; - -const { RemotePageChild } = ChromeUtils.import( - "resource://gre/actors/RemotePageChild.jsm" -); - -class TorConnectChild extends RemotePageChild {} ===================================== browser/components/torconnect/TorConnectChild.sys.mjs ===================================== @@ -0,0 +1,5 @@ +// Copyright (c) 2021, The Tor Project, Inc. + +import { RemotePageChild } from "resource://gre/actors/RemotePageChild.sys.mjs"; + +export class TorConnectChild extends RemotePageChild {} ===================================== browser/components/torconnect/TorConnectParent.jsm → browser/components/torconnect/TorConnectParent.sys.mjs ===================================== @@ -1,14 +1,17 @@ // Copyright (c) 2021, The Tor Project, Inc. -var EXPORTED_SYMBOLS = ["TorConnectParent"]; - -const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { TorStrings } = ChromeUtils.import("resource:///modules/TorStrings.jsm"); -const { InternetStatus, TorConnect, TorConnectTopics, TorConnectState } = - ChromeUtils.import("resource:///modules/TorConnect.jsm"); -const { TorSettings, TorSettingsTopics, TorSettingsData } = ChromeUtils.import( - "resource:///modules/TorSettings.jsm" -); +import { + InternetStatus, + TorConnect, + TorConnectTopics, + TorConnectState, +} from "resource:///modules/TorConnect.sys.mjs"; +import { + TorSettings, + TorSettingsTopics, + TorSettingsData, +} from "resource:///modules/TorSettings.sys.mjs"; const BroadcastTopic = "about-torconnect:broadcast"; @@ -17,7 +20,7 @@ This object is basically a marshalling interface between the TorConnect module and a particular about:torconnect page */ -class TorConnectParent extends JSWindowActorParent { +export class TorConnectParent extends JSWindowActorParent { constructor(...args) { super(...args); @@ -35,10 +38,20 @@ class TorConnectParent extends JSWindowActorParent { DetectedLocation: TorConnect.detectedLocation, ShowViewLog: TorConnect.logHasWarningOrError, HasEverFailed: TorConnect.hasEverFailed, - QuickStartEnabled: TorSettings.quickstart.enabled, UIState: TorConnect.uiState, }; + // Workaround for a race condition, but we should fix it asap. + // about:torconnect is loaded before TorSettings is actually initialized. + // The getter might throw and the page not loaded correctly as a result. + // Silence any warning for now, but we should really fix it. + // See also tor-browser#41921. + try { + this.state.QuickStartEnabled = TorSettings.quickstart.enabled; + } catch (e) { + this.state.QuickStartEnabled = false; + } + // JSWindowActiveParent derived objects cannot observe directly, so create a member // object to do our observing for us // @@ -84,6 +97,16 @@ class TorConnectParent extends JSWindowActorParent { self.state.ShowViewLog = true; break; } + case TorSettingsTopics.Ready: { + if ( + self.state.QuickStartEnabled !== TorSettings.quickstart.enabled + ) { + self.state.QuickStartEnabled = TorSettings.quickstart.enabled; + } else { + return; + } + break; + } case TorSettingsTopics.SettingChanged: { if (aData === TorSettingsData.QuickStartEnabled) { self.state.QuickStartEnabled = obj.value; @@ -107,6 +130,7 @@ class TorConnectParent extends JSWindowActorParent { const topic = TorConnectTopics[key]; Services.obs.addObserver(this.torConnectObserver, topic); } + Services.obs.addObserver(this.torConnectObserver, TorSettingsTopics.Ready); Services.obs.addObserver( this.torConnectObserver, TorSettingsTopics.SettingChanged @@ -130,6 +154,10 @@ class TorConnectParent extends JSWindowActorParent { const topic = TorConnectTopics[key]; Services.obs.removeObserver(this.torConnectObserver, topic); } + Services.obs.removeObserver( + this.torConnectObserver, + TorSettingsTopics.Ready + ); Services.obs.removeObserver( this.torConnectObserver, TorSettingsTopics.SettingChanged ===================================== browser/components/torconnect/moz.build ===================================== @@ -1,6 +1,6 @@ -JAR_MANIFESTS += ['jar.mn'] +JAR_MANIFESTS += ["jar.mn"] -EXTRA_JS_MODULES += [ - 'TorConnectChild.jsm', - 'TorConnectParent.jsm', +FINAL_TARGET_FILES.actors += [ + "TorConnectChild.sys.mjs", + "TorConnectParent.sys.mjs", ] ===================================== browser/components/torpreferences/content/connectionPane.js ===================================== @@ -153,8 +153,16 @@ const gConnectionPane = (function () { // populate xul with strings and cache the relevant elements _populateXUL() { // saves tor settings to disk when navigate away from about:preferences - window.addEventListener("blur", val => { - TorProviderBuilder.build().flushSettings(); + window.addEventListener("blur", async () => { + try { + // Build a new provider each time because this might be called also + // when closing the browser (if about:preferences was open), maybe + // when the provider was already uninitialized. + const provider = await TorProviderBuilder.build(); + provider.flushSettings(); + } catch (e) { + console.warn("Could not save the tor settings.", e); + } }); document @@ -746,11 +754,17 @@ const gConnectionPane = (function () { placeholder.replaceWith(...cards); this._checkBridgeCardsHeight(); }; - this._checkConnectedBridge = () => { + this._checkConnectedBridge = async () => { // TODO: We could make sure TorSettings is in sync by monitoring also // changes of settings. At that point, we could query it, instead of // doing a query over the control port. - const bridge = TorProviderBuilder.build().currentBridge; + let bridge = null; + try { + const provider = await TorProviderBuilder.build(); + bridge = provider.currentBridge; + } catch (e) { + console.warn("Could not get current bridge", e); + } if (bridge?.fingerprint !== this._currentBridgeId) { this._currentBridgeId = bridge?.fingerprint ?? null; this._updateConnectedBridges(); ===================================== browser/components/torpreferences/content/torLogDialog.jsm ===================================== @@ -26,7 +26,7 @@ class TorLogDialog { }; } - _populateXUL(aDialog) { + async _populateXUL(aDialog) { this._dialog = aDialog; const dialogWin = this._dialog.parentElement; dialogWin.setAttribute("title", TorStrings.settings.torLogDialogTitle); @@ -56,7 +56,12 @@ class TorLogDialog { }, RESTORE_TIME); }); - this._logTextarea.value = TorProviderBuilder.build().getLog(); + // A waiting state should not be needed at this point. + // Also, we probably cannot even arrive here if the provider failed to + // initialize, otherwise we could use a try/catch, and write the exception + // text in the logs, instead. + const provider = await TorProviderBuilder.build(); + this._logTextarea.value = provider.getLog(); } init(window, aDialog) { ===================================== browser/modules/Moat.sys.mjs ===================================== @@ -46,9 +46,8 @@ class MeekTransport { try { // figure out which pluggable transport to use const supportedTransports = ["meek", "meek_lite"]; - const proxy = ( - await lazy.TorProviderBuilder.build().getPluggableTransports() - ).find( + const provider = await lazy.TorProviderBuilder.build(); + const proxy = (await provider.getPluggableTransports()).find( pt => pt.type === "exec" && supportedTransports.some(t => pt.transports.includes(t)) ===================================== browser/modules/TorConnect.sys.mjs ===================================== @@ -9,7 +9,6 @@ const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { MoatRPC: "resource:///modules/Moat.sys.mjs", TorBootstrapRequest: "resource://gre/modules/TorBootstrapRequest.sys.mjs", - TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs", }); // TODO: Should we move this to the about:torconnect actor? @@ -19,6 +18,7 @@ ChromeUtils.defineModuleGetter( "resource:///modules/BrowserWindowTracker.jsm" ); +import { TorLauncherUtil } from "resource://gre/modules/TorLauncherUtil.sys.mjs"; import { TorSettings, TorSettingsTopics, @@ -91,15 +91,15 @@ export const TorConnectState = Object.freeze({ │ │ │ │ │ └─┼─────▶ │ │ │ │ └──────────────────────────────────────────────────────────┘ │ - │ │ ▲ │ - │ │ beginAutoBootstrap() │ cancelBootstrap() │ - │ ▼ │ │ - │ ┌───────────────────────┐ │ │ - └────── │ AutoBootstrapping │ ─┘ │ - └───────────────────────┘ │ - │ │ - │ │ - ▼ │ + │ │ ▲ ▲ │ + │ │ beginAutoBootstrap() │ cancelBootstrap() │ │ + │ ▼ │ │ │ + │ ┌───────────────────────┐ │ │ │ + └────── │ AutoBootstrapping │ ─┘ │ │ + └───────────────────────┘ │ │ + │ │ │ + │ ┌────────────────────────────────┘ │ + ▼ │ │ ┌───────────────────────┐ │ │ Bootstrapped │ ◀───────────────────────────────────┘ └───────────────────────┘ @@ -145,8 +145,8 @@ const TorConnectStateTransitions = Object.freeze( ], ], [TorConnectState.Error, [TorConnectState.Configuring]], + [TorConnectState.Bootstrapped, [TorConnectState.Configuring]], // terminal states - [TorConnectState.Bootstrapped, []], [TorConnectState.Disabled, []], ]) ); @@ -703,8 +703,13 @@ export const TorConnect = (() => { // bootstrapped failed for all potential settings, so reset daemon to use original TorSettings.setSettings(this.originalSettings); - await TorSettings.applySettings(); + // The original settings should be good, so we save them to + // preferences before trying to apply them, as it might fail + // if the actual problem is with the connection to the control + // port. + // FIXME: We should handle this case in a better way. TorSettings.saveToPrefs(); + await TorSettings.applySettings(); // only explicitly change state here if something else has not transitioned us if (!this.transitioning) { @@ -718,6 +723,8 @@ export const TorConnect = (() => { // restore original settings in case of error try { TorSettings.setSettings(this.originalSettings); + // As above + TorSettings.saveToPrefs(); await TorSettings.applySettings(); } catch (errRestore) { console.log( @@ -733,12 +740,19 @@ export const TorConnect = (() => { TorConnect._countryCodes = await this.mrpc.circumvention_countries(); } - TorConnect._changeState( - TorConnectState.Error, - err?.message, - err?.details, - true - ); + if (!this.transitioning) { + TorConnect._changeState( + TorConnectState.Error, + err?.message, + err?.details, + true + ); + } else { + console.error( + "TorConnect: Received AutoBootstrapping error after transitioning", + err + ); + } } finally { // important to uninit MoatRPC object or else the pt process will live as long as tor-browser this.mrpc?.uninit(); @@ -751,7 +765,11 @@ export const TorConnect = (() => { TorConnectState.Bootstrapped, new StateCallback(TorConnectState.Bootstrapped, async function () { await new Promise((resolve, reject) => { - // on_transition not defined because no way to leave Bootstrapped state + // We may need to leave the bootstrapped state if the tor daemon + // exits (if it is restarted, we will have to bootstrap again). + this.on_transition = nextState => { + resolve(); + }; // notify observers of bootstrap completion Services.obs.notifyObservers( null, @@ -895,6 +913,25 @@ export const TorConnect = (() => { this._logHasWarningOrError = true; break; } + case TorTopics.ProcessExited: { + // Treat a failure as a possibly broken configuration. + // So, prevent quickstart at the next start. + Services.prefs.setBoolPref(TorLauncherPrefs.prompt_at_startup, true); + switch (this._state) { + case TorConnectState.Bootstrapping: + case TorConnectState.AutoBootstrapping: + case TorConnectState.Bootstrapped: + // If we are in the bootstrap or auto bootstrap, we could go + // through the error phase (and eventually we might do it, if some + // transition calls fail). However, this would start the + // connection assist, so we go directly to configuring. + // FIXME: Find a better way to handle this. + this._changeState(TorConnectState.Configuring); + break; + // Other states naturally resolve in configuration. + } + break; + } default: // ignore break; @@ -911,7 +948,10 @@ export const TorConnect = (() => { * @type {boolean} */ get enabled() { - return lazy.TorProviderBuilder.build().ownsTorDaemon; + // FIXME: This is called before the TorProvider is ready. + // As a matter of fact, at the moment it is equivalent to the following + // line, but this might become a problem in the future. + return TorLauncherUtil.shouldStartAndOwnTor; }, get shouldShowTorConnect() { ===================================== browser/modules/TorSettings.sys.mjs ===================================== @@ -5,6 +5,7 @@ const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { + TorLauncherUtil: "resource://gre/modules/TorLauncherUtil.sys.mjs", TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs", TorProviderTopics: "resource://gre/modules/TorProviderBuilder.sys.mjs", }); @@ -273,9 +274,10 @@ export const TorSettings = (() => { }, /* load or init our settings, and register observers */ - init() { - const provider = lazy.TorProviderBuilder.build(); - if (provider.ownsTorDaemon) { + async init() { + // TODO: We could use a shared promise, and wait for it to be fullfilled + // instead of Service.obs. + if (lazy.TorLauncherUtil.shouldStartAndOwnTor) { // if the settings branch exists, load settings from prefs if (Services.prefs.getBoolPref(TorSettingsPrefs.enabled, false)) { this.loadFromPrefs(); @@ -285,9 +287,12 @@ export const TorSettings = (() => { } Services.obs.addObserver(this, lazy.TorProviderTopics.ProcessIsReady); - if (provider.isRunning) { - this.handleProcessReady(); - } + try { + const provider = await lazy.TorProviderBuilder.build(); + if (provider.isRunning) { + this.handleProcessReady(); + } + } catch {} } }, @@ -559,7 +564,8 @@ export const TorSettings = (() => { } /* Push to Tor */ - await lazy.TorProviderBuilder.build().writeSettings(settingsMap); + const provider = await lazy.TorProviderBuilder.build(); + await provider.writeSettings(settingsMap); return this; }, ===================================== toolkit/components/tor-launcher/TorBootstrapRequest.sys.mjs ===================================== @@ -26,11 +26,6 @@ export class TorBootstrapRequest { #bootstrapPromiseResolve = null; #bootstrapPromise = null; #timeoutID = null; - #provider = null; - - constructor() { - this.#provider = TorProviderBuilder.build(); - } observe(subject, topic, data) { const obj = subject?.wrappedJSObject; @@ -85,10 +80,14 @@ export class TorBootstrapRequest { }, this.timeout); } - // wait for bootstrapping to begin and maybe handle error - this.#provider.connect().catch(err => { - this.#stop(err.message, ""); - }); + // Wait for bootstrapping to begin and maybe handle error. + // Notice that we do not resolve the promise here in case of success, but + // we do it from the BootstrapStatus observer. + TorProviderBuilder.build() + .then(provider => provider.connect()) + .catch(err => { + this.#stop(err.message, err.torMessage); + }); }).finally(() => { // and remove ourselves once bootstrap is resolved Services.obs.removeObserver(this, TorTopics.BootstrapStatus); @@ -111,8 +110,15 @@ export class TorBootstrapRequest { this.#timeoutID = null; } + let provider; + try { + provider = await TorProviderBuilder.build(); + } catch { + // This was probably the error that lead to stop in the first place. + // No need to continue propagating it. + } try { - await this.#provider.stopBootstrap(); + await provider?.stopBootstrap(); } catch (e) { console.error("Failed to stop the bootstrap.", e); if (!message) { ===================================== toolkit/components/tor-launcher/TorControlPort.sys.mjs ===================================== @@ -1,43 +1,16 @@ -import { TorParsers } from "resource://gre/modules/TorParsers.sys.mjs"; - -/** - * @callback MessageCallback A callback to receive messages from the control - * port. - * @param {string} message The message to handle - */ -/** - * @callback RemoveCallback A function used to remove a previously registered - * callback. - */ +/* 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/. */ -class CallbackDispatcher { - #callbackPairs = []; +import { ConsoleAPI } from "resource://gre/modules/Console.sys.mjs"; - /** - * Register a callback to handle a certain type of responses. - * - * @param {RegExp} regex The regex that tells which messages the callback - * wants to handle. - * @param {MessageCallback} callback The function to call - * @returns {RemoveCallback} A function to remove the just added callback - */ - addCallback(regex, callback) { - this.#callbackPairs.push([regex, callback]); - } +import { TorParsers } from "resource://gre/modules/TorParsers.sys.mjs"; - /** - * Push a certain message to all the callbacks whose regex matches it. - * - * @param {string} message The message to push to the callbacks - */ - pushMessage(message) { - for (const [regex, callback] of this.#callbackPairs) { - if (message.match(regex)) { - callback(message); - } - } - } -} +const logger = new ConsoleAPI({ + maxLogLevel: "warn", + maxLogLevelPref: "browser.tor_provider.cp_log_level", + prefix: "TorControlPort", +}); /** * A wrapper around XPCOM sockets and buffers to handle streams in a standard @@ -273,13 +246,38 @@ class AsyncSocket { * @property {Function} reject The function to reject the promise associated to * the command */ - +/** + * The ID of a circuit. + * From control-spec.txt: + * CircuitID = 1*16 IDChar + * IDChar = ALPHA / DIGIT + * Currently, Tor only uses digits, but this may change. + * + * @typedef {string} CircuitID + */ +/** + * The ID of a stream. + * From control-spec.txt: + * CircuitID = 1*16 IDChar + * IDChar = ALPHA / DIGIT + * Currently, Tor only uses digits, but this may change. + * + * @typedef {string} StreamID + */ +/** + * The fingerprint of a node. + * From control-spec.txt: + * Fingerprint = "$" 40*HEXDIG + * However, we do not keep the $ in our structures. + * + * @typedef {string} NodeFingerprint + */ /** * @typedef {object} Bridge * @property {string} transport The transport of the bridge, or vanilla if not * specified. * @property {string} addr The IP address and port of the bridge - * @property {string} id The fingerprint of the bridge + * @property {NodeFingerprint} id The fingerprint of the bridge * @property {string} args Optional arguments passed to the bridge */ /** @@ -303,13 +301,9 @@ class AsyncSocket { * @property {string} Flags Additional flags, such as Permanent */ /** - * @callback EventFilterCallback - * @param {any} data Either a raw string, or already parsed data - * @returns {boolean} - */ -/** - * @callback EventCallback - * @param {any} data Either a raw string, or already parsed data + * @callback EventCallback A callback to receive messages from the control + * port. + * @param {string} message The message to handle */ class TorError extends Error { @@ -324,7 +318,7 @@ class TorError extends Error { } } -class ControlSocket { +export class TorController { /** * The socket to write to the control port. * @@ -332,19 +326,6 @@ class ControlSocket { */ #socket; - /** - * The dispatcher used for the data we receive over the control port. - * - * @type {CallbackDispatcher} - */ - #mainDispatcher = new CallbackDispatcher(); - /** - * A secondary dispatcher used only to dispatch aynchronous events. - * - * @type {CallbackDispatcher} - */ - #notificationDispatcher = new CallbackDispatcher(); - /** * Data we received on a read but that was not a complete line (missing a * final CRLF). We will prepend it to the next read. @@ -365,24 +346,59 @@ class ControlSocket { */ #commandQueue = []; - constructor(asyncSocket) { - this.#socket = asyncSocket; + /** + * The event handler. + * + * @type {TorEventHandler} + */ + #eventHandler; - // #mainDispatcher pushes only async notifications (650) to - // #notificationDispatcher - this.#mainDispatcher.addCallback( - /^650/, - this.#handleNotification.bind(this) - ); - // callback for handling responses and errors - this.#mainDispatcher.addCallback( - /^[245]\d\d/, - this.#handleCommandReply.bind(this) + /** + * Connect to a control port over a Unix socket. + * Not available on Windows. + * + * @param {nsIFile} ipcFile The path to the Unix socket to connect to + * @param {TorEventHandler} eventHandler The event handler to use for + * asynchronous notifications + */ + static fromIpcFile(ipcFile, eventHandler) { + return new TorController(AsyncSocket.fromIpcFile(ipcFile), eventHandler); + } + + /** + * Connect to a control port over a TCP socket. + * + * @param {string} host The hostname to connect to + * @param {number} port The port to connect the to + * @param {TorEventHandler} eventHandler The event handler to use for + * asynchronous notifications + */ + static fromSocketAddress(host, port, eventHandler) { + return new TorController( + AsyncSocket.fromSocketAddress(host, port), + eventHandler ); + } + /** + * Construct the controller and start the message pump. + * The class should not be constructed directly, but through static methods. + * However, this is public because JavaScript does not support private + * constructors. + * + * @private + * @param {AsyncSocket} socket The socket to use + * @param {TorEventHandler} eventHandler The event handler to use for + * asynchronous notifications + */ + constructor(socket, eventHandler) { + this.#socket = socket; + this.#eventHandler = eventHandler; this.#startMessagePump(); } + // Socket and communication handling + /** * Return the next line in the queue. If there is not any, block until one is * read (or until a communication error happens, including the underlying @@ -463,6 +479,24 @@ class ControlSocket { return message.join("\r\n"); } + /** + * Handles a message that was received as a reply to a command (i.e., all the + * messages that are not async notification messages starting with 650). + * + * @param {string} message The message to handle + */ + #handleCommandReply(message) { + const cmd = this.#commandQueue.shift(); + // We resolve also for messages that are failures for sure. The commands + // should always check the output. + cmd.resolve(message); + + // send next command if one is available + if (this.#commandQueue.length) { + this.#writeNextCommand(); + } + } + /** * Read messages on the socket and routed them to a dispatcher until the * socket is open or some error happens (including the underlying socket being @@ -475,14 +509,25 @@ class ControlSocket { // condition becoming false. while (this.#socket) { const message = await this.#readMessage(); - // log("controlPort >> " + message); - this.#mainDispatcher.pushMessage(message); + try { + if (message.startsWith("650")) { + this.#handleNotification(message); + } else { + this.#handleCommandReply(message); + } + } catch (err) { + // E.g., if a notification handler fails. Without this internal + // try/catch we risk of closing the connection while not actually + // needed. + logger.error("Caught an exception while handling a message", err); + } } } catch (err) { + logger.debug("Caught an exception, closing the control port", err); try { this.#close(err); } catch (ec) { - console.error( + logger.error( "Caught another error while closing the control socket.", ec ); @@ -497,7 +542,6 @@ class ControlSocket { */ #writeNextCommand() { const cmd = this.#commandQueue[0]; - // log("controlPort << " + cmd.commandString); this.#socket.write(`${cmd.commandString}\r\n`).catch(cmd.reject); } @@ -508,12 +552,11 @@ class ControlSocket { * needs to handle multi-line messages. * * @param {string} commandString - * @returns {Promise<string>} The message sent by the control port. It will - * always start with 2xx. In case of other codes the function will throw, - * instead. This means that the return value will never be an empty string - * (even though it will not include the final CRLF). + * @returns {Promise<string>} The message sent by the control port. The return + * value should never be an empty string (even though it will not include the + * final CRLF). */ - async sendCommand(commandString) { + async #sendCommand(commandString) { if (!this.#socket) { throw new Error("ControlSocket not open"); } @@ -534,42 +577,16 @@ class ControlSocket { } /** - * Handles a message starting with 2xx, 4xx, or 5xx. - * This function should be used only as a callback for the main dispatcher. - * - * @param {string} message The message to handle - */ - #handleCommandReply(message) { - const cmd = this.#commandQueue.shift(); - if (message[0] === "2") { - cmd.resolve(message); - } else if (message.match(/^[45]/)) { - cmd.reject(new TorError(cmd.commandString, message)); - } else { - // This should never happen, as the dispatcher should filter the messages - // already. - cmd.reject( - new Error(`Received unexpected message:\n----\n${message}\n----`) - ); - } - - // send next command if one is available - if (this.#commandQueue.length) { - this.#writeNextCommand(); - } - } - - /** - * Re-route an event message to the notification dispatcher. - * This function should be used only as a callback for the main dispatcher. + * Send a simple command whose response is expected to be simply a "250 OK". + * The function will not return a reply, but will throw if an unexpected one + * is received. * - * @param {string} message The message received on the control port + * @param {string} command The command to send */ - #handleNotification(message) { - try { - this.#notificationDispatcher.pushMessage(message); - } catch (e) { - console.error("An event watcher threw", e); + async #sendCommandSimple(command) { + const reply = await this.#sendCommand(command); + if (!/^250 OK\s*$/i.test(reply)) { + throw new TorError(command, reply); } } @@ -581,6 +598,7 @@ class ControlSocket { * rejection reason to the commands that are still queued. */ #close(reason) { + logger.info("Closing the control port", reason); const error = new Error( "The control socket has been closed" + (reason ? `: ${reason.message}` : "") @@ -604,98 +622,29 @@ class ControlSocket { this.#close(null); } - /** - * Register an event watcher. - * - * @param {RegExp} regex The regex to filter on messages to receive - * @param {MessageCallback} callback The callback for the messages - */ - addNotificationCallback(regex, callback) { - this.#notificationDispatcher.addCallback(regex, callback); - } - /** * Tells whether the underlying socket is still open. */ get isOpen() { return !!this.#socket; } -} - -class TorController { - /** - * The control socket - * - * @type {ControlSocket} - */ - #socket; - - /** - * Builds a new TorController. - * - * @param {AsyncSocket} socket The socket to communicate to the control port - */ - constructor(socket) { - this.#socket = new ControlSocket(socket); - } - - /** - * Tells whether the underlying socket is open. - * - * @returns {boolean} - */ - get isOpen() { - return this.#socket.isOpen; - } - - /** - * Close the underlying socket. - */ - close() { - this.#socket.close(); - } - - /** - * Send a command over the control port. - * TODO: Make this function private, and force the operations to go through - * specialized methods. - * - * @param {string} cmd The command to send - * @returns {Promise<string>} A 2xx response obtained from the control port. - * For other codes, this function will throw. The returned string will never - * be empty. - */ - async sendCommand(cmd) { - return this.#socket.sendCommand(cmd); - } - - /** - * Send a simple command whose response is expected to be simply a "250 OK". - * The function will not return a reply, but will throw if an unexpected one - * is received. - * - * @param {string} command The command to send - */ - async #sendCommandSimple(command) { - const reply = await this.sendCommand(command); - if (!/^250 OK\s*$/i.test(reply)) { - throw new TorError(command, reply); - } - } /** * Authenticate to the tor daemon. * Notice that a failure in the authentication makes the connection close. * - * @param {string} password The password for the control port. + * @param {Uint8Array} password The password for the control port, as an array + * of bytes */ async authenticate(password) { - if (password) { - this.#expectString(password, "password"); - } - await this.#sendCommandSimple(`authenticate ${password || ""}`); + const passwordString = Array.from(password ?? [], b => + b.toString(16).padStart(2, "0") + ).join(""); + await this.#sendCommandSimple(`authenticate ${passwordString}`); } + // Information + /** * Sends a GETINFO for a single key. * control-spec.txt says "one ReplyLine is sent for each requested value", so, @@ -713,10 +662,10 @@ class TorController { async #getInfo(key) { this.#expectString(key); const cmd = `GETINFO ${key}`; - const reply = await this.sendCommand(cmd); + const reply = await this.#sendCommand(cmd); const match = reply.match(/^250-([^=]+)=(.*)$/m) || - reply.match(/^250\+([^=]+)=([\s\S]*?)^\.\r?\n^250 OK\s*$/m); + reply.match(/^250\+([^=]+)=\r?\n(.*?)\r?\n^\.\r?\n^250 OK\s*$/ms); if (!match || match[1] !== key) { throw new TorError(cmd, reply); } @@ -777,6 +726,17 @@ class TorController { return this.#getInfo(`ip-to-country/${ip}`); } + /** + * Ask Tor a list of circuits. + * + * @returns {string[]} An array with a string for each line + */ + async getCircuits() { + const circuits = await this.#getInfo("circuit-status"); + // TODO: Do more parsing once we move the event parsing to this class! + return circuits.split(/\r?\n/); + } + // Configuration /** @@ -805,7 +765,7 @@ class TorController { throw new Error("The key can be composed only of letters and numbers."); } const cmd = `GETCONF ${key}`; - const reply = await this.sendCommand(cmd); + const reply = await this.#sendCommand(cmd); // From control-spec.txt: a 'default' value semantically different from an // empty string will not have an equal sign, just `250 $key`. const defaultRe = new RegExp(`^250[-\\s]${key}$`, "gim"); @@ -924,7 +884,7 @@ class TorController { */ async onionAuthViewKeys() { const cmd = "onion_client_auth_view"; - const message = await this.sendCommand(cmd); + const message = await this.#sendCommand(cmd); // Either `250-CLIENT`, or `250 OK` if no keys are available. if (!message.startsWith("250")) { throw new TorError(cmd, message); @@ -964,7 +924,7 @@ class TorController { if (isPermanent) { cmd += " Flags=Permanent"; } - const reply = await this.sendCommand(cmd); + const reply = await this.#sendCommand(cmd); const status = reply.substring(0, 3); if (status !== "250" && status !== "251" && status !== "252") { throw new TorError(cmd, reply); @@ -980,7 +940,7 @@ class TorController { async onionAuthRemove(address) { this.#expectString(address, "address"); const cmd = `onion_client_auth_remove ${address}`; - const reply = await this.sendCommand(cmd); + const reply = await this.#sendCommand(cmd); const status = reply.substring(0, 3); if (status !== "250" && status !== "251") { throw new TorError(cmd, reply); @@ -1035,19 +995,77 @@ class TorController { } /** - * Watches for a particular type of asynchronous event. - * Notice: we only observe `"650" SP...` events, currently (no `650+...` or - * `650-...` events). - * Also, you need to enable the events in the control port with SETEVENTS, - * first. + * Parse an asynchronous event and pass the data to the relative handler. + * Only single-line messages are currently supported. * - * @param {string} type The event type to catch - * @param {EventCallback} callback The callback that will handle the event + * @param {string} message The message received on the control port. It should + * starts with `"650" SP`. */ - watchEvent(type, callback) { - this.#expectString(type, "type"); - const start = `650 ${type}`; - this.#socket.addNotificationCallback(new RegExp(`^${start}`), callback); + #handleNotification(message) { + if (!this.#eventHandler) { + return; + } + const data = message.match(/^650\s+(?<type>\S+)\s*(?<data>.*)?/); + if (!data) { + return; + } + switch (data.groups.type) { + case "STATUS_CLIENT": + let status; + try { + status = this.#parseBootstrapStatus(data.groups.data); + } catch (e) { + // Probably, a non bootstrap client status + logger.debug(`Failed to parse STATUS_CLIENT: ${data.groups.data}`, e); + break; + } + this.#eventHandler.onBootstrapStatus(status); + break; + case "CIRC": + const builtEvent = + /^(?<ID>[a-zA-Z0-9]{1,16})\sBUILT\s(?<Path>(,?\$([0-9a-fA-F]{40})(?:~[a-zA-Z0-9]{1,19})?)+)/.exec( + data.groups.data + ); + const closedEvent = /^(?<ID>[a-zA-Z0-9]{1,16})\sCLOSED/.exec( + data.groups.data + ); + if (builtEvent) { + const fp = /\$([0-9a-fA-F]{40})/g; + const nodes = Array.from(builtEvent.groups.Path.matchAll(fp), g => + g[1].toUpperCase() + ); + // In some cases, we might already receive SOCKS credentials in the + // line. However, this might be a problem with onion services: we get + // also a 4-hop circuit that we likely do not want to show to the + // user, especially because it is used only temporarily, and it would + // need a technical explaination. + // const credentials = this.#parseCredentials(data.groups.data); + this.#eventHandler.onCircuitBuilt(builtEvent.groups.ID, nodes); + } else if (closedEvent) { + this.#eventHandler.onCircuitClosed(closedEvent.groups.ID); + } + break; + case "STREAM": + const succeeedEvent = + /^(?<StreamID>[a-zA-Z0-9]{1,16})\sSUCCEEDED\s(?<CircuitID>[a-zA-Z0-9]{1,16})/.exec( + data.groups.data + ); + if (succeeedEvent) { + const credentials = this.#parseCredentials(data.groups.data); + this.#eventHandler.onStreamSucceeded( + succeeedEvent.groups.StreamID, + succeeedEvent.groups.CircuitID, + credentials?.username ?? null, + credentials?.password ?? null + ); + } + break; + case "NOTICE": + case "WARN": + case "ERR": + this.#eventHandler.onLogMessage(data.groups.type, data.groups.data); + break; + } } // Other helpers @@ -1092,6 +1110,24 @@ class TorController { } } + /** + * Check if a STREAM or CIRC response line contains SOCKS_USERNAME and + * SOCKS_PASSWORD. + * + * @param {string} line The circ or stream line to check + * @returns {object?} The credentials, or null if not found + */ + #parseCredentials(line) { + const username = /SOCKS_USERNAME=("(?:[^"\\]|\\.)*")/.exec(line); + const password = /SOCKS_PASSWORD=("(?:[^"\\]|\\.)*")/.exec(line); + return username && password + ? { + username: TorParsers.unescapeString(username[1]), + password: TorParsers.unescapeString(password[1]), + } + : null; + } + /** * Return an object with all the matches that are in the form `key="value"` or * `key=value`. The values will be unescaped, but no additional parsing will @@ -1112,67 +1148,54 @@ class TorController { } } -const controlPortInfo = {}; - /** - * Sets Tor control port connection parameters to be used in future calls to - * the controller() function. + * @typedef {object} TorEventHandler + * The event handler interface. + * The controller owner can implement this methods to receive asynchronous + * notifications from the controller. * - * Example: - * configureControlPortModule(undefined, "127.0.0.1", 9151, "MyPassw0rd"); + * @property {OnBootstrapStatus} onBootstrapStatus Called when a bootstrap + * status is received (i.e., a STATUS_CLIENT event with a BOOTSTRAP action) + * @property {OnLogMessage} onLogMessage Called when a log message is received + * (i.e., a NOTICE, WARN or ERR notification) + * @property {OnCircuitBuilt} onCircuitBuilt Called when a circuit is built + * (i.e., a CIRC event with a BUILT status) + * @property {OnCircuitClosed} onCircuitClosed Called when a circuit is closed + * (i.e., a CIRC event with a CLOSED status) + * @property {OnStreamSucceeded} onStreamSucceeded Called when a stream receives + * a reply (i.e., a STREAM event with a SUCCEEDED status) + */ +/** + * @callback OnBootstrapStatus * - * @param {nsIFile?} ipcFile An optional file to use to communicate to the - * control port on Unix platforms - * @param {string?} host The hostname to connect to the control port. Mutually - * exclusive with ipcFile - * @param {integer?} port The port number of the control port. To be used only - * with host. The default is 9151. - * @param {string} password The password of the control port in clear text. + * @param {object} status An object with the bootstrap information. Its keys + * depend on what the arguments sent by the tor daemon */ -export function configureControlPortModule(ipcFile, host, port, password) { - controlPortInfo.ipcFile = ipcFile; - controlPortInfo.host = host; - controlPortInfo.port = port || 9151; - controlPortInfo.password = password; -} - /** - * Instantiates and returns a controller object that is connected and - * authenticated to a Tor ControlPort using the connection parameters - * provided in the most recent call to configureControlPortModule(). + * @callback OnLogMessage * - * Example: - * // Get a new controller - * let c = await controller(); - * // Send command and receive a `250` reply or an error message: - * let replyPromise = await c.getInfo("ip-to-country/16.16.16.16"); - * // Close the controller permanently - * c.close(); + * @param {string} type The type of message (NOTICE, WARNING, ERR, etc...) + * @param {string} message The actual log message + */ +/** + * @callback OnCircuitBuilt + * + * @param {CircuitID} id The id of the circuit that has been built + * @param {NodeFingerprint[]} nodes The onion routers composing the circuit + */ +/** + * @callback OnCircuitClosed + * + * @param {CircuitID} id The id of the circuit that has been closed + */ +/** + * @callback OnStreamSucceeded + * + * @param {StreamID} streamId The id of the stream that switched to the succeeded + * state + * @param {CircuitID} circuitId The id of the circuit the stream is using + * @param {string?} username The SOCKS username associated to the stream, or + * null if not available + * @param {string?} username The SOCKS password associated to the stream, or + * null if not available */ -export async function controller() { - if (!controlPortInfo.ipcFile && !controlPortInfo.host) { - throw new Error("Please call configureControlPortModule first"); - } - let socket; - if (controlPortInfo.ipcFile) { - socket = AsyncSocket.fromIpcFile(controlPortInfo.ipcFile); - } else { - socket = AsyncSocket.fromSocketAddress( - controlPortInfo.host, - controlPortInfo.port - ); - } - const controller = new TorController(socket); - try { - await controller.authenticate(controlPortInfo.password); - } catch (e) { - try { - controller.close(); - } catch (ec) { - // TODO: Use a custom logger? - console.error("Cannot close the socket", ec); - } - throw e; - } - return controller; -} ===================================== toolkit/components/tor-launcher/TorDomainIsolator.sys.mjs ===================================== @@ -136,8 +136,11 @@ class TorDomainIsolatorImpl { init() { logger.info("Setup circuit isolation by domain and user context"); - if (Services.prefs.getBoolPref(NON_TOR_PROXY_PREF)) { + if (Services.prefs.getBoolPref(NON_TOR_PROXY_PREF, false)) { this.#isolationEnabled = false; + logger.info( + `The domain isolation will not be enabled because of ${NON_TOR_PROXY_PREF}.` + ); } this.#setupProxyFilter(); @@ -257,7 +260,8 @@ class TorDomainIsolatorImpl { ); this.clearIsolation(); try { - await lazy.TorProviderBuilder.build().newnym(); + const provider = await lazy.TorProviderBuilder.build(); + await provider.newnym(); } catch (e) { logger.error("Could not send the newnym command", e); // TODO: What UX to use here? See tor-browser#41708 @@ -305,7 +309,9 @@ class TorDomainIsolatorImpl { try { const searchParams = new URLSearchParams(loadingPrincipalURI.query); if (searchParams.has("url")) { - firstPartyDomain = Services.eTLD.getSchemelessSite(Services.io.newURI(searchParams.get("url"))); + firstPartyDomain = Services.eTLD.getSchemelessSite( + Services.io.newURI(searchParams.get("url")) + ); } } catch (e) { logger.error("Failed to get first party domain for about:reader", e); @@ -562,10 +568,9 @@ class TorDomainIsolatorImpl { return; } + const provider = await lazy.TorProviderBuilder.build(); data = await Promise.all( - circuit.map(fingerprint => - lazy.TorProviderBuilder.build().getNodeInfo(fingerprint) - ) + circuit.map(fingerprint => provider.getNodeInfo(fingerprint)) ); this.#knownCircuits.set(id, data); // We know that something changed, but we cannot know if anyone is @@ -673,7 +678,9 @@ function getDomainForBrowser(browser) { try { const searchParams = new URLSearchParams(documentURI.query); if (searchParams.has("url")) { - fpd = Services.eTLD.getSchemelessSite(Services.io.newURI(searchParams.get("url"))); + fpd = Services.eTLD.getSchemelessSite( + Services.io.newURI(searchParams.get("url")) + ); } } catch (e) { logger.error("Failed to get first party domain for about:reader", e); ===================================== toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs ===================================== @@ -366,6 +366,38 @@ export const TorLauncherUtil = Object.freeze({ return btnIndex === 0; }, + /** + * Ask the user whether they desire to restart tor. + * + * @param {boolean} initError If we could connect to the control port at + * least once and we are showing this prompt because the tor process exited + * suddenly, we will display a different message + * @returns {boolean} true if the user asked to restart tor + */ + showRestartPrompt(initError) { + let s; + if (initError) { + const key = "tor_exited_during_startup"; + s = this.getLocalizedString(key); + } else { + // tor exited suddenly, so configuration should be okay + s = + this.getLocalizedString("tor_exited") + + "\n\n" + + this.getLocalizedString("tor_exited2"); + } + const defaultBtnLabel = this.getLocalizedString("restart_tor"); + let cancelBtnLabel = "OK"; + try { + const kSysBundleURI = "chrome://global/locale/commonDialogs.properties"; + const sysBundle = Services.strings.createBundle(kSysBundleURI); + cancelBtnLabel = sysBundle.GetStringFromName(cancelBtnLabel); + } catch (e) { + console.warn("Could not localize the cancel button", e); + } + return this.showConfirm(null, s, defaultBtnLabel, cancelBtnLabel); + }, + // Localized Strings // TODO: Switch to fluent also these ones. @@ -503,10 +535,6 @@ export const TorLauncherUtil = Object.freeze({ */ getPreferredSocksConfiguration() { if (Services.env.exists("TOR_TRANSPROXY")) { - Services.prefs.setBoolPref("network.proxy.socks_remote_dns", false); - Services.prefs.setIntPref("network.proxy.type", 0); - Services.prefs.setIntPref("network.proxy.socks_port", 0); - Services.prefs.setCharPref("network.proxy.socks", ""); return { transproxy: true }; } @@ -576,6 +604,10 @@ export const TorLauncherUtil = Object.freeze({ setProxyConfiguration(socksPortInfo) { if (socksPortInfo.transproxy) { + Services.prefs.setBoolPref("network.proxy.socks_remote_dns", false); + Services.prefs.setIntPref("network.proxy.type", 0); + Services.prefs.setIntPref("network.proxy.socks_port", 0); + Services.prefs.setCharPref("network.proxy.socks", ""); return; } ===================================== toolkit/components/tor-launcher/TorParsers.sys.mjs ===================================== @@ -6,171 +6,6 @@ export const TorStatuses = Object.freeze({ }); export const TorParsers = Object.freeze({ - commandSucceeded(aReply) { - return aReply?.statusCode === TorStatuses.OK; - }, - - // parseReply() understands simple GETCONF and GETINFO replies. - parseReply(aCmd, aKey, aReply) { - if (!aCmd || !aKey || !aReply || !aReply.lineArray?.length) { - return []; - } - - const lcKey = aKey.toLowerCase(); - const prefix = lcKey + "="; - const prefixLen = prefix.length; - const tmpArray = []; - for (const line of aReply.lineArray) { - var lcLine = line.toLowerCase(); - if (lcLine === lcKey) { - tmpArray.push(""); - } else if (lcLine.indexOf(prefix) !== 0) { - console.warn(`Unexpected ${aCmd} response: ${line}`); - } else { - try { - let s = this.unescapeString(line.substring(prefixLen)); - tmpArray.push(s); - } catch (e) { - console.warn( - `Error while unescaping the response of ${aCmd}: ${line}`, - e - ); - } - } - } - - return tmpArray; - }, - - // Returns false if more lines are needed. The first time, callers - // should pass an empty aReplyObj. - // Parsing errors are indicated by aReplyObj._parseError = true. - parseReplyLine(aLine, aReplyObj) { - if (!aLine || !aReplyObj) { - return false; - } - - if (!("_parseError" in aReplyObj)) { - aReplyObj.statusCode = 0; - aReplyObj.lineArray = []; - aReplyObj._parseError = false; - } - - if (aLine.length < 4) { - console.error("Unexpected response: ", aLine); - aReplyObj._parseError = true; - return true; - } - - // TODO: handle + separators (data) - aReplyObj.statusCode = parseInt(aLine.substring(0, 3), 10); - const s = aLine.length < 5 ? "" : aLine.substring(4); - // Include all lines except simple "250 OK" ones. - if (aReplyObj.statusCode !== TorStatuses.OK || s !== "OK") { - aReplyObj.lineArray.push(s); - } - - return aLine.charAt(3) === " "; - }, - - // Split aStr at spaces, accounting for quoted values. - // Returns an array of strings. - splitReplyLine(aStr) { - // Notice: the original function did not check for escaped quotes. - return aStr - .split('"') - .flatMap((token, index) => { - const inQuotedStr = index % 2 === 1; - return inQuotedStr ? `"${token}"` : token.split(" "); - }) - .filter(s => s); - }, - - // Helper function for converting a raw controller response into a parsed object. - parseCommandResponse(reply) { - if (!reply) { - return {}; - } - const lines = reply.split("\r\n"); - const rv = {}; - for (const line of lines) { - if (this.parseReplyLine(line, rv) || rv._parseError) { - break; - } - } - return rv; - }, - - // If successful, returns a JS object with these fields: - // status.TYPE -- "NOTICE" or "WARN" - // status.PROGRESS -- integer - // status.TAG -- string - // status.SUMMARY -- string - // status.WARNING -- string (optional) - // status.REASON -- string (optional) - // status.COUNT -- integer (optional) - // status.RECOMMENDATION -- string (optional) - // status.HOSTADDR -- string (optional) - // Returns null upon failure. - parseBootstrapStatus(aStatusMsg) { - if (!aStatusMsg || !aStatusMsg.length) { - return null; - } - - let sawBootstrap = false; - const statusObj = {}; - statusObj.TYPE = "NOTICE"; - - // The following code assumes that this is a one-line response. - for (const tokenAndVal of this.splitReplyLine(aStatusMsg)) { - let token, val; - const idx = tokenAndVal.indexOf("="); - if (idx < 0) { - token = tokenAndVal; - } else { - token = tokenAndVal.substring(0, idx); - try { - val = TorParsers.unescapeString(tokenAndVal.substring(idx + 1)); - } catch (e) { - console.debug("Could not parse the token value", e); - } - if (!val) { - // skip this token/value pair. - continue; - } - } - - switch (token) { - case "BOOTSTRAP": - sawBootstrap = true; - break; - case "WARN": - case "NOTICE": - case "ERR": - statusObj.TYPE = token; - break; - case "COUNT": - case "PROGRESS": - statusObj[token] = parseInt(val, 10); - break; - default: - statusObj[token] = val; - break; - } - } - - if (!sawBootstrap) { - if (statusObj.TYPE === "NOTICE") { - console.info(aStatusMsg); - } else { - console.warn(aStatusMsg); - } - return null; - } - - return statusObj; - }, - // Escape non-ASCII characters for use within the Tor Control protocol. // Based on Vidalia's src/common/stringutil.cpp:string_escape(). // Returns the new string. ===================================== toolkit/components/tor-launcher/TorProcess.sys.mjs ===================================== @@ -37,12 +37,11 @@ export class TorProcess { #didConnectToTorControlPort = false; onExit = exitCode => {}; - onRestart = () => {}; constructor(controlSettings, socksSettings) { if ( controlSettings && - !controlSettings.password && + !controlSettings.password?.length && !controlSettings.cookieFilePath ) { throw new Error("Unauthenticated control port is not supported"); @@ -204,43 +203,22 @@ export class TorProcess { #processExitedUnexpectedly(exitCode) { this.#subprocess = null; this.#status = TorProcessStatus.Exited; - - // TODO: Move this logic somewhere else? - let s; + // FIXME: We can probably drop #didConnectToTorControlPort and use only one + // callback. Then we can let the provider actually distinguish between the + // cases. if (!this.#didConnectToTorControlPort) { - // tor might be misconfigured, becauser we could never connect to it - const key = "tor_exited_during_startup"; - s = lazy.TorLauncherUtil.getLocalizedString(key); - } else { - // tor exited suddenly, so configuration should be okay - s = - lazy.TorLauncherUtil.getLocalizedString("tor_exited") + - "\n\n" + - lazy.TorLauncherUtil.getLocalizedString("tor_exited2"); - } - logger.info(s); - const defaultBtnLabel = - lazy.TorLauncherUtil.getLocalizedString("restart_tor"); - let cancelBtnLabel = "OK"; - try { - const kSysBundleURI = "chrome://global/locale/commonDialogs.properties"; - const sysBundle = Services.strings.createBundle(kSysBundleURI); - cancelBtnLabel = sysBundle.GetStringFromName(cancelBtnLabel); - } catch (e) { - logger.warn("Could not localize the cancel button", e); - } - - const restart = lazy.TorLauncherUtil.showConfirm( - null, - s, - defaultBtnLabel, - cancelBtnLabel - ); - if (restart) { - this.start().then(this.onRestart); - } else { + logger.warn("Tor exited before we could connect to its control port."); + // tor might be misconfigured, because we could never connect to it. + // Two instances of Tor Browser trying to use the same port numbers is + // also a typical scenario for this. + // This might happen very early, before the browser UI is actually + // available. So, we will tell the process owner that the process exited, + // without trying to restart it. this.onExit(exitCode); + return; } + logger.warn("Tor exited suddenly."); + this.onExit(exitCode); } #makeArgs() { @@ -318,7 +296,7 @@ export class TorProcess { this.#args.push("+__ControlPort", controlPortArg); } - if (this.#controlSettings.password) { + if (this.#controlSettings.password?.length) { this.#args.push( "HashedControlPassword", this.#hashPassword(this.#controlSettings.password) @@ -357,36 +335,43 @@ export class TorProcess { } } - // Based on Vidalia's TorSettings::hashPassword(). - #hashPassword(aHexPassword) { - if (!aHexPassword) { - return null; - } + /** + * Hash a password to then pass it to Tor as a command line argument. + * Based on Vidalia's TorSettings::hashPassword(). + * + * @param {Uint8Array} password The password, as an array of bytes + */ + #hashPassword(password) { + // The password has already been checked by the caller. // Generate a random, 8 byte salt value. const salt = Array.from(crypto.getRandomValues(new Uint8Array(8))); - // Convert hex-encoded password to an array of bytes. - const password = []; - for (let i = 0; i < aHexPassword.length; i += 2) { - password.push(parseInt(aHexPassword.substring(i, i + 2), 16)); - } - // Run through the S2K algorithm and convert to a string. const toHex = v => v.toString(16).padStart(2, "0"); const arrayToHex = aArray => aArray.map(toHex).join(""); const kCodedCount = 96; - const hashVal = this.#cryptoSecretToKey(password, salt, kCodedCount); + const hashVal = this.#cryptoSecretToKey( + Array.from(password), + salt, + kCodedCount + ); return "16:" + arrayToHex(salt) + toHex(kCodedCount) + arrayToHex(hashVal); } - // #cryptoSecretToKey() is similar to Vidalia's crypto_secret_to_key(). - // It generates and returns a hash of aPassword by following the iterated - // and salted S2K algorithm (see RFC 2440 section 3.6.1.3). - // See also https://gitlab.torproject.org/tpo/core/torspec/-/blob/main/control-spec.txt…. - // Returns an array of bytes. - #cryptoSecretToKey(aPassword, aSalt, aCodedCount) { - const inputArray = aSalt.concat(aPassword); + /** + * Generates and return a hash of a password by following the iterated and + * salted S2K algorithm (see RFC 2440 section 3.6.1.3). + * See also https://gitlab.torproject.org/tpo/core/torspec/-/blob/main/control-spec.txt…. + * #cryptoSecretToKey() is similar to Vidalia's crypto_secret_to_key(). + * + * @param {Array} password The password to hash, as an array of bytes + * @param {Array} salt The salt to use for the hash, as an array of bytes + * @param {number} codedCount The counter, coded as specified in RFC 2440 + * @returns {Array} The hash of the password, as an array of bytes + */ + #cryptoSecretToKey(password, salt, codedCount) { + const inputArray = salt.concat(password); // Subtle crypto only has the final digest, and does not allow incremental // updates. @@ -395,7 +380,7 @@ export class TorProcess { ); hasher.init(hasher.SHA1); const kEXPBIAS = 6; - let count = (16 + (aCodedCount & 15)) << ((aCodedCount >> 4) + kEXPBIAS); + let count = (16 + (codedCount & 15)) << ((codedCount >> 4) + kEXPBIAS); while (count > 0) { if (count > inputArray.length) { hasher.update(inputArray, inputArray.length); ===================================== toolkit/components/tor-launcher/TorProvider.sys.mjs ===================================== @@ -2,21 +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/. */ -import { setTimeout, clearTimeout } from "resource://gre/modules/Timer.sys.mjs"; +import { clearTimeout, setTimeout } from "resource://gre/modules/Timer.sys.mjs"; import { ConsoleAPI } from "resource://gre/modules/Console.sys.mjs"; import { TorLauncherUtil } from "resource://gre/modules/TorLauncherUtil.sys.mjs"; -import { - TorParsers, - TorStatuses, -} from "resource://gre/modules/TorParsers.sys.mjs"; +import { TorParsers } from "resource://gre/modules/TorParsers.sys.mjs"; import { TorProviderTopics } from "resource://gre/modules/TorProviderBuilder.sys.mjs"; const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { - controller: "resource://gre/modules/TorControlPort.sys.mjs", - configureControlPortModule: "resource://gre/modules/TorControlPort.sys.mjs", FileUtils: "resource://gre/modules/FileUtils.sys.mjs", + TorController: "resource://gre/modules/TorControlPort.sys.mjs", TorProcess: "resource://gre/modules/TorProcess.sys.mjs", }); @@ -27,20 +23,23 @@ const logger = new ConsoleAPI({ }); /** - * From control-spec.txt: - * CircuitID = 1*16 IDChar - * IDChar = ALPHA / DIGIT - * Currently, Tor only uses digits, but this may change. - * - * @typedef {string} CircuitID + * @typedef {object} ControlPortSettings An object with the settings to use for + * the control port. All the entries are optional, but an authentication + * mechanism and a communication method must be specified. + * @property {Uint8Array=} password The clear text password as an array of + * bytes. It must always be defined, unless cookieFilePath is + * @property {string=} cookieFilePath The path to the cookie file to use for + * authentication + * @property {nsIFile=} ipcFile The nsIFile object with the path to a Unix + * socket to use for control socket + * @property {string=} host The host to connect for a TCP control port + * @property {number=} port The port number to use for a TCP control port */ /** - * The fingerprint of a node. - * From control-spec.txt: - * Fingerprint = "$" 40*HEXDIG - * However, we do not keep the $ in our structures. - * - * @typedef {string} NodeFingerprint + * @typedef {object} LogEntry An object with a log message + * @property {Date} date The date at which we received the message + * @property {string} type The message level + * @property {string} msg The message */ /** * Stores the data associated with a circuit node. @@ -57,15 +56,13 @@ const logger = new ConsoleAPI({ */ const Preferences = Object.freeze({ + ControlUseIpc: "extensions.torlauncher.control_port_use_ipc", + ControlHost: "extensions.torlauncher.control_host", + ControlPort: "extensions.torlauncher.control_port", + MaxLogEntries: "extensions.torlauncher.max_tor_log_entries", PromptAtStartup: "extensions.torlauncher.prompt_at_startup", }); -const ControlConnTimings = Object.freeze({ - initialDelayMS: 25, // Wait 25ms after the process has started, before trying to connect - maxRetryMS: 10000, // Retry at most every 10 seconds - timeoutMS: 5 * 60 * 1000, // Wait at most 5 minutes for tor to start -}); - /** * This is a Tor provider for the C Tor daemon. * @@ -73,61 +70,169 @@ const ControlConnTimings = Object.freeze({ * In the former case, it also takes its ownership by default. */ export class TorProvider { - #inited = false; + /** + * The control port settings. + * + * @type {ControlPortSettings?} + */ + #controlPortSettings = null; + /** + * An instance of the tor controller. + * We take for granted that if it is not null, we connected to it and managed + * to authenticate. + * Public methods can use the #controller getter, which will throw an + * exception whenever the control port is not open. + * + * @type {TorController?} + */ + #controlConnection = null; + /** + * A helper that can be used to get the control port connection and assert it + * is open and it can be used. + * If this is not the case, this getter will throw. + * + * @returns {TorController} + */ + get #controller() { + if (!this.#controlConnection?.isOpen) { + throw new Error("Control port connection not available."); + } + return this.#controlConnection; + } + /** + * A function that can be called to cancel the current connection attempt. + */ + #cancelConnection = () => {}; - // Maintain a map of tor settings set by Tor Browser so that we don't - // repeatedly set the same key/values over and over. - // This map contains string keys to primitives or array values. - #settingsCache = new Map(); + /** + * The tor process we launched. + * + * @type {TorProcess} + */ + #torProcess = null; - #controlPort = null; - #controlHost = null; - #controlIPCFile = null; // An nsIFile if using IPC for control port. - #controlPassword = null; // JS string that contains hex-encoded password. - #SOCKSPortInfo = null; // An object that contains ipcFile, host, port. + /** + * The logs we received over the control port. + * We store a finite number of log entries which can be configured with + * extensions.torlauncher.max_tor_log_entries. + * + * @type {LogEntry[]} + */ + #logs = []; - #controlConnection = null; // This is cached and reused. + #isBootstrapDone = false; + /** + * Keep the last warning to avoid broadcasting an async warning if it is the + * same one as the last broadcast. + */ + #lastWarning = {}; - // Public methods + /** + * Stores the nodes of a circuit. Keys are cicuit IDs, and values are the node + * fingerprints. + * + * Theoretically, we could hook this map up to the new identity notification, + * but in practice it does not work. Tor pre-builds circuits, and the NEWNYM + * signal does not affect them. So, we might end up using a circuit that was + * built before the new identity but not yet used. If we cleaned the map, we + * risked of not having the data about it. + * + * @type {Map<CircuitID, NodeFingerprint[]>} + */ + #circuits = new Map(); + /** + * The last used bridge, or null if bridges are not in use or if it was not + * possible to detect the bridge. This needs the user to have specified bridge + * lines with fingerprints to work. + * + * @type {NodeFingerprint?} + */ + #currentBridge = null; + /** + * Maintain a map of tor settings set by Tor Browser so that we don't + * repeatedly set the same key/values over and over. + * This map contains string keys to primitives or array values. + * + * @type {Map<string, any>} + */ + #settingsCache = new Map(); + + /** + * Starts a new tor process and connect to its control port, or connect to the + * control port of an existing tor daemon. + */ async init() { - if (this.#inited) { - return; + logger.debug("Initializing the Tor provider."); + + const socksSettings = TorLauncherUtil.getPreferredSocksConfiguration(); + logger.debug("Requested SOCKS configuration", socksSettings); + + try { + await this.#setControlPortConfiguration(); + } catch (e) { + logger.error("We do not have a control port configuration", e); + throw e; } - this.#inited = true; - Services.obs.addObserver(this, TorProviderTopics.ProcessExited); - Services.obs.addObserver(this, TorProviderTopics.ProcessRestarted); + if (socksSettings.transproxy) { + logger.info("Transparent proxy required, not starting a Tor daemon."); + } else if (this.ownsTorDaemon) { + try { + await this.#startDaemon(socksSettings); + } catch (e) { + logger.error("Failed to start the tor daemon", e); + throw e; + } + } else { + logger.debug( + "Not starting a tor daemon because we were requested not to." + ); + } + + try { + await this.#firstConnection(); + } catch (e) { + logger.error("Cannot connect to the control port", e); + throw e; + } - await this.#setSockets(); + // We do not customize SOCKS settings, at least for now. + TorLauncherUtil.setProxyConfiguration(socksSettings); - this._monitorInit(); + logger.info("The Tor provider is ready."); - logger.debug("TorProvider initialized"); + logger.debug(`Notifying ${TorProviderTopics.ProcessIsReady}`); + Services.obs.notifyObservers(null, TorProviderTopics.ProcessIsReady); } + /** + * Close the connection to the tor daemon. + * When Tor is started by Tor Browser, it is configured to exit when the + * control connection is closed. Therefore, as a matter of facts, calling this + * function also makes the child Tor instance stop. + */ uninit() { - Services.obs.removeObserver(this, TorProviderTopics.ProcessExited); - Services.obs.removeObserver(this, TorProviderTopics.ProcessRestarted); - this.#closeConnection(); - this._monitorUninit(); - } + logger.debug("Uninitializing the Tor provider."); - observe(subject, topic, data) { - if (topic === TorProviderTopics.ProcessExited) { - this.#closeConnection(); - } else if (topic === TorProviderTopics.ProcessRestarted) { - this.#reconnect(); + if (this.#torProcess) { + this.#torProcess.forget(); + this.#torProcess.onExit = () => {}; + this.#torProcess = null; } + + this.#closeConnection("Uninitializing the provider."); } - // takes a Map containing tor settings - // throws on error - async writeSettings(aSettingsObj) { + // Provider API + + async writeSettings(settingsObj) { + // TODO: Move the translation from settings object to settings understood by + // tor here. const entries = - aSettingsObj instanceof Map - ? Array.from(aSettingsObj.entries()) - : Object.entries(aSettingsObj); + settingsObj instanceof Map + ? Array.from(settingsObj.entries()) + : Object.entries(settingsObj); // only write settings that have changed const newSettings = entries.filter(([setting, value]) => { if (!this.#settingsCache.has(setting)) { @@ -150,8 +255,7 @@ export class TorProvider { // only write if new setting to save if (newSettings.length) { - const conn = await this.#getConnection(); - await conn.setConf(Object.fromEntries(newSettings)); + await this.#controller.setConf(Object.fromEntries(newSettings)); // save settings to cache after successfully writing to Tor for (const [setting, value] of newSettings) { @@ -160,49 +264,76 @@ export class TorProvider { } } - // writes current tor settings to disk async flushSettings() { - const conn = await this.#getConnection(); - await conn.flushSettings(); + await this.#controller.flushSettings(); } + /** + * Start the bootstrap process. + */ async connect() { - const conn = await this.#getConnection(); - await conn.setNetworkEnabled(true); - this.clearBootstrapError(); + await this.#controller.setNetworkEnabled(true); + this.#lastWarning = {}; this.retrieveBootstrapStatus(); } + /** + * Stop the bootstrap process. + */ async stopBootstrap() { - // Tell tor to disable use of the network; this should stop the bootstrap - // process. - const conn = await this.#getConnection(); - await conn.setNetworkEnabled(false); + // Tell tor to disable use of the network; this should stop the bootstrap. + await this.#controller.setNetworkEnabled(false); // We are not interested in waiting for this, nor in **catching its error**, // so we do not await this. We just want to be notified when the bootstrap // status is actually updated through observers. this.retrieveBootstrapStatus(); } + /** + * Ask Tor to swtich to new circuits and clear the DNS cache. + */ async newnym() { - const conn = await this.#getConnection(); - await conn.newnym(); + await this.#controller.newnym(); } + /** + * Get the bridges Tor has been configured with. + * + * @returns {Bridge[]} The configured bridges + */ async getBridges() { - const conn = await this.#getConnection(); // Ideally, we would not need this function, because we should be the one // setting them with TorSettings. However, TorSettings is not notified of // change of settings. So, asking tor directly with the control connection // is the most reliable way of getting the configured bridges, at the // moment. Also, we are using this for the circuit display, which should // work also when we are not configuring the tor daemon, but just using it. - return conn.getBridges(); + return this.#controller.getBridges(); } + /** + * Get the configured pluggable transports. + * + * @returns {PTInfo[]} An array with the info of all the configured pluggable + * transports. + */ async getPluggableTransports() { - const conn = await this.#getConnection(); - return conn.getPluggableTransports(); + return this.#controller.getPluggableTransports(); + } + + /** + * Ask Tor its bootstrap phase. + * This function will also update the internal state when using an external + * tor daemon. + * + * @returns {object} An object with the bootstrap information received from + * Tor. Its keys might vary, depending on the input + */ + async retrieveBootstrapStatus() { + this.#processBootstrapStatus( + await this.#controller.getBootstrapPhase(), + false + ); } /** @@ -212,14 +343,13 @@ export class TorProvider { * @returns {Promise<NodeData>} */ async getNodeInfo(id) { - const conn = await this.#getConnection(); const node = { fingerprint: id, ipAddrs: [], bridgeType: null, regionCode: null, }; - const bridge = (await conn.getBridges())?.find( + const bridge = (await this.#controller.getBridges())?.find( foundBridge => foundBridge.id?.toUpperCase() === id.toUpperCase() ); if (bridge) { @@ -230,14 +360,14 @@ export class TorProvider { node.ipAddrs.push(ip); } } else { - node.ipAddrs = await conn.getNodeAddresses(id); + node.ipAddrs = await this.#controller.getNodeAddresses(id); } if (node.ipAddrs.length) { // Get the country code for the node's IP address. try { // Expect a 2-letter ISO3166-1 code, which should also be a valid // BCP47 Region subtag. - const regionCode = await conn.getIPCountry(node.ipAddrs[0]); + const regionCode = await this.#controller.getIPCountry(node.ipAddrs[0]); if (regionCode && regionCode !== "??") { node.regionCode = regionCode.toUpperCase(); } @@ -248,301 +378,40 @@ export class TorProvider { return node; } + /** + * Add a private key to the Tor configuration. + * + * @param {string} address The address of the onion service + * @param {string} b64PrivateKey The private key of the service, in base64 + * @param {boolean} isPermanent Tell whether the key should be saved forever + */ async onionAuthAdd(address, b64PrivateKey, isPermanent) { - const conn = await this.#getConnection(); - return conn.onionAuthAdd(address, b64PrivateKey, isPermanent); - } - - async onionAuthRemove(address) { - const conn = await this.#getConnection(); - return conn.onionAuthRemove(address); + return this.#controller.onionAuthAdd(address, b64PrivateKey, isPermanent); } - async onionAuthViewKeys() { - const conn = await this.#getConnection(); - return conn.onionAuthViewKeys(); - } - - // TODO: transform the following 4 functions in getters. - - // Returns Tor password string or null if an error occurs. - torGetPassword() { - return this.#controlPassword; - } - - torGetControlIPCFile() { - return this.#controlIPCFile?.clone(); - } - - torGetControlPort() { - return this.#controlPort; - } - - torGetSOCKSPortInfo() { - return this.#SOCKSPortInfo; - } - - get torControlPortInfo() { - const info = { - password: this.#controlPassword, - }; - if (this.#controlIPCFile) { - info.ipcFile = this.#controlIPCFile?.clone(); - } - if (this.#controlPort) { - info.host = this.#controlHost; - info.port = this.#controlPort; - } - return info; - } - - get torSOCKSPortInfo() { - return this.#SOCKSPortInfo; - } - - async #setSockets() { - try { - const isWindows = TorLauncherUtil.isWindows; - // Determine how Tor Launcher will connect to the Tor control port. - // Environment variables get top priority followed by preferences. - if (!isWindows && Services.env.exists("TOR_CONTROL_IPC_PATH")) { - const ipcPath = Services.env.get("TOR_CONTROL_IPC_PATH"); - this.#controlIPCFile = new lazy.FileUtils.File(ipcPath); - } else { - // Check for TCP host and port environment variables. - if (Services.env.exists("TOR_CONTROL_HOST")) { - this.#controlHost = Services.env.get("TOR_CONTROL_HOST"); - } - if (Services.env.exists("TOR_CONTROL_PORT")) { - this.#controlPort = parseInt( - Services.env.get("TOR_CONTROL_PORT"), - 10 - ); - } - - const useIPC = - !isWindows && - Services.prefs.getBoolPref( - "extensions.torlauncher.control_port_use_ipc", - false - ); - if (!this.#controlHost && !this.#controlPort && useIPC) { - this.#controlIPCFile = TorLauncherUtil.getTorFile( - "control_ipc", - false - ); - } else { - if (!this.#controlHost) { - this.#controlHost = Services.prefs.getCharPref( - "extensions.torlauncher.control_host", - "127.0.0.1" - ); - } - if (!this.#controlPort) { - this.#controlPort = Services.prefs.getIntPref( - "extensions.torlauncher.control_port", - 9151 - ); - } - } - } - - // Populate _controlPassword so it is available when starting tor. - if (Services.env.exists("TOR_CONTROL_PASSWD")) { - this.#controlPassword = Services.env.get("TOR_CONTROL_PASSWD"); - } else if (Services.env.exists("TOR_CONTROL_COOKIE_AUTH_FILE")) { - // TODO: test this code path (TOR_CONTROL_COOKIE_AUTH_FILE). - const cookiePath = Services.env.get("TOR_CONTROL_COOKIE_AUTH_FILE"); - if (cookiePath) { - this.#controlPassword = await this.#readAuthenticationCookie( - cookiePath - ); - } - } - if (!this.#controlPassword) { - this.#controlPassword = this.#generateRandomPassword(); - } - - this.#SOCKSPortInfo = TorLauncherUtil.getPreferredSocksConfiguration(); - TorLauncherUtil.setProxyConfiguration(this.#SOCKSPortInfo); - - // Set the global control port info parameters. - lazy.configureControlPortModule( - this.#controlIPCFile, - this.#controlHost, - this.#controlPort, - this.#controlPassword - ); - } catch (e) { - logger.error("Failed to get environment variables", e); - } - } - - async #getConnection() { - if (!this.#controlConnection?.isOpen) { - this.#controlConnection = await lazy.controller(); - } - return this.#controlConnection; - } - - #closeConnection() { - if (this.#controlConnection) { - logger.info("Closing the control connection"); - this.#controlConnection.close(); - this.#controlConnection = null; - } - } - - async #reconnect() { - this.#closeConnection(); - await this.#getConnection(); - } - - async #readAuthenticationCookie(aPath) { - const bytes = await IOUtils.read(aPath); - return Array.from(bytes, b => this.#toHex(b, 2)).join(""); - } - - // Returns a random 16 character password, hex-encoded. - #generateRandomPassword() { - // Similar to Vidalia's crypto_rand_string(). - const kPasswordLen = 16; - const kMinCharCode = "!".charCodeAt(0); - const kMaxCharCode = "~".charCodeAt(0); - let pwd = ""; - for (let i = 0; i < kPasswordLen; ++i) { - const val = this.#cryptoRandInt(kMaxCharCode - kMinCharCode + 1); - if (val < 0) { - logger.error("_cryptoRandInt() failed"); - return null; - } - pwd += this.#toHex(kMinCharCode + val, 2); - } - - return pwd; - } - - // Returns -1 upon failure. - #cryptoRandInt(aMax) { - // Based on tor's crypto_rand_int(). - const maxUInt = 0xffffffff; - if (aMax <= 0 || aMax > maxUInt) { - return -1; - } - - const cutoff = maxUInt - (maxUInt % aMax); - let val = cutoff; - while (val >= cutoff) { - const uint32 = new Uint32Array(1); - crypto.getRandomValues(uint32); - val = uint32[0]; - } - return val % aMax; - } - - #toHex(aValue, aMinLen) { - return aValue.toString(16).padStart(aMinLen, "0"); - } - - // Former TorMonitorService implementation. - // FIXME: Refactor and integrate more with the rest of the class. - - _connection = null; - _eventHandlers = {}; - _torLog = []; // Array of objects with date, type, and msg properties - _startTimeout = null; - - _isBootstrapDone = false; - _lastWarningPhase = null; - _lastWarningReason = null; - - _torProcess = null; - - _inited = false; - /** - * Stores the nodes of a circuit. Keys are cicuit IDs, and values are the node - * fingerprints. + * Remove a private key from the Tor configuration. * - * Theoretically, we could hook this map up to the new identity notification, - * but in practice it does not work. Tor pre-builds circuits, and the NEWNYM - * signal does not affect them. So, we might end up using a circuit that was - * built before the new identity but not yet used. If we cleaned the map, we - * risked of not having the data about it. - * - * @type {Map<CircuitID, NodeFingerprint[]>} + * @param {string} address The address of the onion service */ - _circuits = new Map(); + async onionAuthRemove(address) { + return this.#controller.onionAuthRemove(address); + } + /** - * The last used bridge, or null if bridges are not in use or if it was not - * possible to detect the bridge. This needs the user to have specified bridge - * lines with fingerprints to work. + * Retrieve the list of private keys. * - * @type {NodeFingerprint?} + * @returns {OnionAuthKeyInfo[]} */ - _currentBridge = null; - - // Public methods - - // Starts Tor, if needed, and starts monitoring for events - _monitorInit() { - if (this._inited) { - return; - } - this._inited = true; - - // We always liten to these events, because they are needed for the circuit - // display. - this._eventHandlers = new Map([ - ["CIRC", this._processCircEvent.bind(this)], - ["STREAM", this._processStreamEvent.bind(this)], - ]); - - if (this.ownsTorDaemon) { - // When we own the tor daemon, we listen to more events, that are used - // for about:torconnect or for showing the logs in the settings page. - this._eventHandlers.set( - "STATUS_CLIENT", - this._processStatusClient.bind(this) - ); - this._eventHandlers.set("NOTICE", this._processLog.bind(this)); - this._eventHandlers.set("WARN", this._processLog.bind(this)); - this._eventHandlers.set("ERR", this._processLog.bind(this)); - this._controlTor(); - } else { - this._startEventMonitor(); - } - logger.info("TorMonitorService initialized"); - } - - // Closes the connection that monitors for events. - // When Tor is started by Tor Browser, it is configured to exit when the - // control connection is closed. Therefore, as a matter of facts, calling this - // function also makes the child Tor instance stop. - _monitorUninit() { - if (this._torProcess) { - this._torProcess.forget(); - this._torProcess.onExit = null; - this._torProcess.onRestart = null; - this._torProcess = null; - } - this._shutDownEventMonitor(); - } - - async retrieveBootstrapStatus() { - if (!this._connection) { - throw new Error("Event monitor connection not available"); - } - - this._processBootstrapStatus( - await this._connection.getBootstrapPhase(), - true - ); + async onionAuthViewKeys() { + return this.#controller.onionAuthViewKeys(); } - // Returns captured log message as a text string (one message per line). + /** + * Returns captured log message as a text string (one message per line). + */ getLog() { - return this._torLog + return this.#logs .map(logObj => { const timeStr = logObj.date .toISOString() @@ -553,22 +422,27 @@ export class TorProvider { .join(TorLauncherUtil.isWindows ? "\r\n" : "\n"); } - // true if we launched and control tor, false if using system tor + /** + * @returns {boolean} true if we launched and control tor, false if we are + * using system tor. + */ get ownsTorDaemon() { return TorLauncherUtil.shouldStartAndOwnTor; } get isBootstrapDone() { - return this._isBootstrapDone; - } - - clearBootstrapError() { - this._lastWarningPhase = null; - this._lastWarningReason = null; + return this.#isBootstrapDone; } + /** + * TODO: Rename to isReady once we remove finish the migration. + * + * @returns {boolean} true if we currently have a connection to the control + * port. We take for granted that if we have one, we authenticated to it, and + * so we have already verified we can send and receive data. + */ get isRunning() { - return !!this._connection; + return this.#controlConnection?.isOpen ?? false; } /** @@ -580,258 +454,380 @@ export class TorProvider { * is not a bridge, or no circuit has been opened, yet. */ get currentBridge() { - return this._currentBridge; + return this.#currentBridge; } - // Private methods + // Process management - async _startProcess() { + async #startDaemon(socksSettings) { // TorProcess should be instanced once, then always reused and restarted // only through the prompt it exposes when the controlled process dies. - if (!this._torProcess) { - this._torProcess = new lazy.TorProcess( - this.torControlPortInfo, - this.torSOCKSPortInfo + if (this.#torProcess) { + logger.warn( + "Ignoring a request to start a tor daemon because one is already running." ); - this._torProcess.onExit = () => { - this._shutDownEventMonitor(); - Services.obs.notifyObservers(null, TorProviderTopics.ProcessExited); - }; - this._torProcess.onRestart = async () => { - this._shutDownEventMonitor(); - await this._controlTor(); - Services.obs.notifyObservers(null, TorProviderTopics.ProcessRestarted); - }; + return; } - // Already running, but we did not start it - if (this._torProcess.isRunning) { - return false; - } + this.#torProcess = new lazy.TorProcess( + this.#controlPortSettings, + socksSettings + ); + // Use a closure instead of bind because we reassign #cancelConnection. + // Also, we now assign an exit handler that cancels the first connection, + // so that a sudden exit before the first connection is completed might + // still be handled as an initialization failure. + // But after the first connection is created successfully, we will change + // the exit handler to broadcast a notification instead. + this.#torProcess.onExit = () => { + this.#cancelConnection( + "The tor process exited before the first connection" + ); + }; - try { - await this._torProcess.start(); - if (this._torProcess.isRunning) { - logger.info("tor started"); - this._torProcessStartTime = Date.now(); - } - } catch (e) { - // TorProcess already logs the error. - this._lastWarningPhase = "startup"; - this._lastWarningReason = e.toString(); - } - return this._torProcess.isRunning; + logger.debug("Trying to start the tor process."); + await this.#torProcess.start(); + logger.info("Started a tor process"); } - async _controlTor() { - if (!this._torProcess?.isRunning && !(await this._startProcess())) { - logger.error("Tor not running, not starting to monitor it."); - return; - } - - let delayMS = ControlConnTimings.initialDelayMS; - const callback = async () => { - if (await this._startEventMonitor()) { - this.retrieveBootstrapStatus().catch(e => { - logger.warn("Could not get the initial bootstrap status", e); - }); - - // FIXME: TorProcess is misleading here. We should use a topic related - // to having a control port connection, instead. - logger.info(`Notifying ${TorProviderTopics.ProcessIsReady}`); - Services.obs.notifyObservers(null, TorProviderTopics.ProcessIsReady); + // Control port setup and connection - // We reset this here hoping that _shutDownEventMonitor can interrupt - // the current monitor, either by calling clearTimeout and preventing it - // from starting, or by closing the control port connection. - if (this._startTimeout === null) { - logger.warn("Someone else reset _startTimeout!"); - } - this._startTimeout = null; - } else if ( - Date.now() - this._torProcessStartTime > - ControlConnTimings.timeoutMS - ) { - let s = TorLauncherUtil.getLocalizedString("tor_controlconn_failed"); - this._lastWarningPhase = "startup"; - this._lastWarningReason = s; - logger.info(s); - if (this._startTimeout === null) { - logger.warn("Someone else reset _startTimeout!"); - } - this._startTimeout = null; - } else { - delayMS *= 2; - if (delayMS > ControlConnTimings.maxRetryMS) { - delayMS = ControlConnTimings.maxRetryMS; + /** + * Read the control port settings from environment variables and from + * preferences. + */ + async #setControlPortConfiguration() { + logger.debug("Reading the control port configuration"); + const settings = {}; + + const isWindows = Services.appinfo.OS === "WINNT"; + // Determine how Tor Launcher will connect to the Tor control port. + // Environment variables get top priority followed by preferences. + if (!isWindows && Services.env.exists("TOR_CONTROL_IPC_PATH")) { + const ipcPath = Services.env.get("TOR_CONTROL_IPC_PATH"); + settings.ipcFile = new lazy.FileUtils.File(ipcPath); + } else { + // Check for TCP host and port environment variables. + if (Services.env.exists("TOR_CONTROL_HOST")) { + settings.host = Services.env.get("TOR_CONTROL_HOST"); + } + if (Services.env.exists("TOR_CONTROL_PORT")) { + const port = parseInt(Services.env.get("TOR_CONTROL_PORT"), 10); + if (Number.isInteger(port) && port > 0 && port <= 65535) { + settings.port = port; } - this._startTimeout = setTimeout(() => { - logger.debug(`Control port not ready, waiting ${delayMS / 1000}s.`); - callback(); - }, delayMS); } - }; - // Check again, in the unfortunate case in which the execution was alrady - // queued, but was waiting network code. - if (this._startTimeout === null) { - this._startTimeout = setTimeout(callback, delayMS); - } else { - logger.error("Possible race? Refusing to start the timeout again"); } - } - async _startEventMonitor() { - if (this._connection) { - return true; + const useIPC = + !isWindows && + Services.prefs.getBoolPref(Preferences.ControlUseIpc, false); + if (!settings.host && !settings.port && useIPC) { + settings.ipcFile = TorLauncherUtil.getTorFile("control_ipc", false); + } else { + if (!settings.host) { + settings.host = Services.prefs.getCharPref( + Preferences.ControlHost, + "127.0.0.1" + ); + } + if (!settings.port) { + settings.port = Services.prefs.getIntPref( + Preferences.ControlPort, + 9151 + ); + } } - let conn; - try { - conn = await lazy.controller(); - } catch (e) { - logger.error("Cannot open a control port connection", e); - if (conn) { - try { - conn.close(); - } catch (e) { - logger.error( - "Also, the connection is not null but cannot be closed", - e - ); + if (Services.env.exists("TOR_CONTROL_PASSWD")) { + const password = Services.env.get("TOR_CONTROL_PASSWD"); + // As per 3.5 of control-spec.txt, AUTHENTICATE can use either a quoted + // string, or a sequence of hex characters. + // However, the password is hashed byte by byte, so we need to convert the + // string to its character codes, or the hex digits to actual bytes. + // Notice that Tor requires at least one hex character, without an upper + // limit, but it does not explicitly tell how to pad an odd number of hex + // characters, so we require the user to hand an even number of hex + // digits. + // We also want to enforce the authentication if we start the daemon. + // So, if a password is not valid (not a hex sequence and not a quoted + // string), or if it is empty (including the quoted empty string), we + // force a random password. + if ( + password.length >= 2 && + password[0] === '"' && + password[password.length - 1] === '"' + ) { + const encoder = new TextEncoder(); + settings.password = encoder.encode(TorParsers.unescapeString(password)); + } else if (/^([0-9a-fA-F]{2})+$/.test(password)) { + settings.password = new Uint8Array(password.length / 2); + for (let i = 0, j = 0; i < settings.password.length; i++, j += 2) { + settings.password[i] = parseInt(password.substring(j, j + 2), 16); } } - return false; - } - - // TODO: optionally monitor INFO and DEBUG log messages. - try { - await conn.setEvents(Array.from(this._eventHandlers.keys())); - } catch (e) { - logger.error("SETEVENTS failed", e); - conn.close(); - return false; - } - - if (this._torProcess) { - this._torProcess.connectionWorked(); - } - if (this.ownsTorDaemon && !TorLauncherUtil.shouldOnlyConfigureTor) { - try { - await this._takeTorOwnership(conn); - } catch (e) { - logger.warn("Could not take ownership of the Tor daemon", e); + if (password && !settings.password?.length) { + logger.warn( + "Invalid password specified at TOR_CONTROL_PASSWD. " + + "You should put it in double quotes, or it should be a hex-encoded sequence. " + + "The password cannot be empty. " + + "A random password will be used, instead." + ); + } + } else if (Services.env.exists("TOR_CONTROL_COOKIE_AUTH_FILE")) { + const cookiePath = Services.env.get("TOR_CONTROL_COOKIE_AUTH_FILE"); + if (cookiePath) { + settings.cookieFilePath = cookiePath; } } - - this._connection = conn; - - for (const [type, callback] of this._eventHandlers.entries()) { - this._monitorEvent(type, callback); + if ( + this.ownsTorDaemon && + !settings.password?.length && + !settings.cookieFilePath + ) { + settings.password = this.#generateRandomPassword(); } + this.#controlPortSettings = settings; + logger.debug("Control port configuration read"); + } - // Populate the circuit map already, in case we are connecting to an - // external tor daemon. - try { - const reply = await this._connection.sendCommand( - "GETINFO circuit-status" - ); - const lines = reply.split(/\r?\n/); - if (lines.shift() === "250+circuit-status=") { - for (const line of lines) { - if (line === ".") { - break; - } - // _processCircEvent processes only one line at a time - this._processCircEvent("CIRC", [line]); + /** + * Start the first connection to the Tor daemon. + * This function should be called only once during the initialization. + */ + async #firstConnection() { + let canceled = false; + let timeout = 0; + const maxDelay = 10_000; + let delay = 5; + logger.debug("Connecting to the control port for the first time."); + this.#controlConnection = await new Promise((resolve, reject) => { + this.#cancelConnection = reason => { + canceled = true; + clearTimeout(timeout); + reject(new Error(reason)); + }; + const tryConnect = () => { + if (this.ownsTorDaemon && !this.#torProcess?.isRunning) { + reject(new Error("The controlled tor daemon is not running.")); + return; } + this.#openControlPort() + .then(controller => { + this.#torProcess?.connectionWorked(); + this.#cancelConnection = () => {}; + // The cancel function should have already called reject. + if (!canceled) { + logger.info("Connected to the control port."); + resolve(controller); + } + }) + .catch(e => { + if (delay < maxDelay && !canceled) { + logger.info( + `Failed to connect to the control port. Trying again in ${delay}ms.`, + e + ); + timeout = setTimeout(tryConnect, delay); + delay *= 2; + } else { + reject(e); + } + }); + }; + tryConnect(); + }); + + // The following code will never throw, but we still want to wait for it + // before marking the provider as initialized. + + if (this.ownsTorDaemon) { + // The first connection cannot be canceled anymore, and the rest of the + // code is supposed not to fail. If the tor process exits, from now on we + // can only close the connection and broadcast a notification. + this.#torProcess.onExit = exitCode => { + logger.info(`The tor process exited with code ${exitCode}`); + this.#closeConnection("The tor process exited suddenly"); + Services.obs.notifyObservers(null, TorProviderTopics.ProcessExited); + }; + if (!TorLauncherUtil.shouldOnlyConfigureTor) { + await this.#takeOwnership(); } - } catch (e) { - logger.warn("Could not populate the initial circuit map", e); } - - return true; + await this.#setupEvents(); } - // Try to become the primary controller (TAKEOWNERSHIP). - async _takeTorOwnership(conn) { + /** + * Try to become the primary controller. This will make tor exit when our + * connection is closed. + * This function cannot fail or throw (any exception will be treated as a + * warning and just logged). + */ + async #takeOwnership() { + logger.debug("Taking the ownership of the tor process."); try { - conn.takeOwnership(); + await this.#controlConnection.takeOwnership(); } catch (e) { logger.warn("Take ownership failed", e); return; } try { - conn.resetOwningControllerProcess(); + await this.#controlConnection.resetOwningControllerProcess(); } catch (e) { logger.warn("Clear owning controller process failed", e); } } - _monitorEvent(type, callback) { - logger.info(`Watching events of type ${type}.`); - let replyObj = {}; - this._connection.watchEvent(type, line => { - if (!line) { - return; - } - logger.debug("Event response: ", line); - const isComplete = TorParsers.parseReplyLine(line, replyObj); - if (!isComplete || replyObj._parseError || !replyObj.lineArray.length) { - return; - } - const reply = replyObj; - replyObj = {}; - if (reply.statusCode !== TorStatuses.EventNotification) { - logger.error("Unexpected event status code:", reply.statusCode); - return; + /** + * Tells the Tor daemon which events we want to receive. + * This function will never throw. Any failure will be treated as a warning of + * a possibly degraded experience, not as an error. + */ + async #setupEvents() { + // We always listen to these events, because they are needed for the circuit + // display. + const events = ["CIRC", "STREAM"]; + if (this.ownsTorDaemon) { + events.push("STATUS_CLIENT", "NOTICE", "WARN", "ERR"); + // Do not await on the first bootstrap status retrieval, and do not + // propagate its errors. + this.#controlConnection + .getBootstrapPhase() + .then(status => this.#processBootstrapStatus(status, false)) + .catch(e => + logger.error("Failed to get the first bootstrap status", e) + ); + } + try { + logger.debug(`Setting events: ${events.join(" ")}`); + await this.#controlConnection.setEvents(events); + } catch (e) { + logger.error( + "We could not enable all the events we need. Tor Browser's functionalities might be reduced.", + e + ); + } + } + + /** + * Open a connection to the control port and authenticate to it. + * #setControlPortConfiguration must have been called before, as this function + * will follow the configuration set by it. + * + * @returns {Promise<TorController>} An authenticated TorController + */ + async #openControlPort() { + let controlPort; + if (this.#controlPortSettings.ipcFile) { + controlPort = lazy.TorController.fromIpcFile( + this.#controlPortSettings.ipcFile, + this + ); + } else { + controlPort = lazy.TorController.fromSocketAddress( + this.#controlPortSettings.host, + this.#controlPortSettings.port, + this + ); + } + try { + let password = this.#controlPortSettings.password; + if (password === undefined && this.#controlPortSettings.cookieFilePath) { + password = await this.#readAuthenticationCookie( + this.#controlPortSettings.cookieFilePath + ); } - if (!reply.lineArray[0].startsWith(`${type} `)) { - logger.error("Wrong format for the first line:", reply.lineArray[0]); - return; + await controlPort.authenticate(password); + } catch (e) { + try { + controlPort.close(); + } catch (ec) { + // Tor already closes the control port when the authentication fails. + logger.debug( + "Expected exception when closing the control port for a failed authentication", + ec + ); } - reply.lineArray[0] = reply.lineArray[0].substring(type.length + 1); + throw e; + } + return controlPort; + } + + /** + * Close the connection to the control port. + * + * @param {string} reason The reason for which we are closing the connection + * (used for logging and in case this ends up canceling the current connection + * attempt) + */ + #closeConnection(reason) { + this.#cancelConnection(reason); + if (this.#controlConnection) { + logger.info("Closing the control connection", reason); try { - callback(type, reply.lineArray); + this.#controlConnection.close(); } catch (e) { - logger.error("Exception while handling an event", reply, e); + logger.error("Failed to close the control port connection", e); } - }); + this.#controlConnection = null; + } else { + logger.trace( + "Requested to close an already closed control port connection" + ); + } + this.#isBootstrapDone = false; + this.#lastWarning = {}; } - _processLog(type, lines) { - if (type === "WARN" || type === "ERR") { - // Notify so that Copy Log can be enabled. - Services.obs.notifyObservers(null, TorProviderTopics.HasWarnOrErr); - } + // Authentication - const date = new Date(); - const maxEntries = Services.prefs.getIntPref( - "extensions.torlauncher.max_tor_log_entries", - 1000 - ); - if (maxEntries > 0 && this._torLog.length >= maxEntries) { - this._torLog.splice(0, 1); - } + /** + * Read a cookie file to perform cookie-based authentication. + * + * @param {string} path The path to the cookie file + * @returns {Uint8Array} The content of the file in bytes + */ + async #readAuthenticationCookie(path) { + return IOUtils.read(path); + } - const msg = lines.join("\n"); - this._torLog.push({ date, type, msg }); - const logString = `Tor ${type}: ${msg}`; - logger.info(logString); + /** + * @returns {Uint8Array} A random 16-byte password. + */ + #generateRandomPassword() { + const kPasswordLen = 16; + return crypto.getRandomValues(new Uint8Array(kPasswordLen)); + } + + // Notification handlers + + /** + * Receive and process a notification with the bootstrap status. + * + * @param {object} status The status object + */ + onBootstrapStatus(status) { + this.#processBootstrapStatus(status, true); } - // Process a bootstrap status to update the current state, and broadcast it - // to TorBootstrapStatus observers. - // If aSuppressErrors is true, errors are ignored. This is used when we - // are handling the response to a "GETINFO status/bootstrap-phase" command. - _processBootstrapStatus(statusObj, suppressErrors) { + /** + * Process a bootstrap status to update the current state, and broadcast it + * to TorBootstrapStatus observers. + * + * @param {object} statusObj The status object that the controller returned. + * Its entries depend on what Tor sent to us. + * @param {boolean} isNotification We broadcast warnings only when we receive + * them through an asynchronous notification. + */ + #processBootstrapStatus(statusObj, isNotification) { // Notify observers Services.obs.notifyObservers( { wrappedJSObject: statusObj }, - "TorBootstrapStatus" + TorProviderTopics.BootstrapStatus ); if (statusObj.PROGRESS === 100) { - this._isBootstrapDone = true; + this.#isBootstrapDone = true; try { Services.prefs.setBoolPref(Preferences.PromptAtStartup, false); } catch (e) { @@ -840,23 +836,29 @@ export class TorProvider { return; } - this._isBootstrapDone = false; + this.#isBootstrapDone = false; if ( + isNotification && statusObj.TYPE === "WARN" && - statusObj.RECOMMENDATION !== "ignore" && - !suppressErrors + statusObj.RECOMMENDATION !== "ignore" ) { - this._notifyBootstrapError(statusObj); + this.#notifyBootstrapError(statusObj); } } - _notifyBootstrapError(statusObj) { + /** + * Broadcast a bootstrap warning or error. + * + * @param {object} statusObj The bootstrap status object with the error + */ + #notifyBootstrapError(statusObj) { try { Services.prefs.setBoolPref(Preferences.PromptAtStartup, true); } catch (e) { logger.warn(`Cannot set ${Preferences.PromptAtStartup}`, e); } + // TODO: Move l10n to the above layers? const phase = TorLauncherUtil.getLocalizedBootstrapStatus(statusObj, "TAG"); const reason = TorLauncherUtil.getLocalizedBootstrapStatus( statusObj, @@ -872,11 +874,11 @@ export class TorProvider { ); if ( - statusObj.TAG !== this._lastWarningPhase || - statusObj.REASON !== this._lastWarningReason + statusObj.TAG !== this.#lastWarning.phase || + statusObj.REASON !== this.#lastWarning.reason ) { - this._lastWarningPhase = statusObj.TAG; - this._lastWarningReason = statusObj.REASON; + this.#lastWarning.phase = statusObj.TAG; + this.#lastWarning.reason = statusObj.REASON; const message = TorLauncherUtil.getLocalizedString( "tor_bootstrap_failed" @@ -888,123 +890,122 @@ export class TorProvider { } } - _processStatusClient(_type, lines) { - const statusObj = TorParsers.parseBootstrapStatus(lines[0]); - if (!statusObj) { - // No `BOOTSTRAP` in the line - return; + /** + * Handle a log message from the tor daemon. It will be added to the internal + * logs. If it is a warning or an error, a notification will be broadcast. + * + * @param {string} type The message type + * @param {string} msg The message + */ + onLogMessage(type, msg) { + if (type === "WARN" || type === "ERR") { + // Notify so that Copy Log can be enabled. + Services.obs.notifyObservers(null, TorProviderTopics.HasWarnOrErr); } - this._processBootstrapStatus(statusObj, false); - } - async _processCircEvent(_type, lines) { - const builtEvent = - /^(?<CircuitID>[a-zA-Z0-9]{1,16})\sBUILT\s(?<Path>(?:,?\$[0-9a-fA-F]{40}(?:~[a-zA-Z0-9]{1,19})?)+)/.exec( - lines[0] - ); - const closedEvent = /^(?<ID>[a-zA-Z0-9]{1,16})\sCLOSED/.exec(lines[0]); - if (builtEvent) { - const fp = /\$([0-9a-fA-F]{40})/g; - const nodes = Array.from(builtEvent.groups.Path.matchAll(fp), g => - g[1].toUpperCase() - ); - this._circuits.set(builtEvent.groups.CircuitID, nodes); - // Ignore circuits of length 1, that are used, for example, to probe - // bridges. So, only store them, since we might see streams that use them, - // but then early-return. - if (nodes.length === 1) { - return; - } - // In some cases, we might already receive SOCKS credentials in the line. - // However, this might be a problem with onion services: we get also a - // 4-hop circuit that we likely do not want to show to the user, - // especially because it is used only temporarily, and it would need a - // technical explaination. - // this._checkCredentials(lines[0], nodes); - if (this._currentBridge?.fingerprint !== nodes[0]) { - const nodeInfo = await this.getNodeInfo(nodes[0]); - let notify = false; - if (nodeInfo?.bridgeType) { - logger.info(`Bridge changed to ${nodes[0]}`); - this._currentBridge = nodeInfo; - notify = true; - } else if (this._currentBridge) { - logger.info("Bridges disabled"); - this._currentBridge = null; - notify = true; - } - if (notify) { - Services.obs.notifyObservers( - null, - TorProviderTopics.BridgeChanged, - this._currentBridge - ); - } - } - } else if (closedEvent) { - this._circuits.delete(closedEvent.groups.ID); + const date = new Date(); + const maxEntries = Services.prefs.getIntPref( + Preferences.MaxLogEntries, + 1000 + ); + if (maxEntries > 0 && this.#logs.length >= maxEntries) { + this.#logs.splice(0, 1); + } + + this.#logs.push({ date, type, msg }); + switch (type) { + case "ERR": + logger.error(`[Tor error] ${msg}`); + break; + case "WARN": + logger.warn(`[Tor warning] ${msg}`); + break; + default: + logger.info(`[Tor ${type.toLowerCase()}] ${msg}`); } } - _processStreamEvent(_type, lines) { - // The first block is the stream ID, which we do not need at the moment. - const succeeedEvent = - /^[a-zA-Z0-9]{1,16}\sSUCCEEDED\s(?<CircuitID>[a-zA-Z0-9]{1,16})/.exec( - lines[0] - ); - if (!succeeedEvent) { + /** + * Handle a notification that a new circuit has been built. + * If a change of bridge is detected (including a change from bridge to a + * normal guard), a notification is broadcast. + * + * @param {CircuitID} id The circuit ID + * @param {NodeFingerprint[]} nodes The nodes that compose the circuit + */ + async onCircuitBuilt(id, nodes) { + this.#circuits.set(id, nodes); + // Ignore circuits of length 1, that are used, for example, to probe + // bridges. So, only store them, since we might see streams that use them, + // but then early-return. + if (nodes.length === 1) { return; } - const circuit = this._circuits.get(succeeedEvent.groups.CircuitID); - if (!circuit) { - logger.error( - "Seen a STREAM SUCCEEDED with an unknown circuit. Not notifying observers.", - lines[0] - ); - return; + + if (this.#currentBridge?.fingerprint !== nodes[0]) { + const nodeInfo = await this.getNodeInfo(nodes[0]); + let notify = false; + if (nodeInfo?.bridgeType) { + logger.info(`Bridge changed to ${nodes[0]}`); + this.#currentBridge = nodeInfo; + notify = true; + } else if (this.#currentBridge) { + logger.info("Bridges disabled"); + this.#currentBridge = null; + notify = true; + } + if (notify) { + Services.obs.notifyObservers( + null, + TorProviderTopics.BridgeChanged, + this.#currentBridge + ); + } } - this._checkCredentials(lines[0], circuit); } /** - * Check if a STREAM or CIRC response line contains SOCKS_USERNAME and - * SOCKS_PASSWORD. In case, notify observers that we could associate a certain - * circuit to these credentials. + * Handle a notification of a circuit being closed. We use it to clean the + * internal data. + * + * @param {CircuitID} id The circuit id + */ + onCircuitClosed(id) { + logger.debug("Circuit closed event", id); + this.#circuits.delete(id); + } + + /** + * Handle a notification about a stream switching to the succeeded state. * - * @param {string} line The circ or stream line to check - * @param {NodeFingerprint[]} circuit The fingerprints of the nodes in the - * circuit. + * @param {StreamID} streamId The ID of the stream that switched to the + * succeeded state. + * @param {CircuitID} circuitId The ID of the circuit used by the stream + * @param {string} username The SOCKS username + * @param {string} password The SOCKS password + * @returns */ - _checkCredentials(line, circuit) { - const username = /SOCKS_USERNAME=("(?:[^"\\]|\\.)*")/.exec(line); - const password = /SOCKS_PASSWORD=("(?:[^"\\]|\\.)*")/.exec(line); + onStreamSucceeded(streamId, circuitId, username, password) { if (!username || !password) { return; } + logger.debug("Stream succeeded event", username, password, circuitId); + const circuit = this.#circuits.get(circuitId); + if (!circuit) { + logger.error( + "Seen a STREAM SUCCEEDED with an unknown circuit. Not notifying observers." + ); + return; + } Services.obs.notifyObservers( { wrappedJSObject: { - username: TorParsers.unescapeString(username[1]), - password: TorParsers.unescapeString(password[1]), + username, + password, circuit, }, }, TorProviderTopics.StreamSucceeded ); } - - _shutDownEventMonitor() { - try { - this._connection?.close(); - } catch (e) { - logger.error("Could not close the connection to the control port", e); - } - this._connection = null; - if (this._startTimeout !== null) { - clearTimeout(this._startTimeout); - this._startTimeout = null; - } - this._isBootstrapDone = false; - this.clearBootstrapError(); - } } ===================================== toolkit/components/tor-launcher/TorProviderBuilder.sys.mjs ===================================== @@ -4,13 +4,13 @@ const lazy = {}; ChromeUtils.defineESModuleGetters(lazy, { + TorLauncherUtil: "resource://gre/modules/TorLauncherUtil.sys.mjs", TorProvider: "resource://gre/modules/TorProvider.sys.mjs", }); export const TorProviderTopics = Object.freeze({ ProcessIsReady: "TorProcessIsReady", ProcessExited: "TorProcessExited", - ProcessRestarted: "TorProcessRestarted", BootstrapStatus: "TorBootstrapStatus", BootstrapError: "TorBootstrapError", HasWarnOrErr: "TorLogHasWarnOrErr", @@ -18,26 +18,141 @@ export const TorProviderTopics = Object.freeze({ StreamSucceeded: "TorStreamSucceeded", }); +/** + * The factory to get a Tor provider. + * Currently we support only TorProvider, i.e., the one that interacts with + * C-tor through the control port protocol. + */ export class TorProviderBuilder { + /** + * A promise with the instance of the provider that we are using. + * + * @type {Promise<TorProvider>?} + */ static #provider = null; + /** + * The observer that checks when the tor process exits, and reinitializes the + * provider. + * + * @type {nsIObserver?} + */ + static #observer = null; + + /** + * Tell whether the browser UI is ready. + * We ignore any errors until it is because we cannot show them. + * + * @type {boolean} + */ + static #uiReady = false; + + /** + * Initialize the provider of choice. + * Even though initialization is asynchronous, we do not expect the caller to + * await this method. The reason is that any call to build() will wait the + * initialization anyway (and re-throw any initialization error). + */ static async init() { - const provider = new lazy.TorProvider(); - await provider.init(); - // Assign it only when initialization succeeds. - TorProviderBuilder.#provider = provider; + this.#observer = { + observe(subject, topic, data) { + if (topic !== TorProviderTopics.ProcessExited) { + return; + } + if (!TorProviderBuilder.#uiReady) { + console.warn( + `Seen ${TorProviderTopics.ProcessExited}, but not doing anything because the UI is not ready yet.` + ); + return; + } + TorProviderBuilder.#torExited(); + }, + }; + Services.obs.addObserver(this.#observer, TorProviderTopics.ProcessExited); + await this.#initProvider(); + } + + static async #initProvider() { + try { + const old = await this.#provider; + old?.uninit(); + } catch {} + this.#provider = new Promise((resolve, reject) => { + const provider = new lazy.TorProvider(); + provider + .init() + .then(() => resolve(provider)) + .catch(reject); + }); + await this.#provider; } static uninit() { - TorProviderBuilder.#provider.uninit(); - TorProviderBuilder.#provider = null; + this.#provider?.then(provider => { + provider.uninit(); + this.#provider = null; + }); + if (this.#observer) { + Services.obs.removeObserver( + this.#observer, + TorProviderTopics.ProcessExited + ); + this.#observer = null; + } + } + + /** + * Build a provider. + * This method will wait for the system to be initialized, and allows you to + * catch also any initialization errors. + */ + static async build() { + if (!this.#provider) { + throw new Error( + "The provider has not been initialized or already uninitialized." + ); + } + return this.#provider; + } + + /** + * Check if the provider has been succesfully initialized when the first + * browser window is shown. + * This is a workaround we need because ideally we would like the tor process + * to start as soon as possible, to avoid delays in the about:torconnect page, + * but we should modify TorConnect and about:torconnect to handle this case + * there with a better UX. + */ + static async firstWindowLoaded() { + // FIXME: Just integrate this with the about:torconnect or about:tor UI. + let running = false; + try { + const provider = await this.#provider; + // The initialization might have succeeded, but so far we have ignored any + // error notification. So, check that the process has not exited after the + // provider has been initialized successfully, but the UI was not ready + // yet. + running = provider.isRunning; + } catch { + // Not even initialized, running is already false. + } + while (!running && lazy.TorLauncherUtil.showRestartPrompt(true)) { + try { + await this.#initProvider(); + running = true; + } catch {} + } + // The user might have canceled the restart, but at this point the UI is + // ready in any case. + this.#uiReady = true; } - // TODO: Switch to an async build? - static build() { - if (!TorProviderBuilder.#provider) { - throw new Error("TorProviderBuilder has not been initialized yet."); + static async #torExited() { + while (lazy.TorLauncherUtil.showRestartPrompt(false)) { + try { + await this.#initProvider(); + break; + } catch {} } - return TorProviderBuilder.#provider; } } ===================================== toolkit/components/tor-launcher/TorStartupService.sys.mjs ===================================== @@ -34,9 +34,12 @@ export class TorStartupService { async #init() { Services.obs.addObserver(this, BrowserTopics.QuitApplicationGranted); - await lazy.TorProviderBuilder.init(); + // Do not await on this init. build() is expected to await the + // initialization, so anything that should need the Tor Provider should + // block there, instead. + lazy.TorProviderBuilder.init(); - lazy.TorSettings.init(); + await lazy.TorSettings.init(); lazy.TorConnect.init(); lazy.TorDomainIsolator.init(); ===================================== toolkit/mozapps/update/UpdateService.sys.mjs ===================================== @@ -388,13 +388,13 @@ XPCOMUtils.defineLazyGetter( } ); -function _shouldRegisterBootstrapObserver(errorCode) { - const provider = lazy.TorProviderBuilder.build(); - return ( - errorCode == PROXY_SERVER_CONNECTION_REFUSED && - !provider.isBootstrapDone && - provider.ownsTorDaemon - ); +async function _shouldRegisterBootstrapObserver(errorCode) { + try { + const provider = await lazy.TorProviderBuilder.build(); + return !provider.isBootstrapDone && provider.ownsTorDaemon; + } catch { + return false; + } } /** @@ -3338,7 +3338,10 @@ UpdateService.prototype = { AUSTLMY.pingCheckCode(this._pingSuffix, AUSTLMY.CHK_OFFLINE); } return; - } else if (_shouldRegisterBootstrapObserver(update.errorCode)) { + } else if ( + update.errorCode === PROXY_SERVER_CONNECTION_REFUSED && + (await _shouldRegisterBootstrapObserver()) + ) { // Register boostrap observer to try again, but only when we own the // tor process. this._registerBootstrapObserver(); @@ -6735,7 +6738,10 @@ Downloader.prototype = { ); shouldRegisterOnlineObserver = true; deleteActiveUpdate = false; - } else if (_shouldRegisterBootstrapObserver(status)) { + } else if ( + status === PROXY_SERVER_CONNECTION_REFUSED && + (await _shouldRegisterBootstrapObserver()) + ) { // Register a bootstrap observer to try again. // The bootstrap observer will continue the incremental download by // calling downloadUpdate on the active update which continues ===================================== toolkit/torbutton/chrome/locale/en-US/torlauncher.properties ===================================== @@ -9,7 +9,6 @@ torlauncher.tor_exited_during_startup=Tor exited during startup. This might be d torlauncher.tor_exited=Tor unexpectedly exited. This might be due to a bug in Tor itself, another program on your system, or faulty hardware. Until you restart Tor, Tor Browser will not be able to reach any websites. If the problem persists, please send a copy of your Tor Log to the support team. torlauncher.tor_exited2=Restarting Tor will not close your browser tabs. torlauncher.restart_tor=Restart Tor -torlauncher.tor_controlconn_failed=Could not connect to Tor control port. torlauncher.tor_bootstrap_failed=Tor failed to establish a Tor network connection. torlauncher.tor_bootstrap_failed_details=%1$S failed (%2$S). @@ -60,3 +59,7 @@ torlauncher.bootstrapWarning.pt_missing=missing pluggable transport torlauncher.nsresult.NS_ERROR_NET_RESET=The connection to the server was lost. torlauncher.nsresult.NS_ERROR_CONNECTION_REFUSED=Could not connect to the server. torlauncher.nsresult.NS_ERROR_PROXY_CONNECTION_REFUSED=Could not connect to the proxy. + +## 12.5-only strings that can be removed once it goes EOL. + +torlauncher.tor_controlconn_failed=Could not connect to Tor control port. View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/47de2a… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/47de2a… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-update-responses][main] alpha: new version, 13.0a4
by richard (@richard) 14 Sep '23

14 Sep '23
richard pushed to branch main at The Tor Project / Applications / Tor Browser update responses Commits: 3bd814cb by Richard Pospesel at 2023-09-14T16:58:58+00:00 alpha: new version, 13.0a4 - - - - - 30 changed files: - update_3/alpha/.htaccess - + update_3/alpha/13.0a1-13.0a4-linux-i686-ALL.xml - + update_3/alpha/13.0a1-13.0a4-linux-x86_64-ALL.xml - + update_3/alpha/13.0a1-13.0a4-macos-ALL.xml - + update_3/alpha/13.0a1-13.0a4-windows-i686-ALL.xml - + update_3/alpha/13.0a1-13.0a4-windows-x86_64-ALL.xml - + update_3/alpha/13.0a2-13.0a4-linux-i686-ALL.xml - + update_3/alpha/13.0a2-13.0a4-linux-x86_64-ALL.xml - + update_3/alpha/13.0a2-13.0a4-macos-ALL.xml - + update_3/alpha/13.0a2-13.0a4-windows-i686-ALL.xml - + update_3/alpha/13.0a2-13.0a4-windows-x86_64-ALL.xml - + update_3/alpha/13.0a3-13.0a4-linux-i686-ALL.xml - + update_3/alpha/13.0a3-13.0a4-linux-x86_64-ALL.xml - + update_3/alpha/13.0a3-13.0a4-macos-ALL.xml - + update_3/alpha/13.0a3-13.0a4-windows-i686-ALL.xml - + update_3/alpha/13.0a3-13.0a4-windows-x86_64-ALL.xml - − update_3/alpha/13.0a3-linux-i686-ALL.xml - − update_3/alpha/13.0a3-linux-x86_64-ALL.xml - − update_3/alpha/13.0a3-macos-ALL.xml - − update_3/alpha/13.0a3-windows-i686-ALL.xml - − update_3/alpha/13.0a3-windows-x86_64-ALL.xml - + update_3/alpha/13.0a4-linux-i686-ALL.xml - + update_3/alpha/13.0a4-linux-x86_64-ALL.xml - + update_3/alpha/13.0a4-macos-ALL.xml - + update_3/alpha/13.0a4-windows-i686-ALL.xml - + update_3/alpha/13.0a4-windows-x86_64-ALL.xml - update_3/alpha/download-android-aarch64.json - update_3/alpha/download-android-armv7.json - update_3/alpha/download-android-x86.json - update_3/alpha/download-android-x86_64.json The diff was not included because it is too large. View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-update-responses… -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-update-responses… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
[Git][tpo/applications/tor-browser-build] Pushed new tag mb-13.0a4-build1
by richard (@richard) 14 Sep '23

14 Sep '23
richard pushed new tag mb-13.0a4-build1 at The Tor Project / Applications / tor-browser-build -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/tree/mb-… You're receiving this email because of your account on gitlab.torproject.org.
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • ...
  • 804
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.