tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

SessionSaver.sys.mjs (13526B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
      3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 
      5 import {
      6  cancelIdleCallback,
      7  clearTimeout,
      8  requestIdleCallback,
      9  setTimeout,
     10 } from "resource://gre/modules/Timer.sys.mjs";
     11 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
     12 import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
     13 
     14 const lazy = {};
     15 
     16 ChromeUtils.defineESModuleGetters(lazy, {
     17  PrivacyFilter: "resource://gre/modules/sessionstore/PrivacyFilter.sys.mjs",
     18  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
     19  RunState: "resource:///modules/sessionstore/RunState.sys.mjs",
     20  SessionFile: "resource:///modules/sessionstore/SessionFile.sys.mjs",
     21  SessionStore: "resource:///modules/sessionstore/SessionStore.sys.mjs",
     22  sessionStoreLogger: "resource:///modules/sessionstore/SessionLogger.sys.mjs",
     23 });
     24 
     25 /*
     26 * Minimal interval between two save operations (in milliseconds).
     27 *
     28 * To save system resources, we generally do not save changes immediately when
     29 * a change is detected. Rather, we wait a little to see if this change is
     30 * followed by other changes, in which case only the last write is necessary.
     31 * This delay is defined by "browser.sessionstore.interval".
     32 *
     33 * Furthermore, when the user is not actively using the computer, webpages
     34 * may still perform changes that require (re)writing to sessionstore, e.g.
     35 * updating Session Cookies or DOM Session Storage, or refreshing, etc. We
     36 * expect that these changes are much less critical to the user and do not
     37 * need to be saved as often. In such cases, we increase the delay to
     38 *  "browser.sessionstore.interval.idle".
     39 *
     40 * When the user returns to the computer, if a save is pending, we reschedule
     41 * it to happen soon, with "browser.sessionstore.interval".
     42 */
     43 const PREF_INTERVAL_ACTIVE = "browser.sessionstore.interval";
     44 const PREF_INTERVAL_IDLE = "browser.sessionstore.interval.idle";
     45 const PREF_IDLE_DELAY = "browser.sessionstore.idleDelay";
     46 
     47 // Notify observers about a given topic with a given subject.
     48 function notify(subject, topic) {
     49  Services.obs.notifyObservers(subject, topic);
     50 }
     51 
     52 /**
     53 * The external API implemented by the SessionSaver module.
     54 */
     55 export var SessionSaver = Object.freeze({
     56  /**
     57   * Immediately saves the current session to disk.
     58   */
     59  run() {
     60    if (!lazy.RunState.isRunning) {
     61      lazy.sessionStoreLogger.debug("SessionSave run called during shutdown");
     62    }
     63    return SessionSaverInternal.run();
     64  },
     65 
     66  /**
     67   * Saves the current session to disk delayed by a given amount of time. Should
     68   * another delayed run be scheduled already, we will ignore the given delay
     69   * and state saving may occur a little earlier.
     70   */
     71  runDelayed() {
     72    SessionSaverInternal.runDelayed();
     73  },
     74 
     75  /**
     76   * Returns the timestamp that keeps track of the last time we attempted to save the session.
     77   */
     78  get lastSaveTime() {
     79    return SessionSaverInternal._lastSaveTime;
     80  },
     81 
     82  /**
     83   * Sets the last save time to the current time. This will cause us to wait for
     84   * at least the configured interval when runDelayed() is called next.
     85   */
     86  updateLastSaveTime() {
     87    SessionSaverInternal.updateLastSaveTime();
     88  },
     89 
     90  /**
     91   * Cancels all pending session saves.
     92   */
     93  cancel() {
     94    SessionSaverInternal.cancel();
     95  },
     96 });
     97 
     98 /**
     99 * The internal API.
    100 */
    101 var SessionSaverInternal = {
    102  /**
    103   * The timeout ID referencing an active timer for a delayed save. When no
    104   * save is pending, this is null.
    105   */
    106  _timeoutID: null,
    107 
    108  /**
    109   * The idle callback ID referencing an active idle callback. When no idle
    110   * callback is pending, this is null.
    111   */
    112  _idleCallbackID: null,
    113 
    114  /**
    115   * A timestamp that keeps track of when we saved the session last. We will
    116   * this to determine the correct interval between delayed saves to not deceed
    117   * the configured session write interval.
    118   */
    119  _lastSaveTime: 0,
    120 
    121  /**
    122   * `true` if the user has been idle for at least
    123   * `SessionSaverInternal._intervalWhileIdle` ms. Idleness is computed
    124   * with `nsIUserIdleService`.
    125   */
    126  _isIdle: false,
    127 
    128  /**
    129   * `true` if the user was idle when we last scheduled a delayed save.
    130   * See `_isIdle` for details on idleness.
    131   */
    132  _wasIdle: false,
    133 
    134  /**
    135   * Minimal interval between two save operations (in ms), while the user
    136   * is active.
    137   */
    138  _intervalWhileActive: null,
    139 
    140  /**
    141   * Minimal interval between two save operations (in ms), while the user
    142   * is idle.
    143   */
    144  _intervalWhileIdle: null,
    145 
    146  /**
    147   * How long before we assume that the user is idle (ms).
    148   */
    149  _idleDelay: null,
    150 
    151  /**
    152   * Immediately saves the current session to disk.
    153   */
    154  run() {
    155    return this._saveState(true /* force-update all windows */);
    156  },
    157 
    158  /**
    159   * Saves the current session to disk delayed by a given amount of time. Should
    160   * another delayed run be scheduled already, we will ignore the given delay
    161   * and state saving may occur a little earlier.
    162   *
    163   * @param delay (optional)
    164   *        The minimum delay in milliseconds to wait for until we collect and
    165   *        save the current session.
    166   */
    167  runDelayed(delay = 2000) {
    168    // Bail out if there's a pending run.
    169    if (this._timeoutID) {
    170      return;
    171    }
    172 
    173    // Interval until the next disk operation is allowed.
    174    let interval = this._isIdle
    175      ? this._intervalWhileIdle
    176      : this._intervalWhileActive;
    177    delay = Math.max(this._lastSaveTime + interval - Date.now(), delay, 0);
    178 
    179    // Schedule a state save.
    180    this._wasIdle = this._isIdle;
    181    if (!lazy.RunState.isRunning) {
    182      lazy.sessionStoreLogger.debug(
    183        "SessionSaver scheduling a state save during shutdown"
    184      );
    185    }
    186    this._timeoutID = setTimeout(() => {
    187      // Execute _saveStateAsync when we have idle time.
    188      let saveStateAsyncWhenIdle = () => {
    189        if (!lazy.RunState.isRunning) {
    190          lazy.sessionStoreLogger.debug(
    191            "SessionSaver saveStateAsyncWhenIdle callback during shutdown"
    192          );
    193        }
    194        this._saveStateAsync();
    195      };
    196 
    197      this._idleCallbackID = requestIdleCallback(saveStateAsyncWhenIdle);
    198    }, delay);
    199  },
    200 
    201  /**
    202   * Sets the last save time to the current time. This will cause us to wait for
    203   * at least the configured interval when runDelayed() is called next.
    204   */
    205  updateLastSaveTime() {
    206    this._lastSaveTime = Date.now();
    207  },
    208 
    209  /**
    210   * Cancels all pending session saves.
    211   */
    212  cancel() {
    213    clearTimeout(this._timeoutID);
    214    this._timeoutID = null;
    215    cancelIdleCallback(this._idleCallbackID);
    216    this._idleCallbackID = null;
    217  },
    218 
    219  /**
    220   * Observe idle/ active notifications.
    221   */
    222  observe(subject, topic) {
    223    switch (topic) {
    224      case "idle":
    225        this._isIdle = true;
    226        break;
    227      case "active":
    228        this._isIdle = false;
    229        if (this._timeoutID && this._wasIdle) {
    230          // A state save has been scheduled while we were idle.
    231          // Replace it by an active save.
    232          clearTimeout(this._timeoutID);
    233          this._timeoutID = null;
    234          this.runDelayed();
    235        }
    236        break;
    237      default:
    238        throw new Error(`Unexpected change value ${topic}`);
    239    }
    240  },
    241 
    242  /**
    243   * Saves the current session state. Collects data and writes to disk.
    244   *
    245   * @param forceUpdateAllWindows (optional)
    246   *        Forces us to recollect data for all windows and will bypass and
    247   *        update the corresponding caches.
    248   */
    249  _saveState(forceUpdateAllWindows = false) {
    250    // Cancel any pending timeouts.
    251    this.cancel();
    252 
    253    if (lazy.PrivateBrowsingUtils.permanentPrivateBrowsing) {
    254      // Don't save (or even collect) anything in permanent private
    255      // browsing mode
    256 
    257      this.updateLastSaveTime();
    258      return Promise.resolve();
    259    }
    260 
    261    let timerId = Glean.sessionRestore.collectData.start();
    262    let state = lazy.SessionStore.getCurrentState(forceUpdateAllWindows);
    263    lazy.PrivacyFilter.filterPrivateWindowsAndTabs(state);
    264 
    265    // Make sure we only write worth saving tabs to disk.
    266    lazy.SessionStore.keepOnlyWorthSavingTabs(state);
    267 
    268    // Make sure that we keep the previous session if we started with a single
    269    // private window and no non-private windows have been opened, yet.
    270    if (state.deferredInitialState) {
    271      state.windows = state.deferredInitialState.windows || [];
    272      delete state.deferredInitialState;
    273    }
    274 
    275    if (AppConstants.platform != "macosx") {
    276      // We want to restore closed windows that are marked with _shouldRestore.
    277      // We're doing this here because we want to control this only when saving
    278      // the file.
    279      if (lazy.sessionStoreLogger.isDebug) {
    280        lazy.sessionStoreLogger.debug(
    281          "SessionSaver._saveState, closed windows:"
    282        );
    283        for (let closedWin of state._closedWindows) {
    284          lazy.sessionStoreLogger.debug(
    285            `\t${closedWin.closedId}\t${closedWin.closedAt}\t${closedWin._shouldRestore}`
    286          );
    287        }
    288      }
    289 
    290      while (state._closedWindows.length) {
    291        let i = state._closedWindows.length - 1;
    292 
    293        if (!state._closedWindows[i]._shouldRestore) {
    294          // We only need to go until _shouldRestore
    295          // is falsy since we're going in reverse.
    296          break;
    297        }
    298 
    299        delete state._closedWindows[i]._shouldRestore;
    300        state.windows.unshift(state._closedWindows.pop());
    301      }
    302    }
    303 
    304    // Clear cookies and storage on clean shutdown.
    305    this._maybeClearCookiesAndStorage(state);
    306 
    307    Glean.sessionRestore.collectData.stopAndAccumulate(timerId);
    308    return this._writeState(state);
    309  },
    310 
    311  /**
    312   * Purges cookies and DOMSessionStorage data from the session on clean
    313   * shutdown, only if requested by the user's preferences.
    314   */
    315  _maybeClearCookiesAndStorage(state) {
    316    // Only do this on shutdown.
    317    if (!lazy.RunState.isClosing) {
    318      return;
    319    }
    320 
    321    // Don't clear when restarting.
    322    if (
    323      Services.prefs.getBoolPref("browser.sessionstore.resume_session_once")
    324    ) {
    325      return;
    326    }
    327    let sanitizeCookies =
    328      Services.prefs.getBoolPref("privacy.sanitize.sanitizeOnShutdown") &&
    329      Services.prefs.getBoolPref("privacy.clearOnShutdown.cookies");
    330 
    331    if (sanitizeCookies) {
    332      // Remove cookies.
    333      delete state.cookies;
    334 
    335      // Remove DOMSessionStorage data.
    336      for (let window of state.windows) {
    337        for (let tab of window.tabs) {
    338          delete tab.storage;
    339        }
    340      }
    341    }
    342  },
    343 
    344  /**
    345   * Saves the current session state. Collects data asynchronously and calls
    346   * _saveState() to collect data again (with a cache hit rate of hopefully
    347   * 100%) and write to disk afterwards.
    348   */
    349  _saveStateAsync() {
    350    // Allow scheduling delayed saves again.
    351    this._timeoutID = null;
    352 
    353    // Write to disk.
    354    this._saveState();
    355  },
    356 
    357  /**
    358   * Write the given state object to disk.
    359   */
    360  _writeState(state) {
    361    if (!lazy.RunState.isRunning) {
    362      lazy.sessionStoreLogger.debug(
    363        "SessionSaver writing state during shutdown"
    364      );
    365    }
    366    // We update the time stamp before writing so that we don't write again
    367    // too soon, if saving is requested before the write completes. Without
    368    // this update we may save repeatedly if actions cause a runDelayed
    369    // before writing has completed. See Bug 902280
    370    this.updateLastSaveTime();
    371 
    372    // Write (atomically) to a session file, using a tmp file. Once the session
    373    // file is successfully updated, save the time stamp of the last save and
    374    // notify the observers.
    375    return lazy.SessionFile.write(state).then(
    376      () => {
    377        this.updateLastSaveTime();
    378        if (!lazy.RunState.isRunning) {
    379          lazy.sessionStoreLogger.debug(
    380            "SessionSaver sessionstore-state-write-complete during shutdown"
    381          );
    382        }
    383        notify(null, "sessionstore-state-write-complete");
    384      },
    385      err => {
    386        lazy.sessionStoreLogger.error(
    387          "SessionSaver write() rejected with error",
    388          err
    389        );
    390      }
    391    );
    392  },
    393 };
    394 
    395 XPCOMUtils.defineLazyPreferenceGetter(
    396  SessionSaverInternal,
    397  "_intervalWhileActive",
    398  PREF_INTERVAL_ACTIVE,
    399  15000 /* 15 seconds */,
    400  () => {
    401    // Cancel any pending runs and call runDelayed() with
    402    // zero to apply the newly configured interval.
    403    SessionSaverInternal.cancel();
    404    SessionSaverInternal.runDelayed(0);
    405  }
    406 );
    407 
    408 XPCOMUtils.defineLazyPreferenceGetter(
    409  SessionSaverInternal,
    410  "_intervalWhileIdle",
    411  PREF_INTERVAL_IDLE,
    412  3600000 /* 1 h */
    413 );
    414 
    415 XPCOMUtils.defineLazyPreferenceGetter(
    416  SessionSaverInternal,
    417  "_idleDelay",
    418  PREF_IDLE_DELAY,
    419  180 /* 3 minutes */,
    420  (key, previous, latest) => {
    421    // Update the idle observer for the new `PREF_IDLE_DELAY` value. Here we need
    422    // to re-fetch the service instead of the original one in use; This is for a
    423    // case that the Mock service in the unit test needs to be fetched to
    424    // replace the original one.
    425    var idleService = Cc["@mozilla.org/widget/useridleservice;1"].getService(
    426      Ci.nsIUserIdleService
    427    );
    428    if (previous != undefined) {
    429      idleService.removeIdleObserver(SessionSaverInternal, previous);
    430    }
    431    if (latest != undefined) {
    432      idleService.addIdleObserver(SessionSaverInternal, latest);
    433    }
    434  }
    435 );
    436 
    437 var idleService = Cc["@mozilla.org/widget/useridleservice;1"].getService(
    438  Ci.nsIUserIdleService
    439 );
    440 idleService.addIdleObserver(
    441  SessionSaverInternal,
    442  SessionSaverInternal._idleDelay
    443 );