blob: 47a19417f2c8c93752f85e12689a7b6c1e495587 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit09911bf2008-07-26 23:55:294//
5
6#include "chrome/browser/safe_browsing/safe_browsing_service.h"
7
[email protected]613a03b2008-10-24 23:02:008#include "base/command_line.h"
initial.commit09911bf2008-07-26 23:55:299#include "base/histogram.h"
10#include "base/logging.h"
11#include "base/message_loop.h"
12#include "base/path_service.h"
13#include "base/string_util.h"
14#include "chrome/browser/browser_process.h"
[email protected]0a3076572008-12-13 20:48:3615#include "chrome/browser/chrome_thread.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/profile_manager.h"
[email protected]51065cb2009-02-19 00:25:2317#include "chrome/browser/safe_browsing/protocol_manager.h"
[email protected]5b7c7d3c2009-02-19 00:06:2218#include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/safe_browsing/safe_browsing_database.h"
[email protected]dfdb0de72009-02-19 21:58:1420#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]f3ec7742009-01-15 00:59:1621#include "chrome/browser/tab_contents/tab_util.h"
[email protected]dfdb0de72009-02-19 21:58:1422#include "chrome/browser/tab_contents/web_contents.h"
initial.commit09911bf2008-07-26 23:55:2923#include "chrome/common/chrome_constants.h"
24#include "chrome/common/chrome_paths.h"
initial.commit09911bf2008-07-26 23:55:2925#include "chrome/common/pref_names.h"
26#include "chrome/common/pref_service.h"
[email protected]dcf7d352009-02-26 01:56:0227#include "chrome/common/url_constants.h"
initial.commit09911bf2008-07-26 23:55:2928#include "net/base/registry_controlled_domain.h"
29
[email protected]e1acf6f2008-10-27 20:43:3330using base::Time;
31using base::TimeDelta;
32
initial.commit09911bf2008-07-26 23:55:2933SafeBrowsingService::SafeBrowsingService()
34 : io_loop_(NULL),
35 database_(NULL),
36 protocol_manager_(NULL),
37 enabled_(false),
[email protected]613a03b2008-10-24 23:02:0038 resetting_(false),
[email protected]57119c3f2008-12-04 00:33:0439 database_loaded_(false),
40 update_in_progress_(false) {
[email protected]0a3076572008-12-13 20:48:3641 base::SystemMonitor* monitor = base::SystemMonitor::Get();
42 DCHECK(monitor);
43 if (monitor)
44 monitor->AddObserver(this);
initial.commit09911bf2008-07-26 23:55:2945}
46
47SafeBrowsingService::~SafeBrowsingService() {
[email protected]0a3076572008-12-13 20:48:3648 base::SystemMonitor* monitor = base::SystemMonitor::Get();
49 if (monitor)
50 monitor->RemoveObserver(this);
initial.commit09911bf2008-07-26 23:55:2951}
52
53// Only called on the UI thread.
54void SafeBrowsingService::Initialize(MessageLoop* io_loop) {
55 io_loop_ = io_loop;
56
57 // Get the profile's preference for SafeBrowsing.
[email protected]c870c762009-01-28 05:47:1558 FilePath user_data_dir;
initial.commit09911bf2008-07-26 23:55:2959 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
60 ProfileManager* profile_manager = g_browser_process->profile_manager();
[email protected]f7011fcb2009-01-28 21:54:3261 Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
initial.commit09911bf2008-07-26 23:55:2962 PrefService* pref_service = profile->GetPrefs();
63 if (pref_service->GetBoolean(prefs::kSafeBrowsingEnabled))
64 Start();
65}
66
67// Start up SafeBrowsing objects. This can be called at browser start, or when
68// the user checks the "Enable SafeBrowsing" option in the Advanced options UI.
69void SafeBrowsingService::Start() {
70 DCHECK(!db_thread_.get());
[email protected]ab820df2008-08-26 05:55:1071 db_thread_.reset(new base::Thread("Chrome_SafeBrowsingThread"));
initial.commit09911bf2008-07-26 23:55:2972 if (!db_thread_->Start())
73 return;
74
initial.commit09911bf2008-07-26 23:55:2975 // Retrieve client MAC keys.
76 PrefService* local_state = g_browser_process->local_state();
77 std::string client_key, wrapped_key;
78 if (local_state) {
79 client_key =
80 WideToASCII(local_state->GetString(prefs::kSafeBrowsingClientKey));
81 wrapped_key =
82 WideToASCII(local_state->GetString(prefs::kSafeBrowsingWrappedKey));
83 }
84
85 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
86 this, &SafeBrowsingService::OnIOInitialize, MessageLoop::current(),
87 client_key, wrapped_key));
[email protected]2c2fb222008-12-17 02:35:4688
89 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
90 this, &SafeBrowsingService::OnDBInitialize));
initial.commit09911bf2008-07-26 23:55:2991}
92
93void SafeBrowsingService::ShutDown() {
94 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
95 this, &SafeBrowsingService::OnIOShutdown));
96}
97
98void SafeBrowsingService::OnIOInitialize(MessageLoop* notify_loop,
99 const std::string& client_key,
100 const std::string& wrapped_key) {
101 DCHECK(MessageLoop::current() == io_loop_);
102 enabled_ = true;
103 protocol_manager_ = new SafeBrowsingProtocolManager(this,
104 notify_loop,
105 client_key,
106 wrapped_key);
[email protected]613a03b2008-10-24 23:02:00107 // We want to initialize the protocol manager only after the database has
108 // loaded, which we'll receive asynchronously (DatabaseLoadComplete). If
109 // database_loaded_ isn't true, we'll wait for that notification to do the
110 // init.
111 if (database_loaded_)
112 protocol_manager_->Initialize();
initial.commit09911bf2008-07-26 23:55:29113}
114
115void SafeBrowsingService::OnDBInitialize() {
116 DCHECK(MessageLoop::current() == db_thread_->message_loop());
117 GetDatabase();
118}
119
120void SafeBrowsingService::OnIOShutdown() {
121 DCHECK(MessageLoop::current() == io_loop_);
122 if (!enabled_)
123 return;
124
125 enabled_ = false;
[email protected]fbb2b7a2008-11-18 22:54:04126 resetting_ = false;
initial.commit09911bf2008-07-26 23:55:29127
128 // This cancels all in-flight GetHash requests.
129 delete protocol_manager_;
[email protected]fbb2b7a2008-11-18 22:54:04130 protocol_manager_ = NULL;
initial.commit09911bf2008-07-26 23:55:29131
132 if (db_thread_.get())
133 db_thread_->message_loop()->DeleteSoon(FROM_HERE, database_);
134
135 // Flush the database thread. Any in-progress database check results will be
136 // ignored and cleaned up below.
137 db_thread_.reset(NULL);
138
139 database_ = NULL;
[email protected]fbb2b7a2008-11-18 22:54:04140 database_loaded_ = false;
initial.commit09911bf2008-07-26 23:55:29141
[email protected]613a03b2008-10-24 23:02:00142 // Delete queued and pending checks once the database thread is done, calling
143 // back any clients with 'URL_SAFE'.
144 while (!queued_checks_.empty()) {
145 QueuedCheck check = queued_checks_.front();
146 if (check.client)
147 check.client->OnUrlCheckResult(check.url, URL_SAFE);
148 queued_checks_.pop_front();
149 }
150
initial.commit09911bf2008-07-26 23:55:29151 for (CurrentChecks::iterator it = checks_.begin();
152 it != checks_.end(); ++it) {
153 if ((*it)->client)
154 (*it)->client->OnUrlCheckResult((*it)->url, URL_SAFE);
155 delete *it;
156 }
157 checks_.clear();
158
159 gethash_requests_.clear();
160}
161
162// Runs on the UI thread.
163void SafeBrowsingService::OnEnable(bool enabled) {
164 if (enabled)
165 Start();
166 else
167 ShutDown();
168}
169
170bool SafeBrowsingService::CanCheckUrl(const GURL& url) const {
[email protected]dcf7d352009-02-26 01:56:02171 return url.SchemeIs(chrome::kHttpScheme) ||
172 url.SchemeIs(chrome::kHttpsScheme);
initial.commit09911bf2008-07-26 23:55:29173}
174
175bool SafeBrowsingService::CheckUrl(const GURL& url, Client* client) {
176 DCHECK(MessageLoop::current() == io_loop_);
initial.commit09911bf2008-07-26 23:55:29177 if (!enabled_ || !database_)
178 return true;
179
[email protected]613a03b2008-10-24 23:02:00180 if (resetting_ || !database_loaded_) {
181 QueuedCheck check;
182 check.client = client;
183 check.url = url;
184 queued_checks_.push_back(check);
185 return false;
186 }
187
188 std::string list;
189 std::vector<SBPrefix> prefix_hits;
190 std::vector<SBFullHashResult> full_hits;
[email protected]22573822008-11-14 00:40:47191 base::Time check_start = base::Time::Now();
[email protected]c3ff89492008-11-11 02:17:51192 bool prefix_match = database_->ContainsUrl(url, &list, &prefix_hits,
193 &full_hits,
[email protected]613a03b2008-10-24 23:02:00194 protocol_manager_->last_update());
[email protected]f0a51fb52009-03-05 12:46:38195
[email protected]553dba62009-02-24 19:08:23196 UMA_HISTOGRAM_TIMES("SB2.FilterCheck", base::Time::Now() - check_start);
[email protected]22573822008-11-14 00:40:47197
[email protected]613a03b2008-10-24 23:02:00198 if (!prefix_match)
199 return true; // URL is okay.
200
201 // Needs to be asynchronous, since we could be in the constructor of a
202 // ResourceDispatcherHost event handler which can't pause there.
203 SafeBrowsingCheck* check = new SafeBrowsingCheck();
204 check->url = url;
205 check->client = client;
206 check->result = URL_SAFE;
207 check->start = Time::Now();
208 check->need_get_hash = full_hits.empty();
209 check->prefix_hits.swap(prefix_hits);
210 check->full_hits.swap(full_hits);
211 checks_.insert(check);
212
213 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
214 this, &SafeBrowsingService::OnCheckDone, check));
215
initial.commit09911bf2008-07-26 23:55:29216 return false;
217}
218
219void SafeBrowsingService::DisplayBlockingPage(const GURL& url,
220 ResourceType::Type resource_type,
221 UrlCheckResult result,
222 Client* client,
223 MessageLoop* ui_loop,
224 int render_process_host_id,
225 int render_view_id) {
226 // Check if the user has already ignored our warning for this render_view
227 // and domain.
228 for (size_t i = 0; i < white_listed_entries_.size(); ++i) {
229 const WhiteListedEntry& entry = white_listed_entries_[i];
230 if (entry.render_process_host_id == render_process_host_id &&
231 entry.render_view_id == render_view_id &&
232 entry.result == result &&
233 entry.domain ==
[email protected]8ac1a752008-07-31 19:40:37234 net::RegistryControlledDomainService::GetDomainAndRegistry(url)) {
initial.commit09911bf2008-07-26 23:55:29235 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
236 this, &SafeBrowsingService::NotifyClientBlockingComplete,
237 client, true));
238 return;
239 }
240 }
241
[email protected]1b277e72009-01-23 21:05:34242 UnsafeResource resource;
243 resource.url = url;
244 resource.resource_type = resource_type;
245 resource.threat_type= result;
246 resource.client = client;
247 resource.render_process_host_id = render_process_host_id;
248 resource.render_view_id = render_view_id;
[email protected]484c57a2009-03-21 01:24:01249
[email protected]cbab76d2008-10-13 22:42:47250 // The blocking page must be created from the UI thread.
251 ui_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
252 &SafeBrowsingService::DoDisplayBlockingPage,
[email protected]1b277e72009-01-23 21:05:34253 resource));
[email protected]cbab76d2008-10-13 22:42:47254}
255
256// Invoked on the UI thread.
257void SafeBrowsingService::DoDisplayBlockingPage(
[email protected]1b277e72009-01-23 21:05:34258 const UnsafeResource& resource) {
[email protected]a3a1d142008-12-19 00:42:30259 // The tab might have been closed.
[email protected]dfdb0de72009-02-19 21:58:14260 WebContents* wc =
261 tab_util::GetWebContentsByID(resource.render_process_host_id,
262 resource.render_view_id);
263
264 if (!wc) {
[email protected]a3a1d142008-12-19 00:42:30265 // The tab is gone and we did not have a chance at showing the interstitial.
266 // Just act as "Don't Proceed" was chosen.
267 base::Thread* io_thread = g_browser_process->io_thread();
268 if (!io_thread)
269 return;
[email protected]1b277e72009-01-23 21:05:34270 std::vector<UnsafeResource> resources;
271 resources.push_back(resource);
[email protected]a3a1d142008-12-19 00:42:30272 io_thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
[email protected]1b277e72009-01-23 21:05:34273 this, &SafeBrowsingService::OnBlockingPageDone, resources, false));
[email protected]a3a1d142008-12-19 00:42:30274 return;
275 }
[email protected]dfdb0de72009-02-19 21:58:14276
277 // Report the malware sub-resource to the SafeBrowsing servers if we have a
278 // malware sub-resource on a safe page and only if the user has opted in to
279 // reporting statistics.
280 PrefService* prefs = g_browser_process->local_state();
281 DCHECK(prefs);
282 if (prefs && prefs->GetBoolean(prefs::kMetricsReportingEnabled) &&
283 resource.resource_type != ResourceType::MAIN_FRAME &&
284 resource.threat_type == SafeBrowsingService::URL_MALWARE) {
285 GURL page_url = wc->GetURL();
286 GURL referrer_url;
287 if (wc->controller()) {
288 NavigationEntry* entry = wc->controller()->GetActiveEntry();
289 if (entry)
290 referrer_url = entry->referrer();
291 }
292 io_loop_->PostTask(FROM_HERE,
293 NewRunnableMethod(this,
294 &SafeBrowsingService::ReportMalware,
295 resource.url,
296 page_url,
297 referrer_url));
298 }
299
[email protected]1b277e72009-01-23 21:05:34300 SafeBrowsingBlockingPage::ShowBlockingPage(this, resource);
initial.commit09911bf2008-07-26 23:55:29301}
302
303void SafeBrowsingService::CancelCheck(Client* client) {
304 DCHECK(MessageLoop::current() == io_loop_);
305
306 for (CurrentChecks::iterator i = checks_.begin(); i != checks_.end(); ++i) {
307 if ((*i)->client == client)
308 (*i)->client = NULL;
309 }
[email protected]613a03b2008-10-24 23:02:00310
311 // Scan the queued clients store. Clients may be here if they requested a URL
312 // check before the database has finished loading or resetting.
313 if (!database_loaded_ || resetting_) {
314 std::deque<QueuedCheck>::iterator it = queued_checks_.begin();
315 for (; it != queued_checks_.end(); ++it) {
316 if (it->client == client)
317 it->client = NULL;
318 }
319 }
initial.commit09911bf2008-07-26 23:55:29320}
321
322void SafeBrowsingService::CheckDatabase(SafeBrowsingCheck* info,
323 Time last_update) {
324 DCHECK(MessageLoop::current() == db_thread_->message_loop());
325 // If client == NULL it means it was cancelled, no need for db lookup.
326 if (info->client && GetDatabase()) {
327 Time now = Time::Now();
328 std::string list;
329 if (GetDatabase()->ContainsUrl(info->url,
330 &list,
331 &info->prefix_hits,
332 &info->full_hits,
333 last_update)) {
334 if (info->prefix_hits.empty()) {
335 info->result = GetResultFromListname(list);
336 } else {
337 if (info->full_hits.empty())
338 info->need_get_hash = true;
339 }
340 }
341 info->db_time = Time::Now() - now;
342 }
343
344 if (io_loop_)
345 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
346 this, &SafeBrowsingService::OnCheckDone, info));
347}
348
[email protected]613a03b2008-10-24 23:02:00349void SafeBrowsingService::OnCheckDone(SafeBrowsingCheck* check) {
initial.commit09911bf2008-07-26 23:55:29350 DCHECK(MessageLoop::current() == io_loop_);
351
352 // If we've been shutdown during the database lookup, this check will already
353 // have been deleted (in OnIOShutdown).
[email protected]613a03b2008-10-24 23:02:00354 if (!enabled_ || checks_.find(check) == checks_.end())
initial.commit09911bf2008-07-26 23:55:29355 return;
356
[email protected]553dba62009-02-24 19:08:23357 UMA_HISTOGRAM_TIMES("SB.Database", Time::Now() - check->start);
[email protected]613a03b2008-10-24 23:02:00358 if (check->client && check->need_get_hash) {
initial.commit09911bf2008-07-26 23:55:29359 // We have a partial match so we need to query Google for the full hash.
360 // Clean up will happen in HandleGetHashResults.
361
362 // See if we have a GetHash request already in progress for this particular
363 // prefix. If so, we just append ourselves to the list of interested parties
364 // when the results arrive. We only do this for checks involving one prefix,
365 // since that is the common case (multiple prefixes will issue the request
366 // as normal).
[email protected]613a03b2008-10-24 23:02:00367 if (check->prefix_hits.size() == 1) {
368 SBPrefix prefix = check->prefix_hits[0];
initial.commit09911bf2008-07-26 23:55:29369 GetHashRequests::iterator it = gethash_requests_.find(prefix);
370 if (it != gethash_requests_.end()) {
371 // There's already a request in progress.
[email protected]613a03b2008-10-24 23:02:00372 it->second.push_back(check);
initial.commit09911bf2008-07-26 23:55:29373 return;
374 }
375
376 // No request in progress, so we're the first for this prefix.
377 GetHashRequestors requestors;
[email protected]613a03b2008-10-24 23:02:00378 requestors.push_back(check);
initial.commit09911bf2008-07-26 23:55:29379 gethash_requests_[prefix] = requestors;
380 }
381
382 // Reset the start time so that we can measure the network time without the
383 // database time.
[email protected]613a03b2008-10-24 23:02:00384 check->start = Time::Now();
385 protocol_manager_->GetFullHash(check, check->prefix_hits);
initial.commit09911bf2008-07-26 23:55:29386 } else {
387 // We may have cached results for previous GetHash queries.
[email protected]613a03b2008-10-24 23:02:00388 HandleOneCheck(check, check->full_hits);
initial.commit09911bf2008-07-26 23:55:29389 }
390}
391
392SafeBrowsingDatabase* SafeBrowsingService::GetDatabase() {
393 DCHECK(MessageLoop::current() == db_thread_->message_loop());
394 if (database_)
395 return database_;
396
[email protected]c870c762009-01-28 05:47:15397 FilePath path;
initial.commit09911bf2008-07-26 23:55:29398 bool result = PathService::Get(chrome::DIR_USER_DATA, &path);
399 DCHECK(result);
[email protected]c870c762009-01-28 05:47:15400 path = path.Append(chrome::kSafeBrowsingFilename);
initial.commit09911bf2008-07-26 23:55:29401
402 Time before = Time::Now();
[email protected]54d80bb02008-09-20 02:03:08403 SafeBrowsingDatabase* database = SafeBrowsingDatabase::Create();
[email protected]613a03b2008-10-24 23:02:00404 Callback0::Type* chunk_callback =
initial.commit09911bf2008-07-26 23:55:29405 NewCallback(this, &SafeBrowsingService::ChunkInserted);
[email protected]613a03b2008-10-24 23:02:00406 bool init_success = database->Init(path, chunk_callback);
407
408 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
409 this, &SafeBrowsingService::DatabaseLoadComplete, !init_success));
410
411 if (!init_success) {
initial.commit09911bf2008-07-26 23:55:29412 NOTREACHED();
413 return NULL;
414 }
415
416 database_ = database;
417
418 TimeDelta open_time = Time::Now() - before;
419 SB_DLOG(INFO) << "SafeBrowsing database open took " <<
420 open_time.InMilliseconds() << " ms.";
421
422 return database_;
423}
424
425// Public API called only on the IO thread.
426// The SafeBrowsingProtocolManager has received the full hash results for
427// prefix hits detected in the database.
428void SafeBrowsingService::HandleGetHashResults(
429 SafeBrowsingCheck* check,
[email protected]200abc32008-09-05 01:44:33430 const std::vector<SBFullHashResult>& full_hashes,
431 bool can_cache) {
initial.commit09911bf2008-07-26 23:55:29432 if (checks_.find(check) == checks_.end())
433 return;
434
435 DCHECK(enabled_);
436
[email protected]484c57a2009-03-21 01:24:01437 UMA_HISTOGRAM_LONG_TIMES("SB2.Network", Time::Now() - check->start);
[email protected]22573822008-11-14 00:40:47438
[email protected]200abc32008-09-05 01:44:33439 std::vector<SBPrefix> prefixes = check->prefix_hits;
initial.commit09911bf2008-07-26 23:55:29440 OnHandleGetHashResults(check, full_hashes); // 'check' is deleted here.
441
[email protected]484c57a2009-03-21 01:24:01442 if (can_cache && database_) {
443 // Cache the GetHash results in memory:
444 database_->CacheHashResults(prefixes, full_hashes);
[email protected]613a03b2008-10-24 23:02:00445 }
initial.commit09911bf2008-07-26 23:55:29446}
447
448void SafeBrowsingService::OnHandleGetHashResults(
449 SafeBrowsingCheck* check,
450 const std::vector<SBFullHashResult>& full_hashes) {
451 SBPrefix prefix = check->prefix_hits[0];
452 GetHashRequests::iterator it = gethash_requests_.find(prefix);
453 if (check->prefix_hits.size() > 1 || it == gethash_requests_.end()) {
454 HandleOneCheck(check, full_hashes);
455 return;
456 }
457
458 // Call back all interested parties.
459 GetHashRequestors& requestors = it->second;
460 for (GetHashRequestors::iterator r = requestors.begin();
461 r != requestors.end(); ++r) {
462 HandleOneCheck(*r, full_hashes);
463 }
464
465 gethash_requests_.erase(it);
466}
467
468void SafeBrowsingService::HandleOneCheck(
469 SafeBrowsingCheck* check,
470 const std::vector<SBFullHashResult>& full_hashes) {
471 if (check->client) {
472 UrlCheckResult result = URL_SAFE;
473 int index = safe_browsing_util::CompareFullHashes(check->url, full_hashes);
474 if (index != -1)
475 result = GetResultFromListname(full_hashes[index].list_name);
476
477 // Let the client continue handling the original request.
478 check->client->OnUrlCheckResult(check->url, result);
479 }
480
481 checks_.erase(check);
482 delete check;
483}
484
[email protected]57119c3f2008-12-04 00:33:04485void SafeBrowsingService::UpdateStarted() {
initial.commit09911bf2008-07-26 23:55:29486 DCHECK(MessageLoop::current() == io_loop_);
487 DCHECK(enabled_);
[email protected]57119c3f2008-12-04 00:33:04488 DCHECK(!update_in_progress_);
489 update_in_progress_ = true;
initial.commit09911bf2008-07-26 23:55:29490 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
491 this, &SafeBrowsingService::GetAllChunksFromDatabase));
492}
493
[email protected]613a03b2008-10-24 23:02:00494void SafeBrowsingService::UpdateFinished(bool update_succeeded) {
[email protected]aad08752008-10-02 22:13:41495 DCHECK(MessageLoop::current() == io_loop_);
496 DCHECK(enabled_);
[email protected]57119c3f2008-12-04 00:33:04497 if (update_in_progress_) {
498 update_in_progress_ = false;
499 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
500 this, &SafeBrowsingService::DatabaseUpdateFinished, update_succeeded));
501 }
[email protected]aad08752008-10-02 22:13:41502}
503
[email protected]613a03b2008-10-24 23:02:00504void SafeBrowsingService::DatabaseUpdateFinished(bool update_succeeded) {
[email protected]aad08752008-10-02 22:13:41505 DCHECK(MessageLoop::current() == db_thread_->message_loop());
506 if (GetDatabase())
[email protected]613a03b2008-10-24 23:02:00507 GetDatabase()->UpdateFinished(update_succeeded);
[email protected]aad08752008-10-02 22:13:41508}
509
[email protected]1b277e72009-01-23 21:05:34510void SafeBrowsingService::OnBlockingPageDone(
511 const std::vector<UnsafeResource>& resources,
512 bool proceed) {
513 for (std::vector<UnsafeResource>::const_iterator iter = resources.begin();
514 iter != resources.end(); ++iter) {
515 const UnsafeResource& resource = *iter;
516 NotifyClientBlockingComplete(resource.client, proceed);
initial.commit09911bf2008-07-26 23:55:29517
[email protected]1b277e72009-01-23 21:05:34518 if (proceed) {
519 // Whitelist this domain and warning type for the given tab.
520 WhiteListedEntry entry;
521 entry.render_process_host_id = resource.render_process_host_id;
522 entry.render_view_id = resource.render_view_id;
523 entry.domain = net::RegistryControlledDomainService::GetDomainAndRegistry(
524 resource.url);
525 entry.result = resource.threat_type;
526 white_listed_entries_.push_back(entry);
527 }
initial.commit09911bf2008-07-26 23:55:29528 }
initial.commit09911bf2008-07-26 23:55:29529}
530
531void SafeBrowsingService::NotifyClientBlockingComplete(Client* client,
532 bool proceed) {
533 client->OnBlockingPageComplete(proceed);
534}
535
536// This method runs on the UI loop to access the prefs.
537void SafeBrowsingService::OnNewMacKeys(const std::string& client_key,
538 const std::string& wrapped_key) {
539 PrefService* prefs = g_browser_process->local_state();
540 if (prefs) {
541 prefs->SetString(prefs::kSafeBrowsingClientKey, ASCIIToWide(client_key));
542 prefs->SetString(prefs::kSafeBrowsingWrappedKey, ASCIIToWide(wrapped_key));
543 }
544}
545
546void SafeBrowsingService::ChunkInserted() {
[email protected]fbb2b7a2008-11-18 22:54:04547 DCHECK(MessageLoop::current() == db_thread_->message_loop());
initial.commit09911bf2008-07-26 23:55:29548 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
549 this, &SafeBrowsingService::OnChunkInserted));
550}
551
552void SafeBrowsingService::OnChunkInserted() {
553 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04554 if (enabled_)
555 protocol_manager_->OnChunkInserted();
initial.commit09911bf2008-07-26 23:55:29556}
557
[email protected]613a03b2008-10-24 23:02:00558void SafeBrowsingService::DatabaseLoadComplete(bool database_error) {
559 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04560 if (!enabled_)
561 return;
[email protected]613a03b2008-10-24 23:02:00562
563 database_loaded_ = true;
564
565 // TODO(paulg): More robust database initialization error handling.
566 if (protocol_manager_ && !database_error)
567 protocol_manager_->Initialize();
568
569 // If we have any queued requests, we can now check them.
570 if (!resetting_)
571 RunQueuedClients();
572}
573
initial.commit09911bf2008-07-26 23:55:29574// static
[email protected]919d77f02009-01-06 19:48:35575void SafeBrowsingService::RegisterPrefs(PrefService* prefs) {
initial.commit09911bf2008-07-26 23:55:29576 prefs->RegisterStringPref(prefs::kSafeBrowsingClientKey, L"");
577 prefs->RegisterStringPref(prefs::kSafeBrowsingWrappedKey, L"");
578}
579
580void SafeBrowsingService::ResetDatabase() {
581 DCHECK(MessageLoop::current() == io_loop_);
582 resetting_ = true;
583 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
584 this, &SafeBrowsingService::OnResetDatabase));
585}
586
587void SafeBrowsingService::OnResetDatabase() {
588 DCHECK(MessageLoop::current() == db_thread_->message_loop());
589 GetDatabase()->ResetDatabase();
590 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
591 this, &SafeBrowsingService::OnResetComplete));
592}
593
594void SafeBrowsingService::OnResetComplete() {
595 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04596 if (enabled_) {
597 resetting_ = false;
598 database_loaded_ = true;
599 RunQueuedClients();
600 }
initial.commit09911bf2008-07-26 23:55:29601}
602
603void SafeBrowsingService::HandleChunk(const std::string& list,
604 std::deque<SBChunk>* chunks) {
605 DCHECK(MessageLoop::current() == io_loop_);
606 DCHECK(enabled_);
607 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
608 this, &SafeBrowsingService::HandleChunkForDatabase, list, chunks));
609}
610
611void SafeBrowsingService::HandleChunkForDatabase(
612 const std::string& list_name,
613 std::deque<SBChunk>* chunks) {
614 DCHECK(MessageLoop::current() == db_thread_->message_loop());
615
616 GetDatabase()->InsertChunks(list_name, chunks);
617}
618
619void SafeBrowsingService::HandleChunkDelete(
620 std::vector<SBChunkDelete>* chunk_deletes) {
621 DCHECK(MessageLoop::current() == io_loop_);
622 DCHECK(enabled_);
623 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
624 this, &SafeBrowsingService::DeleteChunks, chunk_deletes));
625}
626
627void SafeBrowsingService::DeleteChunks(
628 std::vector<SBChunkDelete>* chunk_deletes) {
629 DCHECK(MessageLoop::current() == db_thread_->message_loop());
630
631 GetDatabase()->DeleteChunks(chunk_deletes);
632}
633
634// Database worker function.
635void SafeBrowsingService::GetAllChunksFromDatabase() {
636 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]a5a37522008-11-11 21:49:56637 bool database_error = true;
initial.commit09911bf2008-07-26 23:55:29638 std::vector<SBListChunkRanges> lists;
[email protected]53ad8572008-11-13 21:50:34639 if (GetDatabase()) {
640 if (GetDatabase()->UpdateStarted()) {
641 GetDatabase()->GetListsInfo(&lists);
642 database_error = false;
643 } else {
644 GetDatabase()->UpdateFinished(false);
645 }
initial.commit09911bf2008-07-26 23:55:29646 }
647
648 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
649 this, &SafeBrowsingService::OnGetAllChunksFromDatabase, lists,
650 database_error));
651}
652
653// Called on the io thread with the results of all chunks.
654void SafeBrowsingService::OnGetAllChunksFromDatabase(
655 const std::vector<SBListChunkRanges>& lists, bool database_error) {
656 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04657 if (enabled_)
658 protocol_manager_->OnGetChunksComplete(lists, database_error);
initial.commit09911bf2008-07-26 23:55:29659}
660
661SafeBrowsingService::UrlCheckResult SafeBrowsingService::GetResultFromListname(
662 const std::string& list_name) {
663 if (safe_browsing_util::IsPhishingList(list_name)) {
664 return URL_PHISHING;
665 }
666
667 if (safe_browsing_util::IsMalwareList(list_name)) {
668 return URL_MALWARE;
669 }
670
671 SB_DLOG(INFO) << "Unknown safe browsing list " << list_name;
672 return URL_SAFE;
673}
674
initial.commit09911bf2008-07-26 23:55:29675void SafeBrowsingService::LogPauseDelay(TimeDelta time) {
[email protected]484c57a2009-03-21 01:24:01676 UMA_HISTOGRAM_LONG_TIMES("SB2.Delay", time);
initial.commit09911bf2008-07-26 23:55:29677}
678
679void SafeBrowsingService::CacheHashResults(
[email protected]200abc32008-09-05 01:44:33680 const std::vector<SBPrefix>& prefixes,
initial.commit09911bf2008-07-26 23:55:29681 const std::vector<SBFullHashResult>& full_hashes) {
682 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]200abc32008-09-05 01:44:33683 GetDatabase()->CacheHashResults(prefixes, full_hashes);
initial.commit09911bf2008-07-26 23:55:29684}
685
[email protected]0a3076572008-12-13 20:48:36686void SafeBrowsingService::OnSuspend(base::SystemMonitor*) {
initial.commit09911bf2008-07-26 23:55:29687}
688
689// Tell the SafeBrowsing database not to do expensive disk operations for a few
690// minutes after waking up. It's quite likely that the act of resuming from a
691// low power state will involve much disk activity, which we don't want to
692// exacerbate.
[email protected]0a3076572008-12-13 20:48:36693void SafeBrowsingService::OnResume(base::SystemMonitor*) {
initial.commit09911bf2008-07-26 23:55:29694 if (enabled_) {
[email protected]0a3076572008-12-13 20:48:36695 ChromeThread::GetMessageLoop(ChromeThread::DB)->PostTask(FROM_HERE,
696 NewRunnableMethod(this, &SafeBrowsingService::HandleResume));
initial.commit09911bf2008-07-26 23:55:29697 }
698}
699
700void SafeBrowsingService::HandleResume() {
701 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]53ad8572008-11-13 21:50:34702 // We don't call GetDatabase() here, since we want to avoid unnecessary calls
703 // to Open, Reset, etc, or reload the bloom filter while we're coming out of
704 // a suspended state.
705 if (database_)
706 database_->HandleResume();
license.botbf09a502008-08-24 00:55:55707}
[email protected]613a03b2008-10-24 23:02:00708
709void SafeBrowsingService::RunQueuedClients() {
710 DCHECK(MessageLoop::current() == io_loop_);
[email protected]553dba62009-02-24 19:08:23711 HISTOGRAM_COUNTS("SB.QueueDepth", queued_checks_.size());
[email protected]613a03b2008-10-24 23:02:00712 while (!queued_checks_.empty()) {
713 QueuedCheck check = queued_checks_.front();
[email protected]553dba62009-02-24 19:08:23714 HISTOGRAM_TIMES("SB.QueueDelay", Time::Now() - check.start);
[email protected]613a03b2008-10-24 23:02:00715 CheckUrl(check.url, check.client);
716 queued_checks_.pop_front();
717 }
718}
719
[email protected]dfdb0de72009-02-19 21:58:14720void SafeBrowsingService::ReportMalware(const GURL& malware_url,
721 const GURL& page_url,
722 const GURL& referrer_url) {
723 DCHECK(MessageLoop::current() == io_loop_);
724
[email protected]484c57a2009-03-21 01:24:01725 if (!enabled_ || !database_)
[email protected]dfdb0de72009-02-19 21:58:14726 return;
727
728 // Check if 'page_url' is already blacklisted (exists in our cache). Only
729 // report if it's not there.
730 std::string list;
731 std::vector<SBPrefix> prefix_hits;
732 std::vector<SBFullHashResult> full_hits;
733 database_->ContainsUrl(page_url, &list, &prefix_hits, &full_hits,
734 protocol_manager_->last_update());
735
736 if (full_hits.empty())
737 protocol_manager_->ReportMalware(malware_url, page_url, referrer_url);
738}