tor-commits
Threads by month
- ----- 2026 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- 1 participants
- 216254 discussions
[Git][tpo/applications/torbrowser-launcher] Pushed new branch AppArmor-fine-grained-DBus
by intrigeri (@intrigeri) 17 Nov '26
by intrigeri (@intrigeri) 17 Nov '26
17 Nov '26
intrigeri pushed new branch AppArmor-fine-grained-DBus at The Tor Project / Applications / torbrowser-launcher
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/torbrowser-launcher/-/tree/A…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-156.0a1-17.0-2] fixup! TB 44806: Implement the tor integration in Rust.
by Pier Angelo Vendrame (@pierov) 17 Nov '26
by Pier Angelo Vendrame (@pierov) 17 Nov '26
17 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-156.0a1-17.0-2 at The Tor Project / Applications / Tor Browser
Commits:
8f0389b9 by Pier Angelo Vendrame at 2026-11-17T15:19:56+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 45481: Remove the low-level interface.
Now we only use the commands, so we do not need the low level interface
that just does the reply parsing anymore.
- - - - -
4 changed files:
- toolkit/components/tor-integration/torITorService.idl
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/reply_parser/mod.rs
- toolkit/components/tor-integration/tor_service/src/control_port.rs
Changes:
=====================================
toolkit/components/tor-integration/torITorService.idl
=====================================
@@ -5,18 +5,6 @@
#include "nsISupports.idl"
#include "nsIFile.idl"
-[scriptable, uuid(4b250614-968a-412f-9191-9ffd9d4bd001)]
-interface torITorControlPortReceiver : nsISupports {
- void onAsyncMessage(in ACString message);
- void onClosed();
-};
-
-[scriptable, uuid(1389d157-4695-43a2-a7d8-538aaa350766)]
-interface torITorMessageHandler : nsISupports {
- void onMessage(in ACString message);
- void onError(in ACString error);
-};
-
[scriptable, uuid(8d817c29-e35c-4a4b-ad29-fb24b83ea8cd)]
interface torITorReplyCallback : nsISupports {
void onReply([optional] in ACString reply);
@@ -37,9 +25,6 @@ interface torITorNotificationListener : nsISupports {
// TODO: Remove once we have a provider.
[scriptable, uuid(f56d710e-5650-4b8c-8d31-279f360003ee)]
interface torITorControlPort : nsISupports {
- void start(in torITorControlPortReceiver receiver);
- void sendCommand(in ACString command, in torITorMessageHandler handler);
-
void authenticate(in Array<uint8_t> password,
in torITorReplyCallback callback);
void getBootstrapPhase(in torITorReplyCallback callback);
@@ -65,7 +50,7 @@ interface torITorControlPort : nsISupports {
void close();
};
-[scriptable, uuid(2537313c-e120-408c-a2f6-86e6e1bdf899)]
+[builtinclass, scriptable, uuid(2537313c-e120-408c-a2f6-86e6e1bdf899)]
interface torITorService : nsISupports {
// For development purposes...
torITorControlPort createControlPort(in ACString host, in long port);
=====================================
toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
=====================================
@@ -3,7 +3,6 @@
// <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
-use bytes::Bytes;
use std::{net::IpAddr, rc::Rc};
use tinystr::TinyAsciiStr;
@@ -213,23 +212,3 @@ impl<CP: ControlPortInterface> TorController<CP> {
self.send_command(commands::signal_newnym(), handler);
}
}
-
-// TODO: Remove once we merge all parts of tor-browser#44930.
-impl<CP: ControlPortInterface> TorController<CP> {
- #[inline]
- pub fn send_raw_command(
- &self,
- command: Bytes,
- handler: Box<dyn FnOnce(Result<Reply, ControllerError>)>,
- ) {
- self.0.send_command(
- command,
- Box::new(|res| handler(res.map_err(|e| ControllerError::from(e)))),
- );
- }
-
- #[inline]
- pub fn set_async_handler(&self, cb: Option<Box<dyn Fn(Reply)>>) {
- self.0.set_async_handler(cb);
- }
-}
=====================================
toolkit/components/tor-integration/tor_provider/src/ctor/reply_parser/mod.rs
=====================================
@@ -15,7 +15,7 @@ mod test_utils;
pub use dispatcher::ReplyDispatcher;
pub use error::ReplyError;
-pub use line::{DetailReplyLine, EndReplyLine};
+pub use line::DetailReplyLine;
pub use reply::Reply;
#[cfg(test)]
=====================================
toolkit/components/tor-integration/tor_service/src/control_port.rs
=====================================
@@ -10,10 +10,7 @@ use serde_json::{json, Value as JsonValue};
use std::rc::Rc;
use thin_vec::ThinVec;
use tor_provider::ctor::*;
-use xpcom::interfaces::{
- nsIFile, torITorControlPortReceiver, torITorMessageHandler, torITorNotificationListener,
- torITorReplyCallback,
-};
+use xpcom::interfaces::{nsIFile, torITorNotificationListener, torITorReplyCallback};
use xpcom::RefPtr;
// Actually used, but the compiler does not detect it.
@@ -41,80 +38,6 @@ impl ControlPortXpcom {
Ok(Self::allocate(InitControlPortXpcom { control_port }))
}
- xpcom_method!(start => Start(receiver: *const torITorControlPortReceiver));
- pub fn start(&self, receiver: &torITorControlPortReceiver) -> Result<(), nsresult> {
- let receiver = RefPtr::new(receiver);
- let receiver2 = receiver.clone();
- self.control_port
- .set_async_handler(Some(Box::new(move |reply| {
- let mut buf = Vec::new();
- if let Err(e) = reply.write_to(&mut buf) {
- log::error!(
- "Cannot convert the reply to the raw message: {}.",
- e.to_string()
- );
- return;
- }
- if buf.ends_with(b"\r\n") {
- buf.truncate(buf.len() - 2);
- }
- // These conversions re-use the buffer, Gecko uses the same
- // allocator for Rust and C++ (see the nsstring crate).
- let as_str = nsCString::from(buf);
- // Safety: call to an XPCOM method that we expect to be exposed
- // on Rust. As per the documentation in nsstring, it is safe to
- // pass nsCStrings created in Rust to C++.
- unsafe { receiver.OnAsyncMessage(&*as_str) };
- })));
- self.control_port.set_close_handler(Box::new(move || {
- // Safety: call to an XPCOM method of our interface that we crafted
- // to make sure it was exposed on Rust bindings.
- unsafe { receiver2.OnClosed() };
- }));
- Ok(())
- }
-
- xpcom_method!(send_command => SendCommand(command: *const nsACString, handler: *const torITorMessageHandler));
- pub fn send_command(
- &self,
- command: &nsACString,
- handler: &torITorMessageHandler,
- ) -> Result<(), nsresult> {
- let mut command = command.to_vec();
- if !command.ends_with(b"\r\n") {
- command.extend_from_slice(b"\r\n");
- }
- let handler = RefPtr::new(handler);
- self.control_port.send_raw_command(
- command.into(),
- Box::new(move |reply| {
- let mut buf = Vec::new();
- let reply = match reply {
- Ok(r) => r,
- Err(e) => {
- let as_str = nsCString::from(e.to_string());
- // Safety: see the async notification handler.
- unsafe { handler.OnError(&*as_str) };
- return;
- }
- };
- if let Err(e) = reply.write_to(&mut buf) {
- let as_str = nsCString::from(e.to_string());
- // Safety: see the async notification handler.
- unsafe { handler.OnError(&*as_str) };
- return;
- }
- if buf.ends_with(b"\r\n") {
- buf.truncate(buf.len() - 2);
- }
- let as_str = nsCString::from(buf);
- // Safety: see the async notification handler.
- unsafe { handler.OnMessage(&*as_str) };
- }),
- );
- Ok(())
- }
-
xpcom_method!(close => Close());
pub fn close(&self) -> Result<(), nsresult> {
self.control_port.close().map_err(|e| match e {
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/8f0389b…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/8f0389b…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/torbrowser-launcher][main] 2 commits: Allow tor to read geoip, geoip6 and torrc-defaults
by intrigeri (@intrigeri) 17 Nov '26
by intrigeri (@intrigeri) 17 Nov '26
17 Nov '26
intrigeri pushed to branch main at The Tor Project / Applications / torbrowser-launcher
Commits:
2cf2c2e1 by Mario at 2026-11-12T22:30:47+01:00
Allow tor to read geoip, geoip6 and torrc-defaults
Tor Browser >= 10.5 ships geoip, geoip6 and torrc-defaults in
Browser/TorBrowser/Tor/ instead of Browser/TorBrowser/Data/Tor/,
and the torrc generated by Tor Browser points GeoIPFile/GeoIPv6File
at the new location.
The AppArmor profile only allowed reading *.so files from
TorBrowser/Tor/, so the confined tor got EACCES when opening the
geoip databases. Tor keeps running without them, which silently
breaks GETINFO ip-to-country (returns '??'), so the browser circuit
display shows relay IP addresses but no country or flag.
Kernel audit (Debian trixie, torbrowser-launcher 0.3.7-3,
Tor Browser 16.0.1, tor 0.4.9.16):
apparmor="DENIED" operation="open" profile="torbrowser_tor"
name=".../Browser/TorBrowser/Tor/geoip" denied_mask="r"
apparmor="DENIED" operation="open" profile="torbrowser_tor"
name=".../Browser/TorBrowser/Tor/geoip6" denied_mask="r"
apparmor="DENIED" operation="open" profile="torbrowser_tor"
name=".../Browser/TorBrowser/Tor/torrc-defaults" denied_mask="r"
With the added rules the bundled tor logs 'Parsing GEOIP IPv4/IPv6
file ...' and GETINFO ip-to-country resolves countries again
(verified with a test instance of the bundled tor under the patched
profile).
- - - - -
2dfa6cbf by intrigeri at 2026-11-17T13:51:05+00:00
Merge branch 'fix/apparmor-geoip' into 'main'
Allow tor to read geoip, geoip6 and torrc-defaults
See merge request tpo/applications/torbrowser-launcher!53
- - - - -
1 changed file:
- apparmor/torbrowser.Tor.tor
Changes:
=====================================
apparmor/torbrowser.Tor.tor
=====================================
@@ -15,6 +15,9 @@ profile torbrowser_tor @{torbrowser_tor_executable} {
/etc/passwd r,
/etc/resolv.conf r,
owner @{torbrowser_home_dir}/TorBrowser/Tor/tor mr,
+ owner @{torbrowser_home_dir}/TorBrowser/Tor/torrc-defaults r,
+ owner @{torbrowser_home_dir}/TorBrowser/Tor/geoip r,
+ owner @{torbrowser_home_dir}/TorBrowser/Tor/geoip6 r,
owner @{torbrowser_home_dir}/TorBrowser/Data/Tor/ rw,
owner @{torbrowser_home_dir}/TorBrowser/Data/Tor/** rw,
owner @{torbrowser_home_dir}/TorBrowser/Data/Tor/lock rwk,
View it on GitLab: https://gitlab.torproject.org/tpo/applications/torbrowser-launcher/-/compar…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/torbrowser-launcher/-/compar…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-156.0a1-17.0-2] 4 commits: fixup! TB 44806: Implement the tor integration in Rust.
by Pier Angelo Vendrame (@pierov) 17 Nov '26
by Pier Angelo Vendrame (@pierov) 17 Nov '26
17 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-156.0a1-17.0-2 at The Tor Project / Applications / Tor Browser
Commits:
c3db620a by Elena at 2026-11-17T11:31:40+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Expose the new methods over the control port.
- - - - -
499ed2b8 by Elena at 2026-11-17T11:38:16+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
JS wrappers for the Rust control port.
- - - - -
c441ec64 by Elena at 2026-11-17T11:38:17+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Integration tests
- - - - -
a4bd8746 by Elena at 2026-11-17T11:38:17+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Actually use the new control port.
- - - - -
15 changed files:
- Cargo.lock
- + toolkit/components/tor-integration/OxidationAdapters.sys.mjs
- + toolkit/components/tor-integration/OxidizedControlPort.sys.mjs
- toolkit/components/tor-integration/moz.build
- toolkit/components/tor-integration/test/xpcshell/head.js
- + toolkit/components/tor-integration/test/xpcshell/test_adapters.js
- toolkit/components/tor-integration/test/xpcshell/test_control_port.js
- toolkit/components/tor-integration/test/xpcshell/xpcshell.toml
- toolkit/components/tor-integration/torITorService.idl
- toolkit/components/tor-integration/tor_service/Cargo.toml
- toolkit/components/tor-integration/tor_service/src/control_port.rs
- toolkit/components/tor-integration/tor_service/src/lib.rs
- + toolkit/components/tor-integration/tor_service/src/plumbing.rs
- toolkit/components/tor-launcher/TorControlPort.sys.mjs
- toolkit/components/tor-launcher/TorProvider.sys.mjs
Changes:
=====================================
Cargo.lock
=====================================
@@ -8283,10 +8283,13 @@ version = "0.1.0"
dependencies = [
"bytes",
"cstr",
+ "hex",
"log",
"moz_task",
"nserror",
"nsstring",
+ "serde",
+ "serde_json",
"thin-vec",
"tor_provider",
"xpcom",
=====================================
toolkit/components/tor-integration/OxidationAdapters.sys.mjs
=====================================
@@ -0,0 +1,143 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Converters from the JSON created by the Rust crates to the objects expected
+ * by the JS tor-launcher.
+ */
+export class OxidationAdapters {
+ static #bytesToHex(bytes) {
+ return Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
+ }
+
+ static convertCircuit(circuit) {
+ const circ = {
+ id: circuit.id,
+ nodes: circuit.path.map(fp => OxidationAdapters.#bytesToHex(fp)),
+ };
+ if (circuit.conflux_id) {
+ circ.confluxId = OxidationAdapters.#bytesToHex(circuit.conflux_id);
+ }
+ return circ;
+ }
+
+ static convertBootstrapPhase(phase) {
+ return Object.fromEntries(
+ Object.entries(phase).map(([key, value]) => {
+ if (key === "severity") {
+ key = "TYPE";
+ value = value.toUpperCase();
+ } else if (key === "should_warn") {
+ key = "RECOMMENDATION";
+ value = value ? "warn" : "ignore";
+ } else {
+ key = key.toUpperCase();
+ }
+ return [key, value];
+ })
+ );
+ }
+
+ static convertBridge(b) {
+ const bridge = {
+ transport: b.transport ?? "vanilla",
+ addr: b.address,
+ };
+ if (b.fingerprint) {
+ bridge.id = b.fingerprint;
+ }
+ if (b.args) {
+ bridge.args = b.args;
+ }
+ return bridge;
+ }
+
+ static convertPluggableTransports(pts) {
+ return pts.map(pt => {
+ if (pt.pt_type === "exec") {
+ return {
+ transports: pt.transports,
+ type: pt.pt_type,
+ pathToBinary: pt.path_to_binary,
+ options: pt.options ?? "",
+ };
+ }
+ return {
+ transports: pt.transports,
+ type: pt.pt_type,
+ ip: pt.ip,
+ port: pt.port,
+ };
+ });
+ }
+
+ static convertOnionKeys(keys) {
+ return keys.map(k => {
+ const key = {
+ address: k.address,
+ keyType: k.key_type,
+ keyBlob: k.key_blob,
+ flags: [],
+ };
+ if (k.is_permanent) {
+ key.flags.push("Permanent");
+ }
+ return key;
+ });
+ }
+}
+
+/**
+ * A class that converts an XPCOM callback to a JS promise.
+ */
+class PromisifiedCallback {
+ #promise;
+ #resolve;
+ #reject;
+
+ constructor() {
+ const { promise, resolve, reject } = Promise.withResolvers();
+ this.#promise = promise;
+ this.#resolve = resolve;
+ this.#reject = reject;
+ }
+
+ get promise() {
+ return this.#promise;
+ }
+
+ onReply(reply) {
+ if (reply) {
+ this.#resolve(JSON.parse(reply));
+ } else {
+ this.#resolve();
+ }
+ }
+
+ onTorError(code, message) {
+ const err = new Error(message);
+ err.code = code;
+ this.#reject(err);
+ }
+
+ onGenericError(message) {
+ this.#reject(new Error(message));
+ }
+}
+
+/**
+ * Promisify an XPCOM method that has a signature that looks like:
+ * void name(<args>, in torITorReplyCallback callback);
+ *
+ * @param {object} obj The oject that contains the method to call
+ * @param {string} method The name of the method to call
+ * @param {...any} args The arguments to pass before the callback
+ * @returns {PromiseLike} A promise that will be resolved/rejected by the native
+ * method
+ */
+export async function promisifyMethod(obj, method, ...args) {
+ const cb = new PromisifiedCallback();
+ obj[method](...args, cb);
+ return cb.promise;
+}
=====================================
toolkit/components/tor-integration/OxidizedControlPort.sys.mjs
=====================================
@@ -0,0 +1,177 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import {
+ OxidationAdapters,
+ promisifyMethod,
+} from "moz-src:///toolkit/components/tor-integration/OxidationAdapters.sys.mjs";
+
+/**
+ * An adapter between torITorNotificationListener and TorEventHandler.
+ */
+class NotificationAdapter {
+ #actualHandler;
+
+ constructor(handler) {
+ this.#actualHandler = handler;
+ }
+
+ logMessage(severity, message) {
+ this.#actualHandler.onLogMessage(severity, message);
+ }
+
+ bootstrapStatus(status) {
+ this.#actualHandler.onBootstrapStatus(
+ OxidationAdapters.convertBootstrapPhase(JSON.parse(status))
+ );
+ }
+
+ circuitBuilt(circuit) {
+ this.#actualHandler.onCircuitBuilt(
+ OxidationAdapters.convertCircuit(JSON.parse(circuit))
+ );
+ }
+
+ circuitClosed(id) {
+ this.#actualHandler.onCircuitClosed(id);
+ }
+
+ streamSentConnect(stream) {
+ stream = JSON.parse(stream);
+ this.#actualHandler.onStreamSentConnect(
+ stream.stream_id,
+ stream.circuit_id,
+ stream.socks_username,
+ stream.socks_password
+ );
+ }
+
+ connectionClosed() {
+ this.#actualHandler.onClosed();
+ }
+}
+
+/**
+ * An adapter to allow TorProvider use the Rust implementation of the
+ * controller.
+ */
+export class OxidizedControlPort {
+ #native;
+
+ static fromIpcFile(ipcFile) {
+ return new OxidizedControlPort(Services.tor.createControlPortIPC(ipcFile));
+ }
+
+ static fromSocketAddress(host, port) {
+ return new OxidizedControlPort(Services.tor.createControlPort(host, port));
+ }
+
+ constructor(native) {
+ this.#native = native;
+ }
+
+ setEventHandler(eventHandler) {
+ this.#native.setNotificationListener(new NotificationAdapter(eventHandler));
+ }
+
+ close() {
+ this.#native?.close();
+ this.#native = null;
+ }
+
+ get isOpen() {
+ return !!this.#native;
+ }
+
+ authenticate(password) {
+ return promisifyMethod(this.#native, "authenticate", Array.from(password));
+ }
+
+ async getBootstrapPhase() {
+ return OxidationAdapters.convertBootstrapPhase(
+ await promisifyMethod(this.#native, "getBootstrapPhase")
+ );
+ }
+
+ async getNodeAddresses(id) {
+ const addrs = await promisifyMethod(this.#native, "getNodeAddresses", id);
+ const rv = [addrs.ipv4];
+ if (addrs.ipv6) {
+ rv.push(addrs.ipv6);
+ }
+ return rv;
+ }
+
+ async getIPCountry(ip) {
+ return promisifyMethod(this.#native, "getIpCountry", ip);
+ }
+
+ getSocksListeners() {
+ return promisifyMethod(this.#native, "getSocksListeners");
+ }
+
+ async getCircuits() {
+ const circuits = await promisifyMethod(this.#native, "getCircuits");
+ return circuits.map(OxidationAdapters.convertCircuit);
+ }
+
+ async getBridges() {
+ const bridges = await promisifyMethod(this.#native, "getBridges");
+ return bridges.map(OxidationAdapters.convertBridge);
+ }
+
+ async getPluggableTransports() {
+ return OxidationAdapters.convertPluggableTransports(
+ await promisifyMethod(this.#native, "getPluggableTransports")
+ );
+ }
+
+ setConf(values) {
+ return promisifyMethod(this.#native, "setConf", JSON.stringify(values));
+ }
+
+ setNetworkEnabled(enabled) {
+ return promisifyMethod(this.#native, "setNetworkEnabled", enabled);
+ }
+
+ flushSettings() {
+ return promisifyMethod(this.#native, "flushSettings");
+ }
+
+ async onionAuthViewKeys() {
+ return OxidationAdapters.convertOnionKeys(
+ await promisifyMethod(this.#native, "onionAuthViewKeys")
+ );
+ }
+
+ onionAuthAdd(address, b64PrivateKey, isPermanent) {
+ return promisifyMethod(
+ this.#native,
+ "onionAuthAdd",
+ address,
+ b64PrivateKey,
+ isPermanent
+ );
+ }
+
+ onionAuthRemove(address) {
+ return promisifyMethod(this.#native, "onionAuthRemove", address);
+ }
+
+ takeOwnership() {
+ return promisifyMethod(this.#native, "takeOwnership");
+ }
+
+ resetOwningControllerProcess() {
+ return promisifyMethod(this.#native, "resetOwningControllerProcess");
+ }
+
+ newnym() {
+ return promisifyMethod(this.#native, "newnym");
+ }
+
+ setEvents(types) {
+ return promisifyMethod(this.#native, "setEvents", types);
+ }
+}
=====================================
toolkit/components/tor-integration/moz.build
=====================================
@@ -11,3 +11,5 @@ XPCOM_MANIFESTS += [
EXPORTS.torproject += ["TorService.h"]
XPCSHELL_TESTS_MANIFESTS += ["test/xpcshell/xpcshell.toml"]
+
+MOZ_SRC_FILES += ["OxidationAdapters.sys.mjs", "OxidizedControlPort.sys.mjs"]
=====================================
toolkit/components/tor-integration/test/xpcshell/head.js
=====================================
@@ -13,7 +13,7 @@ class ControlPortServer {
#ipcFile;
#protocol;
- constructor(protocol, listener) {
+ constructor(protocol) {
this.#server = Cc["@mozilla.org/network/server-socket;1"].createInstance(
Ci.nsIServerSocket
);
@@ -35,19 +35,23 @@ class ControlPortServer {
return;
}
this.#protocol = protocol;
+ }
+ listenOnce() {
const address =
- protocol === "tcp"
+ this.#protocol === "tcp"
? `localhost:${this.#server.port}`
: this.#ipcFile.path;
- this.#server.asyncListen({
- onSocketAccepted(_socket, transport) {
- info(`Got a new connection on ${address}.`);
- listener(new Transport(transport));
- },
- onStopListening() {
- info(`Stopped listening on ${address}.`);
- },
+ return new Promise(resolve => {
+ this.#server.asyncListen({
+ onSocketAccepted(_socket, transport) {
+ info(`Got a new connection on ${address}.`);
+ resolve(new Transport(transport));
+ },
+ onStopListening() {
+ info(`Stopped listening on ${address}.`);
+ },
+ });
});
}
@@ -73,6 +77,7 @@ class ControlPortServer {
this.#server.close();
if (this.#ipcFile) {
this.#ipcFile.remove(false);
+ this.#ipcFile = null;
}
}
}
@@ -111,11 +116,13 @@ class Transport {
try {
available = this.#scriptableInputStream.available();
} catch (e) {
- reject(e);
- return;
+ if (e.result !== Cr?.NS_BASE_STREAM_CLOSED) {
+ reject(e);
+ return;
+ }
}
if (!available) {
- reject(new Error("Connection closed"));
+ resolve("");
return;
}
const str = this.#scriptableInputStream.read(available);
@@ -131,7 +138,7 @@ class Transport {
async readLine() {
const updateBuffer = idx => {
- const line = this.#lineBuffer.substring(0, idx);
+ const line = this.#lineBuffer.substring(0, idx + 2);
this.#lineBuffer = this.#lineBuffer.substring(idx + 2);
return line;
};
@@ -140,7 +147,13 @@ class Transport {
return updateBuffer(idx);
}
do {
- this.#lineBuffer += await this.read();
+ const r = await this.read();
+ if (!r) {
+ const line = this.#lineBuffer;
+ this.#lineBuffer = "";
+ return line;
+ }
+ this.#lineBuffer += r;
idx = this.#lineBuffer.indexOf("\r\n");
} while (idx == -1);
return updateBuffer(idx);
@@ -172,47 +185,3 @@ class Transport {
this.#transport.close(Cr.NS_OK);
}
}
-
-/**
- * A wrapper to the XPCOM code we are testing for turning it into async JS.
- * It can be extended to actually handle async notifications.
- */
-class ControlPortClient {
- #controlPort;
- constructor(server) {
- if (server.protocol === "tcp") {
- this.#controlPort = Services.tor.createControlPort(
- "localhost",
- server.port
- );
- } else if (server.protocol === "ipc") {
- this.#controlPort = Services.tor.createControlPortIPC(server.ipcFile);
- } else {
- throw new Error("Unknown server protocol");
- }
- this.#controlPort.start(this);
- }
-
- sendCommand(command) {
- const { promise, resolve, reject } = Promise.withResolvers();
- this.#controlPort.sendCommand(`${command}\r\n`, {
- onMessage(message) {
- resolve(message);
- },
- onError(error) {
- reject(new Error(error));
- },
- });
- return promise;
- }
-
- close() {
- this.#controlPort.close();
- }
-
- onAsyncMessage(_message) {
- Assert.ok(false, "This test does not use async notifications.");
- }
-
- onClosed() {}
-}
=====================================
toolkit/components/tor-integration/test/xpcshell/test_adapters.js
=====================================
@@ -0,0 +1,362 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { OxidationAdapters, PromisifiedCallback } = ChromeUtils.importESModule(
+ "moz-src:///toolkit/components/tor-integration/OxidationAdapters.sys.mjs"
+);
+
+add_task(async function test_callback_happy() {
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply("");
+ Assert.strictEqual(await cb.promise, undefined);
+ }
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply("1234");
+ Assert.strictEqual(await cb.promise, 1234);
+ }
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply('"1234"');
+ Assert.strictEqual(await cb.promise, "1234");
+ }
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply('"a string"');
+ Assert.strictEqual(await cb.promise, "a string");
+ }
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply('["an", "array"]');
+ Assert.deepEqual(await cb.promise, ["an", "array"]);
+ }
+ {
+ const cb = new PromisifiedCallback();
+ cb.onReply('{"an": "object"}');
+ Assert.deepEqual(await cb.promise, { an: "object" });
+ }
+});
+
+add_task(async function test_callback_tor_error() {
+ let hadError = false;
+ try {
+ const cb = new PromisifiedCallback();
+ cb.onTorError(400, "Some error message");
+ await cb.promise;
+ } catch (e) {
+ hadError = true;
+ Assert.equal(e.code, 400);
+ Assert.equal(e.message, "Some error message");
+ }
+ Assert.ok(hadError, "We did not get an error, but we expected one.");
+});
+
+add_task(async function test_callback_generic_error() {
+ const message = "A more specific error message, maybe not machine-friendly.";
+ let hadError = false;
+ try {
+ const cb = new PromisifiedCallback();
+ cb.onGenericError(message);
+ await cb.promise;
+ } catch (e) {
+ hadError = true;
+ Assert.equal(e.message, message);
+ }
+ Assert.ok(hadError, "We did not get an error, but we expected one.");
+});
+
+add_task(function test_adapter_circuit() {
+ Assert.deepEqual(
+ OxidationAdapters.convertCircuit({
+ id: "123",
+ path: [
+ [1, 2, 3],
+ [4, 5, 6],
+ [10, 16, 32],
+ ],
+ }),
+ {
+ id: "123",
+ nodes: ["010203", "040506", "0a1020"],
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertCircuit({
+ id: "abc",
+ path: [
+ [1, 2, 3],
+ [4, 5, 6],
+ [10, 16, 32],
+ ],
+ conflux_id: [0xaa, 0xbb, 0xcc, 0xe, 0xf, 1, 2, 3],
+ }),
+ {
+ id: "abc",
+ nodes: ["010203", "040506", "0a1020"],
+ confluxId: "aabbcc0e0f010203",
+ }
+ );
+});
+
+add_task(function test_adapter_bootstrap_phase() {
+ Assert.deepEqual(
+ OxidationAdapters.convertBootstrapPhase({
+ severity: "WARN",
+ should_warn: true,
+ progress: 25,
+ tag: "orconn",
+ summary: "Connection to an onion router",
+ reason: "No route to host",
+ }),
+ {
+ TYPE: "WARN",
+ RECOMMENDATION: "warn",
+ PROGRESS: 25,
+ TAG: "orconn",
+ SUMMARY: "Connection to an onion router",
+ REASON: "No route to host",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBootstrapPhase({
+ severity: "NOTICE",
+ should_warn: false,
+ progress: 75,
+ tag: "loading_descriptors",
+ summary: "Loading relay descriptors",
+ }),
+ {
+ TYPE: "NOTICE",
+ RECOMMENDATION: "ignore",
+ PROGRESS: 75,
+ TAG: "loading_descriptors",
+ SUMMARY: "Loading relay descriptors",
+ }
+ );
+});
+
+add_task(function test_adapter_bridge() {
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({ address: "192.168.1.3:443" }),
+ {
+ transport: "vanilla",
+ addr: "192.168.1.3:443",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({ address: "[2001:dead::beef]:9010" }),
+ {
+ transport: "vanilla",
+ addr: "[2001:dead::beef]:9010",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "meek",
+ address: "192.168.1.3:443",
+ }),
+ {
+ transport: "meek",
+ addr: "192.168.1.3:443",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "meek",
+ address: "192.168.1.3:443",
+ args: null,
+ }),
+ {
+ transport: "meek",
+ addr: "192.168.1.3:443",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "meek",
+ address: "192.168.1.3:443",
+ args: "",
+ }),
+ {
+ transport: "meek",
+ addr: "192.168.1.3:443",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "meek",
+ address: "192.168.1.3:443",
+ fingerprint: null,
+ }),
+ {
+ transport: "meek",
+ addr: "192.168.1.3:443",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "snowflake",
+ address: "192.168.1.4:443",
+ args: "some=param another=one",
+ }),
+ {
+ transport: "snowflake",
+ addr: "192.168.1.4:443",
+ args: "some=param another=one",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "obfs4",
+ address: "192.168.1.5:443",
+ fingerprint: "010203cafe",
+ args: "some=param another=one",
+ }),
+ {
+ transport: "obfs4",
+ addr: "192.168.1.5:443",
+ id: "010203cafe",
+ args: "some=param another=one",
+ }
+ );
+
+ Assert.deepEqual(
+ OxidationAdapters.convertBridge({
+ transport: "obfs4",
+ address: "192.168.1.5:443",
+ fingerprint: "010203cafe",
+ }),
+ {
+ transport: "obfs4",
+ addr: "192.168.1.5:443",
+ id: "010203cafe",
+ }
+ );
+});
+
+add_task(function test_adapter_pluggable_transports() {
+ Assert.deepEqual(OxidationAdapters.convertPluggableTransports([]), []);
+
+ Assert.deepEqual(
+ OxidationAdapters.convertPluggableTransports([
+ {
+ transports: ["obfs4", "meek_lite"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/lyrebird",
+ },
+ {
+ transports: ["snowflake"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/lyrebird",
+ options: "some=option",
+ ip: null,
+ port: null,
+ },
+ {
+ transports: ["conjure"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/conjure-client",
+ // Ignored even when not null.
+ ip: "10.0.2.2",
+ port: 80,
+ },
+ {
+ transports: ["proxy1"],
+ type: "socks4",
+ pathToBinary: null,
+ ip: "10.0.2.2",
+ port: 80,
+ },
+ {
+ transports: ["proxy2"],
+ type: "socks5",
+ pathToBinary: "an/ignored/binary",
+ ip: "[::1]",
+ port: 80,
+ },
+ ]),
+ [
+ {
+ transports: ["obfs4", "meek_lite"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/lyrebird",
+ options: "",
+ },
+ {
+ transports: ["snowflake"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/lyrebird",
+ options: "some=option",
+ },
+ {
+ transports: ["conjure"],
+ type: "exec",
+ pathToBinary: "TorBrowser/Tor/PluggableTransports/conjure-client",
+ options: "",
+ },
+ {
+ transports: ["proxy1"],
+ type: "socks4",
+ ip: "10.0.2.2",
+ port: 80,
+ },
+ {
+ transports: ["proxy2"],
+ type: "socks5",
+ ip: "[::1]",
+ port: 80,
+ },
+ ]
+ );
+});
+
+add_task(function test_adapter_onion_keys() {
+ const address = "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD";
+ const keyType = "x25519";
+ const keyBlob = "abase64key";
+
+ Assert.deepEqual(OxidationAdapters.convertOnionKeys([]), []);
+
+ Assert.deepEqual(
+ OxidationAdapters.convertOnionKeys([
+ {
+ address,
+ key_type: keyType,
+ key_blob: keyBlob,
+ is_permanent: false,
+ },
+ {
+ address,
+ key_type: keyType,
+ key_blob: keyBlob,
+ is_permanent: true,
+ },
+ ]),
+ [
+ {
+ address,
+ keyType,
+ keyBlob,
+ flags: [],
+ },
+ {
+ address,
+ keyType,
+ keyBlob,
+ flags: ["Permanent"],
+ },
+ ]
+ );
+});
=====================================
toolkit/components/tor-integration/test/xpcshell/test_control_port.js
=====================================
@@ -3,170 +3,935 @@
"use strict";
+const { OxidizedControlPort } = ChromeUtils.importESModule(
+ "moz-src:///toolkit/components/tor-integration/OxidizedControlPort.sys.mjs"
+);
+
+/**
+ * Mock server to handle control port commands.
+ */
+class MockServer {
+ #transport;
+ noPassword = false;
+ listeners = [];
+ conf = new Map();
+ onionAuth = new Map();
+ events = [];
+
+ constructor(transport) {
+ this.#transport = transport;
+ }
+
+ async start() {
+ info("Starting a mock server");
+ let line;
+ while ((line = await this.#transport.readLine())) {
+ if (line.endsWith("\r\n")) {
+ line = line.slice(0, -2);
+ }
+ const spaceIdx = line.indexOf(" ");
+ const command = spaceIdx !== -1 ? line.slice(0, spaceIdx) : line;
+ const args = spaceIdx !== -1 ? line.slice(spaceIdx + 1) : "";
+ switch (command.toUpperCase()) {
+ case "AUTHENTICATE":
+ await this.#authenticate(args);
+ break;
+ case "GETINFO":
+ await this.#getInfo(args);
+ break;
+ case "GETCONF":
+ await this.#getConf(args);
+ break;
+ case "SETCONF":
+ await this.#setConf(args);
+ break;
+ case "ONION_CLIENT_AUTH_VIEW":
+ await this.#onionView();
+ break;
+ case "ONION_CLIENT_AUTH_ADD":
+ await this.#onionAdd(args);
+ break;
+ case "ONION_CLIENT_AUTH_REMOVE":
+ await this.#onionRemove(args);
+ break;
+ case "SETEVENTS":
+ await this.#setEvents(args);
+ break;
+ case "SAVECONF":
+ case "TAKEOWNERSHIP":
+ case "RESETCONF":
+ case "SIGNAL":
+ await this.write("250 OK\r\n");
+ break;
+ default:
+ await this.write(`510 Unrecognized command "${command}"\r\n`);
+ break;
+ }
+ }
+ }
+
+ async write(str) {
+ await this.#transport.write(str);
+ }
+
+ close() {
+ this.#transport.close();
+ }
+
+ async #authenticate(args) {
+ if (args == "01234567" || (this.noPassword && !args)) {
+ await this.write("250 OK\r\n");
+ return;
+ }
+ await this.write(`515 Authentication failed: wrong password ${args}\r\n`);
+ this.close();
+ }
+
+ async #getInfo(args) {
+ // We support only a single keyword in this mock server.
+ if (args === "status/bootstrap-phase") {
+ await this.#bootstrapPhase();
+ } else if (args.startsWith("ns/id/")) {
+ await this.#nodeInfo(args.substring(6));
+ } else if (args.startsWith("ip-to-country/")) {
+ await this.#ipToCountry(args.substring("ip-to-country/".length));
+ } else if (args === "net/listeners/socks") {
+ await this.#socksListeners();
+ } else if (args === "circuit-status") {
+ await this.#circuitStatus();
+ } else {
+ await this.write(`552 Unrecognized key "${args}"\r\n`);
+ }
+ }
+
+ async #bootstrapPhase() {
+ await this.write(
+ '250-status/bootstrap-phase=NOTICE BOOTSTRAP PROGRESS=100 TAG=done SUMMARY="Done"\r\n'
+ );
+ await this.write("250 OK\r\n");
+ }
+
+ async #nodeInfo(id) {
+ const reply =
+ `250+ns/id/${id}=\r\n` +
+ "r nickname RGiAFtNSR33prk7Csp+CQCVNgOg rLB4YR4Xkky0sutW2EvMJKmWj/y 2038-01-01 00:00:00 12.34.56.78 9001 0\r\n" +
+ "a [2001:0000:123:4567::89ab]:9001\r\n" +
+ "s Fast Guard Running Stable V2Dir Valid\r\n" +
+ "w Bandwidth=5000\r\n" +
+ ".\r\n" +
+ "250 OK\r\n";
+ await this.write(reply);
+ }
+
+ async #ipToCountry(ip) {
+ const reply = code =>
+ this.write(`250-ip-to-country/${ip}=${code}\r\n250 OK\r\n`);
+ if (ip === "1.2.3.4") {
+ await reply("au");
+ } else if (ip === "12.34.56.78") {
+ await reply("US");
+ } else if (ip === "127.0.0.1") {
+ // tor would say ??, but we use it to trigger a parsing error.
+ await reply("invalid");
+ } else {
+ await reply("??");
+ }
+ }
+
+ async #socksListeners() {
+ await this.write(
+ `250-net/listeners/socks=${this.listeners.join(" ")}\r\n250 OK\r\n`
+ );
+ }
+
+ async #circuitStatus() {
+ const reply =
+ "250+circuit-status=\r\n" +
+ "67 BUILT $1111111111111111111111111111111111111111~R1,$2222222222222222222222222222222222222222~Re2,$3333333333333333333333333333333333333333~Relay3 CONFLUX_ID=cccccccccccccccccccccccccccccccc\r\n" +
+ "68 BUILT $4444444444444444444444444444444444444444~Rel4,$5555555555555555555555555555555555555555~Rela5,$3333333333333333333333333333333333333333~Relay3 CONFLUX_ID=cccccccccccccccccccccccccccccccc\r\n" +
+ "6fF BUILT $1111111111111111111111111111aAbBcCdDeEfF,$7777777777777777777777777777777777777777,$8888888888888888888888888888888888888888\r\n" +
+ "111 OTHER_STATUS SHOULD=BE_IGNORED\r\n" +
+ ".\r\n" +
+ "250 OK\r\n";
+ await this.write(reply);
+ }
+
+ async #getConf(key) {
+ switch (key.toLowerCase()) {
+ case "bridge":
+ await this.#getBridges();
+ break;
+ case "clienttransportplugin":
+ this.#getClientTransportPlugin();
+ break;
+ default:
+ await this.write(`552 Unrecognized configuration key "${key}"\r\n`);
+ }
+ }
+
+ async #getBridges() {
+ const reply =
+ "250-Bridge=obfs4 1.2.3.4:443 1111111111111111111111111111111111111111 cert=IiE5kF0SGOWNDF2nN2RQA5iMszRJdvHA3/6JNr0vPZRO5ra2GslNPT46c1Hkj4O5O0a8/g iat-mode=0\r\n" +
+ "250-Bridge=obfs4 123.4.56.78:80 2222222222222222222222222222222222222222 cert=tTo5rWWGawTCMsEHM3DKVPzFni8d0BZib6xtcPVk6F2spWavYyZ5FXqlsaq8exih/6n+UD iat-mode=1\r\n" +
+ "250-Bridge=snowflake 5.6.7.8:443\r\n" +
+ "250-Bridge=snowflake 12.3.4.5:443 some=param\r\n" +
+ "250 Bridge=123.45.6.78:9050\r\n";
+ await this.write(reply);
+ }
+
+ async #getClientTransportPlugin() {
+ const reply =
+ "250-ClientTransportPlugin=meek_lite,obfs2,obfs3,obfs4,scramblesuit,webtunnel exec ./TorBrowser/Tor/PluggableTransports/lyrebird\r\n" +
+ "250-ClientTransportPlugin=snowflake exec .\\TorBrowser\\Tor\\PluggableTransports\\lyrebird\r\n" +
+ "250-ClientTransportPlugin=conjure exec ./TorBrowser/Tor/PluggableTransports/conjure-client -registerURL https://registration.refraction.network/api\r\n" +
+ "250-ClientTransportPlugin=pt1 socks4 127.0.0.1:9052\r\n" +
+ "250 ClientTransportPlugin=pt2 socks5 [::1]:9053\r\n";
+ await this.write(reply);
+ }
+
+ async #setConf(args) {
+ // Notice: this does not handle escaped quotes.
+ const re = /(\w+)(?:=(\d+)|="([^"]*)")?/g;
+ const conf = new Map();
+ for (const m of args.matchAll(re)) {
+ const key = m[1];
+ // Special key we handled differently to simulate a failure.
+ if (key.toUpperCase() === "INVALID") {
+ await this.write(
+ `552 Unrecognized option: Unknown option '${key}'. Failing.\r\n`
+ );
+ return;
+ }
+ const intVal = m[2] !== undefined ? parseInt(m[2]) : undefined;
+ const value = intVal ?? m[3] ?? null;
+ const existing = conf.get(key);
+ if (existing === undefined) {
+ conf.set(key, value);
+ } else if (Array.isArray(existing)) {
+ existing.push(value);
+ } else {
+ conf.set(key, [existing, value]);
+ }
+ }
+ conf.forEach((v, k) => this.conf.set(k, v));
+ await this.write("250 OK\r\n");
+ }
+
+ async #onionView() {
+ let reply = "250-ONION_CLIENT_AUTH_VIEW\r\n";
+ for (const [address, info] of this.onionAuth) {
+ reply += `250-CLIENT ${address} ${info.key} Flags=${info.flags}\r\n`;
+ }
+ reply += "250 OK\r\n";
+ await this.write(reply);
+ }
+
+ async #onionAdd(args) {
+ args = args.split(" ");
+ const address = args.shift();
+ const info = { key: args.shift() };
+ while (args.length) {
+ const arg = args.shift();
+ if (arg.startsWith("Flags=")) {
+ info.flags = arg.substring(6);
+ }
+ }
+ this.onionAuth.set(address, info);
+ await this.write("250 OK\r\n");
+ }
+
+ async #onionRemove(args) {
+ if (this.onionAuth.delete(args)) {
+ await this.write("250 OK\r\n");
+ } else {
+ await this.write(`251 No credentials for "args"\r\n`);
+ }
+ }
+
+ async #setEvents(args) {
+ this.events = args.split(" ");
+ await this.write("250 OK\r\n");
+ }
+}
+
async function runTest(func) {
- info(`Running ${func.name} with TCP`);
- await func("tcp");
+ const run = async (server, client) => {
+ try {
+ const serverTransport = await server.listenOnce();
+ const controlServer = new MockServer(serverTransport);
+ const serverLoopDone = controlServer.start();
+
+ try {
+ await func(controlServer, client);
+ } finally {
+ try {
+ serverTransport.close();
+ } catch (e) {
+ info(`Failed to close the server-side transport: ${e}`);
+ }
+ try {
+ await serverLoopDone;
+ } catch (e) {
+ info(`Exception on the server loop: ${e}`);
+ }
+ }
+ } finally {
+ try {
+ client?.close();
+ } catch (e) {
+ info(`Failed to close the client: ${e}`);
+ }
+ try {
+ server?.close();
+ } catch (e) {
+ info(`Failed to close the server: ${e}`);
+ }
+ }
+ };
+
+ {
+ info("Running with TCP");
+ const server = new ControlPortServer("tcp");
+ const client = OxidizedControlPort.fromSocketAddress(
+ "127.0.0.1",
+ server.port
+ );
+ await run(server, client);
+ }
+
if (IPC_SUPPORTED) {
- info(`Running ${func.name} with Unix-domain sockets`);
- await func("ipc");
+ info("Running with Unix-domain sockets.");
+ const server = new ControlPortServer("ipc");
+ const client = OxidizedControlPort.fromIpcFile(server.ipcFile);
+ await run(server, client);
}
}
-add_task(async function test_simple() {
- await runTest(async function testSimple(protocol) {
- const server = new ControlPortServer(protocol, async transport => {
- const s = await transport.readLine();
- Assert.equal(s, "TEST");
- await transport.write("250 OK\r\n");
- transport.close();
- });
+add_task(async function test_authenticate_happy() {
+ await runTest(async (_server, client) => {
+ try {
+ await client.authenticate([0x01, 0x23, 0x45, 0x67]);
+ Assert.ok(true, "Authentication succeeded.");
+ } catch (e) {
+ Assert.ok(false, `Authenticate failed: ${e.message}.`);
+ }
+ });
+});
- let cp;
+add_task(async function test_authenticate_failure() {
+ await runTest(async (_server, client) => {
+ let failed = false;
try {
- cp = new ControlPortClient(server);
- const reply = await cp.sendCommand("TEST");
- Assert.equal(reply, "250 OK");
- } finally {
- cp?.close();
- server.close();
+ await client.authenticate([]);
+ } catch (e) {
+ Assert.ok(true, `Authenticate failed as expected: ${e.message}.`);
+ failed = true;
+ }
+ Assert.ok(failed, "Wrong authentication succeeded.");
+ });
+
+ await runTest(async (_server, client) => {
+ let failed = false;
+ try {
+ await client.authenticate([0xde, 0xad, 0xbe, 0xef]);
+ } catch (e) {
+ Assert.ok(true, `Authenticate failed as expected: ${e.message}.`);
+ failed = true;
}
+ Assert.ok(failed, "Wrong authentication succeeded.");
});
});
-add_task(async function test_invalidSyntax() {
- await runTest(async function testInvalidSyntax(protocol) {
- const server = new ControlPortServer(protocol, async transport => {
- await transport.read();
- await transport.write("250|OK\r\n");
- transport.close();
- });
+add_task(async function test_authenticate_no_password() {
+ await runTest(async (server, client) => {
+ server.noPassword = true;
+ try {
+ await client.authenticate([]);
+ Assert.ok(true, "Authentication succeeded.");
+ } catch (e) {
+ Assert.ok(false, `Authenticate failed: ${e.message}.`);
+ }
+ });
+});
+
+add_task(async function test_bootstrap_phase() {
+ await runTest(async (_server, client) => {
+ // TODO: Add various phases to the mock server.
+ let phase = await client.getBootstrapPhase();
+ Assert.equal(phase.TYPE, "NOTICE");
+ Assert.equal(phase.PROGRESS, 100);
+ Assert.equal(phase.TAG, "done");
+ Assert.equal(phase.SUMMARY, "Done");
+ });
+});
+
+add_task(async function test_node_address() {
+ await runTest(async (_server, client) => {
+ const addresses = await client.getNodeAddresses(
+ "1111111111111111111111111111111111111111"
+ );
+ Assert.equal(addresses.length, 2);
+ Assert.equal(addresses[0], "12.34.56.78");
+ Assert.equal(addresses[1], "2001:0:123:4567::89ab");
+ });
+});
+
+add_task(async function test_ip_country() {
+ await runTest(async (_server, client) => {
+ // Test we do not change the case of the code.
+ Assert.equal(await client.getIPCountry("1.2.3.4"), "au");
+ Assert.equal(await client.getIPCountry("12.34.56.78"), "US");
+ Assert.equal(await client.getIPCountry("123.4.56.78"), "??");
let failed = true;
- let cp;
try {
- cp = new ControlPortClient(server);
- await cp.sendCommand("TEST");
+ // The real tor would not fail, it is a peculiarity of our mock server.
+ await client.getIPCountry("127.0.0.1");
+ failed = false;
} catch (e) {
- Assert.ok(true, `We got the expected failure: ${e.message}`);
- } finally {
- try {
- cp.close();
- } catch (e) {
- info(`The control port threw when closing: ${e.message}.`);
+ Assert.ok(true, `Got the expected failure: ${e.message}`);
+ }
+ Assert.ok(failed, "Failed when expected");
+ });
+});
+
+add_task(async function test_socks_listeners() {
+ await runTest(async (server, client) => {
+ // Before bootstrap: no listeners
+ server.listeners = [];
+ let listeners = await client.getSocksListeners();
+ Assert.equal(listeners.length, 0);
+
+ // Normal TCP
+ server.listeners = ['"127.0.0.1:9150"'];
+ listeners = await client.getSocksListeners();
+ Assert.deepEqual(listeners, [{ host: "127.0.0.1", port: 9150 }]);
+
+ // Unix sockets
+ server.listeners = ['"unix:/run/user/1000/Tor/socks.socket"'];
+ listeners = await client.getSocksListeners();
+ Assert.deepEqual(listeners, [
+ { ipcPath: "/run/user/1000/Tor/socks.socket" },
+ ]);
+
+ // Multiple
+ server.listeners = ['"127.0.0.1:9050"', '"127.0.0.1:9150"'];
+ listeners = await client.getSocksListeners();
+ Assert.deepEqual(listeners, [
+ { host: "127.0.0.1", port: 9050 },
+ { host: "127.0.0.1", port: 9150 },
+ ]);
+
+ // IPv6
+ server.listeners = ['"[2001:0db8:7000:0000:0000:dead:beef:1234]:9150"'];
+ listeners = await client.getSocksListeners();
+ Assert.deepEqual(listeners, [
+ { host: "2001:db8:7000::dead:beef:1234", port: 9150 },
+ ]);
+ });
+});
+
+add_task(async function test_circuits() {
+ await runTest(async (_server, client) => {
+ const circs = await client.getCircuits();
+ Assert.deepEqual(circs, [
+ {
+ id: "67",
+ nodes: [
+ "1111111111111111111111111111111111111111",
+ "2222222222222222222222222222222222222222",
+ "3333333333333333333333333333333333333333",
+ ],
+ confluxId: "cccccccccccccccccccccccccccccccc",
+ },
+ {
+ id: "68",
+ nodes: [
+ "4444444444444444444444444444444444444444",
+ "5555555555555555555555555555555555555555",
+ "3333333333333333333333333333333333333333",
+ ],
+ confluxId: "cccccccccccccccccccccccccccccccc",
+ },
+ {
+ id: "6fF",
+ nodes: [
+ "1111111111111111111111111111aabbccddeeff",
+ "7777777777777777777777777777777777777777",
+ "8888888888888888888888888888888888888888",
+ ],
+ },
+ ]);
+ });
+});
+
+add_task(async function test_bridges() {
+ await runTest(async (_server, client) => {
+ const bridges = await client.getBridges();
+ Assert.deepEqual(bridges, [
+ {
+ transport: "obfs4",
+ addr: "1.2.3.4:443",
+ id: "1111111111111111111111111111111111111111",
+ args: "cert=IiE5kF0SGOWNDF2nN2RQA5iMszRJdvHA3/6JNr0vPZRO5ra2GslNPT46c1Hkj4O5O0a8/g iat-mode=0",
+ },
+ {
+ transport: "obfs4",
+ addr: "123.4.56.78:80",
+ id: "2222222222222222222222222222222222222222",
+ args: "cert=tTo5rWWGawTCMsEHM3DKVPzFni8d0BZib6xtcPVk6F2spWavYyZ5FXqlsaq8exih/6n+UD iat-mode=1",
+ },
+ {
+ transport: "snowflake",
+ addr: "5.6.7.8:443",
+ },
+ {
+ transport: "snowflake",
+ addr: "12.3.4.5:443",
+ args: "some=param",
+ },
+ {
+ transport: "vanilla",
+ addr: "123.45.6.78:9050",
+ },
+ ]);
+ });
+});
+
+add_task(async function test_pluggable_transports() {
+ await runTest(async (_server, client) => {
+ const pts = await client.getPluggableTransports();
+ Assert.deepEqual(pts, [
+ {
+ transports: [
+ "meek_lite",
+ "obfs2",
+ "obfs3",
+ "obfs4",
+ "scramblesuit",
+ "webtunnel",
+ ],
+ type: "exec",
+ pathToBinary: "./TorBrowser/Tor/PluggableTransports/lyrebird",
+ options: "",
+ },
+ {
+ transports: ["snowflake"],
+ type: "exec",
+ pathToBinary: ".\\TorBrowser\\Tor\\PluggableTransports\\lyrebird",
+ options: "",
+ },
+ {
+ transports: ["conjure"],
+ type: "exec",
+ pathToBinary: "./TorBrowser/Tor/PluggableTransports/conjure-client",
+ options: "-registerURL https://registration.refraction.network/api",
+ },
+ { transports: ["pt1"], type: "socks4", ip: "127.0.0.1", port: "9052" },
+ { transports: ["pt2"], type: "socks5", ip: "[::1]", port: "9053" },
+ ]);
+ });
+});
+
+add_task(async function test_set_conf() {
+ await runTest(async (server, client) => {
+ const entries = [
+ ["boolean", true],
+ ["integer", 3],
+ ["string", "value"],
+ ["array", ["val1", "val2", "val3"]],
+ ["null", null],
+ ];
+ Assert.equal(server.conf.size, 0, "Initially the conf map is empty.");
+ await client.setConf(entries);
+ // Booleans are converted to 0 and 1.
+ entries[0][1] = 1;
+ Assert.deepEqual(Array.from(server.conf.entries()), entries);
+ });
+});
+
+add_task(async function test_set_conf_bad() {
+ await runTest(async (_server, client) => {
+ let failed = false;
+ try {
+ await client.setConf([["INVALID", true]]);
+ } catch (e) {
+ failed = true;
+ Assert.equal(e.code, 552);
+ Assert.equal(
+ e.message,
+ "Unrecognized option: Unknown option 'INVALID'. Failing."
+ );
+ }
+ Assert.ok(failed, "We expected the SETCONF call to fail.");
+ });
+});
+
+add_task(async function test_set_network_enabled() {
+ await runTest(async (server, client) => {
+ await client.setNetworkEnabled(false);
+ Assert.equal(server.conf.get("DisableNetwork"), 1);
+ await client.setNetworkEnabled(true);
+ Assert.equal(server.conf.get("DisableNetwork"), 0);
+ });
+});
+
+add_task(async function test_onion_auth_flow() {
+ await runTest(async (server, client) => {
+ Assert.equal(server.onionAuth.size, 0);
+ await client.onionAuthAdd(
+ "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd",
+ "r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ false
+ );
+ Assert.equal(server.onionAuth.size, 1);
+ Assert.deepEqual(
+ server.onionAuth.get(
+ "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD"
+ ),
+ { key: "x25519:r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP" }
+ );
+ Assert.deepEqual(await client.onionAuthViewKeys(), [
+ {
+ address: "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD",
+ keyType: "x25519",
+ keyBlob: "r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ flags: [],
+ },
+ ]);
+
+ await client.onionAuthAdd(
+ "PG6MMJiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd",
+ "r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ true
+ );
+ Assert.equal(server.onionAuth.size, 1);
+ Assert.deepEqual(
+ server.onionAuth.get(
+ "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD"
+ ),
+ {
+ key: "x25519:r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ flags: "Permanent",
}
+ );
+ Assert.deepEqual(await client.onionAuthViewKeys(), [
+ {
+ address: "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD",
+ keyType: "x25519",
+ keyBlob: "r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ flags: ["Permanent"],
+ },
+ ]);
+
+ await client.onionAuthRemove(
+ "PG6MMJIYJMcrSSLVykfwnnTlARu7P5sVN6y2yMmjU6NUBxndf4pscryD"
+ );
+ Assert.equal(server.onionAuth.size, 0);
+ Assert.deepEqual(await client.onionAuthViewKeys(), []);
+
+ // Removing again should not throw.
+ await client.onionAuthRemove(
+ "PG6MMJIYJMcrSSLVykfwnnTlARu7P5sVN6y2yMmjU6NUBxndf4pscryD"
+ );
+ });
+});
+
+add_task(async function test_onion_auth_add_bad() {
+ await runTest(async (_server, client) => {
+ let failed = false;
+ try {
+ await client.onionAuthAdd(
+ "invalidonionaddress",
+ "r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ true
+ );
+ } catch (e) {
+ Assert.ok(true, `The ONION_CLIENT_AUTH_ADD request failed: ${e.message}`);
+ Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
+ failed = true;
}
- Assert.ok(failed, "sendCommand threw when we expected it to.");
+ Assert.ok(
+ failed,
+ "This ONION_CLIENT_AUTH_ADD request was expected to fail."
+ );
+ });
- server.close();
+ await runTest(async (_server, client) => {
+ let failed = false;
+ try {
+ await client.onionAuthAdd(
+ "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD",
+ "not!base$64:(",
+ true
+ );
+ } catch (e) {
+ Assert.ok(true, `The ONION_CLIENT_AUTH_ADD request failed: ${e.message}`);
+ failed = true;
+ }
+ Assert.ok(
+ failed,
+ "This ONION_CLIENT_AUTH_ADD request was expected to fail."
+ );
+ });
+});
+
+add_task(async function test_onion_auth_remove_bad() {
+ await runTest(async (_server, client) => {
+ let failed = false;
+ try {
+ await client.onionAuthAdd("invalidonionaddress");
+ } catch (e) {
+ Assert.ok(
+ true,
+ `The ONION_CLIENT_AUTH_REMOVE request failed: ${e.message}`
+ );
+ Assert.equal(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
+ failed = true;
+ }
+ Assert.ok(
+ failed,
+ "This ONION_CLIENT_AUTH_REMOVE request was expected to fail."
+ );
+ });
+});
+
+add_task(async function test_onion_auth_view_bad() {
+ const runCommand = async client => {
+ let failed = false;
+ try {
+ await client.onionAuthView();
+ } catch (e) {
+ Assert.ok(
+ true,
+ `The ONION_CLIENT_AUTH_VIEW request failed: ${e.message}`
+ );
+ failed = true;
+ }
+ Assert.ok(
+ failed,
+ "This ONION_CLIENT_AUTH_VIEW request was expected to fail."
+ );
+ };
+
+ await runTest(async (server, client) => {
+ server.onionAuth.set("invalidoniondomain", {
+ key: "x25519:r9aD8uLN/kDI2Bmk633RvwgB/9uwAxNzhrHgJcs8I7wP",
+ flags: "Permanent",
+ });
+ await runCommand(client);
+ });
+
+ await runTest(async (server, client) => {
+ server.onionAuth.set(
+ "PG6MMJIYJMCRSSLVYKFWNNTLARU7P5SVN6Y2YMMJU6NUBXNDF4PSCRYD",
+ {
+ key: "x25519:not!base:(64$$$$",
+ flags: "",
+ }
+ );
+ await runCommand(client);
+ });
+});
+
+add_task(async function test_set_events() {
+ await runTest(async (server, client) => {
+ Assert.equal(server.events.length, 0);
+ const events = ["NOTICE", "INFO"];
+ await client.setEvents(events);
+ Assert.deepEqual(server.events, events);
+ });
+});
+
+add_task(async function test_simple_commands() {
+ await runTest(async (_server, client) => {
+ await client.flushSettings();
+ await client.takeOwnership();
+ await client.resetOwningControllerProcess();
+ await client.newnym();
});
});
/**
- * A specialized control port client for testing async messages.
+ * A notification listener that will be used for tests.
+ * It implements TorEventHandler as defined in TorControlPort.sys.mjs.
*/
-class ControlPortClientAsyncNotification extends ControlPortClient {
- notificationPromise;
+class NotificationListener {
+ #nextType;
#resolve;
- closedPromise;
- #closedResolve;
+ #reject;
- constructor(server) {
- super(server);
- this.notificationPromise = new Promise(
- resolve => (this.#resolve = resolve)
- );
- this.closedPromise = new Promise(
- resolve => (this.#closedResolve = resolve)
- );
+ #checkType(type) {
+ const next = this.#nextType;
+ this.#nextType = null;
+ if (type !== next) {
+ this.#reject(new Error(`Wrong type: got ${type}, expected ${next}`));
+ return false;
+ }
+ return true;
+ }
+
+ setup(type) {
+ this.#nextType = type;
+ return new Promise((resolve, reject) => {
+ this.#resolve = resolve;
+ this.#reject = reject;
+ });
+ }
+
+ onLogMessage(severity, message) {
+ if (this.#checkType("logMessage")) {
+ this.#resolve({ severity, message });
+ }
+ }
+
+ onBootstrapStatus(status) {
+ if (this.#checkType("bootstrapStatus")) {
+ this.#resolve(status);
+ }
}
- onAsyncMessage(message) {
- Assert.equal(message, "650-Test\r\n650 notification");
- this.#resolve();
+ onCircuitBuilt(circuit) {
+ if (this.#checkType("circuitBuilt")) {
+ this.#resolve(circuit);
+ }
+ }
+
+ onCircuitClosed(id) {
+ if (this.#checkType("circuitClosed")) {
+ this.#resolve(id);
+ }
+ }
+
+ onStreamSentConnect(streamId, circuitId, username, password) {
+ if (this.#checkType("streamSentConnect")) {
+ this.#resolve({
+ streamId,
+ circuitId,
+ username,
+ password,
+ });
+ }
}
onClosed() {
- this.#closedResolve();
+ if (this.#checkType("closed")) {
+ this.#resolve();
+ }
}
}
-add_task(async function test_asyncNotification() {
- await runTest(async function testAsyncNotification(protocol) {
- const server = new ControlPortServer(protocol, async transport => {
- await transport.write("650-Test\r\n650 notification\r\n");
- transport.close();
- });
- const cp = new ControlPortClientAsyncNotification(server);
- await cp.notificationPromise;
- cp.close();
- server.close();
- await cp.closedPromise;
+add_task(async function test_log_notifications() {
+ await runTest(async (server, client) => {
+ const listener = new NotificationListener();
+ client.setEventHandler(listener);
+ const testLog = async (severity, message) => {
+ const test = listener.setup("logMessage");
+ await server.write(`650 ${severity} ${message}\r\n`);
+ Assert.deepEqual(await test, {
+ severity,
+ message,
+ });
+ };
+ await testLog("DEBUG", "Some debug info");
+ await testLog("INFO", "An info message");
+ await testLog("NOTICE", "A notice");
+ await testLog("WARN", "An warning, so not too bad");
+ await testLog("ERR", "A bad error!!");
});
});
-add_task(async function test_failureAfterClosing() {
- await runTest(async function testFailureAfterClosing(protocol) {
+add_task(async function test_circuit_built_notifications() {
+ await runTest(async (server, client) => {
+ const listener = new NotificationListener();
+ client.setEventHandler(listener);
{
- let cp;
- const { promise, resolve, reject } = Promise.withResolvers();
- const server = new ControlPortServer(protocol, async transport => {
- transport.close();
- server.close();
-
- try {
- await cp.sendCommand("TEST");
- reject("We managed to send a command after closing the connection.");
- } catch (e) {
- Assert.ok(
- true,
- `We failed to send the command as expected (${e.message})`
- );
- } finally {
- try {
- cp?.close();
- } catch {}
- }
- resolve();
+ const test = listener.setup("circuitBuilt");
+ await server.write(
+ "650 CIRC abc123 BUILT $1111111111111111111111111111111111111111\r\n"
+ );
+ Assert.deepEqual(await test, {
+ id: "abc123",
+ nodes: ["1111111111111111111111111111111111111111"],
});
- try {
- cp = new ControlPortClient(server);
- } catch {
- server.close();
- }
- await promise;
}
-
{
- const server = new ControlPortServer(protocol, async transport => {
- try {
- const s = await transport.readLine();
- Assert.equal(s, "TEST");
- await transport.write("250 OK\r\n");
- } catch {
- // We do not really care if the client manages to close the socket
- // before we handle it.
- }
- transport.close();
+ const test = listener.setup("circuitBuilt");
+ await server.write(
+ "650 CIRC 456 BUILT $aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,$bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,$cccccccccccccccccccccccccccccccccccccccc\r\n"
+ );
+ Assert.deepEqual(await test, {
+ id: "456",
+ nodes: [
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ "cccccccccccccccccccccccccccccccccccccccc",
+ ],
+ });
+ }
+ {
+ const test = listener.setup("circuitBuilt");
+ await server.write(
+ "650 CIRC conflux BUILT $1111111111111111111111111111111111111111~guard,$2222222222222222222222222222222222222222~mid,$3333333333333333333333333333333333333333~exit CONFLUX_ID=aabbccddeeff00112233445566778899\r\n"
+ );
+ Assert.deepEqual(await test, {
+ id: "conflux",
+ nodes: [
+ "1111111111111111111111111111111111111111",
+ "2222222222222222222222222222222222222222",
+ "3333333333333333333333333333333333333333",
+ ],
+ confluxId: "aabbccddeeff00112233445566778899",
});
+ }
+ });
+});
- const cp = new ControlPortClient(server);
- cp.close();
- let sentCommand = false;
- try {
- await cp.sendCommand("TEST");
- sentCommand = true;
- } catch (e) {
- Assert.ok(
- true,
- `We failed to send the command as expected (${e.message})`
- );
- } finally {
- server.close();
- }
- Assert.ok(
- !sentCommand,
- "We did not send the command as we had already closed the connection"
+add_task(async function test_circuit_closed_notification() {
+ await runTest(async (server, client) => {
+ const listener = new NotificationListener();
+ client.setEventHandler(listener);
+ const test = listener.setup("circuitClosed");
+ await server.write("650 CIRC qwerty CLOSED\r\n");
+ Assert.equal(await test, "qwerty");
+ });
+});
+
+add_task(async function test_sent_connect_notifications() {
+ await runTest(async (server, client) => {
+ const listener = new NotificationListener();
+ client.setEventHandler(listener);
+ {
+ const test = listener.setup("streamSentConnect");
+ await server.write("650 STREAM 1 SENTCONNECT 0 1.2.3.4:443\r\n");
+ Assert.deepEqual(await test, {
+ streamId: "1",
+ circuitId: "0",
+ username: null,
+ password: null,
+ });
+ }
+ {
+ const test = listener.setup("streamSentConnect");
+ await server.write(
+ '650 STREAM 1ab SENTCONNECT xyz 1.2.3.4:443 SOCKS_USERNAME="user" SOCKS_PASSWORD="pass"\r\n'
);
+ Assert.deepEqual(await test, {
+ streamId: "1ab",
+ circuitId: "xyz",
+ username: "user",
+ password: "pass",
+ });
}
});
});
+
+add_task(async function test_closed_notification() {
+ await runTest(async (server, client) => {
+ const listener = new NotificationListener();
+ client.setEventHandler(listener);
+ const test = listener.setup("closed");
+ server.close();
+ await test;
+ });
+});
=====================================
toolkit/components/tor-integration/test/xpcshell/xpcshell.toml
=====================================
@@ -1,4 +1,6 @@
[DEFAULT]
head = "head.js"
+["test_adapters.js"]
+
["test_control_port.js"]
=====================================
toolkit/components/tor-integration/torITorService.idl
=====================================
@@ -17,11 +17,51 @@ interface torITorMessageHandler : nsISupports {
void onError(in ACString error);
};
+[scriptable, uuid(8d817c29-e35c-4a4b-ad29-fb24b83ea8cd)]
+interface torITorReplyCallback : nsISupports {
+ void onReply([optional] in ACString reply);
+ void onTorError(in unsigned short code, in ACString message);
+ void onGenericError(in ACString message);
+};
+
+[scriptable, uuid(d555064e-811c-4e6d-b2d6-3ec88ae14a69)]
+interface torITorNotificationListener : nsISupports {
+ void logMessage(in ACString severity, in ACString message);
+ void bootstrapStatus(in ACString status);
+ void circuitBuilt(in ACString circuit);
+ void circuitClosed(in ACString id);
+ void streamSentConnect(in ACString stream);
+ void connectionClosed();
+};
+
// TODO: Remove once we have a provider.
[scriptable, uuid(f56d710e-5650-4b8c-8d31-279f360003ee)]
interface torITorControlPort : nsISupports {
void start(in torITorControlPortReceiver receiver);
void sendCommand(in ACString command, in torITorMessageHandler handler);
+
+ void authenticate(in Array<uint8_t> password,
+ in torITorReplyCallback callback);
+ void getBootstrapPhase(in torITorReplyCallback callback);
+ void getNodeAddresses(in ACString node, in torITorReplyCallback callback);
+ void getIpCountry(in ACString ip, in torITorReplyCallback callback);
+ void getSocksListeners(in torITorReplyCallback callback);
+ void getCircuits(in torITorReplyCallback callback);
+ void getBridges(in torITorReplyCallback callback);
+ void getPluggableTransports(in torITorReplyCallback callback);
+ void setConf(in ACString values, in torITorReplyCallback callback);
+ void setNetworkEnabled(in boolean enabled, in torITorReplyCallback callback);
+ void flushSettings(in torITorReplyCallback callback);
+ void onionAuthViewKeys(in torITorReplyCallback callback);
+ void onionAuthAdd(in ACString address, in ACString key, in boolean permanent,
+ in torITorReplyCallback callback);
+ void onionAuthRemove(in ACString address, in torITorReplyCallback callback);
+ void takeOwnership(in torITorReplyCallback callback);
+ void resetOwningControllerProcess(in torITorReplyCallback callback);
+ void newnym(in torITorReplyCallback callback);
+ void setEvents(in Array<ACString> events, in torITorReplyCallback callback);
+ void setNotificationListener(in torITorNotificationListener listener);
+
void close();
};
=====================================
toolkit/components/tor-integration/tor_service/Cargo.toml
=====================================
@@ -20,5 +20,8 @@ tor_provider = { path = "../tor_provider" }
bytes = "1.4.0"
cstr = "0.2"
+hex = "0.4.3"
log = "0.4"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
thin-vec = { version = "0.2.1", features = ["gecko-ffi"] }
=====================================
toolkit/components/tor-integration/tor_service/src/control_port.rs
=====================================
@@ -2,18 +2,25 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+use bytes::Bytes;
use nserror::nsresult;
-use nserror::{NS_ERROR_NOT_CONNECTED, NS_ERROR_UNEXPECTED, NS_OK};
+use nserror::{NS_ERROR_INVALID_ARG, NS_ERROR_NOT_CONNECTED, NS_ERROR_UNEXPECTED, NS_OK};
use nsstring::{nsACString, nsCString};
-use tor_provider::ctor::{ControlPort, ControlSocketError, ControllerError, TorController};
-use xpcom::interfaces::{nsIFile, torITorControlPortReceiver, torITorMessageHandler};
+use serde_json::{json, Value as JsonValue};
+use std::rc::Rc;
+use thin_vec::ThinVec;
+use tor_provider::ctor::*;
+use xpcom::interfaces::{
+ nsIFile, torITorControlPortReceiver, torITorMessageHandler, torITorNotificationListener,
+ torITorReplyCallback,
+};
use xpcom::RefPtr;
// Actually used, but the compiler does not detect it.
#[allow(unused)]
use xpcom::interfaces::torITorControlPort;
-use super::control_socket::ControlSocketXpcom;
+use super::{control_socket::ControlSocketXpcom, plumbing::*};
#[xpcom(implement(torITorControlPort), atomic)]
pub struct ControlPortXpcom {
@@ -122,4 +129,311 @@ impl ControlPortXpcom {
ControlSocketError::ConnectionClosed => NS_ERROR_NOT_CONNECTED,
}
}
+
+ xpcom_method!(authenticate => Authenticate(password: *const ThinVec<u8>, callback: *const torITorReplyCallback));
+ pub fn authenticate(
+ &self,
+ password: &ThinVec<u8>,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ self.control_port
+ .authenticate(&password, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(get_bootstrap_phase => GetBootstrapPhase(callback: *const torITorReplyCallback));
+ fn get_bootstrap_phase(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port
+ .get_bootstrap_phase(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(get_node_addresses => GetNodeAddresses(node: *const nsACString, callback: *const torITorReplyCallback));
+ fn get_node_addresses(
+ &self,
+ node: &nsACString,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let node_str = str::from_utf8(&node).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ let mut node = [0; 20];
+ hex::decode_to_slice(node_str, &mut node).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ self.control_port
+ .get_node_addresses(node, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(get_ip_country => GetIpCountry(ip: *const nsACString, callback: *const torITorReplyCallback));
+ fn get_ip_country(
+ &self,
+ ip: &nsACString,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let ip = str::from_utf8(&ip).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ let ip = ip.parse().map_err(|_| NS_ERROR_INVALID_ARG)?;
+ self.control_port
+ .get_ip_country(ip, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(get_socks_listeners => GetSocksListeners(callback: *const torITorReplyCallback));
+ fn get_socks_listeners(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ let cb = make_xpcom_handler(callback);
+ self.control_port.get_socks_listeners(Box::new(|reply| {
+ (cb)(reply.map(|listeners| {
+ listeners
+ .iter()
+ .map(|l| match l {
+ SocksListener::Tcp(addr) => {
+ json!({ "host": addr.ip().to_string(), "port": addr.port() })
+ }
+ SocksListener::UnixSocket(path) => {
+ json!({ "ipcPath": path })
+ }
+ })
+ .collect::<Vec<_>>()
+ }))
+ }));
+ Ok(())
+ }
+
+ xpcom_method!(get_circuits => GetCircuits(callback: *const torITorReplyCallback));
+ fn get_circuits(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port.get_circuits(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(get_bridges => GetBridges(callback: *const torITorReplyCallback));
+ pub fn get_bridges(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port.get_bridges(make_xpcom_handler_mapped(
+ callback,
+ |bridges: Vec<Bridge>| {
+ bridges
+ .iter()
+ .map(|b| BridgeWithStrings::from(b))
+ .collect::<Vec<_>>()
+ },
+ ));
+ Ok(())
+ }
+
+ xpcom_method!(get_pluggable_transports => GetPluggableTransports(callback: *const torITorReplyCallback));
+ pub fn get_pluggable_transports(
+ &self,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ self.control_port
+ .get_pluggable_transports(make_xpcom_handler_mapped(
+ callback,
+ |pts: Vec<PluggableTransport>| {
+ pts.iter()
+ .map(|pt| ExpandedPluggableTransport::from(pt))
+ .collect::<Vec<_>>()
+ },
+ ));
+ Ok(())
+ }
+
+ xpcom_method!(set_conf => SetConf(values: *const nsACString, callback: *const torITorReplyCallback));
+ fn set_conf(
+ &self,
+ values: &nsACString,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let values: Vec<(String, JsonValue)> =
+ serde_json::from_slice(&values).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ let mut conf = Vec::with_capacity(values.len());
+ for (val, c) in values.iter() {
+ let cv = match c {
+ JsonValue::Bool(b) => ConfValue::Bool(*b),
+ JsonValue::Number(n) => {
+ if let Some(i) = n.as_i64().and_then(|i| i.try_into().ok()) {
+ ConfValue::Int(i)
+ } else {
+ return Err(NS_ERROR_INVALID_ARG);
+ }
+ }
+ JsonValue::String(s) => ConfValue::String(s.as_str()),
+ JsonValue::Array(arr) => {
+ let mut strings = Vec::with_capacity(arr.len());
+ for v in arr.iter() {
+ match v {
+ JsonValue::String(s) => strings.push(s.as_str()),
+ _ => {
+ return Err(NS_ERROR_INVALID_ARG);
+ }
+ }
+ }
+ ConfValue::Array(strings)
+ }
+ JsonValue::Null => ConfValue::Null,
+ _ => return Err(NS_ERROR_INVALID_ARG),
+ };
+ conf.push((val.as_str(), cv));
+ }
+ self.control_port
+ .set_conf(&conf, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(set_network_enabled => SetNetworkEnabled(enabled: bool, callback: *const torITorReplyCallback));
+ fn set_network_enabled(
+ &self,
+ enabled: bool,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ self.control_port.set_conf(
+ &[("DisableNetwork", ConfValue::Bool(!enabled))],
+ make_xpcom_handler(callback),
+ );
+ Ok(())
+ }
+
+ xpcom_method!(flush_settings => FlushSettings(callback: *const torITorReplyCallback));
+ fn flush_settings(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port.save_conf(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(onion_auth_view_keys => OnionAuthViewKeys(callback: *const torITorReplyCallback));
+ fn onion_auth_view_keys(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port
+ .onion_auth_view_keys(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(onion_auth_add => OnionAuthAdd(address: *const nsACString, key: *const nsACString, permanent: bool, callback: *const torITorReplyCallback));
+ fn onion_auth_add(
+ &self,
+ address: &nsACString,
+ key: &nsACString,
+ permanent: bool,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let address = HSAddress::from_slice(&address).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ self.control_port
+ .onion_auth_add(address, key, permanent, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(onion_auth_remove => OnionAuthRemove(address: *const nsACString, callback: *const torITorReplyCallback));
+ fn onion_auth_remove(
+ &self,
+ address: &nsACString,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let address = HSAddress::from_slice(&address).map_err(|_| NS_ERROR_INVALID_ARG)?;
+ self.control_port
+ .onion_auth_remove(address, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(take_ownership => TakeOwnership(callback: *const torITorReplyCallback));
+ fn take_ownership(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port
+ .take_ownership(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(reset_owning_controller_process => ResetOwningControllerProcess(callback: *const torITorReplyCallback));
+ fn reset_owning_controller_process(
+ &self,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ self.control_port
+ .reset_owning_controller_process(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(newnym => Newnym(callback: *const torITorReplyCallback));
+ fn newnym(&self, callback: *const torITorReplyCallback) -> Result<(), nsresult> {
+ self.control_port
+ .signal_newnym(make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(set_events => SetEvents(events: *const ThinVec<nsCString>, callback: *const torITorReplyCallback));
+ fn set_events(
+ &self,
+ events: &ThinVec<nsCString>,
+ callback: *const torITorReplyCallback,
+ ) -> Result<(), nsresult> {
+ let events = events
+ .iter()
+ .map(|e| str::from_utf8(&e))
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| NS_ERROR_INVALID_ARG)?;
+ self.control_port
+ .set_events(&events, make_xpcom_handler(callback));
+ Ok(())
+ }
+
+ xpcom_method!(set_notification_listener => SetNotificationListener(listener: *const torITorNotificationListener));
+ fn set_notification_listener(
+ &self,
+ listener: &torITorNotificationListener,
+ ) -> Result<(), nsresult> {
+ self.control_port
+ .set_notification_listener(Some(Rc::new(XpcomNotificationListener::new(listener))));
+ let close_listener = RefPtr::new(listener);
+ // For consistency with the JavaScript interface, we still keep the
+ // close handler with the notifications.
+ self.control_port.set_close_handler(Box::new(move || {
+ // Safety: method from our own interface that we created so that it
+ // was exposed to Rust.
+ unsafe { close_listener.ConnectionClosed() };
+ }));
+ Ok(())
+ }
+}
+
+struct XpcomNotificationListener(RefPtr<torITorNotificationListener>);
+
+impl XpcomNotificationListener {
+ fn new(listener: &torITorNotificationListener) -> Self {
+ Self(RefPtr::new(listener))
+ }
+}
+
+impl NotificationListener for XpcomNotificationListener {
+ fn log_message(&self, severity: String, message: Bytes) {
+ // Safety: method from our own interface that we created so that it was
+ // exposed to Rust.
+ unsafe {
+ self.0.LogMessage(
+ &*nsCString::from(severity),
+ &*nsCString::from(message.as_ref()),
+ )
+ };
+ }
+
+ fn bootstrap_status(&self, status: BootstrapStatus) {
+ if let Ok(status) = serde_json::to_vec(&status) {
+ // Safety: method from our own interface that we created so that it
+ // was exposed to Rust.
+ unsafe { self.0.BootstrapStatus(&*nsCString::from(status)) };
+ }
+ }
+
+ fn circuit_built(&self, circuit: Circuit) {
+ // Safety: method from our own interface that we created so that it was
+ // exposed to Rust.
+ if let Ok(circuit) = serde_json::to_vec(&circuit) {
+ unsafe { self.0.CircuitBuilt(&*nsCString::from(circuit)) };
+ }
+ }
+
+ fn circuit_closed(&self, id: CircuitID) {
+ // Safety: method from our own interface that we created so that it was
+ // exposed to Rust.
+ unsafe { self.0.CircuitClosed(&*nsCString::from(id.as_str())) };
+ }
+
+ fn stream_sent_connect(&self, stream: Stream) {
+ let stream = StreamWithStrings::from(stream);
+ if let Ok(stream) = serde_json::to_vec(&stream) {
+ // Safety: method from our own interface that we created so that it
+ // was exposed to Rust.
+ unsafe { self.0.StreamSentConnect(&*nsCString::from(stream)) };
+ }
+ }
}
=====================================
toolkit/components/tor-integration/tor_service/src/lib.rs
=====================================
@@ -7,4 +7,5 @@ extern crate xpcom;
mod control_port;
mod control_socket;
+mod plumbing;
mod service;
=====================================
toolkit/components/tor-integration/tor_service/src/plumbing.rs
=====================================
@@ -0,0 +1,183 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+use nsstring::nsCString;
+use serde::Serialize;
+use std::net::SocketAddr;
+use tor_provider::ctor::*;
+use xpcom::{interfaces::torITorReplyCallback, RefPtr};
+
+fn call_xpcom_callback<T>(res: Result<T, ControllerError>, callback: RefPtr<torITorReplyCallback>)
+where
+ T: Serialize,
+{
+ // Safety: methods from our own interface that we created so that it was
+ // exposed to Rust.
+ match res {
+ Ok(value) => match serde_json::to_vec(&value) {
+ Ok(vec) => unsafe {
+ callback.OnReply(&*nsCString::from(vec));
+ },
+ Err(e) => unsafe {
+ callback.OnGenericError(&*nsCString::from(e.to_string()));
+ },
+ },
+ Err(ControllerError::TorError { code, message }) => unsafe {
+ callback.OnTorError(code, &*nsCString::from(message));
+ },
+ Err(e) => unsafe {
+ callback.OnGenericError(&*nsCString::from(e.to_string()));
+ },
+ }
+}
+
+pub fn make_xpcom_handler<T>(
+ callback: *const torITorReplyCallback,
+) -> Box<dyn FnOnce(Result<T, ControllerError>)>
+where
+ T: Serialize,
+{
+ // Safety: from_raw will handle the null pointer case for us.
+ // It will also increment the reference count, which is what we need, since
+ // the XPCOM convention is that pointers are borrowed.
+ let callback = unsafe { RefPtr::from_raw(callback) };
+ match callback {
+ Some(callback) => Box::new(move |r| {
+ call_xpcom_callback(r, callback);
+ }),
+ None => Box::new(move |_| {}),
+ }
+}
+
+pub fn make_xpcom_handler_mapped<F, T, R>(
+ callback: *const torITorReplyCallback,
+ map: F,
+) -> Box<dyn FnOnce(Result<T, ControllerError>)>
+where
+ F: FnOnce(T) -> R + 'static,
+ R: Serialize,
+{
+ // Safety: from_raw will handle the null pointer case for us.
+ // It will also increment the reference count, which is what we need, since
+ // the XPCOM convention is that pointers are borrowed.
+ let callback = unsafe { RefPtr::from_raw(callback) };
+ match callback {
+ Some(callback) => Box::new(move |r| {
+ call_xpcom_callback(r.map(map), callback);
+ }),
+ None => Box::new(move |_| {}),
+ }
+}
+
+/// A struct that looks like Stream, but uses strings for username and password,
+/// to avoid converting between bytes and strings in JavaScript.
+#[derive(Serialize)]
+pub(crate) struct StreamWithStrings {
+ stream_id: StreamID,
+ circuit_id: CircuitID,
+ socks_username: Option<String>,
+ socks_password: Option<String>,
+}
+
+impl From<Stream> for StreamWithStrings {
+ fn from(value: Stream) -> Self {
+ // The browser uses a limited set of ASCII characters, so even if we end
+ // up with the replacement character, those streams should be discarded
+ // for our purposes anyway.
+ let socks_username = value
+ .socks_username
+ .map(|s| String::from_utf8_lossy(&s).into_owned());
+ let socks_password = value
+ .socks_password
+ .map(|s| String::from_utf8_lossy(&s).into_owned());
+ Self {
+ stream_id: value.stream_id,
+ circuit_id: value.circuit_id,
+ socks_username,
+ socks_password,
+ }
+ }
+}
+
+#[derive(Serialize)]
+pub(crate) struct BridgeWithStrings {
+ pub transport: Option<String>,
+ pub address: String,
+ pub fingerprint: Option<String>,
+ pub args: Option<String>,
+}
+
+impl From<&Bridge> for BridgeWithStrings {
+ fn from(value: &Bridge) -> Self {
+ Self {
+ transport: value.transport.clone(),
+ address: value.address.to_string(),
+ fingerprint: value.fingerprint.map(|fp| hex::encode(fp)),
+ args: value
+ .args
+ .as_ref()
+ .map(|a| String::from_utf8_lossy(a).into_owned()),
+ }
+ }
+}
+
+/// A flattened version PluggableTransport that is friendlier to serialization.
+/// When pt_type is exec, path_to_binary and options are set and ip/port are
+/// None, opposite when it is another type.
+#[derive(Serialize)]
+pub(crate) struct ExpandedPluggableTransport {
+ transports: Vec<String>,
+ pt_type: String,
+ path_to_binary: Option<String>,
+ options: Option<String>,
+ ip: Option<String>,
+ port: Option<u16>,
+}
+
+impl ExpandedPluggableTransport {
+ fn new_exec(transports: &Vec<String>, path: &Vec<u8>, options: &Option<Vec<u8>>) -> Self {
+ Self {
+ transports: transports.clone(),
+ pt_type: String::from("exec"),
+ path_to_binary: Some(String::from_utf8_lossy(path).into_owned()),
+ options: options
+ .as_ref()
+ .map(|o| String::from_utf8_lossy(o).into_owned()),
+ ip: None,
+ port: None,
+ }
+ }
+
+ fn new_socks(transports: &Vec<String>, socks_type: &str, addr: &SocketAddr) -> Self {
+ let ip = if addr.is_ipv6() {
+ format!("[{}]", addr.ip())
+ } else {
+ addr.ip().to_string()
+ };
+ Self {
+ transports: transports.clone(),
+ pt_type: socks_type.to_string(),
+ path_to_binary: None,
+ options: None,
+ ip: Some(ip),
+ port: Some(addr.port()),
+ }
+ }
+}
+
+impl From<&PluggableTransport> for ExpandedPluggableTransport {
+ fn from(value: &PluggableTransport) -> Self {
+ match &value.plugin {
+ ClientTransportPlugin::Executable { path, options } => {
+ ExpandedPluggableTransport::new_exec(&value.transports, path, options)
+ }
+ ClientTransportPlugin::Socks4(addr) => {
+ ExpandedPluggableTransport::new_socks(&value.transports, "socks4", addr)
+ }
+ ClientTransportPlugin::Socks5(addr) => {
+ ExpandedPluggableTransport::new_socks(&value.transports, "socks5", addr)
+ }
+ }
+ }
+}
=====================================
toolkit/components/tor-launcher/TorControlPort.sys.mjs
=====================================
@@ -396,15 +396,6 @@ export class TorController {
* @returns {TorController}
*/
static fromIpcFile(ipcFile) {
- // Notice: this preference is temporary, only for testing!
- // Do not rely on it to exist forever.
- if (
- Services.tor &&
- Services.prefs.getBoolPref("browser.tor_provider.oxidize", false)
- ) {
- return new TorController(Services.tor.createControlPortIPC(ipcFile));
- }
-
return new TorController(AsyncSocket.fromIpcFile(ipcFile));
}
@@ -416,15 +407,6 @@ export class TorController {
* @returns {TorController}
*/
static fromSocketAddress(host, port) {
- // Notice: this preference is temporary, only for testing!
- // Do not rely on it to exist forever.
- if (
- Services.tor &&
- Services.prefs.getBoolPref("browser.tor_provider.oxidize", false)
- ) {
- return new TorController(Services.tor.createControlPort(host, port));
- }
-
return new TorController(AsyncSocket.fromSocketAddress(host, port));
}
@@ -558,21 +540,6 @@ export class TorController {
* closed).
*/
async #startMessagePump() {
- // Rust control port
- if (this.#socket.start) {
- const self = this;
- const receiver = {
- onAsyncMessage(message) {
- self.#handleNotification(message);
- },
- onClosed() {
- self.#eventHandler?.onClosed();
- },
- };
- this.#socket.start(receiver);
- return;
- }
-
try {
// This while is inside the try block because it is very likely that it
// will be broken by a NS_BASE_STREAM_CLOSED exception, rather than by its
@@ -631,21 +598,6 @@ export class TorController {
throw new Error("ControlSocket not open");
}
- // Rust control port
- if (this.#socket.sendCommand) {
- const { promise, resolve, reject } = Promise.withResolvers();
- const handler = {
- onMessage(message) {
- resolve(message);
- },
- onError(error) {
- reject(new Error(error));
- },
- };
- this.#socket.sendCommand(commandString, handler);
- return promise;
- }
-
// this promise is resolved either in #handleCommandReply, or in
// #startMessagePump (on stream error)
return new Promise((resolve, reject) => {
=====================================
toolkit/components/tor-launcher/TorProvider.sys.mjs
=====================================
@@ -12,6 +12,8 @@ import { TorProviderTopics } from "moz-src:///toolkit/components/tor-launcher/To
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
FileUtils: "resource://gre/modules/FileUtils.sys.mjs",
+ OxidizedControlPort:
+ "moz-src:///toolkit/components/tor-integration/OxidizedControlPort.sys.mjs",
TorController:
"moz-src:///toolkit/components/tor-launcher/TorControlPort.sys.mjs",
TorProcess: "moz-src:///toolkit/components/tor-launcher/TorProcess.sys.mjs",
@@ -799,12 +801,18 @@ export class TorProvider extends TorProviderBase {
*/
async #openControlPort() {
let controlPort;
+ const controllerClass = Services.prefs.getBoolPref(
+ "browser.tor_provider.oxidize",
+ false
+ )
+ ? lazy.OxidizedControlPort
+ : lazy.TorController;
if (this.#controlPortSettings.ipcFile) {
- controlPort = lazy.TorController.fromIpcFile(
+ controlPort = controllerClass.fromIpcFile(
this.#controlPortSettings.ipcFile
);
} else {
- controlPort = lazy.TorController.fromSocketAddress(
+ controlPort = controllerClass.fromSocketAddress(
this.#controlPortSettings.host,
this.#controlPortSettings.port
);
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/2da1ba…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/2da1ba…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser][tor-browser-156.0a1-17.0-2] fixup! TB 44806: Implement the tor integration in Rust.
by Pier Angelo Vendrame (@pierov) 17 Nov '26
by Pier Angelo Vendrame (@pierov) 17 Nov '26
17 Nov '26
Pier Angelo Vendrame pushed to branch tor-browser-156.0a1-17.0-2 at The Tor Project / Applications / Tor Browser
Commits:
2da1bad7 by Elena at 2026-11-17T10:56:27+01:00
fixup! TB 44806: Implement the tor integration in Rust.
TB 44930: Implement the commands on the Rust control port
Implementing async notification parsing.
- - - - -
3 changed files:
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
- toolkit/components/tor-integration/tor_provider/src/ctor/controller/mod.rs
- + toolkit/components/tor-integration/tor_provider/src/ctor/controller/notification.rs
Changes:
=====================================
toolkit/components/tor-integration/tor_provider/src/ctor/controller/controller.rs
=====================================
@@ -4,12 +4,13 @@
// copied, modified, or distributed except according to those terms.
use bytes::Bytes;
-use std::net::IpAddr;
+use std::{net::IpAddr, rc::Rc};
use tinystr::TinyAsciiStr;
use super::{
commands::{self, Command},
error::ControllerError,
+ notification::{AsyncNotification, NotificationListener},
types::*,
};
use crate::ctor::{
@@ -72,6 +73,21 @@ impl<CP: ControlPortInterface> TorController<CP> {
);
}
+ pub fn set_notification_listener(&self, listener: Option<Rc<dyn NotificationListener>>) {
+ self.0.set_async_handler(listener.as_ref().map(|l| {
+ let l = l.clone();
+ Box::new(move |notification| {
+ if let Some(notification) = AsyncNotification::parse(notification) {
+ notification.dispatch(l.as_ref());
+ }
+ }) as Box<dyn Fn(Reply)>
+ }));
+ }
+
+ pub fn set_close_handler(&self, cb: Box<dyn FnOnce()>) {
+ self.0.set_close_handler(cb);
+ }
+
// Setup
/// Authenticate to the tor daemon.
@@ -216,9 +232,4 @@ impl<CP: ControlPortInterface> TorController<CP> {
pub fn set_async_handler(&self, cb: Option<Box<dyn Fn(Reply)>>) {
self.0.set_async_handler(cb);
}
-
- #[inline]
- pub fn set_close_handler(&self, cb: Box<dyn FnOnce()>) {
- self.0.set_close_handler(cb);
- }
}
=====================================
toolkit/components/tor-integration/tor_provider/src/ctor/controller/mod.rs
=====================================
@@ -6,9 +6,11 @@
mod commands;
mod controller;
mod error;
+mod notification;
mod parsers;
mod types;
pub use controller::*;
pub use error::*;
+pub use notification::NotificationListener;
pub use types::*;
=====================================
toolkit/components/tor-integration/tor_provider/src/ctor/controller/notification.rs
=====================================
@@ -0,0 +1,490 @@
+// Licensed under the Apache License, Version 2.0,
+// <http://apache.org/licenses/LICENSE-2.0> or the MIT license
+// <http://opensource.org/licenses/MIT>, at your option. This file may not be
+// copied, modified, or distributed except according to those terms.
+
+use bytes::{Bytes, BytesMut};
+
+use super::{
+ parsers::{parse_bootstrap_status, parse_circuit_built, parse_stream_sentconnect},
+ types::{BootstrapStatus, Circuit, CircuitID, Stream},
+};
+use crate::ctor::reply_parser::{DetailReplyLine, Reply};
+
+pub trait NotificationListener {
+ fn log_message(&self, severity: String, message: Bytes);
+ fn bootstrap_status(&self, status: BootstrapStatus);
+ fn circuit_built(&self, circuit: Circuit);
+ fn circuit_closed(&self, id: CircuitID);
+ fn stream_sent_connect(&self, stream: Stream);
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AsyncNotification {
+ LogMessage { severity: String, message: Bytes },
+ BootstrapStatus(BootstrapStatus),
+ CircuitBuilt(Circuit),
+ CircuitClosed(CircuitID),
+ StreamSentConnect(Stream),
+}
+
+impl AsyncNotification {
+ /// Try to parse a reply as an async notification.
+ /// Async notifications do not have an error handler, so any parsing error
+ /// will cause the reply to be just dropped silently.
+ pub fn parse(reply: Reply) -> Option<Self> {
+ if !reply.is_async() {
+ return None;
+ }
+ let first_line = match reply.details().first() {
+ Some(DetailReplyLine::MidReplyLine { line, .. }) => line,
+ Some(DetailReplyLine::DataReplyLine { lines, .. }) => {
+ if lines.is_empty() {
+ debug_assert!(false, "DataReplyLine must always have at least one line.");
+ return None;
+ }
+ &lines[0]
+ }
+ None => &reply.end_line().line,
+ };
+ let (keyword, data) = get_type(first_line)?;
+ match keyword.as_str() {
+ "STATUS_CLIENT" => Self::parse_bootstrap_status(data),
+ "CIRC" => Self::parse_circuit_event(data),
+ "STREAM" => Self::parse_stream_event(data),
+ "DEBUG" | "INFO" | "NOTICE" | "WARN" | "ERR" => Self::parse_log_message(keyword, reply),
+ _ => {
+ let mut buf = Vec::new();
+ let _ = reply.write_to(&mut buf);
+ log::debug!("Unknown notification: {}", String::from_utf8_lossy(&buf));
+ None
+ }
+ }
+ }
+
+ /// Try to parse a `STATUS_CLIENT ... BOOTSTRAP` event.
+ /// We will silently drop any other kind of STATUS_CLIENT event.
+ fn parse_bootstrap_status(data: &[u8]) -> Option<Self> {
+ parse_bootstrap_status(data)
+ .map(|status| AsyncNotification::BootstrapStatus(status))
+ .ok()
+ }
+
+ /// Try to parse CIRC BUILT/CLOSED events.
+ fn parse_circuit_event(data: &[u8]) -> Option<Self> {
+ let (status, id) = circuit_stream_status(data)?;
+ match status.as_str() {
+ "BUILT" => parse_circuit_built(data)
+ .ok()
+ .and_then(|c| c)
+ .map(AsyncNotification::CircuitBuilt),
+ "CLOSED" => Some(AsyncNotification::CircuitClosed(id)),
+ _ => None,
+ }
+ }
+
+ /// Try to parse a STREAM SENTCONNECT event.
+ fn parse_stream_event(data: &[u8]) -> Option<Self> {
+ let (status, _) = circuit_stream_status(data)?;
+ match status.as_str() {
+ "SENTCONNECT" => parse_stream_sentconnect(data)
+ .ok()
+ .and_then(|stream| stream.map(|s| AsyncNotification::StreamSentConnect(s))),
+ _ => None,
+ }
+ }
+
+ /// Try to parse a log message.
+ fn parse_log_message(severity: String, reply: Reply) -> Option<Self> {
+ match reply.details().first() {
+ Some(DetailReplyLine::DataReplyLine { lines, .. }) => {
+ if lines.len() == 1 {
+ None
+ } else {
+ // No need to join the last line, as it is supposed to be a
+ // `650 OK`.
+ Some(AsyncNotification::LogMessage {
+ severity,
+ message: join_lines(&lines[1..]),
+ })
+ }
+ }
+ None if !reply.has_details() => {
+ if reply.end_line().line.len() <= (severity.len() + 1) {
+ None
+ } else {
+ let message = reply.end_line().line.slice(severity.len() + 1..);
+ Some(AsyncNotification::LogMessage { severity, message })
+ }
+ }
+ _ => {
+ // The logs use data lines, as per the specs.
+ None
+ }
+ }
+ }
+
+ /// Consume self by sending it to a NotificationListener.
+ pub fn dispatch(self, listener: &dyn NotificationListener) {
+ match self {
+ AsyncNotification::LogMessage { severity, message } => {
+ listener.log_message(severity, message)
+ }
+ AsyncNotification::BootstrapStatus(status) => listener.bootstrap_status(status),
+ AsyncNotification::CircuitBuilt(circuit) => listener.circuit_built(circuit),
+ AsyncNotification::CircuitClosed(id) => listener.circuit_closed(id),
+ AsyncNotification::StreamSentConnect(stream) => listener.stream_sent_connect(stream),
+ }
+ }
+}
+
+/// Split a reply line into keyword and data.
+fn get_type<'a>(data: &'a [u8]) -> Option<(String, &'a [u8])> {
+ if data.is_empty() {
+ return None;
+ }
+ let mut parts = data.splitn(2, |b| *b == b' ');
+ let keyword = make_keyword(parts.next())?;
+ let data = parts.next().unwrap_or(&[]);
+ Some((keyword, data))
+}
+
+/// Validate a CIRC/STREAM event.
+/// We handle them together as they have the same structure:
+/// `<id> <event-type> ...` (with compatible formats).
+///
+/// Notice that we have both a CircuitID and a StreamID type, but for stream we
+/// drop the ID, so as a matter of fact we only use the CircuitID variant.
+/// Therefore, we thought it was not worth to make this a generic function.
+fn circuit_stream_status(data: &[u8]) -> Option<(String, CircuitID)> {
+ let mut parts = data.split(|b| *b == b' ');
+ let id = parts.next().and_then(|t| CircuitID::new(t));
+ make_keyword(parts.next()).zip(id)
+}
+
+/// Make a keyword (uppercase string).
+/// We use only ASCII keywords for now, but this function accepts anything as
+/// long as it is valid UTF-8 (including ASCII).
+///
+/// Notice that we need to return an owned string as we are doing the case
+/// conversion.
+fn make_keyword(keyword: Option<&[u8]>) -> Option<String> {
+ // Our keywords are ASCII, so ignore this error silently, we are not
+ // interested in those anyway...
+ keyword.and_then(|kw| String::from_utf8(kw.to_ascii_uppercase()).ok())
+}
+
+/// Join log message lines.
+fn join_lines(lines: &[Bytes]) -> Bytes {
+ let mut result = BytesMut::new();
+ for (i, line) in lines.iter().enumerate() {
+ result.extend_from_slice(line);
+ if i < lines.len() - 1 {
+ result.extend_from_slice(b"\r\n");
+ }
+ }
+ result.freeze()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ctor::reply_parser::make_reply;
+
+ #[test]
+ fn test_make_keyword() {
+ assert_eq!(make_keyword(Some(&b"TEST"[..])).unwrap(), "TEST");
+ assert_eq!(make_keyword(Some(&b"test"[..])).unwrap(), "TEST");
+ assert_eq!(make_keyword(Some(&b"TesT"[..])).unwrap(), "TEST");
+ assert_eq!(make_keyword(Some(&b"Te_sT"[..])).unwrap(), "TE_ST");
+
+ assert!(make_keyword(None).is_none());
+
+ let invalid_utf8 = [0xFF, 0xFE];
+ assert!(make_keyword(Some(&invalid_utf8)).is_none());
+ }
+
+ #[test]
+ fn test_get_type() {
+ {
+ let (keyword, data) = get_type(b"STATUS_CLIENT BOOTSTRAP PROGRESS=50").unwrap();
+ assert_eq!(keyword, "STATUS_CLIENT");
+ assert_eq!(data, b"BOOTSTRAP PROGRESS=50");
+ }
+ {
+ let (keyword, data) = get_type(b"CIRC").unwrap();
+ assert_eq!(keyword, "CIRC");
+ assert_eq!(data, &b""[..]);
+ }
+ {
+ let (keyword, _) = get_type(b"debug message").unwrap();
+ assert_eq!(keyword, "DEBUG");
+ }
+ {
+ let (keyword, _) = get_type(b"StAtUs_ClIeNt data").unwrap();
+ assert_eq!(keyword, "STATUS_CLIENT");
+ }
+ {
+ let (keyword, data) = get_type(b"CIRC id BUILT").unwrap();
+ assert_eq!(keyword, "CIRC");
+ assert_eq!(data, b" id BUILT"); // Splits on first space only
+ }
+ assert!(get_type(b"").is_none());
+ }
+
+ #[test]
+ fn test_circuit_stream_status() {
+ {
+ let (status, id) = circuit_stream_status(b"123 BUILT").unwrap();
+ assert_eq!(status, "BUILT");
+ assert_eq!(id, CircuitID::new(b"123").unwrap());
+ }
+ {
+ let (status, id) = circuit_stream_status(b"456 CLOSED").unwrap();
+ assert_eq!(status, "CLOSED");
+ assert_eq!(id, CircuitID::new(b"456").unwrap());
+ }
+ {
+ let (status, _) = circuit_stream_status(b"1 built").unwrap();
+ assert_eq!(status, "BUILT");
+ }
+ {
+ let (status, _) = circuit_stream_status(b"1 bUIlt").unwrap();
+ assert_eq!(status, "BUILT");
+ }
+
+ // Missing ID
+ assert!(circuit_stream_status(b"BUILT").is_none());
+ // Missing status
+ assert!(circuit_stream_status(b"123").is_none());
+ // Invalid ID
+ assert!(circuit_stream_status(b"ab+c BUILT").is_none());
+ // Empty
+ assert!(circuit_stream_status(b"").is_none());
+ }
+
+ #[test]
+ fn test_join_lines() {
+ {
+ let lines = vec![Bytes::from_static(b"single line")];
+ let result = join_lines(&lines);
+ assert_eq!(result, "single line");
+ }
+ {
+ let lines = vec![
+ Bytes::from_static(b"aaaaaaaaaaa 1234"),
+ Bytes::from_static(b"b b"),
+ Bytes::from_static(b"cccc cc"),
+ ];
+ let result = join_lines(&lines);
+ assert_eq!(result, "aaaaaaaaaaa 1234\r\nb b\r\ncccc cc");
+ }
+ {
+ let lines: Vec<Bytes> = vec![];
+ let result = join_lines(&lines);
+ assert_eq!(result, "");
+ }
+ {
+ let lines = vec![
+ Bytes::from_static(b"second line is"),
+ Bytes::from_static(b""),
+ Bytes::from_static(b"empty"),
+ ];
+ let result = join_lines(&lines);
+ assert_eq!(result, "second line is\r\n\r\nempty");
+ }
+ }
+
+ #[test]
+ fn debug_log() {
+ {
+ let reply = make_reply(b"650 DEBUG Some debug message\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "DEBUG");
+ assert_eq!(message, "Some debug message");
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+ {
+ let reply = make_reply(b"650+DEBUG\r\nSome debug message\r\n.\r\n650 OK\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "DEBUG");
+ assert_eq!(message, "Some debug message");
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+ {
+ let reply = make_reply(b"650-DEBUG Some debug message\r\n650 OK\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ }
+
+ #[test]
+ fn info_log() {
+ let reply = make_reply(b"650 INFO Connection established\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "INFO");
+ assert_eq!(message, "Connection established");
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+
+ #[test]
+ fn warn_log() {
+ let reply = make_reply(b"650 WARN Something suspicious happened\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "WARN");
+ assert_eq!(message, "Something suspicious happened");
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+
+ #[test]
+ fn err_log() {
+ let reply = make_reply(b"650 ERR Critical error occurred\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "ERR");
+ assert_eq!(message, "Critical error occurred")
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+
+ #[test]
+ fn notice_log() {
+ let reply = make_reply(b"650 NOTICE Important notice\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::LogMessage { severity, message } => {
+ assert_eq!(severity, "NOTICE");
+ assert_eq!(message, "Important notice");
+ }
+ _ => unreachable!("Expected LogMessage"),
+ }
+ }
+
+ #[test]
+ fn empty_log() {
+ assert!(AsyncNotification::parse(make_reply(b"650 NOTICE\r\n")).is_none());
+ assert!(AsyncNotification::parse(make_reply(b"650 NOTICE \r\n")).is_none());
+ // At the moment, we do not trim spaces.
+ assert!(AsyncNotification::parse(make_reply(b"650 NOTICE \r\n")).is_some());
+ assert!(AsyncNotification::parse(make_reply(b"650+NOTICE\r\n.\r\n650 OK\r\n")).is_none());
+ assert_eq!(
+ AsyncNotification::parse(make_reply(b"650+NOTICE\r\n\r\n.\r\n650 OK\r\n")).unwrap(),
+ AsyncNotification::LogMessage {
+ severity: String::from("NOTICE"),
+ message: Bytes::new(),
+ }
+ );
+ }
+
+ #[test]
+ fn bootstrap_status() {
+ let reply = make_reply(b"650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=10 TAG=conn_done SUMMARY=\"Connected to a relay\"\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::BootstrapStatus(_) => {
+ // Actual parsing delegated to parse_bootstrap_status
+ }
+ _ => unreachable!("Expected BootstrapStatus"),
+ }
+ }
+
+ #[test]
+ fn circuit_built() {
+ let reply = make_reply(b"650 CIRC 42 BUILT $1111111111111111111111111111111111111111\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::CircuitBuilt(_) => {}
+ _ => unreachable!("Expected CircuitBuilt"),
+ }
+ }
+
+ #[test]
+ fn circuit_closed() {
+ {
+ let reply = make_reply(b"650 CIRC 42 CLOSED\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::CircuitClosed(id) => {
+ assert_eq!(id, CircuitID::new(b"42").unwrap());
+ }
+ _ => unreachable!("Expected CircuitClosed"),
+ }
+ }
+ {
+ let reply = make_reply(b"650-CIRC 42 CLOSED\r\n650 Extended data\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::CircuitClosed(id) => {
+ assert_eq!(id, CircuitID::new(b"42").unwrap());
+ }
+ _ => unreachable!("Expected CircuitClosed"),
+ }
+ }
+ }
+
+ #[test]
+ fn stream_sentconnect() {
+ let reply = make_reply(b"650 STREAM 1 SENTCONNECT 1 1.2.3.4:443\r\n");
+ let notification = AsyncNotification::parse(reply).unwrap();
+ match notification {
+ AsyncNotification::StreamSentConnect(_) => {}
+ _ => unreachable!("Expected StreamSentConnect"),
+ }
+ }
+
+ #[test]
+ fn parse_errors() {
+ {
+ let reply = make_reply(b"650 UNKNOWN_EVENT data\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ {
+ // Empty keyword
+ let reply = make_reply(b"650 \r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ {
+ let reply = make_reply(b"250 Not an async reply\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ // Unkown statuses
+ {
+ let reply = make_reply(b"650 CIRC 42 EXTENDED\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ {
+ let reply = make_reply(b"650 STREAM 1 ATTACHED\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ // Invalid IDs
+ {
+ let reply = make_reply(b"650 CIRC a_b_c BUILT\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ {
+ let reply = make_reply(b"650 STREAM 123 SENTCONNECT a_b_c 1.2.3.4:443\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ {
+ let reply = make_reply(b"650 STREAM 12_3 SENTCONNECT abc 1.2.3.4:443\r\n");
+ assert!(AsyncNotification::parse(reply).is_none());
+ }
+ }
+}
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/2da1bad…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/commit/2da1bad…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/mullvad-browser-update-responses][main] 5 commits: release: new version, 16.0.2 (linux-aarch64)
by morgan (@morgan) 16 Nov '26
by morgan (@morgan) 16 Nov '26
16 Nov '26
morgan pushed to branch main at The Tor Project / Applications / mullvad-browser-update-responses
Commits:
d83e06e7 by Morgan at 2026-11-16T21:06:42+00:00
release: new version, 16.0.2 (linux-aarch64)
- - - - -
ce5e5c2f by Morgan at 2026-11-16T21:06:42+00:00
release: new version, 16.0.2 (linux-x86_64)
- - - - -
da36e835 by Morgan at 2026-11-16T21:06:42+00:00
release: new version, 16.0.2 (macos)
- - - - -
cc1318df by Morgan at 2026-11-16T21:06:42+00:00
release: new version, 16.0.2 (windows-x86_64)
- - - - -
5f508561 by Morgan at 2026-11-16T21:06:42+00:00
release: new version, 16.0.2
- - - - -
38 changed files:
- update_1/release/download-linux-aarch64.json
- update_1/release/download-linux-x86_64.json
- update_1/release/download-macos.json
- update_1/release/download-windows-x86_64.json
- update_1/release/downloads.json
- update_1/release/linux-aarch64/.htaccess
- − update_1/release/linux-aarch64/update-16.0-16.0.1-linux-aarch64.xml
- + update_1/release/linux-aarch64/update-16.0-16.0.2-linux-aarch64.xml
- + update_1/release/linux-aarch64/update-16.0.1-16.0.2-linux-aarch64.xml
- − update_1/release/linux-aarch64/update-16.0.1-linux-aarch64.xml
- + update_1/release/linux-aarch64/update-16.0.2-linux-aarch64.xml
- update_1/release/linux-x86_64/.htaccess
- − update_1/release/linux-x86_64/update-15.0.25-16.0.1-linux-x86_64.xml
- − update_1/release/linux-x86_64/update-15.0.26-16.0.1-linux-x86_64.xml
- + update_1/release/linux-x86_64/update-15.0.26-16.0.2-linux-x86_64.xml
- − update_1/release/linux-x86_64/update-16.0-16.0.1-linux-x86_64.xml
- + update_1/release/linux-x86_64/update-16.0-16.0.2-linux-x86_64.xml
- + update_1/release/linux-x86_64/update-16.0.1-16.0.2-linux-x86_64.xml
- − update_1/release/linux-x86_64/update-16.0.1-linux-x86_64.xml
- + update_1/release/linux-x86_64/update-16.0.2-linux-x86_64.xml
- update_1/release/macos/.htaccess
- − update_1/release/macos/update-15.0.25-16.0.1-macos.xml
- − update_1/release/macos/update-15.0.26-16.0.1-macos.xml
- + update_1/release/macos/update-15.0.26-16.0.2-macos.xml
- − update_1/release/macos/update-16.0-16.0.1-macos.xml
- + update_1/release/macos/update-16.0-16.0.2-macos.xml
- + update_1/release/macos/update-16.0.1-16.0.2-macos.xml
- − update_1/release/macos/update-16.0.1-macos.xml
- + update_1/release/macos/update-16.0.2-macos.xml
- update_1/release/windows-x86_64/.htaccess
- − update_1/release/windows-x86_64/update-15.0.25-16.0.1-windows-x86_64.xml
- − update_1/release/windows-x86_64/update-15.0.26-16.0.1-windows-x86_64.xml
- + update_1/release/windows-x86_64/update-15.0.26-16.0.2-windows-x86_64.xml
- − update_1/release/windows-x86_64/update-16.0-16.0.1-windows-x86_64.xml
- + update_1/release/windows-x86_64/update-16.0-16.0.2-windows-x86_64.xml
- + update_1/release/windows-x86_64/update-16.0.1-16.0.2-windows-x86_64.xml
- − update_1/release/windows-x86_64/update-16.0.1-windows-x86_64.xml
- + update_1/release/windows-x86_64/update-16.0.2-windows-x86_64.xml
The diff was not included because it is too large.
View it on GitLab: https://gitlab.torproject.org/tpo/applications/mullvad-browser-update-respo…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/mullvad-browser-update-respo…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser] Pushed new branch tor-browser-158.0a1-17.0-1
by brizental (@brizental) 16 Nov '26
by brizental (@brizental) 16 Nov '26
16 Nov '26
brizental pushed new branch tor-browser-158.0a1-17.0-1 at The Tor Project / Applications / Tor Browser
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/tree/tor-brows…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser-build][maint-16.0] Bug 41910: Update version in projects/mmdebstrap-image for apt update
by morgan (@morgan) 16 Nov '26
by morgan (@morgan) 16 Nov '26
16 Nov '26
morgan pushed to branch maint-16.0 at The Tor Project / Applications / tor-browser-build
Commits:
8727c326 by Nicolas Vigier at 2026-11-16T17:38:24+00:00
Bug 41910: Update version in projects/mmdebstrap-image for apt update
This change will cause all containers to be rebuilt, except for
stretch-based containers.
To save space `make clean` can be run to remove all unused files from
`out/`. Alternatively it's possible to remove the directories
`out/container-image` and `out/mmdebstrap-image` before starting a new
build.
- - - - -
1 changed file:
- projects/mmdebstrap-image/config
Changes:
=====================================
projects/mmdebstrap-image/config
=====================================
@@ -1,6 +1,6 @@
# vim: filetype=yaml sw=2
filename: 'container-image_[% c("var/container/suite") %]-[% c("var/container/arch") %]-[% c("version") %].tar.[% c("compress_tar") %]'
-version: 1
+version: 2
pkg_type: build
compress_tar: zst
container:
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/8…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/commit/8…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser-build] Pushed new tag mb-16.0.2-build1
by morgan (@morgan) 16 Nov '26
by morgan (@morgan) 16 Nov '26
16 Nov '26
morgan pushed new tag mb-16.0.2-build1 at The Tor Project / Applications / tor-browser-build
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/tree/mb-…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0
[Git][tpo/applications/tor-browser-build][maint-16.0] 2 commits: Revert "Bug 41910: Update version in projects/mmdebstrap-image for apt update"
by morgan (@morgan) 16 Nov '26
by morgan (@morgan) 16 Nov '26
16 Nov '26
morgan pushed to branch maint-16.0 at The Tor Project / Applications / tor-browser-build
Commits:
8c17ab6b by Morgan at 2026-11-16T15:37:00+00:00
Revert "Bug 41910: Update version in projects/mmdebstrap-image for apt update"
This reverts commit 614193ca4e6f6f6a5a175aac6511e6dffc5799c3.
Temporary revert this commit to avoid a full-rebuild for Mullvad Browser 16.0.2
- - - - -
a6011dc9 by Morgan at 2026-11-16T17:36:14+00:00
Bug 41926: Prepare Mullvad Browser 16.0.2
- - - - -
6 changed files:
- projects/browser/Bundle-Data/Docs-MB/ChangeLog.txt
- projects/browser/config
- projects/firefox/config
- projects/mmdebstrap-image/config
- projects/translation/config
- rbm.conf
Changes:
=====================================
projects/browser/Bundle-Data/Docs-MB/ChangeLog.txt
=====================================
@@ -1,3 +1,10 @@
+Mullvad Browser 16.0.2 - November 16 2026
+ * All Platforms
+ * Updated Mullvad Browser Extension to 0.9.11
+ * Updated uBlock Origin to 1.76.4
+ * Bug 593: Re-Add Cloudflare as available DoH provider in about:settings [mullvad-browser]
+ * Bug 594: Update relevant neterror page when Quad9 DoH resolution fails [mullvad-browser]
+
Mullvad Browser 16.0.1 - November 10 2026
* All Platforms
* Updated Firefox to 153.7.0esr
=====================================
projects/browser/config
=====================================
@@ -90,13 +90,13 @@ input_files:
- URL: https://dist.torproject.org/torbrowser/noscript/noscript-13.6.38.1984.xpi
name: noscript
sha256sum: bbd764d65017d88df18ea65eb9981c6c97b79a39df7378e9e01fcfd71a564ab6
- - URL: https://addons.mozilla.org/firefox/downloads/file/5225273/ublock_origin-1.7…
+ - URL: https://addons.mozilla.org/firefox/downloads/file/5257481/ublock_origin-1.7…
name: ublock-origin
- sha256sum: 6f20ff6749193599548770539103069c20948dfcd3e61c3089a67da7bfc3be39
+ sha256sum: 66d0e3f21ce3b32b1bc0a9399b93cb2c9aa598ef18805d92118c76f66e266c1e
enable: '[% c("var/mullvad-browser") %]'
- - URL: https://cdn.mullvad.net/browser-extension/0.9.10/mullvad-browser-extension-…
+ - URL: https://cdn.mullvad.net/browser-extension/0.9.11/mullvad-browser-extension-…
name: mullvad-extension
- sha256sum: d8adfd5d83c67d8d50d9466c6564755de79a8a0825f5c67a151919506d411b30
+ sha256sum: 462cb43b7e87bbae6ea377538c96866dccc193d657f9f430062fdbbab87881fd
enable: '[% c("var/mullvad-browser") %]'
- project: manual
name: manual
=====================================
projects/firefox/config
=====================================
@@ -23,7 +23,7 @@ var:
browser_series: '16.0'
browser_rebase: 1
browser_branch: '[% c("var/browser_series") %]-[% c("var/browser_rebase") %]'
- browser_build: 2
+ browser_build: 3
upstream_firefox_commit: FIREFOX_NIGHTLY_153_END
copyright_year: '[% exec("git show -s --format=%ci " _ c("git_hash") _ "^{commit}", { exec_noco => 1 }).remove("-.*") %]'
nightly_updates_publish_dir: '[% c("var/nightly_updates_publish_dir_prefix") %]nightly-[% c("var/osname") %]'
=====================================
projects/mmdebstrap-image/config
=====================================
@@ -1,6 +1,6 @@
# vim: filetype=yaml sw=2
filename: 'container-image_[% c("var/container/suite") %]-[% c("var/container/arch") %]-[% c("version") %].tar.[% c("compress_tar") %]'
-version: 2
+version: 1
pkg_type: build
compress_tar: zst
container:
=====================================
projects/translation/config
=====================================
@@ -12,7 +12,7 @@ compress_tar: 'gz'
steps:
base-browser:
base-browser: '[% INCLUDE build %]'
- git_hash: 9166a373a2edb5b54c4b6829e87348ebcd724110
+ git_hash: ec65d92c2ee636e7e2d7b93018bf1209a69775fc
targets:
nightly:
git_hash: 'base-browser'
=====================================
rbm.conf
=====================================
@@ -85,7 +85,7 @@ var:
torbrowser_build: 'build1'
# This should be the date of when the build is started. For the build
# to be reproducible, browser_release_date should always be in the past.
- browser_release_date: '2026/11/10 15:00:00'
+ browser_release_date: '2026/11/16 15:56:08'
browser_release_date_timestamp: '[% USE date; date.format(c("var/browser_release_date"), "%s") %]'
browser_default_channel: release
browser_platforms:
@@ -131,9 +131,9 @@ var:
updater_enabled: 1
build_mar: 1
torbrowser_incremental_from:
+ - 16.0.1
- '16.0'
- 15.0.26
- - 15.0.25
mar_channel_id: '[% c("var/projectname") %]-torproject-[% c("var/channel") %]'
# By default, we sort the list of installed packages. This allows sharing
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/compare/…
--
View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser-build/-/compare/…
You're receiving this email because of your account on gitlab.torproject.org. Manage all notifications: https://gitlab.torproject.org/-/profile/notifications | Help: https://gitlab.torproject.org/help
1
0