summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/parent/ext-backgroundPage.js
blob: 568d049b9d8ff5f088042c2a70f866291df30f00 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var { ExtensionParent } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionParent.sys.mjs"
);
var {
  HiddenExtensionPage,
  promiseExtensionViewLoaded,
  watchExtensionWorkerContextLoaded,
} = ExtensionParent;

ChromeUtils.defineESModuleGetters(this, {
  ExtensionTelemetry: "resource://gre/modules/ExtensionTelemetry.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
});

XPCOMUtils.defineLazyGetter(this, "serviceWorkerManager", () => {
  return Cc["@mozilla.org/serviceworkers/manager;1"].getService(
    Ci.nsIServiceWorkerManager
  );
});

XPCOMUtils.defineLazyPreferenceGetter(
  this,
  "backgroundIdleTimeout",
  "extensions.background.idle.timeout",
  30000,
  null,
  // Minimum 100ms, max 5min
  delay => Math.min(Math.max(delay, 100), 5 * 60 * 1000)
);

// eslint-disable-next-line mozilla/reject-importGlobalProperties
Cu.importGlobalProperties(["DOMException"]);

function notifyBackgroundScriptStatus(addonId, isRunning) {
  // Notify devtools when the background scripts is started or stopped
  // (used to show the current status in about:debugging).
  const subject = { addonId, isRunning };
  Services.obs.notifyObservers(subject, "extension:background-script-status");
}

// Same as nsITelemetry msSinceProcessStartExcludingSuspend but returns
// undefined instead of throwing an extension.
function msSinceProcessStartExcludingSuspend() {
  let now;
  try {
    now = Services.telemetry.msSinceProcessStartExcludingSuspend();
  } catch (err) {
    Cu.reportError(err);
  }
  return now;
}

/**
 * Background Page state transitions:
 *
 *    ------> STOPPED <-------
 *    |         |            |
 *    |         v            |
 *    |      STARTING >------|
 *    |         |            |
 *    |         v            ^
 *    |----< RUNNING ----> SUSPENDING
 *              ^            v
 *              |------------|
 *
 * STARTING:   The background is being built.
 * RUNNING:    The background is running.
 * SUSPENDING: The background is suspending, runtime.onSuspend will be called.
 * STOPPED:    The background is not running.
 *
 * For persistent backgrounds, the SUSPENDING is not used.
 */
const BACKGROUND_STATE = {
  STARTING: "starting",
  RUNNING: "running",
  SUSPENDING: "suspending",
  STOPPED: "stopped",
};

// Responsible for the background_page section of the manifest.
class BackgroundPage extends HiddenExtensionPage {
  constructor(extension, options) {
    super(extension, "background");

    this.page = options.page || null;
    this.isGenerated = !!options.scripts;

    // Last background/event page created time (retrieved using
    // Services.telemetry.msSinceProcessStartExcludingSuspend when the
    // parent process proxy context has been created).
    this.msSinceCreated = null;

    if (this.page) {
      this.url = this.extension.baseURI.resolve(this.page);
    } else if (this.isGenerated) {
      this.url = this.extension.baseURI.resolve(
        "_generated_background_page.html"
      );
    }
  }

  async build() {
    const { extension } = this;
    ExtensionTelemetry.backgroundPageLoad.stopwatchStart(extension, this);

    let context;
    try {
      await this.createBrowserElement();
      if (!this.browser) {
        throw new Error(
          "Extension shut down before the background page was created"
        );
      }
      extension._backgroundPageFrameLoader = this.browser.frameLoader;

      extensions.emit("extension-browser-inserted", this.browser);

      let contextPromise = promiseExtensionViewLoaded(this.browser);
      this.browser.fixupAndLoadURIString(this.url, {
        triggeringPrincipal: extension.principal,
      });

      context = await contextPromise;

      this.msSinceCreated = msSinceProcessStartExcludingSuspend();

      ExtensionTelemetry.backgroundPageLoad.stopwatchFinish(extension, this);
    } catch (e) {
      // Extension was down before the background page has loaded.
      ExtensionTelemetry.backgroundPageLoad.stopwatchCancel(extension, this);
      throw e;
    }

    return context;
  }

  shutdown() {
    this.extension._backgroundPageFrameLoader = null;
    super.shutdown();
  }
}

// Responsible for the background.service_worker section of the manifest.
class BackgroundWorker {
  constructor(extension, options) {
    this.extension = extension;
    this.workerScript = options.service_worker;

    if (!this.workerScript) {
      throw new Error("Missing mandatory background.service_worker property");
    }
  }

  get registrationInfo() {
    const { principal } = this.extension;
    return serviceWorkerManager.getRegistrationForAddonPrincipal(principal);
  }

  getWorkerInfo(descriptorId) {
    return this.registrationInfo?.getWorkerByID(descriptorId);
  }

  validateWorkerInfoForContext(context) {
    const { extension } = this;
    if (!this.getWorkerInfo(context.workerDescriptorId)) {
      throw new Error(
        `ServiceWorkerInfo not found for ${extension.policy.debugName} contextId ${context.contextId}`
      );
    }
  }

  async build() {
    const { extension } = this;
    let context;
    const contextPromise = new Promise(resolve => {
      let unwatch = watchExtensionWorkerContextLoaded(
        { extension, viewType: "background_worker" },
        context => {
          unwatch();
          this.validateWorkerInfoForContext(context);
          resolve(context);
        }
      );
    });

    // TODO(Bug 17228327): follow up to spawn the active worker for a previously installed
    // background service worker.
    await serviceWorkerManager.registerForAddonPrincipal(
      this.extension.principal
    );

    context = await contextPromise;

    await this.waitForActiveWorker();
    return context;
  }

  shutdown(isAppShutdown) {
    // All service worker registrations related to the extensions will be unregistered
    // - when the extension is shutting down if the application is not also shutting down
    //   shutdown (in which case a previously registered service worker is expected to stay
    //   active across browser restarts).
    // - when the extension has been uninstalled
    if (!isAppShutdown) {
      this.registrationInfo?.forceShutdown();
    }
  }

  waitForActiveWorker() {
    const { extension, registrationInfo } = this;
    return new Promise((resolve, reject) => {
      const resolveOnActive = () => {
        if (
          registrationInfo.activeWorker?.state ===
          Ci.nsIServiceWorkerInfo.STATE_ACTIVATED
        ) {
          resolve();
          return true;
        }
        return false;
      };

      const rejectOnUnregistered = () => {
        if (registrationInfo.unregistered) {
          reject(
            new Error(
              `Background service worker unregistered for "${extension.policy.debugName}"`
            )
          );
          return true;
        }
        return false;
      };

      if (resolveOnActive() || rejectOnUnregistered()) {
        return;
      }

      const listener = {
        onChange() {
          if (resolveOnActive() || rejectOnUnregistered()) {
            registrationInfo.removeListener(listener);
          }
        },
      };
      registrationInfo.addListener(listener);
    });
  }
}

this.backgroundPage = class extends ExtensionAPI {
  async build() {
    if (this.bgInstance) {
      return;
    }

    let { extension } = this;
    let { manifest } = extension;
    extension.backgroundState = BACKGROUND_STATE.STARTING;

    this.isWorker =
      !!manifest.background.service_worker &&
      WebExtensionPolicy.backgroundServiceWorkerEnabled;

    let BackgroundClass = this.isWorker ? BackgroundWorker : BackgroundPage;

    this.bgInstance = new BackgroundClass(extension, manifest.background);
    let context;
    try {
      context = await this.bgInstance.build();
      // Top level execution already happened, RUNNING is
      // a touch after the fact.
      if (context && this.extension) {
        extension.backgroundState = BACKGROUND_STATE.RUNNING;
      }
    } catch (e) {
      Cu.reportError(e);
      if (extension.persistentListeners) {
        // Clear the primed listeners, but leave them persisted.
        EventManager.clearPrimedListeners(extension, false);
      }
      extension.backgroundState = BACKGROUND_STATE.STOPPED;
      extension.emit("background-script-aborted");
      return;
    }

    if (context) {
      // Wait until all event listeners registered by the script so far
      // to be handled. We then set listenerPromises to null, which indicates
      // to addListener that the background script has finished loading.
      await Promise.all(context.listenerPromises);
      context.listenerPromises = null;
    }

    if (extension.persistentListeners) {
      // |this.extension| may be null if the extension was shut down.
      // In that case, we still want to clear the primed listeners,
      // but not update the persistent listeners in the startupData.
      EventManager.clearPrimedListeners(extension, !!this.extension);
    }

    if (!context || !this.extension) {
      extension.backgroundState = BACKGROUND_STATE.STOPPED;
      extension.emit("background-script-aborted");
      return;
    }
    if (!context.unloaded) {
      notifyBackgroundScriptStatus(extension.id, true);
      context.callOnClose({
        close() {
          notifyBackgroundScriptStatus(extension.id, false);
        },
      });
    }

    extension.emit("background-script-started");
  }

  observe(subject, topic, data) {
    if (topic == "timer-callback") {
      let { extension } = this;
      this.clearIdleTimer();
      extension?.terminateBackground();
    }
  }

  clearIdleTimer() {
    this.backgroundTimer?.cancel();
    this.backgroundTimer = null;
  }

  resetIdleTimer() {
    this.clearIdleTimer();
    let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    timer.init(this, backgroundIdleTimeout, Ci.nsITimer.TYPE_ONE_SHOT);
    this.backgroundTimer = timer;
  }

  async primeBackground(isInStartup = true) {
    let { extension } = this;

    if (this.bgInstance) {
      Cu.reportError(`background script exists before priming ${extension.id}`);
    }
    this.bgInstance = null;

    // When in PPB background pages all run in a private context.  This check
    // simply avoids an extraneous error in the console since the BaseContext
    // will throw.
    if (
      PrivateBrowsingUtils.permanentPrivateBrowsing &&
      !extension.privateBrowsingAllowed
    ) {
      return;
    }

    // Used by runtime messaging to wait for background page listeners.
    let bgStartupPromise = new Promise(resolve => {
      let done = () => {
        extension.off("background-script-started", done);
        extension.off("background-script-aborted", done);
        extension.off("shutdown", done);
        resolve();
      };
      extension.on("background-script-started", done);
      extension.on("background-script-aborted", done);
      extension.on("shutdown", done);
    });

    extension.promiseBackgroundStarted = () => {
      return bgStartupPromise;
    };

    extension.wakeupBackground = () => {
      if (extension.hasShutdown) {
        return Promise.reject(
          new Error(
            "wakeupBackground called while the extension was already shutting down"
          )
        );
      }
      extension.emit("background-script-event");
      // `extension.wakeupBackground` is set back to the original arrow function
      // when the background page is terminated and `primeBackground` is called again.
      extension.wakeupBackground = () => bgStartupPromise;
      return bgStartupPromise;
    };

    let resetBackgroundIdle = (eventName, resetIdleDetails) => {
      this.clearIdleTimer();
      if (!this.extension || extension.persistentBackground) {
        // Extension was already shut down or is persistent and
        // does not idle timout.
        return;
      }
      // TODO remove at an appropriate point in the future prior
      // to general availability.  There may be some racy conditions
      // with idle timeout between an event starting and the event firing
      // but we still want testing with an idle timeout.
      if (
        !Services.prefs.getBoolPref("extensions.background.idle.enabled", true)
      ) {
        return;
      }

      if (extension.backgroundState == BACKGROUND_STATE.SUSPENDING) {
        extension.backgroundState = BACKGROUND_STATE.RUNNING;
        // call runtime.onSuspendCanceled
        extension.emit("background-script-suspend-canceled");
      }
      this.resetIdleTimer();

      if (
        eventName === "background-script-reset-idle" &&
        // TODO(Bug 1790087): record similar telemetry for background service worker.
        !this.isWorker
      ) {
        // Record the reason for resetting the event page idle timeout
        // in a idle result histogram, with the category set based
        // on the reason for resetting (defaults to 'reset_other'
        // if resetIdleDetails.reason is missing or not mapped into the
        // telemetry histogram categories).
        //
        // Keep this in sync with the categories listed in Histograms.json
        // for "WEBEXT_EVENTPAGE_IDLE_RESULT_COUNT".
        let category = "reset_other";
        switch (resetIdleDetails?.reason) {
          case "event":
            category = "reset_event";
            break;
          case "hasActiveNativeAppPorts":
            category = "reset_nativeapp";
            break;
          case "hasActiveStreamFilter":
            category = "reset_streamfilter";
            break;
          case "pendingListeners":
            category = "reset_listeners";
            break;
        }

        ExtensionTelemetry.eventPageIdleResult.histogramAdd({
          extension,
          category,
        });
      }
    };

    // Listen for events from the EventManager
    extension.on("background-script-reset-idle", resetBackgroundIdle);
    // After the background is started, initiate the first timer
    extension.once("background-script-started", resetBackgroundIdle);

    extension.terminateBackground = async ({
      ignoreDevToolsAttached = false,
      disableResetIdleForTest = false, // Disable all reset idle checks for testing purpose.
    } = {}) => {
      await bgStartupPromise;
      if (!this.extension || this.extension.hasShutdown) {
        // Extension was already shut down.
        return;
      }
      if (extension.backgroundState != BACKGROUND_STATE.RUNNING) {
        return;
      }

      if (
        !ignoreDevToolsAttached &&
        ExtensionParent.DebugUtils.hasDevToolsAttached(extension.id)
      ) {
        extension.emit("background-script-suspend-ignored");
        return;
      }

      // Similar to what happens in recent Chrome version for MV3 extensions, extensions non-persistent
      // background scripts with a nativeMessaging port still open or a sendNativeMessage request still
      // pending an answer are exempt from being terminated when the idle timeout expires.
      // The motivation, as for the similar change that Chrome applies to MV3 extensions, is that using
      // the native messaging API have already an higher barrier due to having to specify a native messaging
      // host app in their manifest and the user also have to install the native app separately as a native
      // application).
      if (
        !disableResetIdleForTest &&
        extension.backgroundContext?.hasActiveNativeAppPorts
      ) {
        extension.emit("background-script-reset-idle", {
          reason: "hasActiveNativeAppPorts",
        });
        return;
      }

      if (
        !disableResetIdleForTest &&
        extension.backgroundContext?.pendingRunListenerPromisesCount
      ) {
        extension.emit("background-script-reset-idle", {
          reason: "pendingListeners",
          pendingListeners:
            extension.backgroundContext.pendingRunListenerPromisesCount,
        });
        // Clear the pending promises being tracked when we have reset the idle
        // once because some where still pending, so that the pending listeners
        // calls can reset the idle timer only once.
        extension.backgroundContext.clearPendingRunListenerPromises();
        return;
      }

      const childId = extension.backgroundContext?.childId;
      if (
        childId !== undefined &&
        extension.hasPermission("webRequestBlocking") &&
        (extension.manifestVersion <= 3 ||
          extension.hasPermission("webRequestFilterResponse"))
      ) {
        // Ask to the background page context in the child process to check if there are
        // StreamFilter instances active (e.g. ones with status "transferringdata" or "suspended",
        // see StreamFilterStatus enum defined in StreamFilter.webidl).
        // TODO(Bug 1748533): consider additional changes to prevent a StreamFilter that never gets to an
        // inactive state from preventing an even page from being ever suspended.
        const hasActiveStreamFilter =
          await ExtensionParent.ParentAPIManager.queryStreamFilterSuspendCancel(
            extension.backgroundContext.childId
          ).catch(err => {
            // an AbortError raised from the JSWindowActor is expected if the background page was already been
            // terminated in the meantime, and so we only log the errors that don't match these particular conditions.
            if (
              extension.backgroundState == BACKGROUND_STATE.STOPPED &&
              DOMException.isInstance(err) &&
              err.name === "AbortError"
            ) {
              return false;
            }
            Cu.reportError(err);
            return false;
          });
        if (!disableResetIdleForTest && hasActiveStreamFilter) {
          extension.emit("background-script-reset-idle", {
            reason: "hasActiveStreamFilter",
          });
          return;
        }

        // Return earlier if extension have started or completed its shutdown in the meantime.
        if (
          extension.backgroundState !== BACKGROUND_STATE.RUNNING ||
          extension.hasShutdown
        ) {
          return;
        }
      }

      extension.backgroundState = BACKGROUND_STATE.SUSPENDING;
      this.clearIdleTimer();
      // call runtime.onSuspend
      await extension.emit("background-script-suspend");
      // If in the meantime another event fired, state will be RUNNING,
      // and if it was shutdown it will be STOPPED.
      if (extension.backgroundState != BACKGROUND_STATE.SUSPENDING) {
        return;
      }
      extension.off("background-script-reset-idle", resetBackgroundIdle);
      this.onShutdown(false);

      // TODO(Bug 1790087): record similar telemetry for background service worker.
      if (!this.isWorker) {
        ExtensionTelemetry.eventPageIdleResult.histogramAdd({
          extension,
          category: "suspend",
        });
      }

      EventManager.clearPrimedListeners(this.extension, false);
      // Setup background startup listeners for next primed event.
      await this.primeBackground(false);
    };

    // Persistent backgrounds are started immediately except during APP_STARTUP.
    // Non-persistent backgrounds must be started immediately for new install or enable
    // to initialize the addon and create the persisted listeners.
    // updateReason is set when an extension is updated during APP_STARTUP.
    if (
      isInStartup &&
      (extension.testNoDelayedStartup ||
        extension.startupReason !== "APP_STARTUP" ||
        extension.updateReason)
    ) {
      return this.build();
    }

    EventManager.primeListeners(extension, isInStartup);

    extension.once("start-background-script", async () => {
      if (!this.extension) {
        // Extension was shut down. Don't build the background page.
        // Primed listeners have been cleared in onShutdown.
        return;
      }
      await this.build();
    });

    // There are two ways to start the background page:
    // 1. If a primed event fires, then start the background page as
    //    soon as we have painted a browser window.  Note that we have
    //    to touch browserPaintedPromise here to initialize the listener
    //    or else we can miss it if the event occurs after the first
    //    window is painted but before #2
    // 2. After all windows have been restored on startup (see onManifestEntry).
    extension.once("background-script-event", async () => {
      await ExtensionParent.browserPaintedPromise;
      extension.emit("start-background-script");
    });
  }

  onShutdown(isAppShutdown) {
    this.extension.backgroundState = BACKGROUND_STATE.STOPPED;
    // Ensure there is no backgroundTimer running
    this.clearIdleTimer();

    if (this.bgInstance) {
      const { msSinceCreated } = this.bgInstance;
      this.bgInstance.shutdown(isAppShutdown);
      this.bgInstance = null;

      const { extension } = this;

      // Emit an event for tests.
      extension.emit("shutdown-background-script");

      const now = msSinceProcessStartExcludingSuspend();
      if (
        msSinceCreated &&
        now &&
        // TODO(Bug 1790087): record similar telemetry for background service worker.
        !(this.isWorker || extension.persistentBackground)
      ) {
        ExtensionTelemetry.eventPageRunningTime.histogramAdd({
          extension,
          value: now - msSinceCreated,
        });
      }
    } else {
      EventManager.clearPrimedListeners(this.extension, false);
    }
  }

  async onManifestEntry(entryName) {
    let { extension } = this;
    extension.backgroundState = BACKGROUND_STATE.STOPPED;

    // runtime.onStartup event support.  We listen for the first
    // background startup then emit a first-run event.
    extension.once("background-script-started", () => {
      extension.emit("background-first-run");
    });

    await this.primeBackground();

    ExtensionParent.browserStartupPromise.then(() => {
      // Return early if the background was created in the first
      // primeBackground call.  This happens for install, upgrade, downgrade.
      if (this.bgInstance) {
        return;
      }

      // If there are no listeners for the extension that were persisted, we need to
      // start the event page so they can be registered.
      if (
        extension.persistentBackground ||
        !extension.persistentListeners?.size ||
        // If runtime.onStartup has a listener and this is app_startup,
        // start the extension so it will fire the event.
        (extension.startupReason == "APP_STARTUP" &&
          extension.persistentListeners?.get("runtime").has("onStartup"))
      ) {
        extension.emit("start-background-script");
      } else {
        // During startup we only prime startup blocking listeners.  At
        // this stage we need to prime all listeners for event pages.
        EventManager.clearPrimedListeners(extension, false);
        // Allow re-priming by deleting existing listeners.
        extension.persistentListeners = null;
        EventManager.primeListeners(extension, false);
      }
    });
  }
};