browsing_data_api.cc revision 868fa2fe829687343ffae624259930155e16dbd8
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Defines the Chrome Extensions BrowsingData API functions, which entail
6// clearing browsing data, and clearing the browser's cache (which, let's be
7// honest, are the same thing), as specified in the extension API JSON.
8
9#include "chrome/browser/extensions/api/browsing_data/browsing_data_api.h"
10
11#include <string>
12
13#include "base/stringprintf.h"
14#include "base/values.h"
15#include "chrome/browser/browsing_data/browsing_data_helper.h"
16#include "chrome/browser/browsing_data/browsing_data_remover.h"
17#include "chrome/browser/plugins/plugin_data_remover_helper.h"
18#include "chrome/browser/plugins/plugin_prefs.h"
19#include "chrome/browser/profiles/profile.h"
20#include "chrome/browser/ui/browser.h"
21#include "chrome/common/extensions/extension.h"
22#include "chrome/common/pref_names.h"
23#include "content/public/browser/browser_thread.h"
24#include "extensions/common/error_utils.h"
25
26using content::BrowserThread;
27
28namespace extension_browsing_data_api_constants {
29
30// Parameter name keys.
31const char kDataRemovalPermittedKey[] = "dataRemovalPermitted";
32const char kDataToRemoveKey[] = "dataToRemove";
33const char kOptionsKey[] = "options";
34
35// Type keys.
36const char kAppCacheKey[] = "appcache";
37const char kCacheKey[] = "cache";
38const char kCookiesKey[] = "cookies";
39const char kDownloadsKey[] = "downloads";
40const char kFileSystemsKey[] = "fileSystems";
41const char kFormDataKey[] = "formData";
42const char kHistoryKey[] = "history";
43const char kIndexedDBKey[] = "indexedDB";
44const char kLocalStorageKey[] = "localStorage";
45const char kServerBoundCertsKey[] = "serverBoundCertificates";
46const char kPasswordsKey[] = "passwords";
47const char kPluginDataKey[] = "pluginData";
48const char kWebSQLKey[] = "webSQL";
49
50// Option keys.
51const char kExtensionsKey[] = "extension";
52const char kOriginTypesKey[] = "originTypes";
53const char kProtectedWebKey[] = "protectedWeb";
54const char kSinceKey[] = "since";
55const char kUnprotectedWebKey[] = "unprotectedWeb";
56
57// Errors!
58// The placeholder will be filled by the name of the affected data type (e.g.,
59// "history").
60const char kBadDataTypeDetails[] = "Invalid value for data type '%s'.";
61const char kDeleteProhibitedError[] = "Browsing history and downloads are not "
62                                      "permitted to be removed.";
63const char kOneAtATimeError[] = "Only one 'browsingData' API call can run at "
64                                "a time.";
65
66}  // namespace extension_browsing_data_api_constants
67
68namespace {
69int MaskForKey(const char* key) {
70  if (strcmp(key, extension_browsing_data_api_constants::kAppCacheKey) == 0)
71    return BrowsingDataRemover::REMOVE_APPCACHE;
72  if (strcmp(key, extension_browsing_data_api_constants::kCacheKey) == 0)
73    return BrowsingDataRemover::REMOVE_CACHE;
74  if (strcmp(key, extension_browsing_data_api_constants::kCookiesKey) == 0)
75    return BrowsingDataRemover::REMOVE_COOKIES;
76  if (strcmp(key, extension_browsing_data_api_constants::kDownloadsKey) == 0)
77    return BrowsingDataRemover::REMOVE_DOWNLOADS;
78  if (strcmp(key, extension_browsing_data_api_constants::kFileSystemsKey) == 0)
79    return BrowsingDataRemover::REMOVE_FILE_SYSTEMS;
80  if (strcmp(key, extension_browsing_data_api_constants::kFormDataKey) == 0)
81    return BrowsingDataRemover::REMOVE_FORM_DATA;
82  if (strcmp(key, extension_browsing_data_api_constants::kHistoryKey) == 0)
83    return BrowsingDataRemover::REMOVE_HISTORY;
84  if (strcmp(key, extension_browsing_data_api_constants::kIndexedDBKey) == 0)
85    return BrowsingDataRemover::REMOVE_INDEXEDDB;
86  if (strcmp(key, extension_browsing_data_api_constants::kLocalStorageKey) == 0)
87    return BrowsingDataRemover::REMOVE_LOCAL_STORAGE;
88  if (strcmp(key,
89             extension_browsing_data_api_constants::kServerBoundCertsKey) == 0)
90    return BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS;
91  if (strcmp(key, extension_browsing_data_api_constants::kPasswordsKey) == 0)
92    return BrowsingDataRemover::REMOVE_PASSWORDS;
93  if (strcmp(key, extension_browsing_data_api_constants::kPluginDataKey) == 0)
94    return BrowsingDataRemover::REMOVE_PLUGIN_DATA;
95  if (strcmp(key, extension_browsing_data_api_constants::kWebSQLKey) == 0)
96    return BrowsingDataRemover::REMOVE_WEBSQL;
97
98  return 0;
99}
100
101// Returns false if any of the selected data types are not allowed to be
102// deleted.
103bool IsRemovalPermitted(int removal_mask, PrefService* prefs) {
104  // Enterprise policy or user preference might prohibit deleting browser or
105  // download history.
106  if ((removal_mask & BrowsingDataRemover::REMOVE_HISTORY) ||
107      (removal_mask & BrowsingDataRemover::REMOVE_DOWNLOADS)) {
108    return prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory);
109  }
110  return true;
111}
112
113}  // namespace
114
115
116bool BrowsingDataSettingsFunction::RunImpl() {
117  PrefService* prefs = profile()->GetPrefs();
118
119  // Fill origin types.
120  // The "cookies" and "hosted apps" UI checkboxes both map to
121  // REMOVE_SITE_DATA in browsing_data_remover.h, the former for the unprotected
122  // web, the latter for  protected web data. There is no UI control for
123  // extension data.
124  scoped_ptr<DictionaryValue> origin_types(new DictionaryValue);
125  origin_types->SetBoolean(
126      extension_browsing_data_api_constants::kUnprotectedWebKey,
127      prefs->GetBoolean(prefs::kDeleteCookies));
128  origin_types->SetBoolean(
129      extension_browsing_data_api_constants::kProtectedWebKey,
130      prefs->GetBoolean(prefs::kDeleteHostedAppsData));
131  origin_types->SetBoolean(
132      extension_browsing_data_api_constants::kExtensionsKey, false);
133
134  // Fill deletion time period.
135  int period_pref = prefs->GetInteger(prefs::kDeleteTimePeriod);
136  BrowsingDataRemover::TimePeriod period =
137      static_cast<BrowsingDataRemover::TimePeriod>(period_pref);
138  double since = 0;
139  if (period != BrowsingDataRemover::EVERYTHING) {
140    base::Time time = BrowsingDataRemover::CalculateBeginDeleteTime(period);
141    since = time.ToJsTime();
142  }
143
144  scoped_ptr<DictionaryValue> options(new DictionaryValue);
145  options->Set(extension_browsing_data_api_constants::kOriginTypesKey,
146               origin_types.release());
147  options->SetDouble(extension_browsing_data_api_constants::kSinceKey, since);
148
149  // Fill dataToRemove and dataRemovalPermitted.
150  scoped_ptr<DictionaryValue> selected(new DictionaryValue);
151  scoped_ptr<DictionaryValue> permitted(new DictionaryValue);
152
153  bool delete_site_data = prefs->GetBoolean(prefs::kDeleteCookies) ||
154                          prefs->GetBoolean(prefs::kDeleteHostedAppsData);
155
156  SetDetails(selected.get(), permitted.get(),
157             extension_browsing_data_api_constants::kAppCacheKey,
158             delete_site_data);
159  SetDetails(selected.get(), permitted.get(),
160             extension_browsing_data_api_constants::kCookiesKey,
161             delete_site_data);
162  SetDetails(selected.get(), permitted.get(),
163             extension_browsing_data_api_constants::kFileSystemsKey,
164             delete_site_data);
165  SetDetails(selected.get(), permitted.get(),
166             extension_browsing_data_api_constants::kIndexedDBKey,
167             delete_site_data);
168  SetDetails(selected.get(), permitted.get(),
169      extension_browsing_data_api_constants::kLocalStorageKey,
170      delete_site_data);
171  SetDetails(selected.get(), permitted.get(),
172             extension_browsing_data_api_constants::kWebSQLKey,
173             delete_site_data);
174  SetDetails(selected.get(), permitted.get(),
175      extension_browsing_data_api_constants::kServerBoundCertsKey,
176      delete_site_data);
177
178  SetDetails(selected.get(), permitted.get(),
179      extension_browsing_data_api_constants::kPluginDataKey,
180      delete_site_data && prefs->GetBoolean(prefs::kClearPluginLSODataEnabled));
181
182  SetDetails(selected.get(), permitted.get(),
183             extension_browsing_data_api_constants::kHistoryKey,
184             prefs->GetBoolean(prefs::kDeleteBrowsingHistory));
185  SetDetails(selected.get(), permitted.get(),
186             extension_browsing_data_api_constants::kDownloadsKey,
187             prefs->GetBoolean(prefs::kDeleteDownloadHistory));
188  SetDetails(selected.get(), permitted.get(),
189             extension_browsing_data_api_constants::kCacheKey,
190             prefs->GetBoolean(prefs::kDeleteCache));
191  SetDetails(selected.get(), permitted.get(),
192             extension_browsing_data_api_constants::kFormDataKey,
193             prefs->GetBoolean(prefs::kDeleteFormData));
194  SetDetails(selected.get(), permitted.get(),
195             extension_browsing_data_api_constants::kPasswordsKey,
196             prefs->GetBoolean(prefs::kDeletePasswords));
197
198  scoped_ptr<DictionaryValue> result(new DictionaryValue);
199  result->Set(extension_browsing_data_api_constants::kOptionsKey,
200              options.release());
201  result->Set(extension_browsing_data_api_constants::kDataToRemoveKey,
202              selected.release());
203  result->Set(extension_browsing_data_api_constants::kDataRemovalPermittedKey,
204              permitted.release());
205  SetResult(result.release());
206  return true;
207}
208
209void BrowsingDataSettingsFunction::SetDetails(DictionaryValue* selected_dict,
210                                              DictionaryValue* permitted_dict,
211                                              const char* data_type,
212                                              bool is_selected) {
213  bool is_permitted = IsRemovalPermitted(MaskForKey(data_type),
214                                         profile()->GetPrefs());
215  selected_dict->SetBoolean(data_type, is_selected && is_permitted);
216  permitted_dict->SetBoolean(data_type, is_permitted);
217}
218
219void BrowsingDataRemoveFunction::OnBrowsingDataRemoverDone() {
220  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
221  this->SendResponse(true);
222
223  Release();  // Balanced in RunImpl.
224}
225
226bool BrowsingDataRemoveFunction::RunImpl() {
227  // If we don't have a profile, something's pretty wrong.
228  DCHECK(profile());
229
230  // Grab the initial |options| parameter, and parse out the arguments.
231  DictionaryValue* options;
232  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &options));
233  DCHECK(options);
234
235  origin_set_mask_ = ParseOriginSetMask(*options);
236
237  // If |ms_since_epoch| isn't set, default it to 0.
238  double ms_since_epoch;
239  if (!options->GetDouble(extension_browsing_data_api_constants::kSinceKey,
240                          &ms_since_epoch))
241    ms_since_epoch = 0;
242
243  // base::Time takes a double that represents seconds since epoch. JavaScript
244  // gives developers milliseconds, so do a quick conversion before populating
245  // the object. Also, Time::FromDoubleT converts double time 0 to empty Time
246  // object. So we need to do special handling here.
247  remove_since_ = (ms_since_epoch == 0) ?
248      base::Time::UnixEpoch() :
249      base::Time::FromDoubleT(ms_since_epoch / 1000.0);
250
251  removal_mask_ = GetRemovalMask();
252  if (bad_message_)
253    return false;
254
255  // Check for prohibited data types.
256  if (!IsRemovalPermitted(removal_mask_, profile()->GetPrefs())) {
257    error_ = extension_browsing_data_api_constants::kDeleteProhibitedError;
258    return false;
259  }
260
261  if (removal_mask_ & BrowsingDataRemover::REMOVE_PLUGIN_DATA) {
262    // If we're being asked to remove plugin data, check whether it's actually
263    // supported.
264    BrowserThread::PostTask(
265        BrowserThread::FILE, FROM_HERE,
266        base::Bind(
267            &BrowsingDataRemoveFunction::CheckRemovingPluginDataSupported,
268            this,
269            PluginPrefs::GetForProfile(profile())));
270  } else {
271    StartRemoving();
272  }
273
274  // Will finish asynchronously.
275  return true;
276}
277
278void BrowsingDataRemoveFunction::CheckRemovingPluginDataSupported(
279    scoped_refptr<PluginPrefs> plugin_prefs) {
280  if (!PluginDataRemoverHelper::IsSupported(plugin_prefs.get()))
281    removal_mask_ &= ~BrowsingDataRemover::REMOVE_PLUGIN_DATA;
282
283  BrowserThread::PostTask(
284      BrowserThread::UI, FROM_HERE,
285      base::Bind(&BrowsingDataRemoveFunction::StartRemoving, this));
286}
287
288void BrowsingDataRemoveFunction::StartRemoving() {
289  if (BrowsingDataRemover::is_removing()) {
290    error_ = extension_browsing_data_api_constants::kOneAtATimeError;
291    SendResponse(false);
292    return;
293  }
294
295  // If we're good to go, add a ref (Balanced in OnBrowsingDataRemoverDone)
296  AddRef();
297
298  // Create a BrowsingDataRemover, set the current object as an observer (so
299  // that we're notified after removal) and call remove() with the arguments
300  // we've generated above. We can use a raw pointer here, as the browsing data
301  // remover is responsible for deleting itself once data removal is complete.
302  BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(profile(),
303      remove_since_, base::Time::Max());
304  remover->AddObserver(this);
305  remover->Remove(removal_mask_, origin_set_mask_);
306}
307
308int BrowsingDataRemoveFunction::ParseOriginSetMask(
309    const base::DictionaryValue& options) {
310  // Parse the |options| dictionary to generate the origin set mask. Default to
311  // UNPROTECTED_WEB if the developer doesn't specify anything.
312  int mask = BrowsingDataHelper::UNPROTECTED_WEB;
313
314  const DictionaryValue* d = NULL;
315  if (options.HasKey(extension_browsing_data_api_constants::kOriginTypesKey)) {
316    EXTENSION_FUNCTION_VALIDATE(options.GetDictionary(
317        extension_browsing_data_api_constants::kOriginTypesKey, &d));
318    bool value;
319
320    // The developer specified something! Reset to 0 and parse the dictionary.
321    mask = 0;
322
323    // Unprotected web.
324    if (d->HasKey(extension_browsing_data_api_constants::kUnprotectedWebKey)) {
325      EXTENSION_FUNCTION_VALIDATE(d->GetBoolean(
326          extension_browsing_data_api_constants::kUnprotectedWebKey, &value));
327      mask |= value ? BrowsingDataHelper::UNPROTECTED_WEB : 0;
328    }
329
330    // Protected web.
331    if (d->HasKey(extension_browsing_data_api_constants::kProtectedWebKey)) {
332      EXTENSION_FUNCTION_VALIDATE(d->GetBoolean(
333          extension_browsing_data_api_constants::kProtectedWebKey, &value));
334      mask |= value ? BrowsingDataHelper::PROTECTED_WEB : 0;
335    }
336
337    // Extensions.
338    if (d->HasKey(extension_browsing_data_api_constants::kExtensionsKey)) {
339      EXTENSION_FUNCTION_VALIDATE(d->GetBoolean(
340          extension_browsing_data_api_constants::kExtensionsKey, &value));
341      mask |= value ? BrowsingDataHelper::EXTENSION : 0;
342    }
343  }
344
345  return mask;
346}
347
348// Parses the |dataToRemove| argument to generate the removal mask. Sets
349// |bad_message_| (like EXTENSION_FUNCTION_VALIDATE would if this were a bool
350// method) if 'dataToRemove' is not present or any data-type keys don't have
351// supported (boolean) values.
352int RemoveBrowsingDataFunction::GetRemovalMask() {
353  base::DictionaryValue* data_to_remove;
354  if (!args_->GetDictionary(1, &data_to_remove)) {
355    bad_message_ = true;
356    return 0;
357  }
358
359  int removal_mask = 0;
360
361  for (DictionaryValue::Iterator i(*data_to_remove);
362       !i.IsAtEnd();
363       i.Advance()) {
364    bool selected = false;
365    if (!i.value().GetAsBoolean(&selected)) {
366      bad_message_ = true;
367      return 0;
368    }
369    if (selected)
370      removal_mask |= MaskForKey(i.key().c_str());
371  }
372
373  return removal_mask;
374}
375
376int RemoveAppCacheFunction::GetRemovalMask() {
377  return BrowsingDataRemover::REMOVE_APPCACHE;
378}
379
380int RemoveCacheFunction::GetRemovalMask() {
381  return BrowsingDataRemover::REMOVE_CACHE;
382}
383
384int RemoveCookiesFunction::GetRemovalMask() {
385  return BrowsingDataRemover::REMOVE_COOKIES |
386         BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS;
387}
388
389int RemoveDownloadsFunction::GetRemovalMask() {
390  return BrowsingDataRemover::REMOVE_DOWNLOADS;
391}
392
393int RemoveFileSystemsFunction::GetRemovalMask() {
394  return BrowsingDataRemover::REMOVE_FILE_SYSTEMS;
395}
396
397int RemoveFormDataFunction::GetRemovalMask() {
398  return BrowsingDataRemover::REMOVE_FORM_DATA;
399}
400
401int RemoveHistoryFunction::GetRemovalMask() {
402  return BrowsingDataRemover::REMOVE_HISTORY;
403}
404
405int RemoveIndexedDBFunction::GetRemovalMask() {
406  return BrowsingDataRemover::REMOVE_INDEXEDDB;
407}
408
409int RemoveLocalStorageFunction::GetRemovalMask() {
410  return BrowsingDataRemover::REMOVE_LOCAL_STORAGE;
411}
412
413int RemovePluginDataFunction::GetRemovalMask() {
414  return BrowsingDataRemover::REMOVE_PLUGIN_DATA;
415}
416
417int RemovePasswordsFunction::GetRemovalMask() {
418  return BrowsingDataRemover::REMOVE_PASSWORDS;
419}
420
421int RemoveWebSQLFunction::GetRemovalMask() {
422  return BrowsingDataRemover::REMOVE_WEBSQL;
423}
424