Source code

Revision control

Other Tools

Line Code
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
/* 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/. */

/* globals LoadContextInfo, FormHistory, Accounts */

const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
const {Integration} = ChromeUtils.import("resource://gre/modules/Integration.jsm");

XPCOMUtils.defineLazyModuleGetters(this, {
  Accounts: "resource://gre/modules/Accounts.jsm",
  Downloads: "resource://gre/modules/Downloads.jsm",
  EventDispatcher: "resource://gre/modules/Messaging.jsm",
  FormHistory: "resource://gre/modules/FormHistory.jsm",
  OfflineAppCacheHelper: "resource://gre/modules/offlineAppCache.jsm",
  OS: "resource://gre/modules/osfile.jsm",
  ServiceWorkerCleanUp: "resource://gre/modules/ServiceWorkerCleanUp.jsm",
});

XPCOMUtils.defineLazyServiceGetters(this, {
  quotaManagerService: ["@mozilla.org/dom/quota-manager-service;1", "nsIQuotaManagerService"],
});

/* global DownloadIntegration */
Integration.downloads.defineModuleGetter(this, "DownloadIntegration",
            "resource://gre/modules/DownloadIntegration.jsm");


var EXPORTED_SYMBOLS = ["Sanitizer"];

function Sanitizer() {}
Sanitizer.prototype = {
  clearItem: function(aItemName, startTime, clearUnfinishedDownloads) {
    // Only a subset of items support deletion with startTime.
    // Those who do not will be rejected with error message.
    if (typeof startTime != "undefined") {
      switch (aItemName) {
        // Normal call to DownloadFiles remove actual data from storage, but our web-extension consumer
        // deletes only download history. So, for this reason we are passing a flag 'deleteFiles'.
        case "downloadHistory":
          return this._clear("downloadFiles", { startTime, deleteFiles: false });
        case "formdata":
          return this._clear(aItemName, { startTime });
        default:
          return Promise.reject({message: `Invalid argument: ${aItemName} does not support startTime argument.`});
      }
    } else if (aItemName === "downloadFiles" && typeof clearUnfinishedDownloads != "undefined") {
      return this._clear(aItemName, { clearUnfinishedDownloads });
    } else {
      return this._clear(aItemName);
    }
  },

 _clear: function(aItemName, options) {
    let item = this.items[aItemName];
    let canClear = item.canClear;
    if (typeof canClear == "function") {
      let maybeDoClear = async () => {
        let canClearResult = await new Promise(resolve => {
          canClear(resolve);
        });

        if (canClearResult) {
          return item.clear(options);
        }
      };
      return maybeDoClear();
    } else if (canClear) {
      return item.clear(options);
    }
  },

  // This code is mostly based on the Sanitizer code for desktop Firefox
  // (browser/modules/Sanitzer.jsm), however over the course of time some
  // general differences have evolved:
  // - async shutdown (and seenException handling) isn't implemented in Fennec
  // - currently there is only limited support for range-based clearing of data

  // Any further specific differences caused by architectural differences between
  // Fennec and desktop Firefox are documented below for each item.
  items: {
    // The difference is specifically the Sanitize:Cache message,
    // so that the Android front-end can clear its caches as well,
    // while everything else is unchanged.
    cache: {
      clear: function() {
        let refObj = {};
        TelemetryStopwatch.start("FX_SANITIZE_CACHE", refObj);

        try {
          Services.cache2.clear();
        } catch (er) {}

        let imageCache = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
                                                           .getImgCacheForDocument(null);
        try {
          imageCache.clearCache(false); // true=chrome, false=content
        } catch (er) {}

        return EventDispatcher.instance.sendRequestForResult({ type: "Sanitize:Cache" })
          .catch((err) => {
            Cu.reportError(`Java-side cache clearing failed with error: ${err}`);
          })
          .then(() => {
            TelemetryStopwatch.finish("FX_SANITIZE_CACHE", refObj);
          });
      },

      get canClear() {
        return true;
      },
    },

    // Compared to desktop, we don't clear plugin data, as plugins
    // aren't supported on Android.
    cookies: {
      clear: function() {
        return new Promise(function(resolve, reject) {
          let refObj = {};
          TelemetryStopwatch.start("FX_SANITIZE_COOKIES_2", refObj);

          Services.cookies.removeAll();

          TelemetryStopwatch.finish("FX_SANITIZE_COOKIES_2", refObj);

          // Clear deviceIds. Done asynchronously (returns before complete).
          try {
            let mediaMgr = Cc["@mozilla.org/mediaManagerService;1"]
                             .getService(Ci.nsIMediaManagerService);
            mediaMgr.sanitizeDeviceIds(0);
          } catch (er) { }

          resolve();
        });
      },

      get canClear() {
        return true;
      },
    },

    // Same as desktop Firefox.
    siteSettings: {
      async clear() {
        let refObj = {};
        TelemetryStopwatch.start("FX_SANITIZE_SITESETTINGS", refObj);

        // Clear site-specific permissions like "Allow this site to open popups"
        Services.perms.removeAll();

        // Clear site-specific settings like page-zoom level
        Cc["@mozilla.org/content-pref/service;1"]
          .getService(Ci.nsIContentPrefService2)
          .removeAllDomains(null);

        // Clear site security settings
        var sss = Cc["@mozilla.org/ssservice;1"]
                    .getService(Ci.nsISiteSecurityService);
        sss.clearAll();

        // Clear push subscriptions
        await new Promise((resolve, reject) => {
          let push = Cc["@mozilla.org/push/Service;1"]
                       .getService(Ci.nsIPushService);
          push.clearForDomain("*", status => {
            if (Components.isSuccessCode(status)) {
              resolve();
            } else {
              reject(new Error("Error clearing push subscriptions: " +
                               status));
            }
          });
        });
        TelemetryStopwatch.finish("FX_SANITIZE_SITESETTINGS", refObj);
      },

      get canClear() {
        return true;
      },
    },

    // Same as desktop Firefox.
    offlineApps: {
      async clear() {
        // AppCache
        // This doesn't wait for the cleanup to be complete.
        OfflineAppCacheHelper.clear();

        // LocalStorage
        Services.obs.notifyObservers(null, "extension:purge-localStorage");

        // ServiceWorkers
        await ServiceWorkerCleanUp.removeAll();

        // QuotaManager
        let promises = [];
        await new Promise(resolve => {
          quotaManagerService.getUsage(request => {
            if (request.resultCode != Cr.NS_OK) {
              // We are probably shutting down. We don't want to propagate the
              // error, rejecting the promise.
              resolve();
              return;
            }

            for (let item of request.result) {
              let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(item.origin);
              let uri = principal.URI;
              if (uri.scheme == "http" || uri.scheme == "https" || uri.scheme == "file") {
                promises.push(new Promise(r => {
                  let req = quotaManagerService.clearStoragesForPrincipal(principal);
                  req.callback = () => { r(); };
                }));
              }
            }
            resolve();
          });
        });

        return Promise.all(promises);
      },

      get canClear() {
          return true;
      },
    },

    // History on Android is implemented by the Java frontend and requires
    // different handling. Everything else is the same as for desktop Firefox.
    history: {
      clear: function() {
        let refObj = {};
        TelemetryStopwatch.start("FX_SANITIZE_HISTORY", refObj);

        return EventDispatcher.instance.sendRequestForResult({ type: "Sanitize:ClearHistory" })
          .catch(e => Cu.reportError("Java-side history clearing failed: " + e))
          .then(function() {
            TelemetryStopwatch.finish("FX_SANITIZE_HISTORY", refObj);
            try {
              Services.obs.notifyObservers(null, "browser:purge-session-history");
            } catch (e) { }

            try {
              var predictor = Cc["@mozilla.org/network/predictor;1"].getService(Ci.nsINetworkPredictor);
              predictor.reset();
            } catch (e) { }
          });
      },

      get canClear() {
        // bug 347231: Always allow clearing history due to dependencies on
        // the browser:purge-session-history notification. (like error console)
        return true;
      },
    },

    // Equivalent to openWindows on desktop, but specific to Fennec's implementation
    // of tabbed browsing and the session store.
    openTabs: {
      clear: function() {
        let refObj = {};
        TelemetryStopwatch.start("FX_SANITIZE_OPENWINDOWS", refObj);

        return EventDispatcher.instance.sendRequestForResult({ type: "Sanitize:OpenTabs" })
          .catch(e => Cu.reportError("Java-side tab clearing failed: " + e))
          .then(function() {
            try {
              // clear "Recently Closed" tabs in Android App
              Services.obs.notifyObservers(null, "browser:purge-session-tabs");
            } catch (e) { }
            TelemetryStopwatch.finish("FX_SANITIZE_OPENWINDOWS", refObj);
          });
      },

      get canClear() {
        return true;
      },
    },

    // Specific to Fennec.
    searchHistory: {
      clear: function() {
        return EventDispatcher.instance.sendRequestForResult({ type: "Sanitize:ClearHistory", clearSearchHistory: true })
          .catch(e => Cu.reportError("Java-side search history clearing failed: " + e));
      },

      get canClear() {
        return true;
      },
    },

    // Browser search is handled by searchHistory above and the find bar doesn't
    // require extra handling. FormHistory itself is cleared like on desktop.
    formdata: {
      clear: function({ startTime = 0 } = {}) {
        return new Promise(function(resolve, reject) {
          let refObj = {};
          TelemetryStopwatch.start("FX_SANITIZE_FORMDATA", refObj);

          // Conver time to microseconds
          let time = startTime * 1000;
          FormHistory.update({
            op: "remove",
            firstUsedStart: time,
          }, {
            handleCompletion() {
              TelemetryStopwatch.finish("FX_SANITIZE_FORMDATA", refObj);
              resolve();
            },
          });
        });
      },

      canClear: function(aCallback) {
        let count = 0;
        let countDone = {
          handleResult: function(aResult) { count = aResult; },
          handleError: function(aError) { Cu.reportError(aError); },
          handleCompletion: function(aReason) { aCallback(aReason == 0 && count > 0); },
        };
        FormHistory.count({}, countDone);
      },
    },

    // Adapted from desktop, but heavily modified - see comments below.
    downloadFiles: {
      async clear({
        startTime = 0,
        deleteFiles = true,
        clearUnfinishedDownloads = false,
      } = {}) {
        let refObj = {};
        TelemetryStopwatch.start("FX_SANITIZE_DOWNLOADS", refObj);

        let list = await Downloads.getList(Downloads.ALL);
        let downloads = await list.getAll();
        var finalizePromises = [];

        // Logic copied from DownloadList.removeFinished. Ideally, we would
        // just use that method directly, but we want to be able to remove the
        // downloaded files as well.
        for (let download of downloads) {
          let downloadFinished = download.stopped &&
                                 (!download.hasPartialData || download.error);
          if ((downloadFinished || clearUnfinishedDownloads) &&
               download.startTime.getTime() >= startTime) {
            // Remove the download first, so that the views don't get the change
            // notifications that may occur during finalization.
            await list.remove(download);
            // Ensure that the download is stopped and no partial data is kept.
            // This works even if the download state has changed meanwhile.  We
            // don't need to wait for the procedure to be complete before
            // processing the other downloads in the list.
            finalizePromises.push(download.finalize(true).then(() => null, Cu.reportError));

            if (deleteFiles) {
              // Delete the downloaded files themselves.
              OS.File.remove(download.target.path).then(() => null, ex => {
                if (!(ex instanceof OS.File.Error && ex.becauseNoSuchFile)) {
                  Cu.reportError(ex);
                }
              });
            }
          }
        }

        await Promise.all(finalizePromises);
        await DownloadIntegration.forceSave();
        TelemetryStopwatch.finish("FX_SANITIZE_DOWNLOADS", refObj);
      },

      get canClear() {
        return true;
      },
    },

    // Specific to Fennec.
    passwords: {
      clear: function() {
        return new Promise(function(resolve, reject) {
          Services.logins.removeAllLogins();
          resolve();
        });
      },

      get canClear() {
        let count = Services.logins.countLogins("", "", ""); // count all logins
        return (count > 0);
      },
    },

    // Same as desktop Firefox.
    sessions: {
      clear: function() {
        return new Promise(function(resolve, reject) {
          let refObj = {};
          TelemetryStopwatch.start("FX_SANITIZE_SESSIONS", refObj);

          // clear all auth tokens
          var sdr = Cc["@mozilla.org/security/sdr;1"].getService(Ci.nsISecretDecoderRing);
          sdr.logoutAndTeardown();

          // clear FTP and plain HTTP auth sessions
          Services.obs.notifyObservers(null, "net:clear-active-logins");

          TelemetryStopwatch.finish("FX_SANITIZE_SESSIONS", refObj);
          resolve();
        });
      },

      get canClear() {
        return true;
      },
    },

    // Specific to Fennec.
    syncedTabs: {
      clear: function() {
        return EventDispatcher.instance.sendRequestForResult({ type: "Sanitize:ClearSyncedTabs" })
          .catch(e => Cu.reportError("Java-side synced tabs clearing failed: " + e));
      },

      canClear: function(aCallback) {
        Accounts.anySyncAccountsExist().then(aCallback)
          .catch(function(err) {
            Cu.reportError("Java-side synced tabs clearing failed: " + err);
            aCallback(false);
          });
      },
    },

  },
};

var Sanitizer = new Sanitizer();