BrowserContentHandler.jsm 30.7 KB
Newer Older
1
2
3
/* 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/. */
4

5
6
var EXPORTED_SYMBOLS = ["nsBrowserContentHandler", "nsDefaultCommandLineHandler"];

7
8
9
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
10

11
12
13
XPCOMUtils.defineLazyModuleGetters(this, {
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
  HeadlessShell: "resource:///modules/HeadlessShell.jsm",
14
  HomePage: "resource:///modules/HomePage.jsm",
15
16
  LaterRun: "resource:///modules/LaterRun.jsm",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
17
  SessionStartup: "resource:///modules/sessionstore/SessionStartup.jsm",
18
  ShellService: "resource:///modules/ShellService.jsm",
19
  UpdatePing: "resource://gre/modules/UpdatePing.jsm",
20
  RemotePages: "resource://gre/modules/remotepagemanager/RemotePageManagerParent.jsm",
21
});
22
XPCOMUtils.defineLazyServiceGetter(this, "WindowsUIUtils",
23
  "@mozilla.org/windows-ui-utils;1", "nsIWindowsUIUtils");
24

25
26
XPCOMUtils.defineLazyGetter(this, "gSystemPrincipal",
  () => Services.scriptSecurityManager.getSystemPrincipal());
27
XPCOMUtils.defineLazyGlobalGetters(this, [URL]);
28

29
30
const NEWINSTALL_PAGE = "about:newinstall";

31
32
33
34
35
function shouldLoadURI(aURI) {
  if (aURI && !aURI.schemeIs("chrome"))
    return true;

  dump("*** Preventing external load of chrome: URI into browser window\n");
36
  dump("    Use --chrome <uri> instead\n");
37
38
39
40
  return false;
}

function resolveURIInternal(aCmdLine, aArgument) {
41
  var uri = aCmdLine.resolveURI(aArgument);
42
  var uriFixup = Services.uriFixup;
43

44
  if (!(uri instanceof Ci.nsIFileURL)) {
45
46
    return uriFixup.createFixupURI(aArgument,
                                   uriFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS);
47
48
49
50
51
  }

  try {
    if (uri.file.exists())
      return uri;
52
  } catch (e) {
53
    Cu.reportError(e);
54
55
56
57
  }

  // We have interpreted the argument as a relative file URI, but the file
  // doesn't exist. Try URI fixup heuristics: see bug 290782.
58

59
  try {
60
    uri = uriFixup.createFixupURI(aArgument, 0);
61
  } catch (e) {
62
    Cu.reportError(e);
63
64
65
66
67
  }

  return uri;
}

68
69
let gRemoteInstallPage = null;

70
function getNewInstallPage() {
71
72
73
74
75
  if (!gRemoteInstallPage) {
    gRemoteInstallPage = new RemotePages(NEWINSTALL_PAGE);
  }

  return NEWINSTALL_PAGE;
76
77
}

78
79
var gFirstWindow = false;

80
81
82
const OVERRIDE_NONE        = 0;
const OVERRIDE_NEW_PROFILE = 1;
const OVERRIDE_NEW_MSTONE  = 2;
83
const OVERRIDE_NEW_BUILD_ID = 3;
84
const OVERRIDE_ALTERNATE_PROFILE = 4;
85
86
87
88
89
90
/**
 * Determines whether a home page override is needed.
 * Returns:
 *  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).
91
92
 *  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).
93
94
 *  OVERRIDE_NONE otherwise.
 */
95
function needHomepageOverride(prefb) {
96
97
98
99
100
  let pService = Cc["@mozilla.org/toolkit/profile-service;1"].
                 getService(Ci.nsIToolkitProfileService);
  if (pService.createdAlternateProfile) {
    return OVERRIDE_ALTERNATE_PROFILE;
  }
101
  var savedmstone = prefb.getCharPref("browser.startup.homepage_override.mstone", "");
102

103
  if (savedmstone == "ignore")
104
    return OVERRIDE_NONE;
105

106
  var mstone = Services.appinfo.platformVersion;
107

108
  var savedBuildID = prefb.getCharPref("browser.startup.homepage_override.buildID", "");
109

110
  var buildID = Services.appinfo.platformBuildID;
111

112
  if (mstone != savedmstone) {
113
114
115
116
117
118
    // 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)
      prefb.setBoolPref("browser.rights.3.shown", true);
119

120
    prefb.setCharPref("browser.startup.homepage_override.mstone", mstone);
121
    prefb.setCharPref("browser.startup.homepage_override.buildID", buildID);
122
    return (savedmstone ? OVERRIDE_NEW_MSTONE : OVERRIDE_NEW_PROFILE);
123
  }
124

125
126
127
128
129
  if (buildID != savedBuildID) {
    prefb.setCharPref("browser.startup.homepage_override.buildID", buildID);
    return OVERRIDE_NEW_BUILD_ID;
  }

130
  return OVERRIDE_NONE;
131
132
}

133
134
135
136
137
138
139
140
/**
 * Gets the override page for the first run after the application has been
 * updated.
 * @param  defaultOverridePage
 *         The default override page.
 * @return The override page.
 */
function getPostUpdateOverridePage(defaultOverridePage) {
141
142
  var um = Cc["@mozilla.org/updates/update-manager;1"]
             .getService(Ci.nsIUpdateManager);
143
144
145
146
147
  // The active update should be present when this code is called. If for
  // whatever reason it isn't fallback to the latest update in the update
  // history.
  if (um.activeUpdate) {
    var update = um.activeUpdate
148
                   .QueryInterface(Ci.nsIWritablePropertyBag);
149
150
151
152
  } else {
    // If the updates.xml file is deleted then getUpdateAt will throw.
    try {
      update = um.getUpdateAt(0)
153
                 .QueryInterface(Ci.nsIWritablePropertyBag);
154
    } catch (e) {
155
      Cu.reportError("Unable to find update: " + e);
156
157
      return defaultOverridePage;
    }
158
159
160
161
162
163
164
165
166
167
  }

  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.
168
  if (actions.includes("silent") || !actions.includes("showURL"))
169
170
    return "";

171
172
173
174
175
176
177
  // 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;
  }

178
179
180
  return update.getProperty("openURL") || defaultOverridePage;
}

181
182
/**
 * Open a browser window. If this is the initial launch, this function will
183
 * attempt to use the navigator:blank window opened by BrowserGlue.jsm during
184
185
186
187
188
189
 * 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.
190
191
 * @param triggeringPrincipal
 *        The nsIPrincipal to use as triggering principal for the page load(s).
192
193
194
195
196
197
198
199
200
201
202
203
204
 * @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.
 */
205
function openBrowserWindow(cmdLine, triggeringPrincipal, urlOrUrlList, postData = null,
206
                           forcePrivate = false) {
207
  let chromeURL = AppConstants.BROWSER_CHROME_URL;
208

209
210
  let args;
  if (!urlOrUrlList) {
211
    // Just pass in the defaultArgs directly. We'll use system principal on the other end.
212
    args = [gBrowserContentHandler.defaultArgs];
213
  } else {
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
    let pService = Cc["@mozilla.org/toolkit/profile-service;1"].
                  getService(Ci.nsIToolkitProfileService);
    if (cmdLine && cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH &&
        pService.createdAlternateProfile) {
      let url = getNewInstallPage();
      if (Array.isArray(urlOrUrlList)) {
        urlOrUrlList.unshift(url);
      } else {
        urlOrUrlList = [url, urlOrUrlList];
      }
    }

    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(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 {
      // 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,
              null, // charset
              null, // referer
              postData,
              undefined, // allowThirdPartyFixup; this would be `false` but that
                         // needs a conversion. Hopefully bug 1485961 will fix.
              undefined, // referrer policy
              undefined, // user context id
              null, // origin principal
              triggeringPrincipal];
    }
257
  }
258

259
  if (cmdLine && cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH) {
260
261
262
263
264
265
266
    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) {
267
        win.docShell
268
269
270
271
272
273
           .QueryInterface(Ci.nsILoadContext)
           .usePrivateBrowsing = true;
      }

      win.location = chromeURL;
      win.arguments = args; // <-- needs to be a plain JS array here.
274

275
276
277
278
279
280
281
282
283
284
      return;
    }
  }

  // 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"]
285
             .createInstance(Ci.nsISupportsString);
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    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;
  }

  let features = "chrome,dialog=no,all" + gBrowserContentHandler.getFeatures(cmdLine);
  if (forcePrivate)
    features += ",private";

  Services.ww.openWindow(null, chromeURL, "_blank", features, args);
305
306
}

307
function openPreferences(cmdLine, extraArgs) {
308
309
310
311
312
  if (extraArgs && extraArgs.origin) {
    Services.telemetry.getHistogramById("FX_PREFERENCES_OPENED_VIA").add(extraArgs.origin);
  } else {
    Services.telemetry.getHistogramById("FX_PREFERENCES_OPENED_VIA").add("other");
  }
313
  openBrowserWindow(cmdLine, gSystemPrincipal, "about:preferences");
314
315
}

316
317
function doSearch(searchTerm, cmdLine) {
  var engine = Services.search.defaultEngine;
318
319
320
321
322
  var countId = (engine.identifier || ("other-" + engine.name)) + ".system";
  var count = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
  count.add(countId);

  var submission = engine.getSubmission(searchTerm, null, "system");
323
324
325

  // XXXbsmedberg: use handURIToExistingBrowser to obey tabbed-browsing
  // preferences, but need nsIBrowserDOMWindow extensions
326
  openBrowserWindow(cmdLine, gSystemPrincipal, submission.uri.spec, submission.postData);
327
328
}

329
function nsBrowserContentHandler() {
330
331
332
333
  if (!gBrowserContentHandler) {
    gBrowserContentHandler = this;
  }
  return gBrowserContentHandler;
334
335
}
nsBrowserContentHandler.prototype = {
336
  /* nsISupports */
337
338
339
340
  QueryInterface: ChromeUtils.generateQI([Ci.nsICommandLineHandler,
                                          Ci.nsIBrowserHandler,
                                          Ci.nsIContentHandler,
                                          Ci.nsICommandLineValidator]),
341
342

  /* nsICommandLineHandler */
343
  handle: function bch_handle(cmdLine) {
344
    if (cmdLine.handleFlag("browser", false)) {
345
      openBrowserWindow(cmdLine, gSystemPrincipal);
346
347
348
      cmdLine.preventDefault = true;
    }

349
350
351
352
353
354
355
356
    // In the past, when an instance was not already running, the -remote
    // option returned an error code. Any script or application invoking the
    // -remote option is expected to be handling this case, otherwise they
    // wouldn't be doing anything when there is no Firefox already running.
    // Making the -remote option always return an error code makes those
    // scripts or applications handle the situation as if Firefox was not
    // already running.
    if (cmdLine.handleFlag("remote", true)) {
357
      throw Cr.NS_ERROR_ABORT;
358
359
    }

360
    var uriparam;
361
    try {
362
      while ((uriparam = cmdLine.handleFlagWithParam("new-window", false))) {
363
        let uri = resolveURIInternal(cmdLine, uriparam);
364
365
        if (!shouldLoadURI(uri))
          continue;
366
        openBrowserWindow(cmdLine, gSystemPrincipal, uri.spec);
367
368
        cmdLine.preventDefault = true;
      }
369
    } catch (e) {
370
      Cu.reportError(e);
371
372
    }

373
374
    try {
      while ((uriparam = cmdLine.handleFlagWithParam("new-tab", false))) {
375
        let uri = resolveURIInternal(cmdLine, uriparam);
376
377
        handURIToExistingBrowser(uri, Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
                                 cmdLine, false,
378
                                 gSystemPrincipal);
379
380
        cmdLine.preventDefault = true;
      }
381
    } catch (e) {
382
      Cu.reportError(e);
383
384
    }

385
386
    var chromeParam = cmdLine.handleFlagWithParam("chrome", false);
    if (chromeParam) {
387
388
      // Handle old preference dialog URLs.
      if (chromeParam == "chrome://browser/content/pref/pref.xul" ||
389
          chromeParam == "chrome://browser/content/preferences/preferences.xul") {
390
        openPreferences(cmdLine, {origin: "commandLineLegacy"});
391
392
        cmdLine.preventDefault = true;
      } else try {
393
394
        let resolvedURI = resolveURIInternal(cmdLine, chromeParam);
        let isLocal = uri => {
395
          let localSchemes = new Set(["chrome", "file", "resource"]);
396
397
          if (uri instanceof Ci.nsINestedURI) {
            uri = uri.QueryInterface(Ci.nsINestedURI).innerMostURI;
398
399
400
          }
          return localSchemes.has(uri.scheme);
        };
401
        if (isLocal(resolvedURI)) {
402
          // If the URI is local, we are sure it won't wrongly inherit chrome privs
403
          let features = "chrome,dialog=no,all" + this.getFeatures(cmdLine);
404
405
406
407
408
409
          // 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);
410
          cmdLine.preventDefault = true;
411
412
413
        } else {
          dump("*** Preventing load of web URI as chrome\n");
          dump("    If you're trying to load a webpage, do not pass --chrome.\n");
414
        }
415
      } catch (e) {
416
        Cu.reportError(e);
417
418
419
      }
    }
    if (cmdLine.handleFlag("preferences", false)) {
420
      openPreferences(cmdLine, {origin: "commandLineLegacy"});
421
422
      cmdLine.preventDefault = true;
    }
423
424
    if (cmdLine.handleFlag("silent", false))
      cmdLine.preventDefault = true;
425
426
427
428

    try {
      var privateWindowParam = cmdLine.handleFlagWithParam("private-window", false);
      if (privateWindowParam) {
429
430
431
432
433
434
435
436
437
438
        let forcePrivate = true;
        let resolvedURI;
        if (!PrivateBrowsingUtils.enabled) {
          // Load about:privatebrowsing in a normal tab, which will display an error indicating
          // access to private browsing has been disabled.
          forcePrivate = false;
          resolvedURI = Services.io.newURI("about:privatebrowsing");
        } else {
          resolvedURI = resolveURIInternal(cmdLine, privateWindowParam);
        }
439
        handURIToExistingBrowser(resolvedURI, Ci.nsIBrowserDOMWindow.OPEN_NEWTAB,
440
                                 cmdLine, forcePrivate, gSystemPrincipal);
441
        cmdLine.preventDefault = true;
442
      }
443
    } catch (e) {
444
      if (e.result != Cr.NS_ERROR_INVALID_ARG) {
445
446
        throw e;
      }
447
448
      // NS_ERROR_INVALID_ARG is thrown when flag exists, but has no param.
      if (cmdLine.handleFlag("private-window", false)) {
449
        openBrowserWindow(cmdLine, gSystemPrincipal, "about:privatebrowsing", null,
450
                          PrivateBrowsingUtils.enabled);
451
452
        cmdLine.preventDefault = true;
      }
453
    }
454
455
456
457
458
459
460

    var searchParam = cmdLine.handleFlagWithParam("search", false);
    if (searchParam) {
      doSearch(searchParam, cmdLine);
      cmdLine.preventDefault = true;
    }

461
462
    // The global PB Service consumes this flag, so only eat it in per-window
    // PB builds.
463
    if (cmdLine.handleFlag("private", false) && PrivateBrowsingUtils.enabled) {
464
      PrivateBrowsingUtils.enterTemporaryAutoStartMode();
465
      if (cmdLine.state == Ci.nsICommandLine.STATE_INITIAL_LAUNCH) {
466
467
        let win = Services.wm.getMostRecentWindow("navigator:blank");
        if (win) {
468
          win.docShell
469
470
471
472
             .QueryInterface(Ci.nsILoadContext)
             .usePrivateBrowsing = true;
        }
      }
473
    }
474
475
476
    if (cmdLine.handleFlag("setDefaultBrowser", false)) {
      ShellService.setDefaultBrowser(true, true);
    }
477

478
479
480
    var fileParam = cmdLine.handleFlagWithParam("file", false);
    if (fileParam) {
      var file = cmdLine.resolveFile(fileParam);
481
      var fileURI = Services.io.newFileURI(file);
482
      openBrowserWindow(cmdLine, gSystemPrincipal, fileURI.spec);
483
484
485
      cmdLine.preventDefault = true;
    }

486
    if (AppConstants.platform == "win") {
487
488
489
490
491
492
      // 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;
493

494
495
496
          searchParam = param.substr(2);
          doSearch(searchParam, cmdLine);
        }
497
498
      }
    }
499
500
  },

501
502
503
504
505
506
507
508
509
510
511
  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";
    }
512
513
    info += "  --screenshot [<path>] Save screenshot to <path> or in working directory.\n";
    info += "  --window-size width[,height] Width and optionally height of screenshot.\n";
514
    info += "  --search <term>    Search <term> with your default search engine.\n";
515
    info += "  --setDefaultBrowser Set this app as the default browser.\n";
516
517
    return info;
  },
518
519
520

  /* nsIBrowserHandler */

521
  get defaultArgs() {
522
    var prefb = Services.prefs;
523

524
525
526
527
528
529
530
    if (!gFirstWindow) {
      gFirstWindow = true;
      if (PrivateBrowsingUtils.isInTemporaryAutoStartMode) {
        return "about:privatebrowsing";
      }
    }

531
    var override;
532
    var overridePage = "";
533
    var additionalPage = "";
534
    var willRestoreSession = false;
535
    try {
536
537
538
539
540
      // 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.
541
      let old_mstone = Services.prefs.getCharPref("browser.startup.homepage_override.mstone", "unknown");
542
      let old_buildId = Services.prefs.getCharPref("browser.startup.homepage_override.buildID", "unknown");
543
      override = needHomepageOverride(prefb);
544
545
      if (override != OVERRIDE_NONE) {
        switch (override) {
546
547
548
549
550
551
          case OVERRIDE_ALTERNATE_PROFILE:
            // Override the welcome page to explain why the user has a new
            // profile. nsBrowserGlue.css will be responsible for showing the
            // modal dialog.
            overridePage = getNewInstallPage();
            break;
552
553
          case OVERRIDE_NEW_PROFILE:
            // New profile.
554
            overridePage = Services.urlFormatter.formatURLPref("startup.homepage_welcome_url");
555
            additionalPage = Services.urlFormatter.formatURLPref("startup.homepage_welcome_url.additional");
556
557
            // Turn on 'later run' pages for new profiles.
            LaterRun.enabled = true;
558
559
            break;
          case OVERRIDE_NEW_MSTONE:
560
561
562
563
564
            // 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.
565
            willRestoreSession = SessionStartup.isAutomaticRestoreEnabled();
566

567
            overridePage = Services.urlFormatter.formatURLPref("startup.homepage_override_url");
568
            if (prefb.prefHasUserValue("app.update.postupdate")) {
569
              overridePage = getPostUpdateOverridePage(overridePage);
570
571
572
              // Send the update ping to signal that the update was successful.
              UpdatePing.handleUpdateSuccess(old_mstone, old_buildId);
            }
573
574

            overridePage = overridePage.replace("%OLD_VERSION%", old_mstone);
575
            break;
576
577
578
579
580
581
          case OVERRIDE_NEW_BUILD_ID:
            if (prefb.prefHasUserValue("app.update.postupdate")) {
              // Send the update ping to signal that the update was successful.
              UpdatePing.handleUpdateSuccess(old_mstone, old_buildId);
            }
            break;
582
        }
583
      }
584
    } catch (ex) {}
585

586
587
588
    // formatURLPref might return "about:blank" if getting the pref fails
    if (overridePage == "about:blank")
      overridePage = "";
589

590
591
    if (!additionalPage) {
      additionalPage = LaterRun.getURL() || "";
592
593
    }

594
595
596
597
598
599
600
601
    if (additionalPage && additionalPage != "about:blank") {
      if (overridePage) {
        overridePage += "|" + additionalPage;
      } else {
        overridePage = additionalPage;
      }
    }

602
    var startPage = "";
603
604
    try {
      var choice = prefb.getIntPref("browser.startup.page");
605
      if (choice == 1 || choice == 3)
606
        startPage = HomePage.get();
607
    } catch (e) {
608
      Cu.reportError(e);
609
    }
610

611
612
    if (startPage == "about:blank")
      startPage = "";
613

614
    let skipStartPage = ((override == OVERRIDE_NEW_PROFILE) || (override == OVERRIDE_ALTERNATE_PROFILE)) &&
615
616
617
618
      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)
619
      return overridePage + "|" + startPage;
620

621
    return overridePage || startPage || "about:blank";
622
623
  },

624
  mFeatures: null,
625

626
  getFeatures: function bch_features(cmdLine) {
627
628
629
    if (this.mFeatures === null) {
      this.mFeatures = "";

630
631
632
633
      if (cmdLine) {
        try {
          var width = cmdLine.handleFlagWithParam("width", false);
          var height = cmdLine.handleFlagWithParam("height", false);
634

635
636
637
638
639
640
          if (width)
            this.mFeatures += ",width=" + width;
          if (height)
            this.mFeatures += ",height=" + height;
        } catch (e) {
        }
641
      }
642
643
644
645

      // The global PB Service consumes this flag, so only eat it in per-window
      // PB builds.
      if (PrivateBrowsingUtils.isInTemporaryAutoStartMode) {
646
647
648
649
650
651
        this.mFeatures += ",private";
      }

      if (Services.prefs.getBoolPref("browser.suppress_first_window_animation") &&
          !Services.wm.getMostRecentWindow("navigator:browser")) {
        this.mFeatures += ",suppressanimation";
652
      }
653
654
655
656
657
658
659
    }

    return this.mFeatures;
  },

  /* nsIContentHandler */

660
  handleContent: function bch_handleContent(contentType, context, request) {
661
662
    const NS_ERROR_WONT_HANDLE_CONTENT = 0x805d0001;

663
    try {
664
      var webNavInfo = Cc["@mozilla.org/webnavigation-info;1"]
665
                         .getService(Ci.nsIWebNavigationInfo);
666
667
668
      if (!webNavInfo.isTypeSupported(contentType, null)) {
        throw NS_ERROR_WONT_HANDLE_CONTENT;
      }
669
670
671
672
    } catch (e) {
      throw NS_ERROR_WONT_HANDLE_CONTENT;
    }

673
674
675
676
    request.QueryInterface(Ci.nsIChannel);
    handURIToExistingBrowser(request.URI, Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW,
                             null, false, request.loadInfo.triggeringPrincipal);
    request.cancel(Cr.NS_BINDING_ABORTED);
677
678
  },

679
  /* nsICommandLineValidator */
680
  validate: function bch_validate(cmdLine) {
681
682
683
684
685
    // Other handlers may use osint so only handle the osint flag if the url
    // flag is also present and the command line is valid.
    var osintFlagIdx = cmdLine.findFlag("osint", false);
    var urlFlagIdx = cmdLine.findFlag("url", false);
    if (urlFlagIdx > -1 && (osintFlagIdx > -1 ||
686
        cmdLine.state == Ci.nsICommandLine.STATE_REMOTE_EXPLICIT)) {
687
      var urlParam = cmdLine.getArgument(urlFlagIdx + 1);
688
      if (cmdLine.length != urlFlagIdx + 2 || /firefoxurl:/i.test(urlParam))
689
        throw Cr.NS_ERROR_ABORT;
690
691
692
693
694
      var isDefault = false;
      try {
        var url = Services.urlFormatter.formatURLPref("app.support.baseURL") +
                  "win10-default-browser";
        if (urlParam == url) {
695
          isDefault = ShellService.isDefaultBrowser(false, false);
696
697
698
699
700
        }
      } catch (ex) {}
      if (isDefault) {
        // Firefox is already the default HTTP handler.
        // We don't have to show the instruction page.
701
        throw Cr.NS_ERROR_ABORT;
702
      }
703
      cmdLine.handleFlag("osint", false);
704
705
    }
  },
706
};
707
var gBrowserContentHandler = new nsBrowserContentHandler();
708

709
function handURIToExistingBrowser(uri, location, cmdLine, forcePrivate, triggeringPrincipal) {
710
711
712
  if (!shouldLoadURI(uri))
    return;

713
714
715
  // Unless using a private window is forced, open external links in private
  // windows only if we're in perma-private mode.
  var allowPrivate = forcePrivate || PrivateBrowsingUtils.permanentPrivateBrowsing;
716
  var navWin = BrowserWindowTracker.getTopWindow({private: allowPrivate});
717
718
  if (!navWin) {
    // if we couldn't load it in an existing window, open a new one
719
    openBrowserWindow(cmdLine, triggeringPrincipal, uri.spec, null, forcePrivate);
720
721
722
    return;
  }

723
  var bwin = navWin.browserDOMWindow;
724
  bwin.openURI(uri, null, location,
725
               Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL, triggeringPrincipal);
726
727
}

728
function nsDefaultCommandLineHandler() {
729
730
731
}

nsDefaultCommandLineHandler.prototype = {
732
  /* nsISupports */
733
  QueryInterface: ChromeUtils.generateQI(["nsICommandLineHandler"]),
734

735
  _haveProfile: false,
736

737
  /* nsICommandLineHandler */
738
  handle: function dch_handle(cmdLine) {
739
740
    var urilist = [];

741
742
743
744
745
746
747
748
749
750
    if (AppConstants.platform == "win") {
      // If we don't have a profile selected yet (e.g. the Profile Manager is
      // displayed) we will crash if we open an url and then select a profile. To
      // prevent this handle all url command line flags and set the command line's
      // preventDefault to true to prevent the display of the ui. The initial
      // command line will be retained when nsAppRunner calls LaunchChild though
      // urls launched after the initial launch will be lost.
      if (!this._haveProfile) {
        try {
          // This will throw when a profile has not been selected.
751
          Services.dirsvc.get("ProfD", Ci.nsIFile);
752
          this._haveProfile = true;
753
        } catch (e) {
754
          while ((ar = cmdLine.handleFlagWithParam("url", false)));
755
756
          cmdLine.preventDefault = true;
        }
757
758
759
      }
    }

760
761
    try {
      var ar;
762
      while ((ar = cmdLine.handleFlagWithParam("url", false))) {
763
        var uri = resolveURIInternal(cmdLine, ar);
764
        urilist.push(uri);
765
      }
766
    } catch (e) {
767
      Cu.reportError(e);
768
769
    }

770
771
772
773
774
    if (cmdLine.findFlag("screenshot", true) != -1) {
      HeadlessShell.handleCmdLineArgs(cmdLine, urilist.filter(shouldLoadURI).map(u => u.spec));
      return;
    }

775
    for (let i = 0; i < cmdLine.length; ++i) {
776
777
      var curarg = cmdLine.getArgument(i);
      if (curarg.match(/^-/)) {
778
        Cu.reportError("Warning: unrecognized command line flag " + curarg + "\n");
779
780
781
782
783
        // To emulate the pre-nsICommandLine behavior, we ignore
        // the argument after an unrecognized flag.
        ++i;
      } else {
        try {
784
          urilist.push(resolveURIInternal(cmdLine, curarg));
785
        } catch (e) {
786
          Cu.reportError("Error opening URI '" + curarg + "' from the command line: " + e + "\n");
787
788
789
790
791
        }
      }
    }

    if (urilist.length) {
792
      if (cmdLine.state != Ci.nsICommandLine.STATE_INITIAL_LAUNCH &&
793
794
795
796
          urilist.length == 1) {
        // Try to find an existing window and load our URI into the
        // current tab, new tab, or new window as prefs determine.
        try {
797
          handURIToExistingBrowser(urilist[0], Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW,
798
                                   cmdLine, false, gSystemPrincipal);
799
          return;
800
        } catch (e) {
801
802
803
        }
      }

804
      var URLlist = urilist.filter(shouldLoadURI).map(u => u.spec);
805
      if (URLlist.length) {
806
        openBrowserWindow(cmdLine, gSystemPrincipal, URLlist);
807
      }
808
    } else if (!cmdLine.preventDefault) {
809
      if (AppConstants.isPlatformAndVersionAtLeast("win", "10") &&
810
          cmdLine.state != Ci.nsICommandLine.STATE_INITIAL_LAUNCH &&
811
812
          WindowsUIUtils.inTabletMode) {
        // In windows 10 tablet mode, do not create a new window, but reuse the existing one.
813
        let win = BrowserWindowTracker.getTopWindow();
814
815
816
817
818
        if (win) {
          win.focus();
          return;
        }
      }
819
      openBrowserWindow(cmdLine, gSystemPrincipal);
820
821
822
823
824
825
826
827
    } else {
      // Need a better solution in the future to avoid opening the blank window
      // when command line parameters say we are not going to show a browser
      // window, but for now the blank window getting closed quickly (and
      // causing only a slight flicker) is better than leaving it open.
      let win = Services.wm.getMostRecentWindow("navigator:blank");
      if (win)
        win.close();
828
829
830
    }
  },

831
  helpInfo: "",
832
};