summaryrefslogtreecommitdiffstats
path: root/toolkit/forgetaboutsite/ForgetAboutSite.jsm
blob: 5250ca75d4eed28372c9ff28e81957e80b27dd96 (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
/* 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";

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
                                  "resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
                                  "resource://gre/modules/Downloads.jsm");

this.EXPORTED_SYMBOLS = ["ForgetAboutSite"];

/**
 * Returns true if the string passed in is part of the root domain of the
 * current string.  For example, if this is "www.mozilla.org", and we pass in
 * "mozilla.org", this will return true.  It would return false the other way
 * around.
 */
function hasRootDomain(str, aDomain)
{
  let index = str.indexOf(aDomain);
  // If aDomain is not found, we know we do not have it as a root domain.
  if (index == -1)
    return false;

  // If the strings are the same, we obviously have a match.
  if (str == aDomain)
    return true;

  // Otherwise, we have aDomain as our root domain iff the index of aDomain is
  // aDomain.length subtracted from our length and (since we do not have an
  // exact match) the character before the index is a dot or slash.
  let prevChar = str[index - 1];
  return (index == (str.length - aDomain.length)) &&
         (prevChar == "." || prevChar == "/");
}

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

this.ForgetAboutSite = {
  removeDataFromDomain: function CRH_removeDataFromDomain(aDomain)
  {
    PlacesUtils.history.removePagesFromHost(aDomain, true);

    // Cache
    let cs = Cc["@mozilla.org/netwerk/cache-storage-service;1"].
             getService(Ci.nsICacheStorageService);
    // NOTE: there is no way to clear just that domain, so we clear out
    //       everything)
    try {
      cs.clear();
    } catch (ex) {
      Cu.reportError("Exception thrown while clearing the cache: " +
        ex.toString());
    }

    // Image Cache
    let imageCache = Cc["@mozilla.org/image/tools;1"].
                     getService(Ci.imgITools).getImgCacheForDocument(null);
    try {
      imageCache.clearCache(false); // true=chrome, false=content
    } catch (ex) {
      Cu.reportError("Exception thrown while clearing the image cache: " +
        ex.toString());
    }

    // Cookies
    let cm = Cc["@mozilla.org/cookiemanager;1"].
             getService(Ci.nsICookieManager2);
    let enumerator = cm.getCookiesWithOriginAttributes(JSON.stringify({}), aDomain);
    while (enumerator.hasMoreElements()) {
      let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
      cm.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);
    }

    // EME
    let mps = Cc["@mozilla.org/gecko-media-plugin-service;1"].
               getService(Ci.mozIGeckoMediaPluginChromeService);
    mps.forgetThisSite(aDomain, JSON.stringify({}));

    // Plugin data
    const phInterface = Ci.nsIPluginHost;
    const FLAG_CLEAR_ALL = phInterface.FLAG_CLEAR_ALL;
    let ph = Cc["@mozilla.org/plugin/host;1"].getService(phInterface);
    let tags = ph.getPluginTags();
    let promises = [];
    for (let i = 0; i < tags.length; i++) {
      let promise = new Promise(resolve => {
        let tag = tags[i];
        try {
          ph.clearSiteData(tags[i], aDomain, FLAG_CLEAR_ALL, -1, function(rv) {
            resolve();
          });
        } catch (e) {
          // Ignore errors from the plugin, but resolve the promise
          resolve();
        }
      });
      promises.push(promise);
    }

    // Downloads
    Task.spawn(function*() {
      let list = yield Downloads.getList(Downloads.ALL);
      list.removeFinished(download => hasRootDomain(
           NetUtil.newURI(download.source.url).host, aDomain));
    }).then(null, Cu.reportError);

    // Passwords
    let lm = Cc["@mozilla.org/login-manager;1"].
             getService(Ci.nsILoginManager);
    // Clear all passwords for domain
    try {
      let logins = lm.getAllLogins();
      for (let i = 0; i < logins.length; i++)
        if (hasRootDomain(logins[i].hostname, aDomain))
          lm.removeLogin(logins[i]);
    }
    // XXXehsan: is there a better way to do this rather than this
    // hacky comparison?
    catch (ex) {
      if (!ex.message.includes("User canceled Master Password entry")) {
        throw ex;
      }
    }

    // Permissions
    let pm = Cc["@mozilla.org/permissionmanager;1"].
             getService(Ci.nsIPermissionManager);
    // Enumerate all of the permissions, and if one matches, remove it
    enumerator = pm.enumerator;
    while (enumerator.hasMoreElements()) {
      let perm = enumerator.getNext().QueryInterface(Ci.nsIPermission);
      try {
        if (hasRootDomain(perm.principal.URI.host, aDomain)) {
          pm.removePermission(perm);
        }
      } catch (e) {
        /* Ignore entry */
      }
    }

    // Offline Storages
    let qms = Cc["@mozilla.org/dom/quota-manager-service;1"].
              getService(Ci.nsIQuotaManagerService);
    // delete data from both HTTP and HTTPS sites
    let caUtils = {};
    let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
                       getService(Ci.mozIJSSubScriptLoader);
    scriptLoader.loadSubScript("chrome://global/content/contentAreaUtils.js",
                               caUtils);
    let httpURI = caUtils.makeURI("http://" + aDomain);
    let httpsURI = caUtils.makeURI("https://" + aDomain);
    // Following code section has been reverted to the state before Bug 1238183,
    // but added a new argument to clearStoragesForPrincipal() for indicating
    // clear all storages under a given origin.
    let httpPrincipal = Services.scriptSecurityManager
                                .createCodebasePrincipal(httpURI, {});
    let httpsPrincipal = Services.scriptSecurityManager
                                 .createCodebasePrincipal(httpsURI, {});
    qms.clearStoragesForPrincipal(httpPrincipal, null, true);
    qms.clearStoragesForPrincipal(httpsPrincipal, null, true);


    function onContentPrefsRemovalFinished() {
      // Everybody else (including extensions)
      Services.obs.notifyObservers(null, "browser:purge-domain-data", aDomain);
    }

    // Content Preferences
    let cps2 = Cc["@mozilla.org/content-pref/service;1"].
               getService(Ci.nsIContentPrefService2);
    cps2.removeBySubdomain(aDomain, null, {
      handleCompletion: () => onContentPrefsRemovalFinished(),
      handleError: function() {}
    });

    // Predictive network data - like cache, no way to clear this per
    // domain, so just trash it all
    let np = Cc["@mozilla.org/network/predictor;1"].
             getService(Ci.nsINetworkPredictor);
    np.reset();

    // Push notifications.
    promises.push(new Promise(resolve => {
      var push = Cc["@mozilla.org/push/Service;1"]
                  .getService(Ci.nsIPushService);
      push.clearForDomain(aDomain, status => {
        (Components.isSuccessCode(status) ? resolve : reject)(status);
      });
    }).catch(e => {
      Cu.reportError("Exception thrown while clearing Push notifications: " +
                     e.toString());
    }));

    // HSTS and HPKP
    // TODO (bug 1290529): also remove HSTS/HPKP information for subdomains.
    // Since we can't enumerate the information in the site security service
    // (bug 1115712), we can't implement this right now.
    try {
      let sss = Cc["@mozilla.org/ssservice;1"].
                getService(Ci.nsISiteSecurityService);
      sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS, httpsURI, 0);
      sss.removeState(Ci.nsISiteSecurityService.HEADER_HPKP, httpsURI, 0);
    } catch (e) {
      Cu.reportError("Exception thrown while clearing HSTS/HPKP: " +
                     e.toString());
    }

    return Promise.all(promises);
  }
};