Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / browsing_data / browsing_data_remover.cc
blob12f3277708054a61f69dc3a4e5c6aa0a12d2e2d4
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.
5 #include "chrome/browser/browsing_data/browsing_data_remover.h"
7 #include <map>
8 #include <set>
9 #include <string>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/callback.h"
14 #include "base/logging.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/prefs/pref_service.h"
17 #include "chrome/browser/autofill/personal_data_manager_factory.h"
18 #include "chrome/browser/browser_process.h"
19 #include "chrome/browser/browsing_data/browsing_data_helper.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/domain_reliability/service_factory.h"
22 #include "chrome/browser/download/download_prefs.h"
23 #include "chrome/browser/download/download_service_factory.h"
24 #include "chrome/browser/history/history_service_factory.h"
25 #include "chrome/browser/history/web_history_service_factory.h"
26 #include "chrome/browser/io_thread.h"
27 #include "chrome/browser/media/media_device_id_salt.h"
28 #include "chrome/browser/net/predictor.h"
29 #include "chrome/browser/password_manager/password_store_factory.h"
30 #include "chrome/browser/prerender/prerender_manager.h"
31 #include "chrome/browser/prerender/prerender_manager_factory.h"
32 #include "chrome/browser/profiles/profile.h"
33 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
34 #include "chrome/browser/search_engines/template_url_service_factory.h"
35 #include "chrome/browser/sessions/session_service.h"
36 #include "chrome/browser/sessions/session_service_factory.h"
37 #include "chrome/browser/sessions/tab_restore_service.h"
38 #include "chrome/browser/sessions/tab_restore_service_factory.h"
39 #include "chrome/browser/web_data_service_factory.h"
40 #include "chrome/common/pref_names.h"
41 #include "chrome/common/url_constants.h"
42 #include "components/autofill/core/browser/personal_data_manager.h"
43 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
44 #include "components/browsing_data/storage_partition_http_cache_data_remover.h"
45 #include "components/content_settings/core/browser/host_content_settings_map.h"
46 #include "components/domain_reliability/service.h"
47 #include "components/history/core/browser/history_service.h"
48 #include "components/nacl/browser/nacl_browser.h"
49 #include "components/nacl/browser/pnacl_host.h"
50 #include "components/omnibox/browser/omnibox_pref_names.h"
51 #include "components/password_manager/core/browser/password_store.h"
52 #include "components/power/origin_power_map.h"
53 #include "components/power/origin_power_map_factory.h"
54 #include "components/search_engines/template_url_service.h"
55 #include "components/web_cache/browser/web_cache_manager.h"
56 #include "content/public/browser/browser_thread.h"
57 #include "content/public/browser/download_manager.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/plugin_data_remover.h"
60 #include "content/public/browser/ssl_host_state_delegate.h"
61 #include "content/public/browser/storage_partition.h"
62 #include "content/public/browser/user_metrics.h"
63 #include "net/base/net_errors.h"
64 #include "net/cookies/cookie_store.h"
65 #include "net/http/transport_security_state.h"
66 #include "net/ssl/channel_id_service.h"
67 #include "net/ssl/channel_id_store.h"
68 #include "net/url_request/url_request_context.h"
69 #include "net/url_request/url_request_context_getter.h"
70 #include "storage/browser/quota/special_storage_policy.h"
71 #include "url/origin.h"
73 #if defined(OS_ANDROID)
74 #include "chrome/browser/precache/precache_manager_factory.h"
75 #include "components/precache/content/precache_manager.h"
76 #endif
78 #if defined(OS_CHROMEOS)
79 #include "chrome/browser/chromeos/profiles/profile_helper.h"
80 #include "chromeos/attestation/attestation_constants.h"
81 #include "chromeos/dbus/cryptohome_client.h"
82 #include "chromeos/dbus/dbus_thread_manager.h"
83 #include "components/user_manager/user.h"
84 #endif
86 #if defined(ENABLE_EXTENSIONS)
87 #include "chrome/browser/apps/ephemeral_app_service.h"
88 #include "chrome/browser/extensions/activity_log/activity_log.h"
89 #include "chrome/browser/extensions/extension_service.h"
90 #include "chrome/browser/extensions/extension_special_storage_policy.h"
91 #include "extensions/browser/extension_prefs.h"
92 #endif
94 #if defined(ENABLE_WEBRTC)
95 #include "chrome/browser/media/webrtc_log_list.h"
96 #include "chrome/browser/media/webrtc_log_util.h"
97 #endif
99 using base::UserMetricsAction;
100 using content::BrowserContext;
101 using content::BrowserThread;
102 using content::DOMStorageContext;
104 namespace {
106 using CallbackList =
107 base::CallbackList<void(const BrowsingDataRemover::NotificationDetails&)>;
109 // Contains all registered callbacks for browsing data removed notifications.
110 CallbackList* g_on_browsing_data_removed_callbacks = nullptr;
112 // Accessor for |*g_on_browsing_data_removed_callbacks|. Creates a new object
113 // the first time so that it always returns a valid object.
114 CallbackList* GetOnBrowsingDataRemovedCallbacks() {
115 if (!g_on_browsing_data_removed_callbacks)
116 g_on_browsing_data_removed_callbacks = new CallbackList();
117 return g_on_browsing_data_removed_callbacks;
120 } // namespace
122 bool BrowsingDataRemover::is_removing_ = false;
124 BrowsingDataRemover::CompletionInhibitor*
125 BrowsingDataRemover::completion_inhibitor_ = nullptr;
127 // Helper to create callback for BrowsingDataRemover::DoesOriginMatchMask.
128 // Static.
129 bool DoesOriginMatchMask(
130 int origin_type_mask,
131 const GURL& origin,
132 storage::SpecialStoragePolicy* special_storage_policy) {
133 return BrowsingDataHelper::DoesOriginMatchMask(
134 origin, origin_type_mask, special_storage_policy);
137 BrowsingDataRemover::NotificationDetails::NotificationDetails()
138 : removal_begin(base::Time()),
139 removal_mask(-1),
140 origin_type_mask(-1) {
143 BrowsingDataRemover::NotificationDetails::NotificationDetails(
144 const BrowsingDataRemover::NotificationDetails& details)
145 : removal_begin(details.removal_begin),
146 removal_mask(details.removal_mask),
147 origin_type_mask(details.origin_type_mask) {
150 BrowsingDataRemover::NotificationDetails::NotificationDetails(
151 base::Time removal_begin,
152 int removal_mask,
153 int origin_type_mask)
154 : removal_begin(removal_begin),
155 removal_mask(removal_mask),
156 origin_type_mask(origin_type_mask) {
159 BrowsingDataRemover::NotificationDetails::~NotificationDetails() {}
161 // Static.
162 BrowsingDataRemover* BrowsingDataRemover::CreateForUnboundedRange(
163 Profile* profile) {
164 return new BrowsingDataRemover(profile, base::Time(), base::Time::Max());
167 // Static.
168 BrowsingDataRemover* BrowsingDataRemover::CreateForRange(Profile* profile,
169 base::Time start, base::Time end) {
170 return new BrowsingDataRemover(profile, start, end);
173 // Static.
174 BrowsingDataRemover* BrowsingDataRemover::CreateForPeriod(Profile* profile,
175 TimePeriod period) {
176 switch (period) {
177 case LAST_HOUR:
178 content::RecordAction(
179 UserMetricsAction("ClearBrowsingData_LastHour"));
180 break;
181 case LAST_DAY:
182 content::RecordAction(
183 UserMetricsAction("ClearBrowsingData_LastDay"));
184 break;
185 case LAST_WEEK:
186 content::RecordAction(
187 UserMetricsAction("ClearBrowsingData_LastWeek"));
188 break;
189 case FOUR_WEEKS:
190 content::RecordAction(
191 UserMetricsAction("ClearBrowsingData_LastMonth"));
192 break;
193 case EVERYTHING:
194 content::RecordAction(
195 UserMetricsAction("ClearBrowsingData_Everything"));
196 break;
198 return new BrowsingDataRemover(profile,
199 BrowsingDataRemover::CalculateBeginDeleteTime(period),
200 base::Time::Max());
203 BrowsingDataRemover::BrowsingDataRemover(Profile* profile,
204 base::Time delete_begin,
205 base::Time delete_end)
206 : profile_(profile),
207 delete_begin_(delete_begin),
208 delete_end_(delete_end),
209 main_context_getter_(profile->GetRequestContext()),
210 media_context_getter_(profile->GetMediaRequestContext()) {
211 DCHECK(profile);
212 // crbug.com/140910: Many places were calling this with base::Time() as
213 // delete_end, even though they should've used base::Time::Max(). Work around
214 // it here. New code should use base::Time::Max().
215 DCHECK(delete_end_ != base::Time());
216 if (delete_end_ == base::Time())
217 delete_end_ = base::Time::Max();
220 BrowsingDataRemover::~BrowsingDataRemover() {
221 DCHECK(AllDone());
224 // Static.
225 void BrowsingDataRemover::set_removing(bool is_removing) {
226 DCHECK(is_removing_ != is_removing);
227 is_removing_ = is_removing;
230 void BrowsingDataRemover::Remove(int remove_mask, int origin_type_mask) {
231 RemoveImpl(remove_mask, GURL(), origin_type_mask);
234 void BrowsingDataRemover::RemoveImpl(int remove_mask,
235 const GURL& remove_url,
236 int origin_type_mask) {
237 DCHECK_CURRENTLY_ON(BrowserThread::UI);
238 set_removing(true);
239 remove_mask_ = remove_mask;
240 origin_type_mask_ = origin_type_mask;
241 url::Origin remove_origin(remove_url);
243 PrefService* prefs = profile_->GetPrefs();
244 bool may_delete_history = prefs->GetBoolean(
245 prefs::kAllowDeletingBrowserHistory);
247 // All the UI entry points into the BrowsingDataRemover should be disabled,
248 // but this will fire if something was missed or added.
249 DCHECK(may_delete_history || (remove_mask & REMOVE_NOCHECKS) ||
250 (!(remove_mask & REMOVE_HISTORY) && !(remove_mask & REMOVE_DOWNLOADS)));
252 if (origin_type_mask_ & BrowsingDataHelper::UNPROTECTED_WEB) {
253 content::RecordAction(
254 UserMetricsAction("ClearBrowsingData_MaskContainsUnprotectedWeb"));
256 if (origin_type_mask_ & BrowsingDataHelper::PROTECTED_WEB) {
257 content::RecordAction(
258 UserMetricsAction("ClearBrowsingData_MaskContainsProtectedWeb"));
260 if (origin_type_mask_ & BrowsingDataHelper::EXTENSION) {
261 content::RecordAction(
262 UserMetricsAction("ClearBrowsingData_MaskContainsExtension"));
264 // If this fires, we added a new BrowsingDataHelper::OriginTypeMask without
265 // updating the user metrics above.
266 static_assert(
267 BrowsingDataHelper::ALL == (BrowsingDataHelper::UNPROTECTED_WEB |
268 BrowsingDataHelper::PROTECTED_WEB |
269 BrowsingDataHelper::EXTENSION),
270 "OriginTypeMask has been updated without updating user metrics");
272 if ((remove_mask & REMOVE_HISTORY) && may_delete_history) {
273 history::HistoryService* history_service =
274 HistoryServiceFactory::GetForProfile(
275 profile_, ServiceAccessType::EXPLICIT_ACCESS);
276 if (history_service) {
277 std::set<GURL> restrict_urls;
278 if (!remove_url.is_empty())
279 restrict_urls.insert(remove_url);
280 content::RecordAction(UserMetricsAction("ClearBrowsingData_History"));
281 waiting_for_clear_history_ = true;
283 history_service->ExpireLocalAndRemoteHistoryBetween(
284 WebHistoryServiceFactory::GetForProfile(profile_),
285 restrict_urls, delete_begin_, delete_end_,
286 base::Bind(&BrowsingDataRemover::OnHistoryDeletionDone,
287 base::Unretained(this)),
288 &history_task_tracker_);
290 #if defined(ENABLE_EXTENSIONS)
291 // The extension activity contains details of which websites extensions
292 // were active on. It therefore indirectly stores details of websites a
293 // user has visited so best clean from here as well.
294 extensions::ActivityLog::GetInstance(profile_)->RemoveURLs(restrict_urls);
295 #endif
298 #if defined(ENABLE_EXTENSIONS)
299 // Clear launch times as they are a form of history.
300 extensions::ExtensionPrefs* extension_prefs =
301 extensions::ExtensionPrefs::Get(profile_);
302 extension_prefs->ClearLastLaunchTimes();
303 #endif
305 // The power consumption history by origin contains details of websites
306 // that were visited.
307 power::OriginPowerMap* origin_power_map =
308 power::OriginPowerMapFactory::GetForBrowserContext(profile_);
309 if (origin_power_map)
310 origin_power_map->ClearOriginMap();
312 // Need to clear the host cache and accumulated speculative data, as it also
313 // reveals some history: we have no mechanism to track when these items were
314 // created, so we'll clear them all. Better safe than sorry.
315 if (g_browser_process->io_thread()) {
316 waiting_for_clear_hostname_resolution_cache_ = true;
317 BrowserThread::PostTask(
318 BrowserThread::IO, FROM_HERE,
319 base::Bind(
320 &BrowsingDataRemover::ClearHostnameResolutionCacheOnIOThread,
321 base::Unretained(this),
322 g_browser_process->io_thread()));
324 if (profile_->GetNetworkPredictor()) {
325 waiting_for_clear_network_predictor_ = true;
326 BrowserThread::PostTask(
327 BrowserThread::IO, FROM_HERE,
328 base::Bind(&BrowsingDataRemover::ClearNetworkPredictorOnIOThread,
329 base::Unretained(this),
330 profile_->GetNetworkPredictor()));
333 // As part of history deletion we also delete the auto-generated keywords.
334 TemplateURLService* keywords_model =
335 TemplateURLServiceFactory::GetForProfile(profile_);
336 if (keywords_model && !keywords_model->loaded()) {
337 template_url_sub_ = keywords_model->RegisterOnLoadedCallback(
338 base::Bind(&BrowsingDataRemover::OnKeywordsLoaded,
339 base::Unretained(this)));
340 keywords_model->Load();
341 waiting_for_clear_keyword_data_ = true;
342 } else if (keywords_model) {
343 keywords_model->RemoveAutoGeneratedForOriginBetween(
344 remove_url, delete_begin_, delete_end_);
347 // The PrerenderManager keeps history of prerendered pages, so clear that.
348 // It also may have a prerendered page. If so, the page could be
349 // considered to have a small amount of historical information, so delete
350 // it, too.
351 prerender::PrerenderManager* prerender_manager =
352 prerender::PrerenderManagerFactory::GetForProfile(profile_);
353 if (prerender_manager) {
354 prerender_manager->ClearData(
355 prerender::PrerenderManager::CLEAR_PRERENDER_CONTENTS |
356 prerender::PrerenderManager::CLEAR_PRERENDER_HISTORY);
359 // If the caller is removing history for all hosts, then clear ancillary
360 // historical information.
361 if (remove_url.is_empty()) {
362 // We also delete the list of recently closed tabs. Since these expire,
363 // they can't be more than a day old, so we can simply clear them all.
364 TabRestoreService* tab_service =
365 TabRestoreServiceFactory::GetForProfile(profile_);
366 if (tab_service) {
367 tab_service->ClearEntries();
368 tab_service->DeleteLastSession();
371 #if defined(ENABLE_SESSION_SERVICE)
372 // We also delete the last session when we delete the history.
373 SessionService* session_service =
374 SessionServiceFactory::GetForProfile(profile_);
375 if (session_service)
376 session_service->DeleteLastSession();
377 #endif
380 // The saved Autofill profiles and credit cards can include the origin from
381 // which these profiles and credit cards were learned. These are a form of
382 // history, so clear them as well.
383 scoped_refptr<autofill::AutofillWebDataService> web_data_service =
384 WebDataServiceFactory::GetAutofillWebDataForProfile(
385 profile_, ServiceAccessType::EXPLICIT_ACCESS);
386 if (web_data_service.get()) {
387 waiting_for_clear_autofill_origin_urls_ = true;
388 web_data_service->RemoveOriginURLsModifiedBetween(
389 delete_begin_, delete_end_);
390 // The above calls are done on the UI thread but do their work on the DB
391 // thread. So wait for it.
392 BrowserThread::PostTaskAndReply(
393 BrowserThread::DB, FROM_HERE,
394 base::Bind(&base::DoNothing),
395 base::Bind(&BrowsingDataRemover::OnClearedAutofillOriginURLs,
396 base::Unretained(this)));
398 autofill::PersonalDataManager* data_manager =
399 autofill::PersonalDataManagerFactory::GetForProfile(profile_);
400 if (data_manager)
401 data_manager->Refresh();
404 #if defined(ENABLE_WEBRTC)
405 waiting_for_clear_webrtc_logs_ = true;
406 BrowserThread::PostTaskAndReply(
407 BrowserThread::FILE,
408 FROM_HERE,
409 base::Bind(
410 &WebRtcLogUtil::DeleteOldAndRecentWebRtcLogFiles,
411 WebRtcLogList::GetWebRtcLogDirectoryForProfile(profile_->GetPath()),
412 delete_begin_),
413 base::Bind(&BrowsingDataRemover::OnClearedWebRtcLogs,
414 base::Unretained(this)));
415 #endif
417 // The SSL Host State that tracks SSL interstitial "proceed" decisions may
418 // include origins that the user has visited, so it must be cleared.
419 if (profile_->GetSSLHostStateDelegate())
420 profile_->GetSSLHostStateDelegate()->Clear();
422 #if defined(OS_ANDROID)
423 precache::PrecacheManager* precache_manager =
424 precache::PrecacheManagerFactory::GetForBrowserContext(profile_);
425 // |precache_manager| could be nullptr if the profile is off the record.
426 if (!precache_manager) {
427 waiting_for_clear_precache_history_ = true;
428 precache_manager->ClearHistory();
429 // The above calls are done on the UI thread but do their work on the DB
430 // thread. So wait for it.
431 BrowserThread::PostTaskAndReply(
432 BrowserThread::DB, FROM_HERE,
433 base::Bind(&base::DoNothing),
434 base::Bind(&BrowsingDataRemover::OnClearedPrecacheHistory,
435 base::Unretained(this)));
437 #endif
440 if ((remove_mask & REMOVE_DOWNLOADS) && may_delete_history) {
441 content::RecordAction(UserMetricsAction("ClearBrowsingData_Downloads"));
442 content::DownloadManager* download_manager =
443 BrowserContext::GetDownloadManager(profile_);
444 if (remove_origin.unique())
445 download_manager->RemoveDownloadsBetween(delete_begin_, delete_end_);
446 else
447 download_manager->RemoveDownloadsByOriginAndTime(
448 remove_origin, delete_begin_, delete_end_);
449 DownloadPrefs* download_prefs = DownloadPrefs::FromDownloadManager(
450 download_manager);
451 download_prefs->SetSaveFilePath(download_prefs->DownloadPath());
454 uint32 storage_partition_remove_mask = 0;
456 // We ignore the REMOVE_COOKIES request if UNPROTECTED_WEB is not set,
457 // so that callers who request REMOVE_SITE_DATA with PROTECTED_WEB
458 // don't accidentally remove the cookies that are associated with the
459 // UNPROTECTED_WEB origin. This is necessary because cookies are not separated
460 // between UNPROTECTED_WEB and PROTECTED_WEB.
461 if (remove_mask & REMOVE_COOKIES &&
462 origin_type_mask_ & BrowsingDataHelper::UNPROTECTED_WEB) {
463 content::RecordAction(UserMetricsAction("ClearBrowsingData_Cookies"));
465 storage_partition_remove_mask |=
466 content::StoragePartition::REMOVE_DATA_MASK_COOKIES;
468 #if defined(SAFE_BROWSING_SERVICE)
469 // Clear the safebrowsing cookies only if time period is for "all time". It
470 // doesn't make sense to apply the time period of deleting in the last X
471 // hours/days to the safebrowsing cookies since they aren't the result of
472 // any user action.
473 if (delete_begin_ == base::Time()) {
474 SafeBrowsingService* sb_service =
475 g_browser_process->safe_browsing_service();
476 if (sb_service) {
477 net::URLRequestContextGetter* sb_context =
478 sb_service->url_request_context();
479 ++waiting_for_clear_cookies_count_;
480 BrowserThread::PostTask(
481 BrowserThread::IO, FROM_HERE,
482 base::Bind(&BrowsingDataRemover::ClearCookiesOnIOThread,
483 base::Unretained(this), base::Unretained(sb_context)));
486 #endif
487 MediaDeviceIDSalt::Reset(profile_->GetPrefs());
489 // TODO(mkwst): If we're not removing passwords, then clear the 'zero-click'
490 // flag for all credentials in the password store.
493 // Channel IDs are not separated for protected and unprotected web
494 // origins. We check the origin_type_mask_ to prevent unintended deletion.
495 if (remove_mask & REMOVE_CHANNEL_IDS &&
496 origin_type_mask_ & BrowsingDataHelper::UNPROTECTED_WEB) {
497 content::RecordAction(
498 UserMetricsAction("ClearBrowsingData_ChannelIDs"));
499 // Since we are running on the UI thread don't call GetURLRequestContext().
500 net::URLRequestContextGetter* rq_context = profile_->GetRequestContext();
501 if (rq_context) {
502 waiting_for_clear_channel_ids_ = true;
503 BrowserThread::PostTask(
504 BrowserThread::IO, FROM_HERE,
505 base::Bind(&BrowsingDataRemover::ClearChannelIDsOnIOThread,
506 base::Unretained(this), base::Unretained(rq_context)));
510 if (remove_mask & REMOVE_LOCAL_STORAGE) {
511 storage_partition_remove_mask |=
512 content::StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
515 if (remove_mask & REMOVE_INDEXEDDB) {
516 storage_partition_remove_mask |=
517 content::StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
519 if (remove_mask & REMOVE_WEBSQL) {
520 storage_partition_remove_mask |=
521 content::StoragePartition::REMOVE_DATA_MASK_WEBSQL;
523 if (remove_mask & REMOVE_APPCACHE) {
524 storage_partition_remove_mask |=
525 content::StoragePartition::REMOVE_DATA_MASK_APPCACHE;
527 if (remove_mask & REMOVE_SERVICE_WORKERS) {
528 storage_partition_remove_mask |=
529 content::StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS;
531 if (remove_mask & REMOVE_CACHE_STORAGE) {
532 storage_partition_remove_mask |=
533 content::StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE;
535 if (remove_mask & REMOVE_FILE_SYSTEMS) {
536 storage_partition_remove_mask |=
537 content::StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
540 #if defined(ENABLE_PLUGINS)
541 // Plugin is data not separated for protected and unprotected web origins. We
542 // check the origin_type_mask_ to prevent unintended deletion.
543 if (remove_mask & REMOVE_PLUGIN_DATA &&
544 origin_type_mask_ & BrowsingDataHelper::UNPROTECTED_WEB) {
545 content::RecordAction(UserMetricsAction("ClearBrowsingData_LSOData"));
547 waiting_for_clear_plugin_data_ = true;
548 if (!plugin_data_remover_.get())
549 plugin_data_remover_.reset(content::PluginDataRemover::Create(profile_));
550 base::WaitableEvent* event =
551 plugin_data_remover_->StartRemoving(delete_begin_);
553 base::WaitableEventWatcher::EventCallback watcher_callback =
554 base::Bind(&BrowsingDataRemover::OnWaitableEventSignaled,
555 base::Unretained(this));
556 watcher_.StartWatching(event, watcher_callback);
558 #endif
560 if (remove_mask & REMOVE_SITE_USAGE_DATA || remove_mask & REMOVE_HISTORY) {
561 profile_->GetHostContentSettingsMap()->ClearSettingsForOneType(
562 CONTENT_SETTINGS_TYPE_APP_BANNER);
563 profile_->GetHostContentSettingsMap()->ClearSettingsForOneType(
564 CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT);
567 if (remove_mask & REMOVE_PASSWORDS) {
568 content::RecordAction(UserMetricsAction("ClearBrowsingData_Passwords"));
569 password_manager::PasswordStore* password_store =
570 PasswordStoreFactory::GetForProfile(
571 profile_, ServiceAccessType::EXPLICIT_ACCESS).get();
573 if (password_store) {
574 waiting_for_clear_passwords_ = true;
575 password_store->RemoveLoginsCreatedBetween(
576 delete_begin_, delete_end_,
577 base::Bind(&BrowsingDataRemover::OnClearedPasswords,
578 base::Unretained(this)));
582 if (remove_mask & REMOVE_FORM_DATA) {
583 content::RecordAction(UserMetricsAction("ClearBrowsingData_Autofill"));
584 scoped_refptr<autofill::AutofillWebDataService> web_data_service =
585 WebDataServiceFactory::GetAutofillWebDataForProfile(
586 profile_, ServiceAccessType::EXPLICIT_ACCESS);
588 if (web_data_service.get()) {
589 waiting_for_clear_form_ = true;
590 web_data_service->RemoveFormElementsAddedBetween(delete_begin_,
591 delete_end_);
592 web_data_service->RemoveAutofillDataModifiedBetween(
593 delete_begin_, delete_end_);
594 // The above calls are done on the UI thread but do their work on the DB
595 // thread. So wait for it.
596 BrowserThread::PostTaskAndReply(
597 BrowserThread::DB, FROM_HERE,
598 base::Bind(&base::DoNothing),
599 base::Bind(&BrowsingDataRemover::OnClearedFormData,
600 base::Unretained(this)));
602 autofill::PersonalDataManager* data_manager =
603 autofill::PersonalDataManagerFactory::GetForProfile(profile_);
604 if (data_manager)
605 data_manager->Refresh();
609 if (remove_mask & REMOVE_CACHE) {
610 // Tell the renderers to clear their cache.
611 web_cache::WebCacheManager::GetInstance()->ClearCache();
613 content::RecordAction(UserMetricsAction("ClearBrowsingData_Cache"));
615 waiting_for_clear_cache_ = true;
616 // StoragePartitionHttpCacheDataRemover deletes itself when it is done.
617 browsing_data::StoragePartitionHttpCacheDataRemover::CreateForRange(
618 BrowserContext::GetDefaultStoragePartition(profile_), delete_begin_,
619 delete_end_)
620 ->Remove(base::Bind(&BrowsingDataRemover::ClearedCache,
621 base::Unretained(this)));
623 #if !defined(DISABLE_NACL)
624 waiting_for_clear_nacl_cache_ = true;
626 BrowserThread::PostTask(
627 BrowserThread::IO, FROM_HERE,
628 base::Bind(&BrowsingDataRemover::ClearNaClCacheOnIOThread,
629 base::Unretained(this)));
631 waiting_for_clear_pnacl_cache_ = true;
632 BrowserThread::PostTask(
633 BrowserThread::IO, FROM_HERE,
634 base::Bind(&BrowsingDataRemover::ClearPnaclCacheOnIOThread,
635 base::Unretained(this), delete_begin_, delete_end_));
636 #endif
638 // The PrerenderManager may have a page actively being prerendered, which
639 // is essentially a preemptively cached page.
640 prerender::PrerenderManager* prerender_manager =
641 prerender::PrerenderManagerFactory::GetForProfile(profile_);
642 if (prerender_manager) {
643 prerender_manager->ClearData(
644 prerender::PrerenderManager::CLEAR_PRERENDER_CONTENTS);
647 // Tell the shader disk cache to clear.
648 content::RecordAction(UserMetricsAction("ClearBrowsingData_ShaderCache"));
649 storage_partition_remove_mask |=
650 content::StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE;
652 storage_partition_remove_mask |=
653 content::StoragePartition::REMOVE_DATA_MASK_WEBRTC_IDENTITY;
655 #if defined(ENABLE_EXTENSIONS)
656 // Clear the ephemeral apps cache. This is nullptr while testing. OTR
657 // Profile has neither apps nor an ExtensionService, so ClearCachedApps
658 // fails.
659 EphemeralAppService* ephemeral_app_service =
660 EphemeralAppService::Get(profile_);
661 if (ephemeral_app_service && !profile_->IsOffTheRecord())
662 ephemeral_app_service->ClearCachedApps();
663 #endif
666 if (remove_mask & REMOVE_WEBRTC_IDENTITY) {
667 storage_partition_remove_mask |=
668 content::StoragePartition::REMOVE_DATA_MASK_WEBRTC_IDENTITY;
671 if (storage_partition_remove_mask) {
672 waiting_for_clear_storage_partition_data_ = true;
674 content::StoragePartition* storage_partition;
675 if (storage_partition_for_testing_)
676 storage_partition = storage_partition_for_testing_;
677 else
678 storage_partition = BrowserContext::GetDefaultStoragePartition(profile_);
680 uint32 quota_storage_remove_mask =
681 ~content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
683 if (delete_begin_ == base::Time() ||
684 origin_type_mask_ &
685 (BrowsingDataHelper::PROTECTED_WEB | BrowsingDataHelper::EXTENSION)) {
686 // If we're deleting since the beginning of time, or we're removing
687 // protected origins, then remove persistent quota data.
688 quota_storage_remove_mask |=
689 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT;
692 storage_partition->ClearData(
693 storage_partition_remove_mask, quota_storage_remove_mask, remove_url,
694 base::Bind(&DoesOriginMatchMask, origin_type_mask_), delete_begin_,
695 delete_end_,
696 base::Bind(&BrowsingDataRemover::OnClearedStoragePartitionData,
697 base::Unretained(this)));
700 #if defined(ENABLE_PLUGINS)
701 if (remove_mask & REMOVE_CONTENT_LICENSES) {
702 content::RecordAction(
703 UserMetricsAction("ClearBrowsingData_ContentLicenses"));
705 waiting_for_clear_content_licenses_ = true;
706 if (!pepper_flash_settings_manager_.get()) {
707 pepper_flash_settings_manager_.reset(
708 new PepperFlashSettingsManager(this, profile_));
710 deauthorize_content_licenses_request_id_ =
711 pepper_flash_settings_manager_->DeauthorizeContentLicenses(prefs);
712 #if defined(OS_CHROMEOS)
713 // On Chrome OS, also delete any content protection platform keys.
714 const user_manager::User* user =
715 chromeos::ProfileHelper::Get()->GetUserByProfile(profile_);
716 if (!user) {
717 LOG(WARNING) << "Failed to find user for current profile.";
718 } else {
719 chromeos::DBusThreadManager::Get()->GetCryptohomeClient()->
720 TpmAttestationDeleteKeys(
721 chromeos::attestation::KEY_USER,
722 user->email(),
723 chromeos::attestation::kContentProtectionKeyPrefix,
724 base::Bind(&BrowsingDataRemover::OnClearPlatformKeys,
725 base::Unretained(this)));
726 waiting_for_clear_platform_keys_ = true;
728 #endif
730 #endif
732 // Remove omnibox zero-suggest cache results.
733 if ((remove_mask & (REMOVE_CACHE | REMOVE_COOKIES)))
734 prefs->SetString(omnibox::kZeroSuggestCachedResults, std::string());
736 // Always wipe accumulated network related data (TransportSecurityState and
737 // HttpServerPropertiesManager data).
738 waiting_for_clear_networking_history_ = true;
739 profile_->ClearNetworkingHistorySince(
740 delete_begin_,
741 base::Bind(&BrowsingDataRemover::OnClearedNetworkingHistory,
742 base::Unretained(this)));
744 if (remove_mask & (REMOVE_COOKIES | REMOVE_HISTORY)) {
745 domain_reliability::DomainReliabilityService* service =
746 domain_reliability::DomainReliabilityServiceFactory::
747 GetForBrowserContext(profile_);
748 if (service) {
749 domain_reliability::DomainReliabilityClearMode mode;
750 if (remove_mask & REMOVE_COOKIES)
751 mode = domain_reliability::CLEAR_CONTEXTS;
752 else
753 mode = domain_reliability::CLEAR_BEACONS;
755 waiting_for_clear_domain_reliability_monitor_ = true;
756 service->ClearBrowsingData(
757 mode,
758 base::Bind(&BrowsingDataRemover::OnClearedDomainReliabilityMonitor,
759 base::Unretained(this)));
763 // Record the combined deletion of cookies and cache.
764 CookieOrCacheDeletionChoice choice = NEITHER_COOKIES_NOR_CACHE;
765 if (remove_mask & REMOVE_COOKIES &&
766 origin_type_mask_ & BrowsingDataHelper::UNPROTECTED_WEB) {
767 choice = remove_mask & REMOVE_CACHE ? BOTH_COOKIES_AND_CACHE
768 : ONLY_COOKIES;
769 } else if (remove_mask & REMOVE_CACHE) {
770 choice = ONLY_CACHE;
773 UMA_HISTOGRAM_ENUMERATION(
774 "History.ClearBrowsingData.UserDeletedCookieOrCache",
775 choice, MAX_CHOICE_VALUE);
778 void BrowsingDataRemover::AddObserver(Observer* observer) {
779 observer_list_.AddObserver(observer);
782 void BrowsingDataRemover::RemoveObserver(Observer* observer) {
783 observer_list_.RemoveObserver(observer);
786 void BrowsingDataRemover::OnHistoryDeletionDone() {
787 waiting_for_clear_history_ = false;
788 NotifyAndDeleteIfDone();
791 void BrowsingDataRemover::OverrideStoragePartitionForTesting(
792 content::StoragePartition* storage_partition) {
793 storage_partition_for_testing_ = storage_partition;
796 base::Time BrowsingDataRemover::CalculateBeginDeleteTime(
797 TimePeriod time_period) {
798 base::TimeDelta diff;
799 base::Time delete_begin_time = base::Time::Now();
800 switch (time_period) {
801 case LAST_HOUR:
802 diff = base::TimeDelta::FromHours(1);
803 break;
804 case LAST_DAY:
805 diff = base::TimeDelta::FromHours(24);
806 break;
807 case LAST_WEEK:
808 diff = base::TimeDelta::FromHours(7*24);
809 break;
810 case FOUR_WEEKS:
811 diff = base::TimeDelta::FromHours(4*7*24);
812 break;
813 case EVERYTHING:
814 delete_begin_time = base::Time();
815 break;
816 default:
817 NOTREACHED() << L"Missing item";
818 break;
820 return delete_begin_time - diff;
823 bool BrowsingDataRemover::AllDone() {
824 return !waiting_for_clear_autofill_origin_urls_ &&
825 !waiting_for_clear_cache_ &&
826 !waiting_for_clear_content_licenses_ &&
827 !waiting_for_clear_channel_ids_ &&
828 !waiting_for_clear_cookies_count_ &&
829 !waiting_for_clear_domain_reliability_monitor_ &&
830 !waiting_for_clear_form_ &&
831 !waiting_for_clear_history_ &&
832 !waiting_for_clear_hostname_resolution_cache_ &&
833 !waiting_for_clear_keyword_data_ &&
834 !waiting_for_clear_nacl_cache_ &&
835 !waiting_for_clear_network_predictor_ &&
836 !waiting_for_clear_networking_history_ &&
837 !waiting_for_clear_passwords_ &&
838 !waiting_for_clear_platform_keys_ &&
839 !waiting_for_clear_plugin_data_ &&
840 !waiting_for_clear_pnacl_cache_ &&
841 #if defined(OS_ANDROID)
842 !waiting_for_clear_precache_history_ &&
843 #endif
844 #if defined(ENABLE_WEBRTC)
845 !waiting_for_clear_webrtc_logs_ &&
846 #endif
847 !waiting_for_clear_storage_partition_data_;
850 void BrowsingDataRemover::OnKeywordsLoaded() {
851 // Deletes the entries from the model, and if we're not waiting on anything
852 // else notifies observers and deletes this BrowsingDataRemover.
853 TemplateURLService* model =
854 TemplateURLServiceFactory::GetForProfile(profile_);
855 model->RemoveAutoGeneratedBetween(delete_begin_, delete_end_);
856 waiting_for_clear_keyword_data_ = false;
857 template_url_sub_.reset();
858 NotifyAndDeleteIfDone();
861 void BrowsingDataRemover::NotifyAndDelete() {
862 set_removing(false);
864 // Notify observers.
865 BrowsingDataRemover::NotificationDetails details(delete_begin_, remove_mask_,
866 origin_type_mask_);
868 GetOnBrowsingDataRemovedCallbacks()->Notify(details);
870 FOR_EACH_OBSERVER(Observer, observer_list_, OnBrowsingDataRemoverDone());
872 // History requests aren't happy if you delete yourself from the callback.
873 // As such, we do a delete later.
874 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
877 void BrowsingDataRemover::NotifyAndDeleteIfDone() {
878 // TODO(brettw) http://crbug.com/305259: This should also observe session
879 // clearing (what about other things such as passwords, etc.?) and wait for
880 // them to complete before continuing.
882 if (!AllDone())
883 return;
885 if (completion_inhibitor_) {
886 completion_inhibitor_->OnBrowsingDataRemoverWouldComplete(
887 this,
888 base::Bind(&BrowsingDataRemover::NotifyAndDelete,
889 base::Unretained(this)));
890 } else {
891 NotifyAndDelete();
895 void BrowsingDataRemover::OnClearedHostnameResolutionCache() {
896 DCHECK_CURRENTLY_ON(BrowserThread::UI);
897 waiting_for_clear_hostname_resolution_cache_ = false;
898 NotifyAndDeleteIfDone();
901 void BrowsingDataRemover::ClearHostnameResolutionCacheOnIOThread(
902 IOThread* io_thread) {
903 DCHECK_CURRENTLY_ON(BrowserThread::IO);
905 io_thread->ClearHostCache();
907 // Notify the UI thread that we are done.
908 BrowserThread::PostTask(
909 BrowserThread::UI,
910 FROM_HERE,
911 base::Bind(&BrowsingDataRemover::OnClearedHostnameResolutionCache,
912 base::Unretained(this)));
915 void BrowsingDataRemover::OnClearedNetworkPredictor() {
916 DCHECK_CURRENTLY_ON(BrowserThread::UI);
917 waiting_for_clear_network_predictor_ = false;
918 NotifyAndDeleteIfDone();
921 void BrowsingDataRemover::ClearNetworkPredictorOnIOThread(
922 chrome_browser_net::Predictor* predictor) {
923 DCHECK_CURRENTLY_ON(BrowserThread::IO);
924 DCHECK(predictor);
926 predictor->DiscardInitialNavigationHistory();
927 predictor->DiscardAllResults();
929 // Notify the UI thread that we are done.
930 BrowserThread::PostTask(
931 BrowserThread::UI,
932 FROM_HERE,
933 base::Bind(&BrowsingDataRemover::OnClearedNetworkPredictor,
934 base::Unretained(this)));
937 void BrowsingDataRemover::OnClearedNetworkingHistory() {
938 DCHECK_CURRENTLY_ON(BrowserThread::UI);
939 waiting_for_clear_networking_history_ = false;
940 NotifyAndDeleteIfDone();
943 void BrowsingDataRemover::ClearedCache() {
944 waiting_for_clear_cache_ = false;
946 NotifyAndDeleteIfDone();
949 #if !defined(DISABLE_NACL)
950 void BrowsingDataRemover::ClearedNaClCache() {
951 // This function should be called on the UI thread.
952 DCHECK_CURRENTLY_ON(BrowserThread::UI);
954 waiting_for_clear_nacl_cache_ = false;
956 NotifyAndDeleteIfDone();
959 void BrowsingDataRemover::ClearedNaClCacheOnIOThread() {
960 // This function should be called on the IO thread.
961 DCHECK_CURRENTLY_ON(BrowserThread::IO);
963 // Notify the UI thread that we are done.
964 BrowserThread::PostTask(
965 BrowserThread::UI, FROM_HERE,
966 base::Bind(&BrowsingDataRemover::ClearedNaClCache,
967 base::Unretained(this)));
970 void BrowsingDataRemover::ClearNaClCacheOnIOThread() {
971 DCHECK_CURRENTLY_ON(BrowserThread::IO);
973 nacl::NaClBrowser::GetInstance()->ClearValidationCache(
974 base::Bind(&BrowsingDataRemover::ClearedNaClCacheOnIOThread,
975 base::Unretained(this)));
978 void BrowsingDataRemover::ClearedPnaclCache() {
979 // This function should be called on the UI thread.
980 DCHECK_CURRENTLY_ON(BrowserThread::UI);
982 waiting_for_clear_pnacl_cache_ = false;
984 NotifyAndDeleteIfDone();
987 void BrowsingDataRemover::ClearedPnaclCacheOnIOThread() {
988 // This function should be called on the IO thread.
989 DCHECK_CURRENTLY_ON(BrowserThread::IO);
991 // Notify the UI thread that we are done.
992 BrowserThread::PostTask(
993 BrowserThread::UI, FROM_HERE,
994 base::Bind(&BrowsingDataRemover::ClearedPnaclCache,
995 base::Unretained(this)));
998 void BrowsingDataRemover::ClearPnaclCacheOnIOThread(base::Time begin,
999 base::Time end) {
1000 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1002 pnacl::PnaclHost::GetInstance()->ClearTranslationCacheEntriesBetween(
1003 begin, end,
1004 base::Bind(&BrowsingDataRemover::ClearedPnaclCacheOnIOThread,
1005 base::Unretained(this)));
1007 #endif
1009 void BrowsingDataRemover::OnWaitableEventSignaled(
1010 base::WaitableEvent* waitable_event) {
1011 waiting_for_clear_plugin_data_ = false;
1012 NotifyAndDeleteIfDone();
1015 #if defined(ENABLE_PLUGINS)
1016 void BrowsingDataRemover::OnDeauthorizeContentLicensesCompleted(
1017 uint32 request_id,
1018 bool /* success */) {
1019 DCHECK(waiting_for_clear_content_licenses_);
1020 DCHECK_EQ(request_id, deauthorize_content_licenses_request_id_);
1022 waiting_for_clear_content_licenses_ = false;
1023 NotifyAndDeleteIfDone();
1025 #endif
1027 #if defined(OS_CHROMEOS)
1028 void BrowsingDataRemover::OnClearPlatformKeys(
1029 chromeos::DBusMethodCallStatus call_status,
1030 bool result) {
1031 DCHECK(waiting_for_clear_platform_keys_);
1032 if (call_status != chromeos::DBUS_METHOD_CALL_SUCCESS || !result) {
1033 LOG(ERROR) << "Failed to clear platform keys.";
1035 waiting_for_clear_platform_keys_ = false;
1036 NotifyAndDeleteIfDone();
1038 #endif
1041 void BrowsingDataRemover::OnClearedPasswords() {
1042 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1043 waiting_for_clear_passwords_ = false;
1044 NotifyAndDeleteIfDone();
1047 void BrowsingDataRemover::OnClearedCookies(int num_deleted) {
1048 if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
1049 BrowserThread::PostTask(
1050 BrowserThread::UI, FROM_HERE,
1051 base::Bind(&BrowsingDataRemover::OnClearedCookies,
1052 base::Unretained(this), num_deleted));
1053 return;
1056 DCHECK_GT(waiting_for_clear_cookies_count_, 0);
1057 --waiting_for_clear_cookies_count_;
1058 NotifyAndDeleteIfDone();
1061 void BrowsingDataRemover::ClearCookiesOnIOThread(
1062 net::URLRequestContextGetter* rq_context) {
1063 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1064 net::CookieStore* cookie_store = rq_context->
1065 GetURLRequestContext()->cookie_store();
1066 cookie_store->DeleteAllCreatedBetweenAsync(
1067 delete_begin_, delete_end_,
1068 base::Bind(&BrowsingDataRemover::OnClearedCookies,
1069 base::Unretained(this)));
1072 void BrowsingDataRemover::ClearChannelIDsOnIOThread(
1073 net::URLRequestContextGetter* rq_context) {
1074 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1075 net::ChannelIDService* channel_id_service =
1076 rq_context->GetURLRequestContext()->channel_id_service();
1077 channel_id_service->GetChannelIDStore()->DeleteAllCreatedBetween(
1078 delete_begin_, delete_end_,
1079 base::Bind(&BrowsingDataRemover::OnClearedChannelIDsOnIOThread,
1080 base::Unretained(this), base::Unretained(rq_context)));
1083 void BrowsingDataRemover::OnClearedChannelIDsOnIOThread(
1084 net::URLRequestContextGetter* rq_context) {
1085 // Need to close open SSL connections which may be using the channel ids we
1086 // are deleting.
1087 // TODO(mattm): http://crbug.com/166069 Make the server bound cert
1088 // service/store have observers that can notify relevant things directly.
1089 rq_context->GetURLRequestContext()->ssl_config_service()->
1090 NotifySSLConfigChange();
1091 BrowserThread::PostTask(
1092 BrowserThread::UI, FROM_HERE,
1093 base::Bind(&BrowsingDataRemover::OnClearedChannelIDs,
1094 base::Unretained(this)));
1097 void BrowsingDataRemover::OnClearedChannelIDs() {
1098 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1099 waiting_for_clear_channel_ids_ = false;
1100 NotifyAndDeleteIfDone();
1103 void BrowsingDataRemover::OnClearedFormData() {
1104 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1105 waiting_for_clear_form_ = false;
1106 NotifyAndDeleteIfDone();
1109 void BrowsingDataRemover::OnClearedAutofillOriginURLs() {
1110 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1111 waiting_for_clear_autofill_origin_urls_ = false;
1112 NotifyAndDeleteIfDone();
1115 void BrowsingDataRemover::OnClearedStoragePartitionData() {
1116 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1117 waiting_for_clear_storage_partition_data_ = false;
1118 NotifyAndDeleteIfDone();
1121 #if defined(ENABLE_WEBRTC)
1122 void BrowsingDataRemover::OnClearedWebRtcLogs() {
1123 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1124 waiting_for_clear_webrtc_logs_ = false;
1125 NotifyAndDeleteIfDone();
1127 #endif
1129 #if defined(OS_ANDROID)
1130 void BrowsingDataRemover::OnClearedPrecacheHistory() {
1131 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1132 waiting_for_clear_precache_history_ = false;
1133 NotifyAndDeleteIfDone();
1135 #endif
1137 void BrowsingDataRemover::OnClearedDomainReliabilityMonitor() {
1138 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1139 waiting_for_clear_domain_reliability_monitor_ = false;
1140 NotifyAndDeleteIfDone();
1143 // static
1144 BrowsingDataRemover::CallbackSubscription
1145 BrowsingDataRemover::RegisterOnBrowsingDataRemovedCallback(
1146 const BrowsingDataRemover::Callback& callback) {
1147 return GetOnBrowsingDataRemovedCallbacks()->Add(callback);