Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
266cf821 by Henry Wilkes at 2025-01-21T17:10:38+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Reset bootstrap stage when bridge settings change.
In particular, this will cancel an autobootstrap when the user manually
changes the bridge settings. However we apply this to all bootstrap
attempts for consistency.
By resetting to the Start stage, we also ensure that about:torconnect
UI no longer shows the "Try bridges" pages when the user manually
changes their bridges themselves.
- - - - -
ecdccd3f by Henry Wilkes at 2025-01-21T17:10:38+00:00
fixup! TB 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection
TB 41921: Also show the "Connect" button for bridge dialogs when we have
an ongoing bootstrap attempt.
With the new behaviour, changing the settings while not bootstrapped
will cancel any ongoing bootstrap. Therefore, we can start a new
bootstrap using the new settings.
- - - - -
6 changed files:
- browser/components/torpreferences/content/builtinBridgeDialog.js
- browser/components/torpreferences/content/connectionPane.js
- browser/components/torpreferences/content/provideBridgeDialog.js
- browser/components/torpreferences/content/requestBridgeDialog.js
- toolkit/modules/TorConnect.sys.mjs
- toolkit/modules/TorSettings.sys.mjs
Changes:
=====================================
browser/components/torpreferences/content/builtinBridgeDialog.js
=====================================
@@ -4,9 +4,8 @@ const { TorSettings, TorBridgeSource } = ChromeUtils.importESModule(
"resource://gre/modules/TorSettings.sys.mjs"
);
-const { TorConnect, TorConnectTopics } = ChromeUtils.importESModule(
- "resource://gre/modules/TorConnect.sys.mjs"
-);
+const { TorConnect, TorConnectStage, TorConnectTopics } =
+ ChromeUtils.importESModule("resource://gre/modules/TorConnect.sys.mjs");
const gBuiltinBridgeDialog = {
init() {
@@ -96,7 +95,7 @@ const gBuiltinBridgeDialog = {
},
onAcceptStateChange() {
- const connect = TorConnect.canBeginBootstrap;
+ const connect = TorConnect.stageName !== TorConnectStage.Bootstrapped;
this._result.connect = connect;
this._acceptButton.setAttribute(
"data-l10n-id",
=====================================
browser/components/torpreferences/content/connectionPane.js
=====================================
@@ -2257,6 +2257,8 @@ const gBridgeSettings = {
}
// Wait until the settings are applied before bootstrapping.
+ // NOTE: Saving the settings should also cancel any existing bootstrap
+ // attempt first. See tor-browser#41921.
savedSettings.then(() => {
// The bridge dialog button is "connect" when Tor is not
// bootstrapped, so do the connect.
=====================================
browser/components/torpreferences/content/provideBridgeDialog.js
=====================================
@@ -3,9 +3,8 @@
const { TorSettings, TorBridgeSource, validateBridgeLines } =
ChromeUtils.importESModule("resource://gre/modules/TorSettings.sys.mjs");
-const { TorConnect, TorConnectTopics } = ChromeUtils.importESModule(
- "resource://gre/modules/TorConnect.sys.mjs"
-);
+const { TorConnect, TorConnectStage, TorConnectTopics } =
+ ChromeUtils.importESModule("resource://gre/modules/TorConnect.sys.mjs");
const { TorParsers } = ChromeUtils.importESModule(
"resource://gre/modules/TorParsers.sys.mjs"
@@ -190,7 +189,7 @@ const gProvideBridgeDialog = {
"user-provide-bridge-dialog-next-button"
);
} else {
- connect = TorConnect.canBeginBootstrap;
+ connect = TorConnect.stageName !== TorConnectStage.Bootstrapped;
this._acceptButton.setAttribute(
"data-l10n-id",
connect ? "bridge-dialog-button-connect" : "bridge-dialog-button-accept"
=====================================
browser/components/torpreferences/content/requestBridgeDialog.js
=====================================
@@ -4,9 +4,8 @@ const { BridgeDB } = ChromeUtils.importESModule(
"resource://gre/modules/BridgeDB.sys.mjs"
);
-const { TorConnect, TorConnectTopics } = ChromeUtils.importESModule(
- "resource://gre/modules/TorConnect.sys.mjs"
-);
+const { TorConnect, TorConnectStage, TorConnectTopics } =
+ ChromeUtils.importESModule("resource://gre/modules/TorConnect.sys.mjs");
const log = console.createInstance({
maxLogLevel: "Warn",
@@ -102,7 +101,7 @@ const gRequestBridgeDialog = {
},
onAcceptStateChange() {
- const connect = TorConnect.canBeginBootstrap;
+ const connect = TorConnect.stageName !== TorConnectStage.Bootstrapped;
this._result.connect = connect;
this._submitButton.setAttribute(
"data-l10n-id",
=====================================
toolkit/modules/TorConnect.sys.mjs
=====================================
@@ -13,6 +13,7 @@ ChromeUtils.defineESModuleGetters(lazy, {
TorProviderTopics: "resource://gre/modules/TorProviderBuilder.sys.mjs",
TorLauncherUtil: "resource://gre/modules/TorLauncherUtil.sys.mjs",
TorSettings: "resource://gre/modules/TorSettings.sys.mjs",
+ TorSettingsTopics: "resource://gre/modules/TorSettings.sys.mjs",
});
const TorConnectPrefs = Object.freeze({
@@ -629,16 +630,6 @@ class AutoBootstrapAttempt {
// Send the new settings directly to the provider. We will save them only
// if the bootstrap succeeds.
- // FIXME: We should somehow signal TorSettings users that we have set
- // custom settings, and they should not apply theirs until we are done
- // with trying ours.
- // Otherwise, the new settings provided by the user while we were
- // bootstrapping could be the ones that cause the bootstrap to succeed,
- // but we overwrite them (unless we backup the original settings, and then
- // save our new settings only if they have not changed).
- // Another idea (maybe easier to implement) is to disable the settings
- // UI while *any* bootstrap is going on.
- // This is also documented in tor-browser#41921.
await lazy.TorSettings.applyTemporaryBridges(bridges);
if (this.#cancelled || this.#resolved) {
@@ -1036,6 +1027,7 @@ export const TorConnect = {
// register the Tor topics we always care about
observeTopic(lazy.TorProviderTopics.ProcessExited);
observeTopic(lazy.TorProviderTopics.HasWarnOrErr);
+ observeTopic(lazy.TorSettingsTopics.SettingsChanged);
// NOTE: At this point, _requestedStage should still be `null`.
this._setStage(TorConnectStage.Start);
@@ -1070,8 +1062,32 @@ export const TorConnect = {
Services.prefs.setBoolPref(TorConnectPrefs.prompt_at_startup, true);
this._makeStageRequest(TorConnectStage.Start, true);
break;
- default:
- // ignore
+ case lazy.TorSettingsTopics.SettingsChanged:
+ if (
+ this._stageName !== TorConnectStage.Bootstrapped &&
+ this._stageName !== TorConnectStage.Loading &&
+ this._stageName !== TorConnectStage.Start &&
+ subject.wrappedJSObject.changes.some(propertyName =>
+ propertyName.startsWith("bridges.")
+ )
+ ) {
+ // A change in bridge settings before we are bootstrapped, we reset
+ // the stage to Start to:
+ // + Cancel any ongoing bootstrap attempt. In particular, we
+ // definitely do not want to continue with an auto-bootstrap's
+ // temporary bridges if the settings have changed.
+ // + Reset the UI to be ready for normal bootstrapping in case the
+ // user returns to about:torconnect.
+ // See tor-browser#41921.
+ // NOTE: We do not reset in response to a change in the quickstart,
+ // firewall or proxy settings.
+ lazy.logger.warn(
+ "Resetting to Start stage since bridge settings changed"
+ );
+ // Rather than cancel and return to the pre-bootstrap stage, we
+ // explicitly cancel and return to the start stage.
+ this._makeStageRequest(TorConnectStage.Start);
+ }
break;
}
},
=====================================
toolkit/modules/TorSettings.sys.mjs
=====================================
@@ -953,6 +953,7 @@ class TorSettingsImpl {
};
if ("bridges" in newValues) {
+ const changesLength = changes.length;
if ("source" in newValues.bridges) {
this.#fixupBridgeSettings(newValues.bridges);
changeSetting("bridges", "source", newValues.bridges.source);
@@ -982,6 +983,19 @@ class TorSettingsImpl {
if ("enabled" in newValues.bridges) {
changeSetting("bridges", "enabled", newValues.bridges.enabled);
}
+
+ if (this.#temporaryBridgeSettings && changes.length !== changesLength) {
+ // A change in the bridges settings.
+ // We want to clear the temporary bridge settings to ensure that they
+ // cannot be used to overwrite these user-provided settings.
+ // See tor-browser#41921.
+ // NOTE: This should also trigger TorConnect to cancel any ongoing
+ // AutoBootstrap that would have otherwise used these settings.
+ this.#temporaryBridgeSettings = null;
+ lazy.logger.warn(
+ "Cleared temporary bridges since bridge settings were changed"
+ );
+ }
}
if ("proxy" in newValues) {
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/0bb78c…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/0bb78c…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
0bb78caa by clairehurst at 2025-01-21T16:51:39+00:00
fixup! [android] Add standalone Tor Bootstrap
Bug 43368: Add @Suppress for linting error "Overriding method should call super. onNewIntent"
- - - - -
1 changed file:
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
Changes:
=====================================
mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
=====================================
@@ -4,6 +4,7 @@
package org.mozilla.fenix
+import android.annotation.SuppressLint
import android.app.assist.AssistContent
import android.app.PendingIntent
import android.content.Context
@@ -710,6 +711,7 @@ open class HomeActivity : LocaleAwareAppCompatActivity(), NavHostActivity, TorIn
/**
* Handles intents received when the activity is open.
*/
+ @SuppressLint("MissingSuperCall") // super.onNewIntent is called in [onNewIntentInternal(intent)]
final override fun onNewIntent(intent: Intent?) {
if (intent?.action == ACTION_MAIN || components.torController.isConnected) {
onNewIntentInternal(intent)
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0bb78ca…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/0bb78ca…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
eabeaa5b by clairehurst at 2025-01-21T16:50:59+00:00
fixup! [android] Add standalone Tor Bootstrap
Bug 43360: Replace custom variable isBeingRecreated with built-in isFinishing function
- - - - -
1 changed file:
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
Changes:
=====================================
mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
=====================================
@@ -176,8 +176,6 @@ open class HomeActivity : LocaleAwareAppCompatActivity(), NavHostActivity, TorIn
private var isToolbarInflated = false
- private var isBeingRecreated = false
-
private val webExtensionPopupObserver by lazy {
WebExtensionPopupObserver(components.core.store, ::openPopup)
}
@@ -652,7 +650,7 @@ open class HomeActivity : LocaleAwareAppCompatActivity(), NavHostActivity, TorIn
stopMediaSession()
}
- if (!isBeingRecreated && !(application as FenixApplication).isTerminating()) {
+ if (isFinishing && !(application as FenixApplication).isTerminating()) {
// We assume the Activity is being destroyed because the user
// swiped away the app on the Recent screen. When this happens,
// we assume the user expects the entire Application is destroyed
@@ -686,8 +684,6 @@ open class HomeActivity : LocaleAwareAppCompatActivity(), NavHostActivity, TorIn
message = "recreate()",
)
- isBeingRecreated = true
-
super.recreate()
}
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/eabeaa5…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/eabeaa5…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
8e5e2d5c by clairehurst at 2025-01-21T16:49:29+00:00
fixup! [android] Implement Android-native Connection Assist UI
Bug 43359: Improper handling of TorBootstrapChangeListener with respect to system onDestroy() calls for HomeActivity
- - - - -
1 changed file:
- mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
Changes:
=====================================
mobile/android/fenix/app/src/main/java/org/mozilla/fenix/HomeActivity.kt
=====================================
@@ -659,12 +659,13 @@ open class HomeActivity : LocaleAwareAppCompatActivity(), NavHostActivity, TorIn
// and not only the top Activity/Task. Therefore we kill the
// underlying Application, as well.
(application as FenixApplication).terminate()
- }
-
- val engine = components.core.engine
- if (engine is GeckoEngine) {
- val torIntegration = engine.getTorIntegrationController()
- torIntegration.unregisterBootstrapStateChangeListener(this)
+ if (settings().useHtmlConnectionUi) {
+ val engine = components.core.engine
+ if (engine is GeckoEngine) {
+ val torIntegration = engine.getTorIntegrationController()
+ torIntegration.unregisterBootstrapStateChangeListener(this)
+ }
+ }
}
}
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/8e5e2d5…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/8e5e2d5…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
4b7dc6cc by Henry Wilkes at 2025-01-21T15:54:08+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Do not wait for TorSettings to initialise before allowing a
bootstrap.
Instead, we wait for TorSettings as required: for preparing
AutoBootstrap attempts, and TorBootstrapRequest should already wait for
TorSettings before attempting to connect.
- - - - -
34cfa54a by Henry Wilkes at 2025-01-21T15:54:13+00:00
fixup! TB 40933: Add tor-launcher functionality
TB 41921: Ensure TorProviderBuilder.build can be called immediately
after TorProviderBuilder.init returns (without await).
We make sure that the `#provider` instance is created before any break
in execution caused by an `await`.
- - - - -
1dc47dd9 by Henry Wilkes at 2025-01-21T15:54:14+00:00
fixup! TB 42247: Android helpers for the TorProvider
TB 41921: Do not wait for TorProviderBuilder.init since it is no longer
async.
- - - - -
fff7daea by Henry Wilkes at 2025-01-21T15:54:14+00:00
fixup! TB 40933: Add tor-launcher functionality
TB 41921: Add a note to TorBootstrapRequest explaining the expectation
that the TorProvider has already read from TorSettings before it
connects.
- - - - -
4 changed files:
- toolkit/components/tor-launcher/TorBootstrapRequest.sys.mjs
- toolkit/components/tor-launcher/TorProviderBuilder.sys.mjs
- toolkit/modules/TorAndroidIntegration.sys.mjs
- toolkit/modules/TorConnect.sys.mjs
Changes:
=====================================
toolkit/components/tor-launcher/TorBootstrapRequest.sys.mjs
=====================================
@@ -90,6 +90,11 @@ export class TorBootstrapRequest {
// 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.
+ // NOTE: After TorProviderBuilder.build resolves, TorProvider.init will
+ // have completed. In particular, assuming no errors, the TorSettings will
+ // have been initialised and passed on to the provider via
+ // TorProvider.writeSettings. Therefore we should be safe to immediately
+ // call `connect` using the latest user settings.
lazy.TorProviderBuilder.build()
.then(provider => provider.connect())
.catch(err => {
=====================================
toolkit/components/tor-launcher/TorProviderBuilder.sys.mjs
=====================================
@@ -54,14 +54,15 @@ export class TorProviderBuilder {
/**
* 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() {
+ static init() {
switch (this.providerType) {
case TorProviders.tor:
- await this.#initTorProvider();
+ // Even though initialization of the initial TorProvider is
+ // asynchronous, we do not expect the caller to await it. The reason is
+ // that any call to build() will wait the initialization anyway (and
+ // re-throw any initialization error).
+ this.#initTorProvider();
break;
case TorProviders.none:
lazy.TorLauncherUtil.setProxyConfiguration(
@@ -74,7 +75,12 @@ export class TorProviderBuilder {
}
}
- static async #initTorProvider() {
+ /**
+ * Replace #provider with a new instance.
+ *
+ * @returns {Promise<TorProvider>} The new instance.
+ */
+ static #initTorProvider() {
if (!this.#exitObserver) {
this.#exitObserver = this.#torExited.bind(this);
Services.obs.addObserver(
@@ -83,18 +89,39 @@ export class TorProviderBuilder {
);
}
+ // NOTE: We need to ensure that the #provider is set as soon
+ // TorProviderBuilder.init is called.
+ // I.e. it should be safe to call
+ // TorProviderBuilder.init();
+ // TorProviderBuilder.build();
+ // without any await.
+ //
+ // Therefore, we await the oldProvider within the Promise rather than make
+ // #initTorProvider async.
+ //
+ // In particular, this is needed by TorConnect when the user has selected
+ // quickstart, in which case `TorConnect.init` will immediately request the
+ // provider. See tor-browser#41921.
+ this.#provider = this.#replaceTorProvider(this.#provider);
+ return this.#provider;
+ }
+
+ /**
+ * Replace a TorProvider instance. Resolves once the TorProvider is
+ * initialised.
+ *
+ * @param {Promise<TorProvider>?} oldProvider - The previous's provider's
+ * promise, if any.
+ * @returns {TorProvider} The new TorProvider instance.
+ */
+ static async #replaceTorProvider(oldProvider) {
try {
- const old = await this.#provider;
- old?.uninit();
+ // Uninitialise the old TorProvider, if there is any.
+ (await oldProvider)?.uninit();
} catch {}
- this.#provider = new Promise((resolve, reject) => {
- const provider = new lazy.TorProvider();
- provider
- .init()
- .then(() => resolve(provider))
- .catch(reject);
- });
- await this.#provider;
+ const provider = new lazy.TorProvider();
+ await provider.init();
+ return provider;
}
static uninit() {
=====================================
toolkit/modules/TorAndroidIntegration.sys.mjs
=====================================
@@ -68,9 +68,12 @@ class TorAndroidIntegrationImpl {
Services.obs.addObserver(this, lazy.TorSettingsTopics[topic]);
}
- lazy.TorProviderBuilder.init().finally(() => {
- lazy.TorProviderBuilder.firstWindowLoaded();
- });
+ lazy.TorProviderBuilder.init();
+ // On Android immediately call firstWindowLoaded. This should be safe to
+ // call since it will await the initialisation of the TorProvider set up
+ // by TorProviderBuilder.init.
+ lazy.TorProviderBuilder.firstWindowLoaded();
+
try {
await lazy.TorSettings.init();
await lazy.TorConnect.init();
=====================================
toolkit/modules/TorConnect.sys.mjs
=====================================
@@ -10,7 +10,6 @@ ChromeUtils.defineESModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
MoatRPC: "resource://gre/modules/Moat.sys.mjs",
TorBootstrapRequest: "resource://gre/modules/TorBootstrapRequest.sys.mjs",
- TorProviderBuilder: "resource://gre/modules/TorProviderBuilder.sys.mjs",
TorProviderTopics: "resource://gre/modules/TorProviderBuilder.sys.mjs",
TorLauncherUtil: "resource://gre/modules/TorLauncherUtil.sys.mjs",
TorSettings: "resource://gre/modules/TorSettings.sys.mjs",
@@ -436,15 +435,23 @@ class AutoBootstrapAttempt {
return;
}
this.#resolved = true;
- try {
- // Run cleanup before we resolve the promise to ensure two instances
- // of AutoBootstrapAttempt are not trying to change the settings at
- // the same time.
- if (arg.result !== "complete") {
- await lazy.TorSettings.clearTemporaryBridges();
+
+ if (lazy.TorSettings.initialized) {
+ // If not initialized, then we won't have applied any settings.
+ try {
+ // Run cleanup before we resolve the promise to ensure two instances
+ // of AutoBootstrapAttempt are not trying to change the settings at
+ // the same time.
+ if (arg.result !== "complete") {
+ // Should do nothing if we never called applyTemporaryBridges.
+ await lazy.TorSettings.clearTemporaryBridges();
+ }
+ } catch (error) {
+ lazy.logger.error(
+ "Unexpected error in auto-bootstrap cleanup",
+ error
+ );
}
- } catch (error) {
- lazy.logger.error("Unexpected error in auto-bootstrap cleanup", error);
}
if (arg.error) {
reject(arg.error);
@@ -483,6 +490,16 @@ class AutoBootstrapAttempt {
* @param {BootstrapOptions} options - Options to apply to the bootstrap.
*/
async #runInternal(progressCallback, options) {
+ // Wait for TorSettings to be initialised, which is used for the
+ // AutoBootstrapping set up.
+ await Promise.race([
+ lazy.TorSettings.initializedPromise,
+ this.#cancelledPromise,
+ ]);
+ if (this.#cancelled || this.#resolved) {
+ return;
+ }
+
await this.#fetchBridges(options);
if (this.#cancelled || this.#resolved) {
return;
@@ -1016,19 +1033,20 @@ export const TorConnect = {
lazy.logger.debug(`Observing topic '${addTopic}'`);
};
- // Wait for TorSettings, as we will need it.
- // We will wait for a TorProvider only after TorSettings is ready,
- // because the TorProviderBuilder initialization might not have finished
- // at this point, and TorSettings initialization is a prerequisite for
- // having a provider.
- // So, we prefer initializing TorConnect as soon as possible, so that
- // the UI will be able to detect it is in the Initializing state and act
- // consequently.
- lazy.TorSettings.initializedPromise.then(() => this._settingsInitialized());
-
// register the Tor topics we always care about
observeTopic(lazy.TorProviderTopics.ProcessExited);
observeTopic(lazy.TorProviderTopics.HasWarnOrErr);
+
+ // NOTE: At this point, _requestedStage should still be `null`.
+ this._setStage(TorConnectStage.Start);
+ if (
+ // Quickstart setting is enabled.
+ this.quickstart &&
+ // And the previous bootstrap attempt must have succeeded.
+ !Services.prefs.getBoolPref(TorConnectPrefs.prompt_at_startup, true)
+ ) {
+ this.beginBootstrapping();
+ }
},
async observe(subject, topic) {
@@ -1058,26 +1076,6 @@ export const TorConnect = {
}
},
- async _settingsInitialized() {
- // TODO: Handle failures here, instead of the prompt to restart the
- // daemon when it exits (tor-browser#21053, tor-browser#41921).
- await lazy.TorProviderBuilder.build();
-
- lazy.logger.debug("The TorProvider is ready, changing state.");
- // NOTE: If the tor process exits before this point, then
- // shouldQuickStart would be `false`.
- // NOTE: At this point, _requestedStage should still be `null`.
- this._setStage(TorConnectStage.Start);
- if (
- // Quickstart setting is enabled.
- this.quickstart &&
- // And the previous bootstrap attempt must have succeeded.
- !Services.prefs.getBoolPref(TorConnectPrefs.prompt_at_startup, true)
- ) {
- this.beginBootstrapping();
- }
- },
-
/**
* Set the user stage.
*
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/b5cd60…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/b5cd60…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
21b2be4c by Henry Wilkes at 2025-01-21T15:25:28+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Move quickstart setting from TorSettings to TorConnect.
- - - - -
cfd39fb0 by Henry Wilkes at 2025-01-21T15:25:29+00:00
fixup! TB 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection
TB 41921: Move quickstart setting from TorSettings to TorConnect.
- - - - -
62e7a81f by Henry Wilkes at 2025-01-21T15:25:30+00:00
fixup! TB 27476: Implement about:torconnect captive portal within Tor Browser
TB 41921: Move quickstart setting from TorSettings to TorConnect.
This also means we no longer need to listen for TorSettingsTopics.Ready
for the initial value.
Also fix typo in signal name: "quickstart-changed" to "quickstart-change".
- - - - -
b5cd602f by Henry Wilkes at 2025-01-21T15:25:31+00:00
fixup! TB 42247: Android helpers for the TorProvider
TB 41921: Move quickstart setting from TorSettings to TorConnect.
- - - - -
5 changed files:
- browser/components/torpreferences/content/connectionPane.js
- toolkit/components/torconnect/TorConnectParent.sys.mjs
- toolkit/modules/TorAndroidIntegration.sys.mjs
- toolkit/modules/TorConnect.sys.mjs
- toolkit/modules/TorSettings.sys.mjs
Changes:
=====================================
browser/components/torpreferences/content/connectionPane.js
=====================================
@@ -2550,12 +2550,10 @@ const gConnectionPane = (function () {
"torPreferences-quickstart-toggle"
);
this._enableQuickstartCheckbox.addEventListener("command", () => {
- TorSettings.changeSettings({
- quickstart: { enabled: this._enableQuickstartCheckbox.checked },
- });
+ TorConnect.quickstart = this._enableQuickstartCheckbox.checked;
});
- this._enableQuickstartCheckbox.checked = TorSettings.quickstart.enabled;
- Services.obs.addObserver(this, TorSettingsTopics.SettingsChanged);
+ this._enableQuickstartCheckbox.checked = TorConnect.quickstart;
+ Services.obs.addObserver(this, TorConnectTopics.QuickstartChange);
// Location
{
@@ -2667,7 +2665,7 @@ const gConnectionPane = (function () {
gBridgeSettings.init();
gNetworkStatus.init();
- TorSettings.initializedPromise.then(() => this._populateXUL());
+ this._populateXUL();
const onUnload = () => {
window.removeEventListener("unload", onUnload);
@@ -2681,7 +2679,7 @@ const gConnectionPane = (function () {
gNetworkStatus.uninit();
// unregister our observer topics
- Services.obs.removeObserver(this, TorSettingsTopics.SettingsChanged);
+ Services.obs.removeObserver(this, TorConnectTopics.QuickstartChange);
Services.obs.removeObserver(this, TorConnectTopics.StageChange);
},
@@ -2696,12 +2694,8 @@ const gConnectionPane = (function () {
observe(subject, topic) {
switch (topic) {
- // triggered when a TorSettings param has changed
- case TorSettingsTopics.SettingsChanged: {
- if (subject.wrappedJSObject.changes.includes("quickstart.enabled")) {
- this._enableQuickstartCheckbox.checked =
- TorSettings.quickstart.enabled;
- }
+ case TorConnectTopics.QuickstartChange: {
+ this._enableQuickstartCheckbox.checked = TorConnect.quickstart;
break;
}
// triggered when tor connect state changes and we may
@@ -2713,7 +2707,10 @@ const gConnectionPane = (function () {
}
},
- onAdvancedSettings() {
+ async onAdvancedSettings() {
+ // Ensure TorSettings is complete before loading the dialog, which reads
+ // from TorSettings.
+ await TorSettings.initializedPromise;
gSubDialog.open(
"chrome://browser/content/torpreferences/connectionSettingsDialog.xhtml",
{ features: "resizable=yes" }
=====================================
toolkit/components/torconnect/TorConnectParent.sys.mjs
=====================================
@@ -5,10 +5,6 @@ import {
TorConnect,
TorConnectTopics,
} from "resource://gre/modules/TorConnect.sys.mjs";
-import {
- TorSettings,
- TorSettingsTopics,
-} from "resource://gre/modules/TorSettings.sys.mjs";
const lazy = {};
@@ -47,15 +43,10 @@ export class TorConnectParent extends JSWindowActorParent {
case TorConnectTopics.BootstrapProgress:
self.sendAsyncMessage("torconnect:bootstrap-progress", obj);
break;
- case TorSettingsTopics.SettingsChanged:
- if (!obj.changes.includes("quickstart.enabled")) {
- break;
- }
- // eslint-disable-next-lined no-fallthrough
- case TorSettingsTopics.Ready:
+ case TorConnectTopics.QuickstartChange:
self.sendAsyncMessage(
- "torconnect:quickstart-changed",
- TorSettings.quickstart.enabled
+ "torconnect:quickstart-change",
+ TorConnect.quickstart
);
break;
}
@@ -70,10 +61,9 @@ export class TorConnectParent extends JSWindowActorParent {
this.torConnectObserver,
TorConnectTopics.BootstrapProgress
);
- Services.obs.addObserver(this.torConnectObserver, TorSettingsTopics.Ready);
Services.obs.addObserver(
this.torConnectObserver,
- TorSettingsTopics.SettingsChanged
+ TorConnectTopics.QuickstartChange
);
}
@@ -88,11 +78,7 @@ export class TorConnectParent extends JSWindowActorParent {
);
Services.obs.removeObserver(
this.torConnectObserver,
- TorSettingsTopics.Ready
- );
- Services.obs.removeObserver(
- this.torConnectObserver,
- TorSettingsTopics.SettingsChanged
+ TorConnectTopics.QuickstartChange
);
}
@@ -104,7 +90,7 @@ export class TorConnectParent extends JSWindowActorParent {
// If there are multiple home pages, just load the first one.
return Promise.resolve(TorConnect.fixupURIs(lazy.HomePage.get())[0]);
case "torconnect:set-quickstart":
- TorSettings.changeSettings({ quickstart: { enabled: message.data } });
+ TorConnect.quickstart = message.data;
break;
case "torconnect:open-tor-preferences":
this.browsingContext.top.embedderElement.ownerGlobal.openPreferences(
@@ -133,31 +119,16 @@ export class TorConnectParent extends JSWindowActorParent {
case "torconnect:cancel-bootstrapping":
TorConnect.cancelBootstrapping();
break;
- case "torconnect:get-init-args": {
+ case "torconnect:get-init-args":
// Called on AboutTorConnect.init(), pass down all state data it needs
// to init.
-
- let quickstartEnabled = false;
-
- // 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 {
- quickstartEnabled = TorSettings.quickstart.enabled;
- } catch (e) {
- // Do not throw.
- }
-
return {
TorStrings,
Direction: Services.locale.isAppLocaleRTL ? "rtl" : "ltr",
CountryNames: TorConnect.countryNames,
stage: TorConnect.stage,
- quickstartEnabled,
+ quickstartEnabled: TorConnect.quickstart,
};
- }
case "torconnect:get-country-codes":
return TorConnect.getCountryCodes();
}
=====================================
toolkit/modules/TorAndroidIntegration.sys.mjs
=====================================
@@ -79,6 +79,23 @@ class TorAndroidIntegrationImpl {
}
}
+ /**
+ * Combine the current TorSettings settings with the TorConnect settings.
+ *
+ * @returns {object} The TorSettings in an object, which also has a
+ * `quickstart.enabled` property.
+ */
+ // This is added for backward compatibility with TorSettings.getSettings prior
+ // to tor-browser#41921, when it used to control the quickstart setting.
+ // TODO: Have android separate out the request for TorConnect.quickstart. In
+ // principle, this would allow android tor connect UI to be loaded before
+ // TorSettings has initialized (the SettingsReady signal), similar to desktop.
+ // See tor-browser#43408.
+ #getAllSettings() {
+ const settings = lazy.TorSettings.getSettings();
+ settings.quickstart = { enabled: lazy.TorConnect.quickstart };
+ }
+
observe(subj, topic) {
switch (topic) {
// TODO: Replace with StageChange.
@@ -120,7 +137,7 @@ class TorAndroidIntegrationImpl {
case lazy.TorSettingsTopics.Ready:
lazy.EventDispatcher.instance.sendRequest({
type: EmittedEvents.settingsReady,
- settings: lazy.TorSettings.getSettings(),
+ settings: this.#getAllSettings(),
});
break;
case lazy.TorSettingsTopics.SettingsChanged:
@@ -129,7 +146,20 @@ class TorAndroidIntegrationImpl {
lazy.EventDispatcher.instance.sendRequest({
type: EmittedEvents.settingsChanged,
changes: subj.wrappedJSObject.changes ?? [],
- settings: lazy.TorSettings.getSettings(),
+ settings: this.#getAllSettings(),
+ });
+ break;
+ case lazy.TorConnectTopics.QuickstartChange:
+ // We also include the TorSettings, and a `changes` Array similar to
+ // SettingsChanged signal. This is for backward compatibility with
+ // TorSettings.getSettings prior to tor-browser#41921, when it used to
+ // control the quickstart setting.
+ // TODO: Have android separate out the request for TorConnect.quickstart.
+ // See tor-browser#43408.
+ lazy.EventDispatcher.instance.sendRequest({
+ type: EmittedEvents.settingsChanged,
+ changes: ["quickstart.enabled"],
+ settings: this.#getAllSettings(),
});
break;
}
@@ -140,9 +170,19 @@ class TorAndroidIntegrationImpl {
try {
switch (event) {
case ListenedEvents.settingsGet:
- callback?.onSuccess(lazy.TorSettings.getSettings());
+ callback?.onSuccess(this.#getAllSettings());
return;
case ListenedEvents.settingsSet:
+ // TODO: Set quickstart via a separate event. See tor-browser#43408.
+ // NOTE: Currently this may trigger GeckoView:Tor:SettingsChanged
+ // twice: once for quickstart.enabled, and again for the other
+ // settings.
+ if (
+ "quickstart" in data.settings &&
+ "enabled" in data.settings.quickstart
+ ) {
+ lazy.TorConnect.quickstart = data.settings.quickstart.enabled;
+ }
// TODO: Handle setting throw? This can throw if data.settings is
// incorrectly formatted, but more like it can throw when the settings
// fail to be passed onto the TorProvider. tor-browser#43405.
=====================================
toolkit/modules/TorConnect.sys.mjs
=====================================
@@ -22,6 +22,7 @@ const TorConnectPrefs = Object.freeze({
log_level: "torbrowser.bootstrap.log_level",
/* prompt_at_startup now controls whether the quickstart can trigger. */
prompt_at_startup: "extensions.torlauncher.prompt_at_startup",
+ quickstart: "torbrowser.settings.quickstart.enabled",
});
export const TorConnectState = Object.freeze({
@@ -80,6 +81,7 @@ export const TorConnectTopics = Object.freeze({
StageChange: "torconnect:stage-change",
// TODO: Remove torconnect:state-change when pages have switched to stage.
StateChange: "torconnect:state-change",
+ QuickstartChange: "torconnect:quickstart-change",
BootstrapProgress: "torconnect:bootstrap-progress",
BootstrapComplete: "torconnect:bootstrap-complete",
// TODO: Remove torconnect:error when pages have switched to stage.
@@ -1066,8 +1068,12 @@ export const TorConnect = {
// shouldQuickStart would be `false`.
// NOTE: At this point, _requestedStage should still be `null`.
this._setStage(TorConnectStage.Start);
- if (this.shouldQuickStart) {
- // Quickstart
+ if (
+ // Quickstart setting is enabled.
+ this.quickstart &&
+ // And the previous bootstrap attempt must have succeeded.
+ !Services.prefs.getBoolPref(TorConnectPrefs.prompt_at_startup, true)
+ ) {
this.beginBootstrapping();
}
},
@@ -1120,6 +1126,25 @@ export const TorConnect = {
return lazy.TorLauncherUtil.shouldStartAndOwnTor;
},
+ /**
+ * Whether bootstrapping can begin immediately once Tor Browser has been
+ * opened.
+ *
+ * @type {boolean}
+ */
+ get quickstart() {
+ return Services.prefs.getBoolPref(TorConnectPrefs.quickstart, false);
+ },
+
+ set quickstart(enabled) {
+ enabled = Boolean(enabled);
+ if (enabled === this.quickstart) {
+ return;
+ }
+ Services.prefs.setBoolPref(TorConnectPrefs.quickstart, enabled);
+ Services.obs.notifyObservers(null, TorConnectTopics.QuickstartChange);
+ },
+
get shouldShowTorConnect() {
// TorBrowser must control the daemon
return (
@@ -1163,15 +1188,6 @@ export const TorConnect = {
);
},
- get shouldQuickStart() {
- // quickstart must be enabled
- return (
- lazy.TorSettings.quickstart.enabled &&
- // and the previous bootstrap attempt must have succeeded
- !Services.prefs.getBoolPref(TorConnectPrefs.prompt_at_startup, true)
- );
- },
-
// TODO: Remove when all pages have switched to "stage".
get state() {
// There is no "Error" stage, but about:torconnect relies on receiving the
=====================================
toolkit/modules/TorSettings.sys.mjs
=====================================
@@ -27,10 +27,8 @@ export const TorSettingsTopics = Object.freeze({
/* Prefs used to store settings in TorBrowser prefs */
const TorSettingsPrefs = Object.freeze({
- quickstart: {
- /* bool: does tor connect automatically on launch */
- enabled: "torbrowser.settings.quickstart.enabled",
- },
+ // NOTE: torbrowser.settings.quickstart.enabled used to be managed by
+ // TorSettings but was moved to TorConnect.quickstart in tor-browser#41921.
bridges: {
/* bool: does tor use bridges */
enabled: "torbrowser.settings.bridges.enabled",
@@ -173,9 +171,6 @@ class TorSettingsImpl {
* @type {object}
*/
#settings = {
- quickstart: {
- enabled: false,
- },
bridges: {
/**
* Whether the bridges are enabled or not.
@@ -579,11 +574,6 @@ class TorSettingsImpl {
#loadFromPrefs() {
lazy.logger.debug("loadFromPrefs()");
- /* Quickstart */
- this.#settings.quickstart.enabled = Services.prefs.getBoolPref(
- TorSettingsPrefs.quickstart.enabled,
- false
- );
/* Bridges */
const bridges = {};
bridges.enabled = Services.prefs.getBoolPref(
@@ -691,11 +681,6 @@ class TorSettingsImpl {
this.#checkIfInitialized();
- /* Quickstart */
- Services.prefs.setBoolPref(
- TorSettingsPrefs.quickstart.enabled,
- this.#settings.quickstart.enabled
- );
/* Bridges */
Services.prefs.setBoolPref(
TorSettingsPrefs.bridges.enabled,
@@ -928,7 +913,6 @@ class TorSettingsImpl {
*
* It is possible to set all settings, or only some sections:
*
- * + quickstart.enabled can be set individually.
* + bridges.enabled can be set individually.
* + bridges.source can be set with a corresponding bridge specification for
* the source (bridge_strings, lox_id, builtin_type).
@@ -968,14 +952,6 @@ class TorSettingsImpl {
changes.push(`${group}.${prop}`);
};
- if ("quickstart" in newValues && "enabled" in newValues.quickstart) {
- changeSetting(
- "quickstart",
- "enabled",
- Boolean(newValues.quickstart.enabled)
- );
- }
-
if ("bridges" in newValues) {
if ("source" in newValues.bridges) {
this.#fixupBridgeSettings(newValues.bridges);
@@ -1048,11 +1024,7 @@ class TorSettingsImpl {
// saved the preferences we send the new settings to TorProvider.
// Some properties are unread by TorProvider. So if only these values change
// there is no need to re-apply the settings.
- const unreadProps = [
- "quickstart.enabled",
- "bridges.builtin_type",
- "bridges.lox_id",
- ];
+ const unreadProps = ["bridges.builtin_type", "bridges.lox_id"];
const shouldApply = changes.some(prop => !unreadProps.includes(prop));
if (shouldApply) {
await this.#applySettings(true);
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/7a9894…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/7a9894…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
1ad717fe by Henry Wilkes at 2025-01-21T14:56:40+00:00
fixup! TB 40933: Add tor-launcher functionality
TB 41921: Ensure shouldStartAndOwnTor is constant per-session.
TorConnect and TorSettings `enabled` properties depend on this value,
and shouldn't change per session.
- - - - -
8ae53510 by Henry Wilkes at 2025-01-21T14:56:41+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Tighten up TorSettings.
We ensure TorSettings is enabled before certain operations.
Also tidy up uninit to account for early calls (before init completes)
or repeat calls.
Also stop using "torbrowser.settings.enabled" preference, and read from
the preferences for the first run.
Also make TorSettings.initailizedPromise read-only.
- - - - -
a0c13700 by Henry Wilkes at 2025-01-21T14:56:41+00:00
fixup! TB 40562: Added Tor Browser preferences to 000-tor-browser.js
TB 41921: Set default TorSetting setting values in 000-tor-browser.js.
- - - - -
7a98943f by Henry Wilkes at 2025-01-21T15:00:22+00:00
fixup! TB 41435: Add a Tor Browser migration function
TB 41921: Clear out unused "torbrowser.settings.enabled" preference.
- - - - -
4 changed files:
- browser/app/profile/000-tor-browser.js
- browser/components/BrowserGlue.sys.mjs
- toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs
- toolkit/modules/TorSettings.sys.mjs
Changes:
=====================================
browser/app/profile/000-tor-browser.js
=====================================
@@ -61,6 +61,31 @@ pref("browser.startup.homepage", "about:tor");
// tor-browser#40701: Add new download warning
pref("browser.download.showTorWarning", true);
+
+// Tor connection setting preferences.
+
+pref("torbrowser.settings.quickstart.enabled", false);
+pref("torbrowser.settings.bridges.enabled", false);
+// TorBridgeSource. Initially TorBridgeSource.Invalid = -1.
+pref("torbrowser.settings.bridges.source", -1);
+pref("torbrowser.settings.bridges.lox_id", "");
+// obfs4|meek-azure|snowflake|etc.
+pref("torbrowser.settings.bridges.builtin_type", "");
+// torbrowser.settings.bridges.bridge_strings.0
+// torbrowser.settings.bridges.bridge_strings.1
+// etc hold the bridge lines.
+pref("torbrowser.settings.proxy.enabled", false);
+// TorProxyType. Initially TorProxyType.Invalid = -1.
+pref("torbrowser.settings.proxy.type", -1);
+pref("torbrowser.settings.proxy.address", "");
+pref("torbrowser.settings.proxy.port", 0);
+pref("torbrowser.settings.proxy.username", "");
+pref("torbrowser.settings.proxy.password", "");
+pref("torbrowser.settings.firewall.enabled", false);
+// comma-delimited list of port numbers.
+pref("torbrowser.settings.firewall.allowed_ports", "");
+
+
// This pref specifies an ad-hoc "version" for various pref update hacks we need to do
pref("extensions.torbutton.pref_fixup_version", 0);
=====================================
browser/components/BrowserGlue.sys.mjs
=====================================
@@ -4822,7 +4822,9 @@ BrowserGlue.prototype = {
// YouTube search engines (tor-browser#41835).
// Version 5: Tor Browser 14.0a5: Clear user preference for CFR settings
// since we hid the UI (tor-browser#43118).
- const TBB_MIGRATION_VERSION = 5;
+ // Version 6: Tor Browser 14.5a3: Clear preference for TorSettings that is
+ // no longer used (tor-browser#41921).
+ const TBB_MIGRATION_VERSION = 6;
const MIGRATION_PREF = "torbrowser.migration.version";
// If we decide to force updating users to pass through any version
@@ -4904,6 +4906,10 @@ BrowserGlue.prototype = {
}
}
+ if (currentVersion < 6) {
+ Services.prefs.clearUserPref("torbrowser.settings.enabled");
+ }
+
Services.prefs.setIntPref(MIGRATION_PREF, TBB_MIGRATION_VERSION);
},
=====================================
toolkit/components/tor-launcher/TorLauncherUtil.sys.mjs
=====================================
@@ -17,8 +17,6 @@ const kPropBundleURI = "chrome://torbutton/locale/torlauncher.properties";
const kPropNamePrefix = "torlauncher.";
const kIPCDirPrefName = "extensions.torlauncher.tmp_ipc_dir";
-let gStringBundle = null;
-
/**
* This class allows to lookup for the paths of the various files that are
* needed or can be used with the tor daemon, such as its configuration, the
@@ -332,7 +330,7 @@ class TorFile {
}
}
-export const TorLauncherUtil = Object.freeze({
+export const TorLauncherUtil = {
get isAndroid() {
return Services.appinfo.OS === "Android";
},
@@ -417,6 +415,8 @@ export const TorLauncherUtil = Object.freeze({
return this.showConfirm(null, s, defaultBtnLabel, cancelBtnLabel);
},
+ _stringBundle: null,
+
// Localized Strings
// TODO: Switch to fluent also these ones.
@@ -425,6 +425,9 @@ export const TorLauncherUtil = Object.freeze({
if (!aStringName) {
return aStringName;
}
+ if (!this._stringBundle) {
+ this._stringBundle = Services.strings.createBundle(kPropBundleURI);
+ }
try {
const key = kPropNamePrefix + aStringName;
return this._stringBundle.GetStringFromName(key);
@@ -587,7 +590,12 @@ export const TorLauncherUtil = Object.freeze({
Services.prefs.savePrefFile(null);
},
- get shouldStartAndOwnTor() {
+ /**
+ * Determine the current value for whether we should start and own Tor.
+ *
+ * @returns {boolean} Whether we should start and own Tor.
+ */
+ _getShouldStartAndOwnTor() {
const kPrefStartTor = "extensions.torlauncher.start_tor";
try {
const kBrowserToolboxPort = "MOZ_BROWSER_TOOLBOX_PORT";
@@ -610,6 +618,29 @@ export const TorLauncherUtil = Object.freeze({
return Services.prefs.getBoolPref(kPrefStartTor, true);
},
+ /**
+ * Cached value for shouldStartAndOwnTor, or `null` if not yet initialised.
+ *
+ * @type {boolean}
+ */
+ _shouldStartAndOwnTor: null,
+
+ /**
+ * Whether we should start and own Tor.
+ *
+ * The value should be constant per-session.
+ *
+ * @type {boolean}
+ */
+ get shouldStartAndOwnTor() {
+ // Do not want this value to change within the same session, so always used
+ // the cached valued if it is available.
+ if (this._shouldStartAndOwnTor === null) {
+ this._shouldStartAndOwnTor = this._getShouldStartAndOwnTor();
+ }
+ return this._shouldStartAndOwnTor;
+ },
+
get shouldShowNetworkSettings() {
try {
const kEnvForceShowNetConfig = "TOR_FORCE_NET_CONFIG";
@@ -668,11 +699,4 @@ export const TorLauncherUtil = Object.freeze({
console.warn("Could not remove the IPC directory", e);
}
},
-
- get _stringBundle() {
- if (!gStringBundle) {
- gStringBundle = Services.strings.createBundle(kPropBundleURI);
- }
- return gStringBundle;
- },
-});
+};
=====================================
toolkit/modules/TorSettings.sys.mjs
=====================================
@@ -27,8 +27,6 @@ export const TorSettingsTopics = Object.freeze({
/* Prefs used to store settings in TorBrowser prefs */
const TorSettingsPrefs = Object.freeze({
- /* bool: are we pulling tor settings from the preferences */
- enabled: "torbrowser.settings.enabled",
quickstart: {
/* bool: does tor connect automatically on launch */
enabled: "torbrowser.settings.quickstart.enabled",
@@ -245,6 +243,13 @@ class TorSettingsImpl {
*/
#builtinBridges = {};
+ /**
+ * A promise that resolves once we are initialized, or throws if there was an
+ * initialization error.
+ *
+ * @type {Promise}
+ */
+ #initializedPromise;
/**
* Resolve callback of the initializedPromise.
*/
@@ -261,8 +266,29 @@ class TorSettingsImpl {
*/
#initialized = false;
+ /**
+ * Whether uninit cleanup has been called.
+ *
+ * @type {boolean}
+ */
+ #uninitCalled = false;
+
+ /**
+ * Whether Lox was initialized.
+ *
+ * @type {boolean}
+ */
+ #initializedLox = false;
+
+ /**
+ * Whether observers were initialized.
+ *
+ * @type {boolean}
+ */
+ #initializedObservers = false;
+
constructor() {
- this.initializedPromise = new Promise((resolve, reject) => {
+ this.#initializedPromise = new Promise((resolve, reject) => {
this.#initComplete = resolve;
this.#initFailed = reject;
});
@@ -378,12 +404,22 @@ class TorSettingsImpl {
return this.#builtinBridges[pt] ?? [];
}
+ /**
+ * Whether this module is enabled.
+ *
+ * @type {boolean}
+ */
+ get enabled() {
+ return lazy.TorLauncherUtil.shouldStartAndOwnTor;
+ }
+
/**
* Load or init our settings.
*/
async init() {
if (this.#initialized) {
lazy.logger.warn("Called init twice.");
+ await this.#initializedPromise;
return;
}
try {
@@ -402,6 +438,11 @@ class TorSettingsImpl {
* it easier to update initializatedPromise.
*/
async #initInternal() {
+ if (!this.enabled || this.#uninitCalled) {
+ // Nothing to do.
+ return;
+ }
+
try {
const req = await fetch("chrome://global/content/pt_config.json");
const config = await req.json();
@@ -419,26 +460,37 @@ class TorSettingsImpl {
lazy.logger.error("Could not load the built-in PT config.", e);
}
+ // `uninit` may have been called whilst we awaited pt_config.
+ if (this.#uninitCalled) {
+ lazy.logger.warn("unint was called before init completed.");
+ return;
+ }
+
// Initialize this before loading from prefs because we need Lox initialized
// before any calls to Lox.getBridges().
if (!lazy.TorLauncherUtil.isAndroid) {
try {
+ // Set as initialized before calling to ensure it is cleaned up by our
+ // `uninit` method.
+ this.#initializedLox = true;
await lazy.Lox.init();
} catch (e) {
lazy.logger.error("Could not initialize Lox.", e);
}
}
- if (
- lazy.TorLauncherUtil.shouldStartAndOwnTor &&
- Services.prefs.getBoolPref(TorSettingsPrefs.enabled, false)
- ) {
- this.#loadFromPrefs();
- // We do not pass on the loaded settings to the TorProvider yet. Instead
- // TorProvider will ask for these once it has initialised.
+ // `uninit` may have been called whilst we awaited Lox.init.
+ if (this.#uninitCalled) {
+ lazy.logger.warn("unint was called before init completed.");
+ return;
}
+ this.#loadFromPrefs();
+ // We do not pass on the loaded settings to the TorProvider yet. Instead
+ // TorProvider will ask for these once it has initialised.
+
Services.obs.addObserver(this, lazy.LoxTopics.UpdateBridges);
+ this.#initializedObservers = true;
lazy.logger.info("Ready");
}
@@ -447,8 +499,22 @@ class TorSettingsImpl {
* Unload or uninit our settings.
*/
async uninit() {
- Services.obs.removeObserver(this, lazy.LoxTopics.UpdateBridges);
- await lazy.Lox.uninit();
+ if (this.#uninitCalled) {
+ lazy.logger.warn("Called uninit twice");
+ return;
+ }
+
+ this.#uninitCalled = true;
+ // NOTE: We do not reset #initialized to false because we want it to remain
+ // in place for external callers, and we do not want `#initInternal` to be
+ // re-entered.
+
+ if (this.#initializedObservers) {
+ Services.obs.removeObserver(this, lazy.LoxTopics.UpdateBridges);
+ }
+ if (this.#initializedLox) {
+ await lazy.Lox.uninit();
+ }
}
observe(subject, topic) {
@@ -473,10 +539,13 @@ class TorSettingsImpl {
}
/**
- * Check whether the object has been successfully initialized, and throw if
- * it has not.
+ * Check whether the module is enabled and successfully initialized, and throw
+ * if it is not.
*/
#checkIfInitialized() {
+ if (!this.enabled) {
+ throw new Error("TorSettings is not enabled");
+ }
if (!this.#initialized) {
lazy.logger.trace("Not initialized code path.");
throw new Error(
@@ -494,6 +563,16 @@ class TorSettingsImpl {
return this.#initialized;
}
+ /**
+ * A promise that resolves once we are initialized, or throws if there was an
+ * initialization error.
+ *
+ * @type {Promise}
+ */
+ get initializedPromise() {
+ return this.#initializedPromise;
+ }
+
/**
* Load our settings from prefs.
*/
@@ -701,9 +780,6 @@ class TorSettingsImpl {
} else {
Services.prefs.clearUserPref(TorSettingsPrefs.firewall.allowed_ports);
}
-
- // all tor settings now stored in prefs :)
- Services.prefs.setBoolPref(TorSettingsPrefs.enabled, true);
}
/**
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/06cbcd…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/06cbcd…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
6571ac7b by Henry Wilkes at 2025-01-21T14:15:40+00:00
fixup! TB 40933: Add tor-launcher functionality
TB 41921: Move prompt_at_startup preference from TorProvider to
TorConnect only.
- - - - -
fa81e56c by Henry Wilkes at 2025-01-21T14:15:40+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Move prompt_at_startup pref from TorProvider to TorConnect
only.
This simplifies the logic, where we set the preference any time we have
a bootstrap error and clear it when we are bootstrapped.
- - - - -
093e9483 by Henry Wilkes at 2025-01-21T14:15:41+00:00
fixup! TB 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection
TB 41921: Move flushSettings call to TorSettings.
The call in connectionPane will not necessarily run when the
preference tab is closed, nor will it trigger for bridges added through
auto-bootstrapping.
- - - - -
b50c1c9c by Henry Wilkes at 2025-01-21T14:15:42+00:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Flush TorSettings settings every time they are saved.
- - - - -
06cbcd5d by Henry Wilkes at 2025-01-21T14:15:43+00:00
fixup! TB 40933: Add tor-launcher functionality
TB 41921: Add a NOTE for future development ensuring that writeSettings
is not subject to any races between sequential calls.
- - - - -
5 changed files:
- browser/components/torpreferences/content/connectionPane.js
- toolkit/components/tor-launcher/TorControlPort.sys.mjs
- toolkit/components/tor-launcher/TorProvider.sys.mjs
- toolkit/modules/TorConnect.sys.mjs
- toolkit/modules/TorSettings.sys.mjs
Changes:
=====================================
browser/components/torpreferences/content/connectionPane.js
=====================================
@@ -2545,19 +2545,6 @@ 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", 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);
- }
- });
-
// Quickstart
this._enableQuickstartCheckbox = document.getElementById(
"torPreferences-quickstart-toggle"
=====================================
toolkit/components/tor-launcher/TorControlPort.sys.mjs
=====================================
@@ -364,6 +364,9 @@ export class TorController {
/**
* The commands that need to be run or receive a response.
*
+ * NOTE: This must be in the order with the last requested command at the end
+ * of the queue.
+ *
* @type {Command[]}
*/
#commandQueue = [];
@@ -947,6 +950,10 @@ export class TorController {
* values will be automatically unrolled.
*/
async setConf(values) {
+ // NOTE: This is an async method. It must ensure that sequential calls to
+ // this method do not race against each other. I.e. the last call to this
+ // method must always be the last in #commandQueue. Otherwise a delayed
+ // earlier call could overwrite the configuration of a later call.
const args = values
.flatMap(([key, value]) => {
if (value === undefined || value === null) {
=====================================
toolkit/components/tor-launcher/TorProvider.sys.mjs
=====================================
@@ -70,7 +70,6 @@ const Preferences = Object.freeze({
ControlHost: "extensions.torlauncher.control_host",
ControlPort: "extensions.torlauncher.control_port",
MaxLogEntries: "extensions.torlauncher.max_tor_log_entries",
- PromptAtStartup: "extensions.torlauncher.prompt_at_startup",
});
/* Config Keys used to configure tor daemon */
@@ -335,6 +334,15 @@ export class TorProvider {
}
logger.debug("Mapped settings object", settings, torSettings);
+
+ // Send settings to the tor process.
+ // NOTE: Since everything up to this point has been non-async, the order in
+ // which TorProvider.writeSettings is called should match the order in which
+ // the configuration is passed onto setConf. In turn, TorControlPort.setConf
+ // should similarly ensure that the configuration reaches the tor process in
+ // the same order.
+ // In particular, we do not want a race where an earlier call to
+ // TorProvider.writeSettings can be delayed and override a later call.
await this.#controller.setConf(Array.from(torSettings));
}
@@ -962,11 +970,6 @@ export class TorProvider {
if (statusObj.PROGRESS === 100) {
this.#isBootstrapDone = true;
- try {
- Services.prefs.setBoolPref(Preferences.PromptAtStartup, false);
- } catch (e) {
- logger.warn(`Cannot set ${Preferences.PromptAtStartup}`, e);
- }
return;
}
@@ -988,11 +991,6 @@ export class TorProvider {
* @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);
- }
logger.error("Tor bootstrap error", statusObj);
if (
=====================================
toolkit/modules/TorConnect.sys.mjs
=====================================
@@ -16,15 +16,12 @@ ChromeUtils.defineESModuleGetters(lazy, {
TorSettings: "resource://gre/modules/TorSettings.sys.mjs",
});
-/* Relevant prefs used by tor-launcher */
-const TorLauncherPrefs = Object.freeze({
- prompt_at_startup: "extensions.torlauncher.prompt_at_startup",
-});
-
const TorConnectPrefs = Object.freeze({
censorship_level: "torbrowser.debug.censorship_level",
allow_internet_test: "torbrowser.bootstrap.allow_internet_test",
log_level: "torbrowser.bootstrap.log_level",
+ /* prompt_at_startup now controls whether the quickstart can trigger. */
+ prompt_at_startup: "extensions.torlauncher.prompt_at_startup",
});
export const TorConnectState = Object.freeze({
@@ -1050,7 +1047,7 @@ export const TorConnect = {
lazy.logger.info("Starting again since the tor process exited");
// Treat a failure as a possibly broken configuration.
// So, prevent quickstart at the next start.
- Services.prefs.setBoolPref(TorLauncherPrefs.prompt_at_startup, true);
+ Services.prefs.setBoolPref(TorConnectPrefs.prompt_at_startup, true);
this._makeStageRequest(TorConnectStage.Start, true);
break;
default:
@@ -1171,7 +1168,7 @@ export const TorConnect = {
return (
lazy.TorSettings.quickstart.enabled &&
// and the previous bootstrap attempt must have succeeded
- !Services.prefs.getBoolPref(TorLauncherPrefs.prompt_at_startup, true)
+ !Services.prefs.getBoolPref(TorConnectPrefs.prompt_at_startup, true)
);
},
@@ -1451,6 +1448,8 @@ export const TorConnect = {
this._tryAgain = false;
this._potentiallyBlocked = false;
this._errorDetails = null;
+ // Re-enable quickstart for future sessions.
+ Services.prefs.setBoolPref(TorConnectPrefs.prompt_at_startup, false);
if (requestedStage) {
lazy.logger.warn(
@@ -1491,6 +1490,8 @@ export const TorConnect = {
this._tryAgain = true;
this._potentiallyBlocked = true;
+ // Disable quickstart until we have a successful bootstrap.
+ Services.prefs.setBoolPref(TorConnectPrefs.prompt_at_startup, true);
this._signalError(error);
=====================================
toolkit/modules/TorSettings.sys.mjs
=====================================
@@ -711,10 +711,15 @@ class TorSettingsImpl {
*
* Even though this introduces a circular depdency, it makes the API nicer for
* frontend consumers.
+ *
+ * @param {boolean} flush - Whether to also flush the settings to disk.
*/
- async #applySettings() {
+ async #applySettings(flush) {
const provider = await lazy.TorProviderBuilder.build();
await provider.writeSettings();
+ if (flush) {
+ provider.flushSettings();
+ }
}
/**
@@ -974,7 +979,7 @@ class TorSettingsImpl {
];
const shouldApply = changes.some(prop => !unreadProps.includes(prop));
if (shouldApply) {
- await this.#applySettings();
+ await this.#applySettings(true);
}
}
@@ -1042,7 +1047,8 @@ class TorSettingsImpl {
// After checks are complete, we commit them.
this.#temporaryBridgeSettings = bridgeSettings;
- await this.#applySettings();
+ // Do not flush the temporary bridge settings until they are saved.
+ await this.#applySettings(false);
}
/**
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/909f72…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/909f72…
You're receiving this email because of your account on gitlab.torproject.org.
Pier Angelo Vendrame pushed to branch tor-browser-128.6.0esr-14.5-1 at The Tor Project / Applications / Tor Browser
Commits:
b64f4aad by Henry Wilkes at 2025-01-21T11:50:20+01:00
fixup! TB 40597: Implement TorSettings module
TB 41921: Make the TorSettings properties read-only outside of the
TorSettings modules.
Within TorSettings we make all post initialisation changes in
changeSettings. This means we can simplify the class and move all the
setter logic into one place.
- - - - -
909f72ff by Henry Wilkes at 2025-01-21T11:50:24+01:00
fixup! TB 31286: Implementation of bridge, proxy, and firewall settings in about:preferences#connection
TB 41921: Pass in the BridgeDB bridge_strings as an Array to
TorSettings.
- - - - -
3 changed files:
- browser/components/torpreferences/content/connectionPane.js
- toolkit/modules/DomainFrontedRequests.sys.mjs
- toolkit/modules/TorSettings.sys.mjs
Changes:
=====================================
browser/components/torpreferences/content/connectionPane.js
=====================================
@@ -2319,7 +2319,7 @@ const gBridgeSettings = {
bridges: {
enabled: true,
source: TorBridgeSource.BridgeDB,
- bridge_strings: result.bridges.join("\n"),
+ bridge_strings: result.bridges,
},
});
}
=====================================
toolkit/modules/DomainFrontedRequests.sys.mjs
=====================================
@@ -130,7 +130,7 @@ class MeekTransport {
TOR_PT_CLIENT_TRANSPORTS: meekTransport,
};
if (lazy.TorSettings.proxy.enabled) {
- envAdditions.TOR_PT_PROXY = lazy.TorSettings.proxy.uri;
+ envAdditions.TOR_PT_PROXY = lazy.TorSettings.proxyUri;
}
const opts = {
=====================================
toolkit/modules/TorSettings.sys.mjs
=====================================
@@ -179,10 +179,34 @@ class TorSettingsImpl {
enabled: false,
},
bridges: {
+ /**
+ * Whether the bridges are enabled or not.
+ *
+ * @type {boolean}
+ */
enabled: false,
source: TorBridgeSource.Invalid,
+ /**
+ * The lox id is used with the Lox "source", and remains set with the
+ * stored value when other sources are used.
+ *
+ * @type {string}
+ */
lox_id: "",
+ /**
+ * The built-in type to use when using the BuiltIn "source", or empty when
+ * using any other source.
+ *
+ * @type {string}
+ */
builtin_type: "",
+ /**
+ * The current bridge strings.
+ *
+ * Can only be non-empty if the "source" is not Invalid.
+ *
+ * @type {Array<string>}
+ */
bridge_strings: [],
},
proxy: {
@@ -206,15 +230,6 @@ class TorSettingsImpl {
*/
#temporaryBridgeSettings = null;
- /**
- * Accumulated errors from trying to set settings.
- *
- * Only added to if not null.
- *
- * @type {Array<Error>?}
- */
- #settingErrors = null;
-
/**
* The recommended pluggable transport.
*
@@ -245,13 +260,6 @@ class TorSettingsImpl {
* @type {boolean}
*/
#initialized = false;
- /**
- * During some phases of the initialization, allow calling setters and
- * getters without throwing errors.
- *
- * @type {boolean}
- */
- #allowUninitialized = false;
constructor() {
this.initializedPromise = new Promise((resolve, reject) => {
@@ -259,347 +267,57 @@ class TorSettingsImpl {
this.#initFailed = reject;
});
- this.#addProperties("quickstart", {
- enabled: {},
- });
- this.#addProperties("bridges", {
- /**
- * Whether the bridges are enabled or not.
- *
- * @type {boolean}
- */
- enabled: {},
- /**
- * The current bridge source.
- *
- * @type {integer}
- */
- source: {
- transform: (val, addError) => {
- if (Object.values(TorBridgeSource).includes(val)) {
- return val;
- }
- addError(`Not a valid bridge source: "${val}"`);
- return TorBridgeSource.Invalid;
- },
- },
- /**
- * The current bridge strings.
- *
- * Can only be non-empty if the "source" is not Invalid.
- *
- * @type {Array<string>}
- */
- bridge_strings: {
- transform: val => {
- if (Array.isArray(val)) {
- return [...val];
- }
- // Split the bridge strings, discarding empty.
- return splitBridgeLines(val).filter(val => val);
- },
- copy: val => [...val],
- equal: (val1, val2) => this.#arrayEqual(val1, val2),
- },
- /**
- * The built-in type to use when using the BuiltIn "source", or empty when
- * using any other source.
- *
- * @type {string}
- */
- builtin_type: {
- callback: (val, addError) => {
- if (!val) {
- return;
- }
- const bridgeStrings = this.getBuiltinBridges(val);
- if (bridgeStrings.length) {
- this.bridges.bridge_strings = bridgeStrings;
- return;
- }
-
- addError(`No built-in ${val} bridges found`);
- // Set as invalid, which will make the builtin_type "" and set the
- // bridge_strings to be empty at the next #cleanupSettings.
- this.bridges.source = TorBridgeSource.Invalid;
- },
- },
- /**
- * The lox id is used with the Lox "source", and remains set with the stored value when
- * other sources are used.
- *
- * @type {string}
- */
- lox_id: {
- callback: (val, addError) => {
- if (!val) {
- return;
- }
- let bridgeStrings;
- try {
- bridgeStrings = lazy.Lox.getBridges(val);
- } catch (error) {
- addError(`No bridges for lox_id ${val}: ${error?.message}`);
- // Set as invalid, which will make the builtin_type "" and set the
- // bridge_strings to be empty at the next #cleanupSettings.
- this.bridges.source = TorBridgeSource.Invalid;
- return;
- }
- this.bridges.bridge_strings = bridgeStrings;
- },
- },
- });
- this.#addProperties("proxy", {
- enabled: {},
- type: {
- transform: (val, addError) => {
- if (Object.values(TorProxyType).includes(val)) {
- return val;
- }
- addError(`Not a valid proxy type: "${val}"`);
- return TorProxyType.Invalid;
- },
- },
- address: {},
- port: {
- transform: (val, addError) => {
- if (val === 0) {
- // This is a valid value that "unsets" the port.
- // Keep this value without giving a warning.
- // NOTE: In contrast, "0" is not valid.
- return 0;
- }
- // Unset to 0 if invalid null is returned.
- return this.#parsePort(val, false, addError) ?? 0;
- },
- },
- username: {},
- password: {},
- uri: {
- getter: () => {
- const { type, address, port, username, password } = this.proxy;
- switch (type) {
- case TorProxyType.Socks4:
- return `socks4a://${address}:${port}`;
- case TorProxyType.Socks5:
- if (username) {
- return `socks5://${username}:${password}@${address}:${port}`;
- }
- return `socks5://${address}:${port}`;
- case TorProxyType.HTTPS:
- if (username) {
- return `http://${username}:${password}@${address}:${port}`;
- }
- return `http://${address}:${port}`;
- }
- return null;
- },
- },
- });
- this.#addProperties("firewall", {
- enabled: {},
- allowed_ports: {
- transform: (val, addError) => {
- if (!Array.isArray(val)) {
- val = val === "" ? [] : val.split(",");
- }
- // parse and remove duplicates
- const portSet = new Set(
- val.map(p => this.#parsePort(p, true, addError))
- );
- // parsePort returns null for failed parses, so remove it.
- portSet.delete(null);
- return [...portSet];
- },
- copy: val => [...val],
- equal: (val1, val2) => this.#arrayEqual(val1, val2),
- },
- });
- }
-
- /**
- * Clean the setting values after making some changes, so that the values do
- * not contradict each other.
- */
- #cleanupSettings() {
- this.#freezeNotifications();
- try {
- if (this.bridges.source === TorBridgeSource.Invalid) {
- this.bridges.enabled = false;
- this.bridges.bridge_strings = [];
+ // Add some read-only getters for the #settings object.
+ // E.g. TorSetting.#settings.bridges.source is exposed publicly as
+ // TorSettings.bridges.source.
+ for (const groupname in this.#settings) {
+ const publicGroup = {};
+ for (const name in this.#settings[groupname]) {
+ // Public group only has a getter for the property.
+ Object.defineProperty(publicGroup, name, {
+ get: () => {
+ this.#checkIfInitialized();
+ return structuredClone(this.#settings[groupname][name]);
+ },
+ set: () => {
+ throw new Error(
+ `TorSettings.${groupname}.${name} cannot be set directly`
+ );
+ },
+ });
}
- if (!this.bridges.bridge_strings.length) {
- this.bridges.enabled = false;
- this.bridges.source = TorBridgeSource.Invalid;
- }
- if (this.bridges.source !== TorBridgeSource.BuiltIn) {
- this.bridges.builtin_type = "";
- }
- if (this.bridges.source !== TorBridgeSource.Lox) {
- this.bridges.lox_id = "";
- }
- if (!this.proxy.enabled) {
- this.proxy.type = TorProxyType.Invalid;
- this.proxy.address = "";
- this.proxy.port = 0;
- this.proxy.username = "";
- this.proxy.password = "";
- }
- if (!this.firewall.enabled) {
- this.firewall.allowed_ports = [];
- }
- } finally {
- this.#thawNotifications();
+ // The group object itself should not be writable.
+ Object.preventExtensions(publicGroup);
+ Object.defineProperty(this, groupname, {
+ writable: false,
+ value: publicGroup,
+ });
}
}
/**
- * The current number of freezes applied to the notifications.
- *
- * @type {integer}
- */
- #freezeNotificationsCount = 0;
- /**
- * The queue for settings that have changed. To be broadcast in the
- * notification when not frozen.
- *
- * @type {Set<string>}
- */
- #notificationQueue = new Set();
- /**
- * Send a notification if we have any queued and we are not frozen.
- */
- #tryNotification() {
- if (this.#freezeNotificationsCount || !this.#notificationQueue.size) {
- return;
- }
- Services.obs.notifyObservers(
- { changes: [...this.#notificationQueue] },
- TorSettingsTopics.SettingsChanged
- );
- this.#notificationQueue.clear();
- }
- /**
- * Pause notifications for changes in setting values. This is useful if you
- * need to make batch changes to settings.
- *
- * This should always be paired with a call to thawNotifications once
- * notifications should be released. Usually you should wrap whatever
- * changes you make with a `try` block and call thawNotifications in the
- * `finally` block.
- */
- #freezeNotifications() {
- this.#freezeNotificationsCount++;
- }
- /**
- * Release the hold on notifications so they may be sent out.
- *
- * Note, if some other method has also frozen the notifications, this will
- * only release them once it has also called this method.
- */
- #thawNotifications() {
- this.#freezeNotificationsCount--;
- this.#tryNotification();
- }
- /**
- * @typedef {object} TorSettingProperty
+ * The proxy URI for the current settings, or `null` if no proxy is
+ * configured.
*
- * @property {function} [getter] - A getter for the property. If this is
- * given, the property cannot be set.
- * @property {function} [transform] - Called in the setter for the property,
- * with the new value given. Should transform the given value into the
- * right type.
- * @property {function} [equal] - Test whether two values for the property
- * are considered equal. Otherwise uses `===`.
- * @property {function} [callback] - Called whenever the property value
- * changes, with the new value given. Should be used to trigger any other
- * required changes for the new value.
- * @property {function} [copy] - Called whenever the property is read, with
- * the stored value given. Should return a copy of the value. Otherwise
- * returns the stored value.
+ * @type {?string}
*/
- /**
- * Add properties to the TorSettings instance, to be read or set.
- *
- * @param {string} groupname - The name of the setting group. The given
- * settings will be accessible from the TorSettings property of the same
- * name.
- * @param {object.<string, TorSettingProperty>} propParams - An object that
- * defines the settings to add to this group. The object property names
- * will be mapped to properties of TorSettings under the given groupname
- * property. Details about the setting should be described in the
- * TorSettingProperty property value.
- */
- #addProperties(groupname, propParams) {
- // Create a new object to hold all these settings.
- const group = {};
- for (const name in propParams) {
- const { getter, transform, callback, copy, equal } = propParams[name];
- // Method for adding setting errors.
- const addError = message => {
- message = `TorSettings.${groupname}.${name}: ${message}`;
- lazy.logger.error(message);
- // Only add to #settingErrors if it is not null.
- this.#settingErrors?.push(message);
- };
- Object.defineProperty(group, name, {
- get: getter
- ? () => {
- // Allow getting in loadFromPrefs before we are initialized.
- if (!this.#allowUninitialized) {
- this.#checkIfInitialized();
- }
- return getter();
- }
- : () => {
- // Allow getting in loadFromPrefs before we are initialized.
- if (!this.#allowUninitialized) {
- this.#checkIfInitialized();
- }
- let val = this.#settings[groupname][name];
- if (copy) {
- val = copy(val);
- }
- // Assume string or number value.
- return val;
- },
- set: getter
- ? undefined
- : val => {
- // Allow setting in loadFromPrefs before we are initialized.
- if (!this.#allowUninitialized) {
- this.#checkIfInitialized();
- }
- const prevVal = this.#settings[groupname][name];
- this.#freezeNotifications();
- try {
- if (transform) {
- val = transform(val, addError);
- }
- const isEqual = equal ? equal(val, prevVal) : val === prevVal;
- if (!isEqual) {
- // Set before the callback.
- this.#settings[groupname][name] = val;
- this.#notificationQueue.add(`${groupname}.${name}`);
-
- if (callback) {
- callback(val, addError);
- }
- }
- } catch (e) {
- addError(e.message);
- } finally {
- this.#thawNotifications();
- }
- },
- });
+ get proxyUri() {
+ const { type, address, port, username, password } = this.#settings.proxy;
+ switch (type) {
+ case TorProxyType.Socks4:
+ return `socks4a://${address}:${port}`;
+ case TorProxyType.Socks5:
+ if (username) {
+ return `socks5://${username}:${password}@${address}:${port}`;
+ }
+ return `socks5://${address}:${port}`;
+ case TorProxyType.HTTPS:
+ if (username) {
+ return `http://${username}:${password}@${address}:${port}`;
+ }
+ return `http://${address}:${port}`;
}
- // The group object itself should not be writable.
- Object.preventExtensions(group);
- Object.defineProperty(this, groupname, {
- writable: false,
- value: group,
- });
+ return null;
}
/**
@@ -614,12 +332,11 @@ class TorSettingsImpl {
* @param {string|integer} val - The value to parse.
* @param {boolean} trim - Whether a string value can be stripped of
* whitespace before parsing.
- * @param {function} addError - Callback to add error messages to.
*
* @return {integer?} - The port number, or null if the given value was not
* valid.
*/
- #parsePort(val, trim, addError) {
+ #parsePort(val, trim) {
if (typeof val === "string") {
if (trim) {
val = val.trim();
@@ -628,13 +345,11 @@ class TorSettingsImpl {
if (this.#portRegex.test(val)) {
val = Number.parseInt(val, 10);
} else {
- addError(`Invalid port string "${val}"`);
- return null;
+ throw new Error(`Invalid port string "${val}"`);
}
}
if (!Number.isInteger(val) || val < 1 || val > 65535) {
- addError(`Port out of range: ${val}`);
- return null;
+ throw new Error(`Port out of range: ${val}`);
}
return val;
}
@@ -659,13 +374,8 @@ class TorSettingsImpl {
* @param {string} pt The pluggable transport to return the lines for
* @returns {string[]} The bridge lines in random order
*/
- getBuiltinBridges(pt) {
- if (!this.#allowUninitialized) {
- this.#checkIfInitialized();
- }
- // Shuffle so that Tor Browser users do not all try the built-in bridges in
- // the same order.
- return arrayShuffle(this.#builtinBridges[pt] ?? []);
+ #getBuiltinBridges(pt) {
+ return this.#builtinBridges[pt] ?? [];
}
/**
@@ -698,6 +408,13 @@ class TorSettingsImpl {
lazy.logger.debug("Loaded pt_config.json", config);
this.#recommendedPT = config.recommendedDefault;
this.#builtinBridges = config.bridges;
+ for (const type in this.#builtinBridges) {
+ // Shuffle so that Tor Browser users do not all try the built-in bridges
+ // in the same order.
+ // Only do this once per session. In particular, we don't re-shuffle if
+ // changeSettings is called with the same bridges.builtin_type value.
+ this.#builtinBridges[type] = arrayShuffle(this.#builtinBridges[type]);
+ }
} catch (e) {
lazy.logger.error("Could not load the built-in PT config.", e);
}
@@ -716,18 +433,9 @@ class TorSettingsImpl {
lazy.TorLauncherUtil.shouldStartAndOwnTor &&
Services.prefs.getBoolPref(TorSettingsPrefs.enabled, false)
) {
- // Do not want notifications for initially loaded prefs.
- this.#freezeNotifications();
- try {
- this.#allowUninitialized = true;
- this.#loadFromPrefs();
- // We do not pass on the loaded settings to the TorProvider yet. Instead
- // TorProvider will ask for these once it has initialised.
- } finally {
- this.#allowUninitialized = false;
- this.#notificationQueue.clear();
- this.#thawNotifications();
- }
+ this.#loadFromPrefs();
+ // We do not pass on the loaded settings to the TorProvider yet. Instead
+ // TorProvider will ask for these once it has initialised.
}
Services.obs.addObserver(this, lazy.LoxTopics.UpdateBridges);
@@ -746,16 +454,19 @@ class TorSettingsImpl {
observe(subject, topic) {
switch (topic) {
case lazy.LoxTopics.UpdateBridges:
- if (this.bridges.lox_id) {
- // Fetch the newest bridges.
- this.bridges.bridge_strings = lazy.Lox.getBridges(
- this.bridges.lox_id
- );
- // No need to save to prefs since bridge_strings is not stored for Lox
- // source. But we do pass on the changes to TorProvider.
+ if (
+ this.#settings.bridges.lox_id &&
+ this.#settings.bridges.source === TorBridgeSource.Lox
+ ) {
+ // Re-trigger the call to lazy.Lox.getBridges.
// FIXME: This can compete with TorConnect to reach TorProvider.
// tor-browser#42316
- this.#applySettings();
+ this.changeSettings({
+ bridges: {
+ source: TorBridgeSource.Lox,
+ lox_id: this.#settings.bridges.lox_id,
+ },
+ });
}
break;
}
@@ -790,23 +501,24 @@ class TorSettingsImpl {
lazy.logger.debug("loadFromPrefs()");
/* Quickstart */
- this.quickstart.enabled = Services.prefs.getBoolPref(
+ this.#settings.quickstart.enabled = Services.prefs.getBoolPref(
TorSettingsPrefs.quickstart.enabled,
false
);
/* Bridges */
- this.bridges.enabled = Services.prefs.getBoolPref(
+ const bridges = {};
+ bridges.enabled = Services.prefs.getBoolPref(
TorSettingsPrefs.bridges.enabled,
false
);
- this.bridges.source = Services.prefs.getIntPref(
+ bridges.source = Services.prefs.getIntPref(
TorSettingsPrefs.bridges.source,
TorBridgeSource.Invalid
);
- switch (this.bridges.source) {
+ switch (bridges.source) {
case TorBridgeSource.BridgeDB:
case TorBridgeSource.UserProvided:
- this.bridges.bridge_strings = Services.prefs
+ bridges.bridge_strings = Services.prefs
.getBranch(TorSettingsPrefs.bridges.bridge_strings)
.getChildList("")
.map(pref =>
@@ -817,60 +529,79 @@ class TorSettingsImpl {
break;
case TorBridgeSource.BuiltIn:
// bridge_strings is set via builtin_type.
- this.bridges.builtin_type = Services.prefs.getStringPref(
+ bridges.builtin_type = Services.prefs.getStringPref(
TorSettingsPrefs.bridges.builtin_type,
""
);
break;
case TorBridgeSource.Lox:
// bridge_strings is set via lox id.
- this.bridges.lox_id = Services.prefs.getStringPref(
+ bridges.lox_id = Services.prefs.getStringPref(
TorSettingsPrefs.bridges.lox_id,
""
);
break;
}
+ try {
+ this.#fixupBridgeSettings(bridges);
+ this.#settings.bridges = bridges;
+ } catch (error) {
+ lazy.logger.error("Loaded bridge preferences failed", error);
+ // Keep the default #settings.bridges.
+ }
+
/* Proxy */
- this.proxy.enabled = Services.prefs.getBoolPref(
+ const proxy = {};
+ proxy.enabled = Services.prefs.getBoolPref(
TorSettingsPrefs.proxy.enabled,
false
);
- if (this.proxy.enabled) {
- this.proxy.type = Services.prefs.getIntPref(
+ if (proxy.enabled) {
+ proxy.type = Services.prefs.getIntPref(
TorSettingsPrefs.proxy.type,
TorProxyType.Invalid
);
- this.proxy.address = Services.prefs.getStringPref(
+ proxy.address = Services.prefs.getStringPref(
TorSettingsPrefs.proxy.address,
""
);
- this.proxy.port = Services.prefs.getIntPref(
- TorSettingsPrefs.proxy.port,
- 0
- );
- this.proxy.username = Services.prefs.getStringPref(
+ proxy.port = Services.prefs.getIntPref(TorSettingsPrefs.proxy.port, 0);
+ proxy.username = Services.prefs.getStringPref(
TorSettingsPrefs.proxy.username,
""
);
- this.proxy.password = Services.prefs.getStringPref(
+ proxy.password = Services.prefs.getStringPref(
TorSettingsPrefs.proxy.password,
""
);
}
+ try {
+ this.#fixupProxySettings(proxy);
+ this.#settings.proxy = proxy;
+ } catch (error) {
+ lazy.logger.error("Loaded proxy preferences failed", error);
+ // Keep the default #settings.proxy.
+ }
/* Firewall */
- this.firewall.enabled = Services.prefs.getBoolPref(
+ const firewall = {};
+ firewall.enabled = Services.prefs.getBoolPref(
TorSettingsPrefs.firewall.enabled,
false
);
- if (this.firewall.enabled) {
- this.firewall.allowed_ports = Services.prefs.getStringPref(
+ if (firewall.enabled) {
+ firewall.allowed_ports = Services.prefs.getStringPref(
TorSettingsPrefs.firewall.allowed_ports,
""
);
}
-
- this.#cleanupSettings();
+ try {
+ this.#fixupFirewallSettings(firewall);
+ this.#settings.firewall = firewall;
+ } catch (error) {
+ lazy.logger.error("Loaded firewall preferences failed", error);
+ // Keep the default #settings.firewall.
+ }
}
/**
@@ -880,29 +611,28 @@ class TorSettingsImpl {
lazy.logger.debug("saveToPrefs()");
this.#checkIfInitialized();
- this.#cleanupSettings();
/* Quickstart */
Services.prefs.setBoolPref(
TorSettingsPrefs.quickstart.enabled,
- this.quickstart.enabled
+ this.#settings.quickstart.enabled
);
/* Bridges */
Services.prefs.setBoolPref(
TorSettingsPrefs.bridges.enabled,
- this.bridges.enabled
+ this.#settings.bridges.enabled
);
Services.prefs.setIntPref(
TorSettingsPrefs.bridges.source,
- this.bridges.source
+ this.#settings.bridges.source
);
Services.prefs.setStringPref(
TorSettingsPrefs.bridges.builtin_type,
- this.bridges.builtin_type
+ this.#settings.bridges.builtin_type
);
Services.prefs.setStringPref(
TorSettingsPrefs.bridges.lox_id,
- this.bridges.lox_id
+ this.#settings.bridges.lox_id
);
// erase existing bridge strings
const bridgeBranchPrefs = Services.prefs
@@ -915,10 +645,10 @@ class TorSettingsImpl {
});
// write new ones
if (
- this.bridges.source !== TorBridgeSource.Lox &&
- this.bridges.source !== TorBridgeSource.BuiltIn
+ this.#settings.bridges.source !== TorBridgeSource.Lox &&
+ this.#settings.bridges.source !== TorBridgeSource.BuiltIn
) {
- this.bridges.bridge_strings.forEach((string, index) => {
+ this.#settings.bridges.bridge_strings.forEach((string, index) => {
Services.prefs.setStringPref(
`${TorSettingsPrefs.bridges.bridge_strings}.${index}`,
string
@@ -928,22 +658,28 @@ class TorSettingsImpl {
/* Proxy */
Services.prefs.setBoolPref(
TorSettingsPrefs.proxy.enabled,
- this.proxy.enabled
+ this.#settings.proxy.enabled
);
- if (this.proxy.enabled) {
- Services.prefs.setIntPref(TorSettingsPrefs.proxy.type, this.proxy.type);
+ if (this.#settings.proxy.enabled) {
+ Services.prefs.setIntPref(
+ TorSettingsPrefs.proxy.type,
+ this.#settings.proxy.type
+ );
Services.prefs.setStringPref(
TorSettingsPrefs.proxy.address,
- this.proxy.address
+ this.#settings.proxy.address
+ );
+ Services.prefs.setIntPref(
+ TorSettingsPrefs.proxy.port,
+ this.#settings.proxy.port
);
- Services.prefs.setIntPref(TorSettingsPrefs.proxy.port, this.proxy.port);
Services.prefs.setStringPref(
TorSettingsPrefs.proxy.username,
- this.proxy.username
+ this.#settings.proxy.username
);
Services.prefs.setStringPref(
TorSettingsPrefs.proxy.password,
- this.proxy.password
+ this.#settings.proxy.password
);
} else {
Services.prefs.clearUserPref(TorSettingsPrefs.proxy.type);
@@ -955,12 +691,12 @@ class TorSettingsImpl {
/* Firewall */
Services.prefs.setBoolPref(
TorSettingsPrefs.firewall.enabled,
- this.firewall.enabled
+ this.#settings.firewall.enabled
);
- if (this.firewall.enabled) {
+ if (this.#settings.firewall.enabled) {
Services.prefs.setStringPref(
TorSettingsPrefs.firewall.allowed_ports,
- this.firewall.allowed_ports.join(",")
+ this.#settings.firewall.allowed_ports.join(",")
);
} else {
Services.prefs.clearUserPref(TorSettingsPrefs.firewall.allowed_ports);
@@ -977,11 +713,135 @@ class TorSettingsImpl {
* frontend consumers.
*/
async #applySettings() {
- this.#checkIfInitialized();
const provider = await lazy.TorProviderBuilder.build();
await provider.writeSettings();
}
+ /**
+ * Fixup the given bridges settings to fill in details, establish the correct
+ * types and clean up.
+ *
+ * May throw if there is an error in the given values.
+ *
+ * @param {Object} bridges - The bridges settings to fix up.
+ */
+ #fixupBridgeSettings(bridges) {
+ if (!Object.values(TorBridgeSource).includes(bridges.source)) {
+ throw new Error(`Not a valid bridge source: "${bridges.source}"`);
+ }
+
+ if ("enabled" in bridges) {
+ bridges.enabled = Boolean(bridges.enabled);
+ }
+
+ // Set bridge_strings
+ switch (bridges.source) {
+ case TorBridgeSource.UserProvided:
+ case TorBridgeSource.BridgeDB:
+ // Only accept an Array for UserProvided and BridgeDB bridge_strings.
+ break;
+ case TorBridgeSource.BuiltIn:
+ bridges.builtin_type = String(bridges.builtin_type);
+ bridges.bridge_strings = this.#getBuiltinBridges(bridges.builtin_type);
+ break;
+ case TorBridgeSource.Lox:
+ bridges.lox_id = String(bridges.lox_id);
+ bridges.bridge_strings = lazy.Lox.getBridges(bridges.lox_id);
+ break;
+ case TorBridgeSource.Invalid:
+ bridges.bridge_strings = [];
+ break;
+ }
+
+ if (
+ !Array.isArray(bridges.bridge_strings) ||
+ bridges.bridge_strings.some(str => typeof str !== "string")
+ ) {
+ throw new Error("bridge_strings should be an Array of strings");
+ }
+
+ if (
+ bridges.source !== TorBridgeSource.Invalid &&
+ !bridges.bridge_strings?.length
+ ) {
+ throw new Error(
+ `Missing bridge_strings for bridge source ${bridges.source}`
+ );
+ }
+
+ if (bridges.source !== TorBridgeSource.BuiltIn) {
+ bridges.builtin_type = "";
+ }
+ if (bridges.source !== TorBridgeSource.Lox) {
+ bridges.lox_id = "";
+ }
+
+ if (bridges.source === TorBridgeSource.Invalid) {
+ bridges.enabled = false;
+ }
+ }
+
+ /**
+ * Fixup the given proxy settings to fill in details, establish the correct
+ * types and clean up.
+ *
+ * May throw if there is an error in the given values.
+ *
+ * @param {Object} proxy - The proxy settings to fix up.
+ */
+ #fixupProxySettings(proxy) {
+ proxy.enabled = Boolean(proxy.enabled);
+ if (!proxy.enabled) {
+ proxy.type = TorProxyType.Invalid;
+ proxy.address = "";
+ proxy.port = 0;
+ proxy.username = "";
+ proxy.password = "";
+ return;
+ }
+
+ if (!Object.values(TorProxyType).includes(proxy.type)) {
+ throw new Error(`Invalid proxy type: ${proxy.type}`);
+ }
+ proxy.port = this.#parsePort(proxy.port, false);
+ proxy.address = String(proxy.address);
+ proxy.username = String(proxy.username);
+ proxy.password = String(proxy.password);
+ }
+
+ /**
+ * Fixup the given firewall settings to fill in details, establish the correct
+ * types and clean up.
+ *
+ * May throw if there is an error in the given values.
+ *
+ * @param {Object} firewall - The proxy settings to fix up.
+ */
+ #fixupFirewallSettings(firewall) {
+ firewall.enabled = Boolean(firewall.enabled);
+ if (!firewall.enabled) {
+ firewall.allowed_ports = [];
+ return;
+ }
+
+ let allowed_ports = firewall.allowed_ports;
+ if (!Array.isArray(allowed_ports)) {
+ allowed_ports = allowed_ports === "" ? [] : allowed_ports.split(",");
+ }
+ // parse and remove duplicates
+ const portSet = new Set();
+
+ for (const port of allowed_ports) {
+ try {
+ portSet.add(this.#parsePort(port, true));
+ } catch (e) {
+ // Do not throw for individual ports.
+ lazy.logger.error(`Failed to parse the port ${port}. Ignoring.`, e);
+ }
+ }
+ firewall.allowed_ports = [...portSet];
+ }
+
/**
* Change the Tor settings in use.
*
@@ -994,101 +854,128 @@ class TorSettingsImpl {
* + proxy settings can be set as a group.
* + firewall settings can be set a group.
*
- * @param {object} settings - The settings object to set.
+ * @param {object} newValues - The new setting values, a subset of the
+ * complete settings that should be changed.
*/
- async changeSettings(settings) {
- lazy.logger.debug("changeSettings()", settings);
+ async changeSettings(newValues) {
+ lazy.logger.debug("changeSettings()", newValues);
this.#checkIfInitialized();
- const backup = this.getSettings();
- const backupNotifications = [...this.#notificationQueue];
- // Start collecting errors.
- this.#settingErrors = [];
-
- // Hold off on lots of notifications until all settings are changed.
- this.#freezeNotifications();
- try {
- if ("quickstart" in settings && "enabled" in settings.quickstart) {
- this.quickstart.enabled = !!settings.quickstart.enabled;
+ // Make a structured clone since we change the object and may adopt some of
+ // the Array values.
+ newValues = structuredClone(newValues);
+
+ const completeSettings = structuredClone(this.#settings);
+ const changes = [];
+
+ /**
+ * Change the given setting to a new value. Does nothing if the new value
+ * equals the old one, otherwise the change will be recorded in `changes`.
+ *
+ * @param {string} group - The group name for the property.
+ * @param {string} prop - The property name within the group.
+ * @param {any} value - The value to set.
+ * @param [Function?] equal - A method to test equality between the old and
+ * new value. Otherwise uses `===` to check equality.
+ */
+ const changeSetting = (group, prop, value, equal = null) => {
+ const currentValue = this.#settings[group][prop];
+ if (equal ? equal(currentValue, value) : currentValue === value) {
+ return;
}
+ completeSettings[group][prop] = value;
+ changes.push(`${group}.${prop}`);
+ };
- if ("bridges" in settings) {
- if ("enabled" in settings.bridges) {
- this.bridges.enabled = !!settings.bridges.enabled;
- }
- if ("source" in settings.bridges) {
- this.bridges.source = settings.bridges.source;
- switch (settings.bridges.source) {
- case TorBridgeSource.BridgeDB:
- case TorBridgeSource.UserProvided:
- this.bridges.bridge_strings = settings.bridges.bridge_strings;
- break;
- case TorBridgeSource.BuiltIn:
- this.bridges.builtin_type = settings.bridges.builtin_type;
- break;
- case TorBridgeSource.Lox:
- this.bridges.lox_id = settings.bridges.lox_id;
- break;
- case TorBridgeSource.Invalid:
- break;
- case undefined:
- break;
- }
- }
- }
+ if ("quickstart" in newValues && "enabled" in newValues.quickstart) {
+ changeSetting(
+ "quickstart",
+ "enabled",
+ Boolean(newValues.quickstart.enabled)
+ );
+ }
- if ("proxy" in settings) {
- // proxy settings have to be set as a group.
- this.proxy.enabled = !!settings.proxy.enabled;
- if (this.proxy.enabled) {
- this.proxy.type = settings.proxy.type;
- this.proxy.address = settings.proxy.address;
- this.proxy.port = settings.proxy.port;
- this.proxy.username = settings.proxy.username;
- this.proxy.password = settings.proxy.password;
+ if ("bridges" in newValues) {
+ if ("source" in newValues.bridges) {
+ this.#fixupBridgeSettings(newValues.bridges);
+ changeSetting("bridges", "source", newValues.bridges.source);
+ changeSetting(
+ "bridges",
+ "bridge_strings",
+ newValues.bridges.bridge_strings,
+ this.#arrayEqual
+ );
+ changeSetting("bridges", "lox_id", newValues.bridges.lox_id);
+ changeSetting(
+ "bridges",
+ "builtin_type",
+ newValues.bridges.builtin_type
+ );
+ } else if ("enabled" in newValues.bridges) {
+ // Don't need to fixup all the settings, just need to ensure that the
+ // enabled value is compatible with the current source.
+ newValues.bridges.enabled = Boolean(newValues.bridges.enabled);
+ if (
+ newValues.bridges.enabled &&
+ completeSettings.bridges.source === TorBridgeSource.Invalid
+ ) {
+ throw new Error("Cannot enable bridges without a bridge source.");
}
}
-
- if ("firewall" in settings) {
- // firewall settings have to be set as a group.
- this.firewall.enabled = !!settings.firewall.enabled;
- if (this.firewall.enabled) {
- this.firewall.allowed_ports = settings.firewall.allowed_ports;
- }
+ if ("enabled" in newValues.bridges) {
+ changeSetting("bridges", "enabled", newValues.bridges.enabled);
}
+ }
- this.#cleanupSettings();
+ if ("proxy" in newValues) {
+ // proxy settings have to be set as a group.
+ this.#fixupProxySettings(newValues.proxy);
+ changeSetting("proxy", "enabled", Boolean(newValues.proxy.enabled));
+ changeSetting("proxy", "type", newValues.proxy.type);
+ changeSetting("proxy", "address", newValues.proxy.address);
+ changeSetting("proxy", "port", newValues.proxy.port);
+ changeSetting("proxy", "username", newValues.proxy.username);
+ changeSetting("proxy", "password", newValues.proxy.password);
+ }
- if (this.#settingErrors.length) {
- throw Error(this.#settingErrors.join("; "));
- }
- this.#saveToPrefs();
- } catch (ex) {
- // Restore the old settings without any new notifications generated from
- // the above code.
- // NOTE: Since the code that changes #settings is not async, it should not
- // be possible for some other call to TorSettings to change anything
- // whilst we are in this context (other than lower down in this call
- // stack), so it is safe to discard all changes to settings and
- // notifications.
- this.#settings = backup;
- this.#notificationQueue.clear();
- for (const notification of backupNotifications) {
- this.#notificationQueue.add(notification);
- }
+ if ("firewall" in newValues) {
+ // firewall settings have to be set as a group.
+ this.#fixupFirewallSettings(newValues.firewall);
+ changeSetting("firewall", "enabled", Boolean(newValues.firewall.enabled));
+ changeSetting(
+ "firewall",
+ "allowed_ports",
+ newValues.firewall.allowed_ports,
+ this.#arrayEqual
+ );
+ }
+
+ // No errors so far, so save and commit.
+ this.#settings = completeSettings;
+ this.#saveToPrefs();
- throw ex;
- } finally {
- this.#thawNotifications();
- // Stop collecting errors.
- this.#settingErrors = null;
+ if (changes.length) {
+ Services.obs.notifyObservers(
+ { changes },
+ TorSettingsTopics.SettingsChanged
+ );
}
- lazy.logger.debug("setSettings result", this.#settings);
+ lazy.logger.debug("setSettings result", this.#settings, changes);
// After we have sent out the notifications for the changed settings and
// saved the preferences we send the new settings to TorProvider.
- await this.#applySettings();
+ // Some properties are unread by TorProvider. So if only these values change
+ // there is no need to re-apply the settings.
+ const unreadProps = [
+ "quickstart.enabled",
+ "bridges.builtin_type",
+ "bridges.lox_id",
+ ];
+ const shouldApply = changes.some(prop => !unreadProps.includes(prop));
+ if (shouldApply) {
+ await this.#applySettings();
+ }
}
/**
@@ -1147,29 +1034,11 @@ class TorSettingsImpl {
const bridgeSettings = {
enabled: true,
source: bridges.source,
+ builtin_type: String(bridges.builtin_type),
+ bridge_strings: structuredClone(bridges.bridge_strings),
};
- if (bridges.source === TorBridgeSource.BuiltIn) {
- if (!bridges.builtin_type) {
- throw Error("Missing a built-in type");
- }
- bridgeSettings.builtin_type = String(bridges.builtin_type);
- const bridgeStrings = this.getBuiltinBridges(bridgeSettings.builtin_type);
- if (!bridgeStrings.length) {
- throw new Error(`No builtin bridges for type ${bridges.builtin_type}`);
- }
- bridgeSettings.bridge_strings = bridgeStrings;
- } else {
- // BridgeDB.
- if (!bridges.bridge_strings?.length) {
- throw new Error("Missing bridges strings");
- }
- // TODO: Can we safely verify the format of the bridge addresses sent from
- // Moat?
- bridgeSettings.bridge_strings = Array.from(bridges.bridge_strings, item =>
- String(item)
- );
- }
+ this.#fixupBridgeSettings(bridgeSettings);
// After checks are complete, we commit them.
this.#temporaryBridgeSettings = bridgeSettings;
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3dd180…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/3dd180…
You're receiving this email because of your account on gitlab.torproject.org.