1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
|
/* 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 { GeckoViewModule } from "resource://gre/modules/GeckoViewModule.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
GeckoViewUtils: "resource://gre/modules/GeckoViewUtils.sys.mjs",
E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs",
LoadURIDelegate: "resource://gre/modules/LoadURIDelegate.sys.mjs",
isProductURL: "chrome://global/content/shopping/ShoppingProduct.mjs",
TranslationsParent: "resource://gre/actors/TranslationsParent.sys.mjs",
});
ChromeUtils.defineLazyGetter(lazy, "ReferrerInfo", () =>
Components.Constructor(
"@mozilla.org/referrer-info;1",
"nsIReferrerInfo",
"init"
)
);
// Filter out request headers as per discussion in Bug #1567549
// CONNECTION: Used by Gecko to manage connections
// HOST: Relates to how gecko will ultimately interpret the resulting resource as that
// determines the effective request URI
const BAD_HEADERS = ["connection", "host"];
// Headers use |\r\n| as separator so these characters cannot appear
// in the header name or value
const FORBIDDEN_HEADER_CHARACTERS = ["\n", "\r"];
// Keep in sync with GeckoSession.java
const HEADER_FILTER_CORS_SAFELISTED = 1;
// eslint-disable-next-line no-unused-vars
const HEADER_FILTER_UNRESTRICTED_UNSAFE = 2;
// Create default ReferrerInfo instance for the given referrer URI string.
const createReferrerInfo = aReferrer => {
let referrerUri;
try {
referrerUri = Services.io.newURI(aReferrer);
} catch (ignored) {}
return new lazy.ReferrerInfo(Ci.nsIReferrerInfo.EMPTY, true, referrerUri);
};
function convertFlags(aFlags) {
let navFlags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
if (!aFlags) {
return navFlags;
}
// These need to match the values in GeckoSession.LOAD_FLAGS_*
if (aFlags & (1 << 0)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
}
if (aFlags & (1 << 1)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY;
}
if (aFlags & (1 << 2)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL;
}
if (aFlags & (1 << 3)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_POPUPS;
}
if (aFlags & (1 << 4)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CLASSIFIER;
}
if (aFlags & (1 << 5)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI;
}
if (aFlags & (1 << 6)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY;
}
if (aFlags & (1 << 7)) {
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_LOAD_URI_DELEGATE;
}
return navFlags;
}
// Handles navigation requests between Gecko and a GeckoView.
// Handles GeckoView:GoBack and :GoForward requests dispatched by
// GeckoView.goBack and .goForward.
// Dispatches GeckoView:LocationChange to the GeckoView on location change when
// active.
// Implements nsIBrowserDOMWindow.
export class GeckoViewNavigation extends GeckoViewModule {
onInitBrowser() {
this.window.browserDOMWindow = this;
debug`sessionContextId=${this.settings.sessionContextId}`;
if (this.settings.sessionContextId !== null) {
// Gecko may have issues with strings containing special characters,
// so we restrict the string format to a specific pattern.
if (!/^gvctx(-)?([a-f0-9]+)$/.test(this.settings.sessionContextId)) {
throw new Error("sessionContextId has illegal format");
}
this.browser.setAttribute(
"geckoViewSessionContextId",
this.settings.sessionContextId
);
}
// There may be a GeckoViewNavigation module in another window waiting for
// us to create a browser so it can set openWindowInfo, so allow them to do
// that now.
Services.obs.notifyObservers(this.window, "geckoview-window-created");
}
onInit() {
debug`onInit`;
this.registerListener([
"GeckoView:GoBack",
"GeckoView:GoForward",
"GeckoView:GotoHistoryIndex",
"GeckoView:LoadUri",
"GeckoView:Reload",
"GeckoView:Stop",
"GeckoView:PurgeHistory",
"GeckoView:DotPrintFinish",
]);
this._initialAboutBlank = true;
}
validateHeader(key, value, filter) {
if (!key) {
// Key cannot be empty
return false;
}
for (const c of FORBIDDEN_HEADER_CHARACTERS) {
if (key.includes(c) || value?.includes(c)) {
return false;
}
}
if (BAD_HEADERS.includes(key.toLowerCase().trim())) {
return false;
}
if (
filter == HEADER_FILTER_CORS_SAFELISTED &&
!this.window.windowUtils.isCORSSafelistedRequestHeader(key, value)
) {
return false;
}
return true;
}
// Bundle event handler.
async onEvent(aEvent, aData) {
debug`onEvent: event=${aEvent}, data=${aData}`;
switch (aEvent) {
case "GeckoView:GoBack":
this.browser.goBack(aData.userInteraction);
break;
case "GeckoView:GoForward":
this.browser.goForward(aData.userInteraction);
break;
case "GeckoView:GotoHistoryIndex":
this.browser.gotoIndex(aData.index);
break;
case "GeckoView:LoadUri":
const {
uri,
referrerUri,
referrerSessionId,
flags,
headers,
headerFilter,
} = aData;
let navFlags = convertFlags(flags);
// For performance reasons we don't call the LoadUriDelegate.loadUri
// from Gecko, and instead we call it directly in the loadUri Java API.
navFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_LOAD_URI_DELEGATE;
let triggeringPrincipal, referrerInfo, csp;
if (referrerSessionId) {
const referrerWindow = Services.ww.getWindowByName(referrerSessionId);
triggeringPrincipal = referrerWindow.browser.contentPrincipal;
csp = referrerWindow.browser.csp;
const { contentPrincipal } = this.browser;
const isNormal = contentPrincipal.privateBrowsingId == 0;
const referrerIsPrivate = triggeringPrincipal.privateBrowsingId != 0;
const referrerPolicy = referrerWindow.browser.referrerInfo
? referrerWindow.browser.referrerInfo.referrerPolicy
: Ci.nsIReferrerInfo.EMPTY;
referrerInfo = new lazy.ReferrerInfo(
referrerPolicy,
// Don't `sendReferrer` if the private session (current) is opened by a normal session (referrer)
isNormal || referrerIsPrivate,
referrerWindow.browser.documentURI
);
} else if (referrerUri) {
referrerInfo = createReferrerInfo(referrerUri);
} else {
// External apps are treated like web pages, so they should not get
// a privileged principal.
const isExternal =
navFlags & Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL;
if (!isExternal || Services.io.newURI(uri).schemeIs("content")) {
// Always use the system principal as the triggering principal
// for user-initiated (ie. no referrer session and not external)
// loads. See discussion in bug 1573860.
triggeringPrincipal =
Services.scriptSecurityManager.getSystemPrincipal();
}
}
if (!triggeringPrincipal) {
triggeringPrincipal =
Services.scriptSecurityManager.createNullPrincipal({});
}
let additionalHeaders = null;
if (headers) {
additionalHeaders = "";
for (const [key, value] of Object.entries(headers)) {
if (!this.validateHeader(key, value, headerFilter)) {
console.error(`Ignoring invalid header '${key}'='${value}'.`);
continue;
}
additionalHeaders += `${key}:${value ?? ""}\r\n`;
}
if (additionalHeaders != "") {
additionalHeaders =
lazy.E10SUtils.makeInputStream(additionalHeaders);
} else {
additionalHeaders = null;
}
}
// For any navigation here, we should have an appropriate triggeringPrincipal:
//
// 1) If we have a referring session, triggeringPrincipal is the contentPrincipal from the
// referring document.
// 2) For certain URI schemes listed above, we will have a codebase principal.
// 3) In all other cases, we create a NullPrincipal.
//
// The navigation flags are driven by the app. We purposely do not propagate these from
// the referring document, but expect that the app will in most cases.
//
// The referrerInfo is derived from the referring document, if present, by propagating any
// referrer policy. If we only have the referrerUri from the app, we create a referrerInfo
// with the specified URI and no policy set. If no referrerUri is present and we have no
// referring session, the referrerInfo is null.
//
// csp is only present if we have a referring document, null otherwise.
this.browser.fixupAndLoadURIString(uri, {
flags: navFlags,
referrerInfo,
triggeringPrincipal,
headers: additionalHeaders,
csp,
});
break;
case "GeckoView:Reload":
// At the moment, GeckoView only supports one reload, which uses
// nsIWebNavigation.LOAD_FLAGS_NONE flag, and the telemetry doesn't
// do anything to differentiate reloads (i.e normal vs skip caches)
// So whenever we add more reload methods, please make sure the
// telemetry probe is adjusted
this.browser.reloadWithFlags(convertFlags(aData.flags));
break;
case "GeckoView:Stop":
this.browser.stop();
break;
case "GeckoView:PurgeHistory":
this.browser.purgeSessionHistory();
break;
case "GeckoView:DotPrintFinish":
var printActor = this.moduleManager.getActor("GeckoViewPrintDelegate");
printActor.clearStaticClone();
break;
}
}
waitAndSetupWindow(aSessionId, aOpenWindowInfo, aName) {
if (!aSessionId) {
return Promise.resolve(null);
}
return new Promise(resolve => {
const handler = {
observe(aSubject, aTopic) {
if (
aTopic === "geckoview-window-created" &&
aSubject.name === aSessionId
) {
// This value will be read by nsFrameLoader while it is being initialized.
aSubject.browser.openWindowInfo = aOpenWindowInfo;
// Gecko will use this attribute to set the name of the opened window.
if (aName) {
aSubject.browser.setAttribute("name", aName);
}
if (
!aOpenWindowInfo.isRemote &&
aSubject.browser.hasAttribute("remote")
) {
// We cannot start in remote mode when we have an opener.
aSubject.browser.setAttribute("remote", "false");
aSubject.browser.removeAttribute("remoteType");
}
Services.obs.removeObserver(handler, "geckoview-window-created");
resolve(aSubject);
}
},
};
// This event is emitted from createBrowser() in geckoview.js
Services.obs.addObserver(handler, "geckoview-window-created");
});
}
handleNewSession(aUri, aOpenWindowInfo, aWhere, aFlags, aName) {
debug`handleNewSession: uri=${aUri && aUri.spec}
where=${aWhere} flags=${aFlags}`;
if (!this.enabled) {
return null;
}
const newSessionId = Services.uuid
.generateUUID()
.toString()
.slice(1, -1)
.replace(/-/g, "");
const message = {
type: "GeckoView:OnNewSession",
uri: aUri ? aUri.displaySpec : "",
newSessionId,
};
// The window might be already open by the time we get the response from
// the Java layer, so we need to start waiting before sending the message.
const setupPromise = this.waitAndSetupWindow(
newSessionId,
aOpenWindowInfo,
aName
);
let browser = undefined;
this.eventDispatcher
.sendRequestForResult(message)
.then(didOpenSession => {
if (!didOpenSession) {
return Promise.reject();
}
return setupPromise;
})
.then(
window => {
browser = window.browser;
},
() => {
browser = null;
}
);
// Wait indefinitely for app to respond with a browser or null
Services.tm.spinEventLoopUntil(
"GeckoViewNavigation.sys.mjs:handleNewSession",
() => this.window.closed || browser !== undefined
);
return browser || null;
}
// nsIBrowserDOMWindow.
createContentWindow(
aUri,
aOpenWindowInfo,
aWhere,
aFlags,
aTriggeringPrincipal
) {
debug`createContentWindow: uri=${aUri && aUri.spec}
where=${aWhere} flags=${aFlags}`;
if (
lazy.LoadURIDelegate.load(
this.window,
this.eventDispatcher,
aUri,
aWhere,
aFlags,
aTriggeringPrincipal
)
) {
// The app has handled the load, abort open-window handling.
Components.returnCode = Cr.NS_ERROR_ABORT;
return null;
}
const browser = this.handleNewSession(
aUri,
aOpenWindowInfo,
aWhere,
aFlags,
null
);
if (!browser) {
Components.returnCode = Cr.NS_ERROR_ABORT;
return null;
}
return browser.browsingContext;
}
// nsIBrowserDOMWindow.
createContentWindowInFrame(aUri, aParams, aWhere, aFlags, aName) {
debug`createContentWindowInFrame: uri=${aUri && aUri.spec}
where=${aWhere} flags=${aFlags}
name=${aName}`;
if (aWhere === Ci.nsIBrowserDOMWindow.OPEN_PRINT_BROWSER) {
return this.window.moduleManager.onPrintWindow(aParams);
}
if (
lazy.LoadURIDelegate.load(
this.window,
this.eventDispatcher,
aUri,
aWhere,
aFlags,
aParams.triggeringPrincipal
)
) {
// The app has handled the load, abort open-window handling.
Components.returnCode = Cr.NS_ERROR_ABORT;
return null;
}
const browser = this.handleNewSession(
aUri,
aParams.openWindowInfo,
aWhere,
aFlags,
aName
);
if (!browser) {
Components.returnCode = Cr.NS_ERROR_ABORT;
return null;
}
return browser;
}
handleOpenUri({
uri,
openWindowInfo,
where,
flags,
triggeringPrincipal,
csp,
referrerInfo = null,
name = null,
}) {
debug`handleOpenUri: uri=${uri && uri.spec}
where=${where} flags=${flags}`;
if (
lazy.LoadURIDelegate.load(
this.window,
this.eventDispatcher,
uri,
where,
flags,
triggeringPrincipal
)
) {
return null;
}
let browser = this.browser;
if (
where === Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW ||
where === Ci.nsIBrowserDOMWindow.OPEN_NEWTAB ||
where === Ci.nsIBrowserDOMWindow.OPEN_NEWTAB_BACKGROUND
) {
browser = this.handleNewSession(uri, openWindowInfo, where, flags, name);
}
if (!browser) {
// Should we throw?
return null;
}
// 3) We have a new session and a browser element, load the requested URI.
browser.loadURI(uri, {
triggeringPrincipal,
csp,
referrerInfo,
});
return browser;
}
// nsIBrowserDOMWindow.
openURI(aUri, aOpenWindowInfo, aWhere, aFlags, aTriggeringPrincipal, aCsp) {
const browser = this.handleOpenUri({
uri: aUri,
openWindowInfo: aOpenWindowInfo,
where: aWhere,
flags: aFlags,
triggeringPrincipal: aTriggeringPrincipal,
csp: aCsp,
});
return browser && browser.browsingContext;
}
// nsIBrowserDOMWindow.
openURIInFrame(aUri, aParams, aWhere, aFlags, aName) {
const browser = this.handleOpenUri({
uri: aUri,
openWindowInfo: aParams.openWindowInfo,
where: aWhere,
flags: aFlags,
triggeringPrincipal: aParams.triggeringPrincipal,
csp: aParams.csp,
referrerInfo: aParams.referrerInfo,
name: aName,
});
return browser;
}
// nsIBrowserDOMWindow.
canClose() {
debug`canClose`;
return true;
}
onEnable() {
debug`onEnable`;
const flags = Ci.nsIWebProgress.NOTIFY_LOCATION;
this.progressFilter = Cc[
"@mozilla.org/appshell/component/browser-status-filter;1"
].createInstance(Ci.nsIWebProgress);
this.progressFilter.addProgressListener(this, flags);
this.browser.addProgressListener(this.progressFilter, flags);
}
onDisable() {
debug`onDisable`;
if (!this.progressFilter) {
return;
}
this.progressFilter.removeProgressListener(this);
this.browser.removeProgressListener(this.progressFilter);
}
serializePermission({ type, capability, principal }) {
const { URI, originAttributes, privateBrowsingId } = principal;
return {
uri: Services.io.createExposableURI(URI).displaySpec,
principal: lazy.E10SUtils.serializePrincipal(principal),
perm: type,
value: capability,
contextId: originAttributes.geckoViewSessionContextId,
privateMode: privateBrowsingId != 0,
};
}
async isProductURL(aLocationURI) {
if (lazy.isProductURL(aLocationURI)) {
this.eventDispatcher.sendRequest({
type: "GeckoView:OnProductUrl",
});
}
}
// WebProgress event handler.
onLocationChange(aWebProgress, aRequest, aLocationURI) {
debug`onLocationChange`;
let fixedURI = aLocationURI;
try {
fixedURI = Services.io.createExposableURI(aLocationURI);
} catch (ex) {}
// We manually fire the initial about:blank messages to make sure that we
// consistently send them so there's nothing to do here.
const ignore = this._initialAboutBlank && fixedURI.spec === "about:blank";
this._initialAboutBlank = false;
if (ignore) {
return;
}
const { contentPrincipal } = this.browser;
let permissions;
if (
contentPrincipal &&
lazy.GeckoViewUtils.isSupportedPermissionsPrincipal(contentPrincipal)
) {
let rawPerms = [];
try {
rawPerms = Services.perms.getAllForPrincipal(contentPrincipal);
} catch (ex) {
warn`Could not get permissions for principal. ${ex}`;
}
permissions = rawPerms.map(this.serializePermission);
// The only way for apps to set permissions is to get hold of an existing
// permission and change its value.
// Tracking protection exception permissions are only present when
// explicitly added by the app, so if one is not present, we need to send
// a DENY_ACTION tracking protection permission so that apps can use it
// to add tracking protection exceptions.
const trackingProtectionPermission =
contentPrincipal.privateBrowsingId == 0
? "trackingprotection"
: "trackingprotection-pb";
if (
contentPrincipal.isContentPrincipal &&
rawPerms.findIndex(p => p.type == trackingProtectionPermission) == -1
) {
permissions.push(
this.serializePermission({
type: trackingProtectionPermission,
capability: Ci.nsIPermissionManager.DENY_ACTION,
principal: contentPrincipal,
})
);
}
}
const message = {
type: "GeckoView:LocationChange",
uri: fixedURI.displaySpec,
canGoBack: this.browser.canGoBack,
canGoForward: this.browser.canGoForward,
isTopLevel: aWebProgress.isTopLevel,
permissions,
hasUserGesture:
this.window.document.hasValidTransientUserGestureActivation,
};
lazy.TranslationsParent.onLocationChange(this.browser);
this.eventDispatcher.sendRequest(message);
this.isProductURL(aLocationURI);
}
}
const { debug, warn } = GeckoViewNavigation.initLogging("GeckoViewNavigation");
|