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/2da1bad... -- View it on GitLab: https://gitlab.torproject.org/tpo/applications/tor-browser/-/compare/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