Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion browser_patches/firefox/juggler/NetworkObserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ class NetworkRequest {
constructor(networkObserver, httpChannel, redirectedFrom) {
this._networkObserver = networkObserver;
this.httpChannel = httpChannel;
this._requestHeaders = undefined;

const loadInfo = this.httpChannel.loadInfo;
const browsingContext = loadInfo?.frameBrowsingContext
Expand Down Expand Up @@ -232,6 +233,8 @@ class NetworkRequest {
// An internal redirect does not necessarily have the same channelId,
// but inherits notificationCallbacks and the listener,
// and should be used instead of an old channel.
// Preserve effective headers before interception replaces the channel.
this._requestHeaders ||= requestHeaders(this.httpChannel);
this._networkObserver._channelToRequest.delete(this.httpChannel);
this.httpChannel = newChannel;
this._networkObserver._channelToRequest.set(this.httpChannel, this);
Expand Down Expand Up @@ -512,7 +515,7 @@ class NetworkRequest {
requestId: this.requestId,
redirectedFrom: this.redirectedFromId,
postData: readRequestPostData(this.httpChannel),
headers: requestHeaders(this.httpChannel),
headers: this._requestHeaders || requestHeaders(this.httpChannel),
method: this.httpChannel.requestMethod,
navigationId: this.navigationId,
cause: causeTypeToString(causeType),
Expand Down
211 changes: 205 additions & 6 deletions browser_patches/firefox/juggler/TargetRegistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {Helper} = ChromeUtils.importESModule('chrome://juggler/content/Helper.js'
const {Preferences} = ChromeUtils.importESModule("resource://gre/modules/Preferences.sys.mjs");
const {ContextualIdentityService} = ChromeUtils.importESModule("moz-src:///toolkit/components/contextualidentity/ContextualIdentityService.sys.mjs");
const {NetUtil} = ChromeUtils.importESModule('resource://gre/modules/NetUtil.sys.mjs');
const {Downloads} = ChromeUtils.importESModule('resource://gre/modules/Downloads.sys.mjs');
const {AppConstants} = ChromeUtils.importESModule("resource://gre/modules/AppConstants.sys.mjs");

const Cr = Components.results;
Expand All @@ -28,11 +29,22 @@ let globalNewPageChain = Promise.resolve();

let globalContextCloseCounter = 0;

const HELPER_APP_DIALOG_CONTRACT_ID = '@mozilla.org/helperapplauncherdialog;1';

class DownloadInterceptor {
constructor(registry) {
this._registry = registry
this._handlerToUuid = new Map();
this._uuidToHandler = new Map();
this._registered = false;
}

register() {
if (this._registered)
return;
this._registered = true;
const extHelperAppSvc = Cc["@mozilla.org/uriloader/external-helper-app-service;1"].getService(Ci.nsIExternalHelperAppService);
extHelperAppSvc.setDownloadInterceptor(this);
}

//
Expand All @@ -48,7 +60,7 @@ class DownloadInterceptor {

const browserContext = pageTarget.browserContext();
const options = browserContext.downloadOptions;
if (!options)
if (!options || !options.legacyInterceptor)
return false;

const uuid = helper.generateId();
Expand Down Expand Up @@ -105,6 +117,166 @@ class DownloadInterceptor {
}
}

// See also BiDi implementation at
// - remote/webdriver-bidi/HelperAppDialogHandler.sys.mjs
// - remote/shared/listeners/DownloadListener.sys.mjs
class DownloadManager {
constructor(registry) {
this._registry = registry;
this._pendingInfos = new Map(); // path -> info, until Download object is created
this._downloads = new Map(); // Download -> { info, finished, finishedPromise, finishedCallback }
this._uuidToDownload = new Map();
this._registeredPromise = null;
}

register() {
if (!this._registeredPromise)
this._registeredPromise = this._register();
return this._registeredPromise;
}

async _register() {
this._registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
this._originalCID = this._registrar.contractIDToCID(HELPER_APP_DIALOG_CONTRACT_ID);
this._cid = Services.uuid.generateUUID();
this._factory = {
createInstance: iid => this._createDialog().QueryInterface(iid),
QueryInterface: ChromeUtils.generateQI(['nsIFactory']),
};
this._registrar.registerFactory(this._cid, 'Juggler helper app dialog', HELPER_APP_DIALOG_CONTRACT_ID, this._factory);
// Closing the last window or quitting with downloads in progress shows a synchronous
// "Cancel all downloads?" prompt that blocks the main thread. Skip it and let the
// downloads be canceled instead, the same way RemoteAgent.sys.mjs does.
Services.obs.addObserver({
observe: subject => { subject.QueryInterface(Ci.nsISupportsPRBool).data = false; },
}, 'before-cancel-download-prompt');
const list = await Downloads.getList(Downloads.ALL);
list.addView({
onDownloadAdded: download => this._onDownloadAdded(list, download),
onDownloadChanged: download => this._onDownloadChanged(list, download),
});
}

_createOriginalDialog() {
this._registrar.registerFactory(this._originalCID, 'Original helper app dialog', HELPER_APP_DIALOG_CONTRACT_ID, null);
try {
return Cc[HELPER_APP_DIALOG_CONTRACT_ID].createInstance(Ci.nsIHelperAppLauncherDialog);
} finally {
this._registrar.registerFactory(this._cid, 'Juggler helper app dialog', HELPER_APP_DIALOG_CONTRACT_ID, null);
}
}

_pageTargetForLauncher(launcher) {
const browsingContext = launcher.browsingContextId ? BrowsingContext.get(launcher.browsingContextId) : null;
if (!browsingContext)
return undefined;
return this._registry._browserIdToTarget.get(browsingContext.top.browserId);
}

_createDialog() {
let original = null;
return {
QueryInterface: ChromeUtils.generateQI(['nsIHelperAppLauncherDialog']),

show: (launcher, context, reason) => {
const pageTarget = this._pageTargetForLauncher(launcher);
const options = pageTarget?.browserContext().downloadOptions;
if (!options || options.legacyInterceptor) {
original ||= this._createOriginalDialog();
original.show(launcher, context, reason);
return;
}
launcher.promptForSaveDestination();
},

promptForSaveToFileAsync: (launcher, context, defaultFileName, suggestedFileExtension, forcePrompt) => {
const pageTarget = this._pageTargetForLauncher(launcher);
const options = pageTarget?.browserContext().downloadOptions;
if (!options || options.legacyInterceptor) {
original ||= this._createOriginalDialog();
original.promptForSaveToFileAsync(launcher, context, defaultFileName, suggestedFileExtension, forcePrompt);
return;
}

const info = {
uuid: helper.generateId(),
browserContextId: pageTarget.browserContext().browserContextId,
pageTargetId: pageTarget.id(),
frameId: helper.browsingContextToFrameId(BrowsingContext.get(launcher.browsingContextId)),
url: launcher.source.spec,
suggestedFileName: launcher.suggestedFileName,
};
if (options.behavior !== 'saveToDisk') {
this._registry.emit(TargetRegistry.Events.DownloadCreated, info);
this._registry.emit(TargetRegistry.Events.DownloadFinished, { uuid: info.uuid, canceled: true });
launcher.saveDestinationAvailable(null);
return;
}

const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(options.downloadsDir);
file.append(info.uuid);
this._pendingInfos.set(file.path, info);
// Pretend that a dialog was shown to keep the downloads panel closed.
launcher.saveDestinationAvailable(file, true);
},
};
}

_onDownloadAdded(downloadList, download) {
const info = this._pendingInfos.get(download.target.path);
if (!info)
return;
this._pendingInfos.delete(download.target.path);
const state = { info, finished: false };
state.finishedPromise = new Promise(f => state.finishedCallback = f);
this._downloads.set(download, state);
this._uuidToDownload.set(info.uuid, download);
this._registry.emit(TargetRegistry.Events.DownloadCreated, info);
this._onDownloadChanged(downloadList, download);
}

async _onDownloadChanged(downloadList, download) {
const state = this._downloads.get(download);
if (!state || state.finished || !download.stopped)
return;
state.finished = true;
this._uuidToDownload.delete(state.info.uuid);

const downloadInfo = { uuid: state.info.uuid };
if (download.succeeded) {
await download.whenSucceeded();
} else if (download.canceled || !download.error || download.error.result === Cr.NS_BINDING_ABORTED) {
downloadInfo.canceled = true;
} else {
downloadInfo.error = ChromeUtils.getXPCOMErrorName(download.error.result) || download.error.message;
}
this._registry.emit(TargetRegistry.Events.DownloadFinished, downloadInfo);

this._downloads.delete(download);
downloadList.remove(download);
state.finishedCallback();
}

async cancelDownload(uuid) {
const download = this._uuidToDownload.get(uuid);
if (!download)
return;
await download.finalize(true);
}

async cancelDownloadsForContext(browserContext) {
const promises = [];
for (const [download, state] of this._downloads) {
if (state.finished || state.info.browserContextId !== browserContext.browserContextId)
continue;
download.finalize(true).catch(() => {});
promises.push(state.finishedPromise);
}
await Promise.all(promises);
}
}

const screencastService = Cc['@mozilla.org/juggler/screencast;1'].getService(Ci.nsIScreencastService);

const FILE_PICKER_CONTRACT_ID = '@mozilla.org/filepicker;1';
Expand Down Expand Up @@ -209,6 +381,8 @@ export class TargetRegistry {
this._proxiesWithClashingAuthCacheKeys = new Set();
this._browserProxy = null;
this._filePickerOverride = new FilePickerOverride(this);
this._downloadManager = new DownloadManager(this);
this._downloadInterceptor = new DownloadInterceptor(this);

// Cleanup containers from previous runs (if any)
for (const identity of ContextualIdentityService.getPublicIdentities()) {
Expand Down Expand Up @@ -314,10 +488,6 @@ export class TargetRegistry {
onTabCloseListener({ target: tab });
};

const extHelperAppSvc = Cc["@mozilla.org/uriloader/external-helper-app-service;1"].getService(Ci.nsIExternalHelperAppService);
this._downloadInterceptor = new DownloadInterceptor(this);
extHelperAppSvc.setDownloadInterceptor(this._downloadInterceptor);

Services.wm.addListener({ onOpenWindow, onCloseWindow });
for (const win of Services.wm.getEnumerator(null))
onOpenWindow(win);
Expand Down Expand Up @@ -382,7 +552,8 @@ export class TargetRegistry {
}

async cancelDownload(options) {
this._downloadInterceptor.cancelDownload(options.uuid);
await this._downloadInterceptor.cancelDownload(options.uuid);
await this._downloadManager.cancelDownload(options.uuid);
}

setBrowserProxy(proxy) {
Expand Down Expand Up @@ -529,6 +700,7 @@ export class PageTarget {
helper.addProgressListener(tab.linkedBrowser, navigationListener, Ci.nsIWebProgress.NOTIFY_LOCATION),
helper.addEventListener(this._linkedBrowser, 'DOMModalDialogClosed', event => this._updateModalDialogs()),
helper.addEventListener(this._linkedBrowser, 'WillChangeBrowserRemoteness', event => this._willChangeBrowserRemoteness()),
helper.addEventListener(this._linkedBrowser, 'DidChangeBrowserRemoteness', event => this._didChangeBrowserRemoteness()),
];

this._disposed = false;
Expand Down Expand Up @@ -591,6 +763,15 @@ export class PageTarget {
this.removeActor(this._actor);
}

_didChangeBrowserRemoteness() {
// The top-level browsing context might have been replaced, e.g. by a cross-origin-opener-policy
// navigation, and CanonicalBrowsingContext::ReplacedBy() does not carry emulation overrides
// over to the new context. This event is dispatched synchronously during the process switch,
// before the load is resumed in the new process, so the re-applied overrides reach the new
// document before any of its scripts run.
this.updateOverridesForBrowsingContext();
}

dialog(dialogId) {
return this._dialogs.get(dialogId);
}
Expand Down Expand Up @@ -627,6 +808,13 @@ export class PageTarget {
this.updateForcedColorsOverride(browsingContext);
this.updateForceOffline(browsingContext);
this.updateCacheDisabled(browsingContext);
this.updateDownloadFolderOverride(browsingContext);
}

updateDownloadFolderOverride(browsingContext = undefined) {
// The helper app service writes the partial download to this folder before the destination
// is known, see GetInitialDownloadDirectory in nsExternalHelperAppService.cpp.
(browsingContext || this._linkedBrowser.browsingContext).downloadFolderOverride = this._browserContext.downloadOptions?.downloadsDir || '';
}

updateForceOffline(browsingContext = undefined) {
Expand Down Expand Up @@ -1090,6 +1278,7 @@ class BrowserContext {

async destroy() {
if (this.userContextId !== 0) {
await this._registry._downloadManager.cancelDownloadsForContext(this);
ContextualIdentityService.remove(this.userContextId);
for (const page of this.pages)
page.close();
Expand Down Expand Up @@ -1181,6 +1370,16 @@ class BrowserContext {
page.updateForceOffline();
}

async setDownloadOptions(downloadOptions) {
this.downloadOptions = downloadOptions;
for (const page of this.pages)
page.updateDownloadFolderOverride();
if (downloadOptions?.legacyInterceptor)
this._registry._downloadInterceptor.register();
else if (downloadOptions)
await this._registry._downloadManager.register();
}

setCacheDisabled(disabled) {
this.disableCache = disabled;
for (const page of this.pages)
Expand Down
7 changes: 6 additions & 1 deletion browser_patches/firefox/juggler/content/FrameTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class FrameTree {
this._frameIdToFrame = new Map();
this._pageReady = false;
this._javaScriptDisabled = false;
this._isolatedWorldExtendedPrincipal = false;
for (const browsingContext of helper.collectAllBrowsingContexts(rootBrowsingContext))
this._createFrame(browsingContext);
this._mainFrame = this.frameForBrowsingContext(rootBrowsingContext);
Expand Down Expand Up @@ -134,6 +135,10 @@ export class FrameTree {
frame._updateJavaScriptDisabled();
}

setIsolatedWorldExtendedPrincipal(extendedPrincipal) {
this._isolatedWorldExtendedPrincipal = extendedPrincipal;
}

_onWorkerCreated(workerDebugger) {
// Note: we do not interoperate with firefox devtools.
if (workerDebugger.isInitialized)
Expand Down Expand Up @@ -503,7 +508,7 @@ class Frame {
}

_createIsolatedContext(name) {
const principal = [this.domWindow()]; // extended principal
const principal = this._frameTree._isolatedWorldExtendedPrincipal ? [this.domWindow()] : this.domWindow();
const sandbox = Cu.Sandbox(principal, {
sandboxPrototype: this.domWindow(),
wantComponents: false,
Expand Down
32 changes: 29 additions & 3 deletions browser_patches/firefox/juggler/content/PageAgent.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,34 @@ class WorkerData {
}
}

// Scrolls the node into view, or, when it has no layout object (e.g. display: contents),
// the first of its flattened descendants that has one. Returns false when there is none.
function scrollNodeIntoViewIfNeeded(node, rect) {
// Only Element, Text and Document have scrollRectIntoViewIfNeeded (see GeometryUtils.webidl).
if (node.scrollRectIntoViewIfNeeded) {
try {
node.scrollRectIntoViewIfNeeded(rect.x, rect.y, rect.width, rect.height);
return true;
} catch (e) {
// nsINode::ScrollRectIntoViewIfNeeded (dom/base/nsINode.cpp in bootstrap.diff)
// throws a NotFoundError DOMException when the node has no primary frame.
// Anything else is unexpected.
if (e.name !== 'NotFoundError')
throw e;
}
}
let flatTreeChildren = node.childNodes;
if (node.openOrClosedShadowRoot)
flatTreeChildren = node.openOrClosedShadowRoot.childNodes;
else if (node.localName === 'slot' && node.assignedNodes && node.assignedNodes().length)
flatTreeChildren = node.assignedNodes();
for (const child of flatTreeChildren) {
if (scrollNodeIntoViewIfNeeded(child, rect))
return true;
}
return false;
}

export class PageAgent {
constructor(browserChannel, frameTree) {
this._browserChannel = browserChannel;
Expand Down Expand Up @@ -440,9 +468,7 @@ export class PageAgent {
throw new Error('Node is detached from document');
if (!rect)
rect = { x: -1, y: -1, width: -1, height: -1};
if (unsafeObject.scrollRectIntoViewIfNeeded)
unsafeObject.scrollRectIntoViewIfNeeded(rect.x, rect.y, rect.width, rect.height);
else
if (!scrollNodeIntoViewIfNeeded(unsafeObject, rect))
throw new Error('Node does not have a layout object');
}

Expand Down
Loading
Loading