forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBrowserContentHandler.sys.mjs
1544 lines (1405 loc) · 52 KB
/
BrowserContentHandler.sys.mjs
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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 { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
FirstStartup: "resource://gre/modules/FirstStartup.sys.mjs",
HeadlessShell: "resource:///modules/HeadlessShell.sys.mjs",
HomePage: "resource:///modules/HomePage.sys.mjs",
LaterRun: "resource:///modules/LaterRun.sys.mjs",
NimbusFeatures: "resource://nimbus/ExperimentAPI.sys.mjs",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
SessionStartup: "resource:///modules/sessionstore/SessionStartup.sys.mjs",
ShellService: "resource:///modules/ShellService.sys.mjs",
SpecialMessageActions:
"resource://messaging-system/lib/SpecialMessageActions.sys.mjs",
UpdatePing: "resource://gre/modules/UpdatePing.sys.mjs",
});
XPCOMUtils.defineLazyServiceGetters(lazy, {
UpdateManager: ["@mozilla.org/updates/update-manager;1", "nsIUpdateManager"],
WinTaskbar: ["@mozilla.org/windows-taskbar;1", "nsIWinTaskbar"],
WindowsUIUtils: ["@mozilla.org/windows-ui-utils;1", "nsIWindowsUIUtils"],
});
ChromeUtils.defineLazyGetter(lazy, "gSystemPrincipal", () =>
Services.scriptSecurityManager.getSystemPrincipal()
);
ChromeUtils.defineLazyGetter(lazy, "gWindowsAlertsService", () => {
// We might not have the Windows alerts service: e.g., on Windows 7 and Windows 8.
if (!("nsIWindowsAlertsService" in Ci)) {
return null;
}
return Cc["@mozilla.org/system-alerts-service;1"]
?.getService(Ci.nsIAlertsService)
?.QueryInterface(Ci.nsIWindowsAlertsService);
});
// One-time startup homepage override configurations
const ONCE_DOMAINS = ["mozilla.org", "firefox.com"];
const ONCE_PREF = "browser.startup.homepage_override.once";
// Index of Private Browsing icon in firefox.exe
// Must line up with the one in nsNativeAppSupportWin.h.
const PRIVATE_BROWSING_ICON_INDEX = 5;
function shouldLoadURI(aURI) {
if (aURI && !aURI.schemeIs("chrome")) {
return true;
}
dump("*** Preventing external load of chrome: URI into browser window\n");
dump(" Use --chrome <uri> instead\n");
return false;
}
function validateFirefoxProtocol(aCmdLine, launchedWithArg_osint) {
let paramCount = 0;
// Only accept one parameter when we're handling the protocol.
for (let i = 0; i < aCmdLine.length; i++) {
if (!aCmdLine.getArgument(i).startsWith("-")) {
paramCount++;
}
if (paramCount > 1) {
return false;
}
}
// `-osint` and handling registered file types and protocols is Windows-only.
return AppConstants.platform != "win" || launchedWithArg_osint;
}
function resolveURIInternal(
aCmdLine,
aArgument,
launchedWithArg_osint = false
) {
let principal = lazy.gSystemPrincipal;
// If using Firefox protocol handler remove it from URI
// at this stage. This is before we would otherwise
// record telemetry so do that here.
let handleFirefoxProtocol = protocol => {
let protocolWithColon = protocol + ":";
if (aArgument.startsWith(protocolWithColon)) {
if (!validateFirefoxProtocol(aCmdLine, launchedWithArg_osint)) {
throw new Error(
"Invalid use of Firefox-bridge and Firefox-private-bridge protocols."
);
}
aArgument = aArgument.substring(protocolWithColon.length);
if (
!aArgument.startsWith("http://") &&
!aArgument.startsWith("https://")
) {
throw new Error(
"Firefox-bridge and Firefox-private-bridge protocols can only be used in conjunction with http and https urls."
);
}
principal = Services.scriptSecurityManager.createNullPrincipal({});
Services.telemetry.keyedScalarAdd(
"os.environment.launched_to_handle",
protocol,
1
);
}
};
handleFirefoxProtocol("firefox-bridge");
handleFirefoxProtocol("firefox-private-bridge");
var uri = aCmdLine.resolveURI(aArgument);
var uriFixup = Services.uriFixup;
if (!(uri instanceof Ci.nsIFileURL)) {
let prefURI = Services.uriFixup.getFixupURIInfo(
aArgument,
uriFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS
).preferredURI;
return { uri: prefURI, principal };
}
try {
if (uri.file.exists()) {
return { uri, principal };
}
} catch (e) {
console.error(e);
}
// We have interpreted the argument as a relative file URI, but the file
// doesn't exist. Try URI fixup heuristics: see bug 290782.
try {
uri = Services.uriFixup.getFixupURIInfo(aArgument).preferredURI;
} catch (e) {
console.error(e);
}
return { uri, principal };
}
let gKiosk = false;
let gMajorUpgrade = false;
let gFirstRunProfile = false;
var gFirstWindow = false;
const OVERRIDE_NONE = 0;
const OVERRIDE_NEW_PROFILE = 1;
const OVERRIDE_NEW_MSTONE = 2;
const OVERRIDE_NEW_BUILD_ID = 3;
/**
* Determines whether a home page override is needed.
* @param {boolean} [updateMilestones=true]
* True if we should update the milestone prefs after comparing those prefs
* with the current platform version and build ID.
*
* If updateMilestones is false, then this function has no side-effects.
*
* @returns {number}
* One of the following constants:
* OVERRIDE_NEW_PROFILE
* if this is the first run with a new profile.
* OVERRIDE_NEW_MSTONE
* if this is the first run with a build with a different Gecko milestone
* (i.e. right after an upgrade).
* OVERRIDE_NEW_BUILD_ID
* if this is the first run with a new build ID of the same Gecko
* milestone (i.e. after a nightly upgrade).
* OVERRIDE_NONE
* otherwise.
*/
function needHomepageOverride(updateMilestones = true) {
var savedmstone = Services.prefs.getCharPref(
"browser.startup.homepage_override.mstone",
""
);
if (savedmstone == "ignore") {
return OVERRIDE_NONE;
}
var mstone = Services.appinfo.platformVersion;
var savedBuildID = Services.prefs.getCharPref(
"browser.startup.homepage_override.buildID",
""
);
var buildID = Services.appinfo.platformBuildID;
if (mstone != savedmstone) {
// Bug 462254. Previous releases had a default pref to suppress the EULA
// agreement if the platform's installer had already shown one. Now with
// about:rights we've removed the EULA stuff and default pref, but we need
// a way to make existing profiles retain the default that we removed.
if (savedmstone) {
Services.prefs.setBoolPref("browser.rights.3.shown", true);
// Remember that we saw a major version change.
gMajorUpgrade = true;
}
if (updateMilestones) {
Services.prefs.setCharPref(
"browser.startup.homepage_override.mstone",
mstone
);
Services.prefs.setCharPref(
"browser.startup.homepage_override.buildID",
buildID
);
}
return savedmstone ? OVERRIDE_NEW_MSTONE : OVERRIDE_NEW_PROFILE;
}
if (buildID != savedBuildID) {
if (updateMilestones) {
Services.prefs.setCharPref(
"browser.startup.homepage_override.buildID",
buildID
);
}
return OVERRIDE_NEW_BUILD_ID;
}
return OVERRIDE_NONE;
}
/**
* Gets the override page for the first run after the application has been
* updated.
* @param update
* The nsIUpdate for the update that has been applied.
* @param defaultOverridePage
* The default override page
* @param nimbusOverridePage
* Nimbus provided URL
* @return The override page.
*/
function getPostUpdateOverridePage(
update,
defaultOverridePage,
nimbusOverridePage
) {
update = update.QueryInterface(Ci.nsIWritablePropertyBag);
let actions = update.getProperty("actions");
// When the update doesn't specify actions fallback to the original behavior
// of displaying the default override page.
if (!actions) {
return defaultOverridePage;
}
// The existence of silent or the non-existence of showURL in the actions both
// mean that an override page should not be displayed.
if (actions.includes("silent") || !actions.includes("showURL")) {
return "";
}
// If a policy was set to not allow the update.xml-provided URL to be used,
// use the default fallback (which will also be provided by the policy).
if (!Services.policies.isAllowed("postUpdateCustomPage")) {
return defaultOverridePage;
}
if (nimbusOverridePage) {
return nimbusOverridePage;
}
return update.getProperty("openURL") || defaultOverridePage;
}
/**
* Open a browser window. If this is the initial launch, this function will
* attempt to use the navigator:blank window opened by BrowserGlue.sys.mjs during
* early startup.
*
* @param cmdLine
* The nsICommandLine object given to nsICommandLineHandler's handle
* method.
* Used to check if we are processing the command line for the initial launch.
* @param triggeringPrincipal
* The nsIPrincipal to use as triggering principal for the page load(s).
* @param urlOrUrlList (optional)
* When omitted, the browser window will be opened with the default
* arguments, which will usually load the homepage.
* This can be a JS array of urls provided as strings, each url will be
* loaded in a tab. postData will be ignored in this case.
* This can be a single url to load in the new window, provided as a string.
* postData will be used in this case if provided.
* @param postData (optional)
* An nsIInputStream object to use as POST data when loading the provided
* url, or null.
* @param forcePrivate (optional)
* Boolean. If set to true, the new window will be a private browsing one.
*
* @returns {ChromeWindow}
* Returns the top level window opened.
*/
function openBrowserWindow(
cmdLine,
triggeringPrincipal,
urlOrUrlList,
postData = null,
forcePrivate = false
) {
const isStartup =
cmdLine && cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH;
let args;
if (!urlOrUrlList) {
// Just pass in the defaultArgs directly. We'll use system principal on the other end.
args = [gBrowserContentHandler.getArgs(isStartup)];
} else if (Array.isArray(urlOrUrlList)) {
// There isn't an explicit way to pass a principal here, so we load multiple URLs
// with system principal when we get to actually loading them.
if (
!triggeringPrincipal ||
!triggeringPrincipal.equals(lazy.gSystemPrincipal)
) {
throw new Error(
"Can't open multiple URLs with something other than system principal."
);
}
// Passing an nsIArray for the url disables the "|"-splitting behavior.
let uriArray = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
urlOrUrlList.forEach(function (uri) {
var sstring = Cc["@mozilla.org/supports-string;1"].createInstance(
Ci.nsISupportsString
);
sstring.data = uri;
uriArray.appendElement(sstring);
});
args = [uriArray];
} else {
let extraOptions = Cc["@mozilla.org/hash-property-bag;1"].createInstance(
Ci.nsIWritablePropertyBag2
);
extraOptions.setPropertyAsBool("fromExternal", true);
// Always pass at least 3 arguments to avoid the "|"-splitting behavior,
// ie. avoid the loadOneOrMoreURIs function.
// Also, we need to pass the triggering principal.
args = [
urlOrUrlList,
extraOptions,
null, // refererInfo
postData,
undefined, // allowThirdPartyFixup; this would be `false` but that
// needs a conversion. Hopefully bug 1485961 will fix.
undefined, // user context id
null, // origin principal
null, // origin storage principal
triggeringPrincipal,
];
}
if (isStartup) {
let win = Services.wm.getMostRecentWindow("navigator:blank");
if (win) {
// Remove the windowtype of our blank window so that we don't close it
// later on when seeing cmdLine.preventDefault is true.
win.document.documentElement.removeAttribute("windowtype");
if (forcePrivate) {
win.docShell.QueryInterface(
Ci.nsILoadContext
).usePrivateBrowsing = true;
if (
AppConstants.platform == "win" &&
lazy.NimbusFeatures.majorRelease2022.getVariable(
"feltPrivacyWindowSeparation"
)
) {
lazy.WinTaskbar.setGroupIdForWindow(
win,
lazy.WinTaskbar.defaultPrivateGroupId
);
lazy.WindowsUIUtils.setWindowIconFromExe(
win,
Services.dirsvc.get("XREExeF", Ci.nsIFile).path,
// This corresponds to the definitions in
// nsNativeAppSupportWin.h
PRIVATE_BROWSING_ICON_INDEX
);
}
}
let openTime = win.openTime;
win.location = AppConstants.BROWSER_CHROME_URL;
win.arguments = args; // <-- needs to be a plain JS array here.
ChromeUtils.addProfilerMarker("earlyBlankWindowVisible", openTime);
lazy.BrowserWindowTracker.registerOpeningWindow(win, forcePrivate);
return win;
}
}
// We can't provide arguments to openWindow as a JS array.
if (!urlOrUrlList) {
// If we have a single string guaranteed to not contain '|' we can simply
// wrap it in an nsISupportsString object.
let [url] = args;
args = Cc["@mozilla.org/supports-string;1"].createInstance(
Ci.nsISupportsString
);
args.data = url;
} else {
// Otherwise, pass an nsIArray.
if (args.length > 1) {
let string = Cc["@mozilla.org/supports-string;1"].createInstance(
Ci.nsISupportsString
);
string.data = args[0];
args[0] = string;
}
let array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
args.forEach(a => {
array.appendElement(a);
});
args = array;
}
return lazy.BrowserWindowTracker.openWindow({
args,
features: gBrowserContentHandler.getFeatures(cmdLine),
private: forcePrivate,
});
}
function openPreferences(cmdLine) {
openBrowserWindow(cmdLine, lazy.gSystemPrincipal, "about:preferences");
}
async function doSearch(searchTerm, cmdLine) {
// XXXbsmedberg: use handURIToExistingBrowser to obey tabbed-browsing
// preferences, but need nsIBrowserDOMWindow extensions
// Open the window immediately as BrowserContentHandler needs to
// be handled synchronously. Then load the search URI when the
// SearchService has loaded.
let win = openBrowserWindow(cmdLine, lazy.gSystemPrincipal, "about:blank");
await new Promise(resolve => {
Services.obs.addObserver(function observe(subject) {
if (subject == win) {
Services.obs.removeObserver(
observe,
"browser-delayed-startup-finished"
);
resolve();
}
}, "browser-delayed-startup-finished");
});
win.BrowserSearch.loadSearchFromCommandLine(
searchTerm,
lazy.PrivateBrowsingUtils.isInTemporaryAutoStartMode ||
lazy.PrivateBrowsingUtils.isWindowPrivate(win),
lazy.gSystemPrincipal,
win.gBrowser.selectedBrowser.csp
).catch(console.error);
}
export function nsBrowserContentHandler() {
if (!gBrowserContentHandler) {
gBrowserContentHandler = this;
}
return gBrowserContentHandler;
}
nsBrowserContentHandler.prototype = {
/* nsISupports */
QueryInterface: ChromeUtils.generateQI([
"nsICommandLineHandler",
"nsIBrowserHandler",
"nsIContentHandler",
"nsICommandLineValidator",
]),
/* nsICommandLineHandler */
handle: function bch_handle(cmdLine) {
if (
cmdLine.handleFlag("kiosk", false) ||
cmdLine.handleFlagWithParam("kiosk-monitor", false)
) {
gKiosk = true;
}
if (cmdLine.handleFlag("disable-pinch", false)) {
let defaults = Services.prefs.getDefaultBranch(null);
defaults.setBoolPref("apz.allow_zooming", false);
Services.prefs.lockPref("apz.allow_zooming");
defaults.setCharPref("browser.gesture.pinch.in", "");
Services.prefs.lockPref("browser.gesture.pinch.in");
defaults.setCharPref("browser.gesture.pinch.in.shift", "");
Services.prefs.lockPref("browser.gesture.pinch.in.shift");
defaults.setCharPref("browser.gesture.pinch.out", "");
Services.prefs.lockPref("browser.gesture.pinch.out");
defaults.setCharPref("browser.gesture.pinch.out.shift", "");
Services.prefs.lockPref("browser.gesture.pinch.out.shift");
}
if (cmdLine.handleFlag("browser", false)) {
openBrowserWindow(cmdLine, lazy.gSystemPrincipal);
cmdLine.preventDefault = true;
}
var uriparam;
try {
while ((uriparam = cmdLine.handleFlagWithParam("new-window", false))) {
let { uri, principal } = resolveURIInternal(cmdLine, uriparam);
if (!shouldLoadURI(uri)) {
continue;
}
openBrowserWindow(cmdLine, principal, uri.spec);
cmdLine.preventDefault = true;
}
} catch (e) {
console.error(e);
}
try {
while ((uriparam = cmdLine.handleFlagWithParam("new-tab", false))) {
let { uri, principal } = resolveURIInternal(cmdLine, uriparam);
handURIToExistingBrowser(
uri,
Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
cmdLine,
false,
principal
);
cmdLine.preventDefault = true;
}
} catch (e) {
console.error(e);
}
var chromeParam = cmdLine.handleFlagWithParam("chrome", false);
if (chromeParam) {
// Handle old preference dialog URLs.
if (
chromeParam == "chrome://browser/content/pref/pref.xul" ||
chromeParam == "chrome://browser/content/preferences/preferences.xul"
) {
openPreferences(cmdLine);
cmdLine.preventDefault = true;
} else {
try {
let { uri: resolvedURI } = resolveURIInternal(cmdLine, chromeParam);
let isLocal = uri => {
let localSchemes = new Set(["chrome", "file", "resource"]);
if (uri instanceof Ci.nsINestedURI) {
uri = uri.QueryInterface(Ci.nsINestedURI).innerMostURI;
}
return localSchemes.has(uri.scheme);
};
if (isLocal(resolvedURI)) {
// If the URI is local, we are sure it won't wrongly inherit chrome privs
let features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
// Provide 1 null argument, as openWindow has a different behavior
// when the arg count is 0.
let argArray = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
argArray.appendElement(null);
Services.ww.openWindow(
null,
resolvedURI.spec,
"_blank",
features,
argArray
);
cmdLine.preventDefault = true;
} else {
dump("*** Preventing load of web URI as chrome\n");
dump(
" If you're trying to load a webpage, do not pass --chrome.\n"
);
}
} catch (e) {
console.error(e);
}
}
}
if (cmdLine.handleFlag("preferences", false)) {
openPreferences(cmdLine);
cmdLine.preventDefault = true;
}
if (cmdLine.handleFlag("silent", false)) {
cmdLine.preventDefault = true;
}
try {
var privateWindowParam = cmdLine.handleFlagWithParam(
"private-window",
false
);
// Check for Firefox private browsing protocol handler here.
let url = null;
let urlFlagIdx = cmdLine.findFlag("url", false);
if (urlFlagIdx > -1 && cmdLine.length > 1) {
url = cmdLine.getArgument(urlFlagIdx + 1);
}
if (privateWindowParam || url?.startsWith("firefox-private-bridge:")) {
// Check if the osint flag is present on Windows
let launchedWithArg_osint =
AppConstants.platform == "win" &&
cmdLine.findFlag("osint", false) == 0;
let forcePrivate = true;
let resolvedInfo;
if (!lazy.PrivateBrowsingUtils.enabled) {
// Load about:privatebrowsing in a normal tab, which will display an error indicating
// access to private browsing has been disabled.
forcePrivate = false;
resolvedInfo = {
uri: Services.io.newURI("about:privatebrowsing"),
principal: lazy.gSystemPrincipal,
};
} else if (url?.startsWith("firefox-private-bridge:")) {
cmdLine.removeArguments(urlFlagIdx, urlFlagIdx + 1);
resolvedInfo = resolveURIInternal(
cmdLine,
url,
launchedWithArg_osint
);
} else {
resolvedInfo = resolveURIInternal(
cmdLine,
privateWindowParam,
launchedWithArg_osint
);
}
handURIToExistingBrowser(
resolvedInfo.uri,
Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
cmdLine,
forcePrivate,
resolvedInfo.principal
);
cmdLine.preventDefault = true;
}
} catch (e) {
if (e.result != Cr.NS_ERROR_INVALID_ARG) {
throw e;
}
// NS_ERROR_INVALID_ARG is thrown when flag exists, but has no param.
if (cmdLine.handleFlag("private-window", false)) {
openBrowserWindow(
cmdLine,
lazy.gSystemPrincipal,
"about:privatebrowsing",
null,
lazy.PrivateBrowsingUtils.enabled
);
cmdLine.preventDefault = true;
}
}
var searchParam = cmdLine.handleFlagWithParam("search", false);
if (searchParam) {
doSearch(searchParam, cmdLine);
cmdLine.preventDefault = true;
}
// The global PB Service consumes this flag, so only eat it in per-window
// PB builds.
if (
cmdLine.handleFlag("private", false) &&
lazy.PrivateBrowsingUtils.enabled
) {
lazy.PrivateBrowsingUtils.enterTemporaryAutoStartMode();
if (cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH) {
let win = Services.wm.getMostRecentWindow("navigator:blank");
if (win) {
win.docShell.QueryInterface(
Ci.nsILoadContext
).usePrivateBrowsing = true;
}
}
}
if (cmdLine.handleFlag("setDefaultBrowser", false)) {
// Note that setDefaultBrowser is an async function, but "handle" (the method being executed)
// is an implementation of an interface method and changing it to be async would be complicated
// and ultimately nothing here needs the result of setDefaultBrowser, so we do not bother doing
// an await.
lazy.ShellService.setDefaultBrowser(true).catch(e => {
console.error("setDefaultBrowser failed:", e);
});
}
if (cmdLine.handleFlag("first-startup", false)) {
// We don't want subsequent calls to needHompageOverride to have different
// values because the milestones in prefs got updated, so we intentionally
// tell needHomepageOverride to leave the milestone prefs alone when doing
// this check.
let override = needHomepageOverride(false /* updateMilestones */);
lazy.FirstStartup.init(override == OVERRIDE_NEW_PROFILE /* newProfile */);
}
var fileParam = cmdLine.handleFlagWithParam("file", false);
if (fileParam) {
var file = cmdLine.resolveFile(fileParam);
var fileURI = Services.io.newFileURI(file);
openBrowserWindow(cmdLine, lazy.gSystemPrincipal, fileURI.spec);
cmdLine.preventDefault = true;
}
if (AppConstants.platform == "win") {
// Handle "? searchterm" for Windows Vista start menu integration
for (var i = cmdLine.length - 1; i >= 0; --i) {
var param = cmdLine.getArgument(i);
if (param.match(/^\? /)) {
cmdLine.removeArguments(i, i);
cmdLine.preventDefault = true;
searchParam = param.substr(2);
doSearch(searchParam, cmdLine);
}
}
}
},
get helpInfo() {
let info =
" --browser Open a browser window.\n" +
" --new-window <url> Open <url> in a new window.\n" +
" --new-tab <url> Open <url> in a new tab.\n" +
" --private-window <url> Open <url> in a new private window.\n";
if (AppConstants.platform == "win") {
info += " --preferences Open Options dialog.\n";
} else {
info += " --preferences Open Preferences dialog.\n";
}
info +=
" --screenshot [<path>] Save screenshot to <path> or in working directory.\n";
info +=
" --window-size width[,height] Width and optionally height of screenshot.\n";
info +=
" --search <term> Search <term> with your default search engine.\n";
info += " --setDefaultBrowser Set this app as the default browser.\n";
info +=
" --first-startup Run post-install actions before opening a new window.\n";
info += " --kiosk Start the browser in kiosk mode.\n";
info +=
" --kiosk-monitor <num> Place kiosk browser window on given monitor.\n";
info +=
" --disable-pinch Disable touch-screen and touch-pad pinch gestures.\n";
return info;
},
/* nsIBrowserHandler */
get defaultArgs() {
return this.getArgs();
},
getArgs(isStartup = false) {
var prefb = Services.prefs;
if (!gFirstWindow) {
gFirstWindow = true;
if (lazy.PrivateBrowsingUtils.isInTemporaryAutoStartMode) {
return "about:privatebrowsing";
}
}
var override;
var overridePage = "";
var additionalPage = "";
var willRestoreSession = false;
try {
// Read the old value of homepage_override.mstone before
// needHomepageOverride updates it, so that we can later add it to the
// URL if we do end up showing an overridePage. This makes it possible
// to have the overridePage's content vary depending on the version we're
// upgrading from.
let old_mstone = Services.prefs.getCharPref(
"browser.startup.homepage_override.mstone",
"unknown"
);
let old_buildId = Services.prefs.getCharPref(
"browser.startup.homepage_override.buildID",
"unknown"
);
override = needHomepageOverride();
if (override != OVERRIDE_NONE) {
switch (override) {
case OVERRIDE_NEW_PROFILE:
// New profile.
gFirstRunProfile = true;
if (lazy.NimbusFeatures.aboutwelcome.getVariable("showModal")) {
break;
}
overridePage = Services.urlFormatter.formatURLPref(
"startup.homepage_welcome_url"
);
additionalPage = Services.urlFormatter.formatURLPref(
"startup.homepage_welcome_url.additional"
);
// Turn on 'later run' pages for new profiles.
lazy.LaterRun.enable(lazy.LaterRun.ENABLE_REASON_NEW_PROFILE);
break;
case OVERRIDE_NEW_MSTONE: {
// Check whether we will restore a session. If we will, we assume
// that this is an "update" session. This does not take crashes
// into account because that requires waiting for the session file
// to be read. If a crash occurs after updating, before restarting,
// we may open the startPage in addition to restoring the session.
willRestoreSession =
lazy.SessionStartup.isAutomaticRestoreEnabled();
overridePage = Services.urlFormatter.formatURLPref(
"startup.homepage_override_url"
);
let update = lazy.UpdateManager.readyUpdate;
/** If the override URL is provided by an experiment, is a valid
* Firefox What's New Page URL, and the update version is less than
* or equal to the maxVersion set by the experiment, we'll try to use
* the experiment override URL instead of the default or the
* update-provided URL. Additional policy checks are done in
* @see getPostUpdateOverridePage */
const nimbusOverrideUrl = Services.urlFormatter.formatURLPref(
"startup.homepage_override_url_nimbus"
);
const maxVersion = Services.prefs.getCharPref(
"startup.homepage_override_nimbus_maxVersion",
""
);
let nimbusWNP;
// Update version should be less than or equal to maxVersion set by
// the experiment
if (
nimbusOverrideUrl &&
Services.vc.compare(update.appVersion, maxVersion) <= 0
) {
try {
let uri = Services.io.newURI(nimbusOverrideUrl);
// Only allow https://www.mozilla.org and https://www.mozilla.com
if (
uri.scheme === "https" &&
["www.mozilla.org", "www.mozilla.com"].includes(uri.host)
) {
nimbusWNP = uri.spec;
} else {
throw new Error("Bad URL");
}
} catch {
console.error("Invalid WNP URL: ", nimbusOverrideUrl);
}
}
if (
update &&
Services.vc.compare(update.appVersion, old_mstone) > 0
) {
overridePage = getPostUpdateOverridePage(
update,
overridePage,
nimbusWNP
);
// Record a Nimbus exposure event for the whatsNewPage feature.
// The override page could be set in 3 ways: 1. set by Nimbus 2.
// set by the update file(openURL) 3. The default evergreen page(Set by the
// startup.homepage_override_url pref, could be different
// depending on the Fx channel). This is done to record that the
// control cohort could have seen the experimental What's New Page
// (and will instead see the default What's New Page).
// recordExposureEvent only records an event if the user is
// enrolled in an experiment or rollout on the whatsNewPage
// feature, so it's safe to call it unconditionally.
if (overridePage) {
let nimbusWNPFeature = lazy.NimbusFeatures.whatsNewPage;
nimbusWNPFeature
.ready()
.then(() => nimbusWNPFeature.recordExposureEvent());
}
// Send the update ping to signal that the update was successful.
lazy.UpdatePing.handleUpdateSuccess(old_mstone, old_buildId);
lazy.LaterRun.enable(lazy.LaterRun.ENABLE_REASON_UPDATE_APPLIED);
}
overridePage = overridePage.replace("%OLD_VERSION%", old_mstone);
break;
}
case OVERRIDE_NEW_BUILD_ID:
if (lazy.UpdateManager.readyUpdate) {
// Send the update ping to signal that the update was successful.
lazy.UpdatePing.handleUpdateSuccess(old_mstone, old_buildId);
lazy.LaterRun.enable(lazy.LaterRun.ENABLE_REASON_UPDATE_APPLIED);
}
break;
}
}
} catch (ex) {}
// formatURLPref might return "about:blank" if getting the pref fails
if (overridePage == "about:blank") {
overridePage = "";
}
// Allow showing a one-time startup override if we're not showing one
if (isStartup && overridePage == "" && prefb.prefHasUserValue(ONCE_PREF)) {
try {
// Show if we haven't passed the expiration or there's no expiration
const { expire, url } = JSON.parse(
Services.urlFormatter.formatURLPref(ONCE_PREF)
);
if (!(Date.now() > expire)) {
// Only set allowed urls as override pages
overridePage = url
.split("|")
.map(val => {
try {
return new URL(val);
} catch (ex) {
// Invalid URL, so filter out below
console.error("Invalid once url:", ex);
return null;
}
})
.filter(
parsed =>
parsed &&
parsed.protocol == "https:" &&
// Only accept exact hostname or subdomain; without port
ONCE_DOMAINS.includes(
Services.eTLD.getBaseDomainFromHost(parsed.host)
)
)
.join("|");
// Be noisy as properly configured urls should be unchanged
if (overridePage != url) {
console.error(`Mismatched once urls: ${url}`);
}
}
} catch (ex) {
// Invalid json pref, so ignore (and clear below)
console.error("Invalid once pref:", ex);
} finally {
prefb.clearUserPref(ONCE_PREF);
}
}
if (!additionalPage) {
additionalPage = lazy.LaterRun.getURL() || "";
}
if (additionalPage && additionalPage != "about:blank") {
if (overridePage) {
overridePage += "|" + additionalPage;
} else {
overridePage = additionalPage;
}
}
var startPage = "";
try {
var choice = prefb.getIntPref("browser.startup.page");
if (choice == 1 || choice == 3) {
startPage = lazy.HomePage.get();
}
} catch (e) {
console.error(e);
}
if (startPage == "about:blank") {
startPage = "";
}
let skipStartPage =
override == OVERRIDE_NEW_PROFILE &&
prefb.getBoolPref("browser.startup.firstrunSkipsHomepage");
// Only show the startPage if we're not restoring an update session and are
// not set to skip the start page on this profile
if (overridePage && startPage && !willRestoreSession && !skipStartPage) {
return overridePage + "|" + startPage;
}
return overridePage || startPage || "about:blank";
},
mFeatures: null,
getFeatures: function bch_features(cmdLine) {
if (this.mFeatures === null) {
this.mFeatures = "";
if (cmdLine) {
try {