blob: 1a1c88a325bb7cb0134a3edc7c1c0ce6c7f77fc0 [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;
[email protected]613a03b2008-10-24 23:02:00207 check->need_get_hash = full_hits.empty();
208 check->prefix_hits.swap(prefix_hits);
209 check->full_hits.swap(full_hits);
210 checks_.insert(check);
211
212 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
213 this, &SafeBrowsingService::OnCheckDone, check));
214
initial.commit09911bf2008-07-26 23:55:29215 return false;
216}
217
218void SafeBrowsingService::DisplayBlockingPage(const GURL& url,
219 ResourceType::Type resource_type,
220 UrlCheckResult result,
221 Client* client,
222 MessageLoop* ui_loop,
223 int render_process_host_id,
224 int render_view_id) {
225 // Check if the user has already ignored our warning for this render_view
226 // and domain.
227 for (size_t i = 0; i < white_listed_entries_.size(); ++i) {
228 const WhiteListedEntry& entry = white_listed_entries_[i];
229 if (entry.render_process_host_id == render_process_host_id &&
230 entry.render_view_id == render_view_id &&
231 entry.result == result &&
232 entry.domain ==
[email protected]8ac1a752008-07-31 19:40:37233 net::RegistryControlledDomainService::GetDomainAndRegistry(url)) {
initial.commit09911bf2008-07-26 23:55:29234 MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
235 this, &SafeBrowsingService::NotifyClientBlockingComplete,
236 client, true));
237 return;
238 }
239 }
240
[email protected]1b277e72009-01-23 21:05:34241 UnsafeResource resource;
242 resource.url = url;
243 resource.resource_type = resource_type;
244 resource.threat_type= result;
245 resource.client = client;
246 resource.render_process_host_id = render_process_host_id;
247 resource.render_view_id = render_view_id;
[email protected]484c57a2009-03-21 01:24:01248
[email protected]cbab76d2008-10-13 22:42:47249 // The blocking page must be created from the UI thread.
250 ui_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
251 &SafeBrowsingService::DoDisplayBlockingPage,
[email protected]1b277e72009-01-23 21:05:34252 resource));
[email protected]cbab76d2008-10-13 22:42:47253}
254
255// Invoked on the UI thread.
256void SafeBrowsingService::DoDisplayBlockingPage(
[email protected]1b277e72009-01-23 21:05:34257 const UnsafeResource& resource) {
[email protected]a3a1d142008-12-19 00:42:30258 // The tab might have been closed.
[email protected]dfdb0de72009-02-19 21:58:14259 WebContents* wc =
260 tab_util::GetWebContentsByID(resource.render_process_host_id,
261 resource.render_view_id);
262
263 if (!wc) {
[email protected]a3a1d142008-12-19 00:42:30264 // The tab is gone and we did not have a chance at showing the interstitial.
265 // Just act as "Don't Proceed" was chosen.
[email protected]1b277e72009-01-23 21:05:34266 std::vector<UnsafeResource> resources;
267 resources.push_back(resource);
[email protected]bc0caef2009-04-03 17:18:04268 MessageLoop* message_loop;
269 if (g_browser_process->io_thread())
270 message_loop = g_browser_process->io_thread()->message_loop();
271 else // For unit-tests, just post on the current thread.
272 message_loop = MessageLoop::current();
273 message_loop->PostTask(FROM_HERE, NewRunnableMethod(
[email protected]1b277e72009-01-23 21:05:34274 this, &SafeBrowsingService::OnBlockingPageDone, resources, false));
[email protected]a3a1d142008-12-19 00:42:30275 return;
276 }
[email protected]dfdb0de72009-02-19 21:58:14277
278 // Report the malware sub-resource to the SafeBrowsing servers if we have a
279 // malware sub-resource on a safe page and only if the user has opted in to
280 // reporting statistics.
281 PrefService* prefs = g_browser_process->local_state();
282 DCHECK(prefs);
283 if (prefs && prefs->GetBoolean(prefs::kMetricsReportingEnabled) &&
284 resource.resource_type != ResourceType::MAIN_FRAME &&
285 resource.threat_type == SafeBrowsingService::URL_MALWARE) {
286 GURL page_url = wc->GetURL();
287 GURL referrer_url;
[email protected]1ef5ad422009-04-18 19:52:40288 if (wc->controller()) {
289 NavigationEntry* entry = wc->controller()->GetActiveEntry();
290 if (entry)
291 referrer_url = entry->referrer();
292 }
[email protected]dfdb0de72009-02-19 21:58:14293 io_loop_->PostTask(FROM_HERE,
294 NewRunnableMethod(this,
295 &SafeBrowsingService::ReportMalware,
296 resource.url,
297 page_url,
298 referrer_url));
299 }
300
[email protected]1b277e72009-01-23 21:05:34301 SafeBrowsingBlockingPage::ShowBlockingPage(this, resource);
initial.commit09911bf2008-07-26 23:55:29302}
303
304void SafeBrowsingService::CancelCheck(Client* client) {
305 DCHECK(MessageLoop::current() == io_loop_);
306
307 for (CurrentChecks::iterator i = checks_.begin(); i != checks_.end(); ++i) {
308 if ((*i)->client == client)
309 (*i)->client = NULL;
310 }
[email protected]613a03b2008-10-24 23:02:00311
312 // Scan the queued clients store. Clients may be here if they requested a URL
313 // check before the database has finished loading or resetting.
314 if (!database_loaded_ || resetting_) {
315 std::deque<QueuedCheck>::iterator it = queued_checks_.begin();
316 for (; it != queued_checks_.end(); ++it) {
317 if (it->client == client)
318 it->client = NULL;
319 }
320 }
initial.commit09911bf2008-07-26 23:55:29321}
322
[email protected]613a03b2008-10-24 23:02:00323void SafeBrowsingService::OnCheckDone(SafeBrowsingCheck* check) {
initial.commit09911bf2008-07-26 23:55:29324 DCHECK(MessageLoop::current() == io_loop_);
325
326 // If we've been shutdown during the database lookup, this check will already
327 // have been deleted (in OnIOShutdown).
[email protected]613a03b2008-10-24 23:02:00328 if (!enabled_ || checks_.find(check) == checks_.end())
initial.commit09911bf2008-07-26 23:55:29329 return;
330
[email protected]613a03b2008-10-24 23:02:00331 if (check->client && check->need_get_hash) {
initial.commit09911bf2008-07-26 23:55:29332 // We have a partial match so we need to query Google for the full hash.
333 // Clean up will happen in HandleGetHashResults.
334
335 // See if we have a GetHash request already in progress for this particular
336 // prefix. If so, we just append ourselves to the list of interested parties
337 // when the results arrive. We only do this for checks involving one prefix,
338 // since that is the common case (multiple prefixes will issue the request
339 // as normal).
[email protected]613a03b2008-10-24 23:02:00340 if (check->prefix_hits.size() == 1) {
341 SBPrefix prefix = check->prefix_hits[0];
initial.commit09911bf2008-07-26 23:55:29342 GetHashRequests::iterator it = gethash_requests_.find(prefix);
343 if (it != gethash_requests_.end()) {
344 // There's already a request in progress.
[email protected]613a03b2008-10-24 23:02:00345 it->second.push_back(check);
initial.commit09911bf2008-07-26 23:55:29346 return;
347 }
348
349 // No request in progress, so we're the first for this prefix.
350 GetHashRequestors requestors;
[email protected]613a03b2008-10-24 23:02:00351 requestors.push_back(check);
initial.commit09911bf2008-07-26 23:55:29352 gethash_requests_[prefix] = requestors;
353 }
354
355 // Reset the start time so that we can measure the network time without the
356 // database time.
[email protected]613a03b2008-10-24 23:02:00357 check->start = Time::Now();
358 protocol_manager_->GetFullHash(check, check->prefix_hits);
initial.commit09911bf2008-07-26 23:55:29359 } else {
360 // We may have cached results for previous GetHash queries.
[email protected]613a03b2008-10-24 23:02:00361 HandleOneCheck(check, check->full_hits);
initial.commit09911bf2008-07-26 23:55:29362 }
363}
364
365SafeBrowsingDatabase* SafeBrowsingService::GetDatabase() {
366 DCHECK(MessageLoop::current() == db_thread_->message_loop());
367 if (database_)
368 return database_;
369
[email protected]c870c762009-01-28 05:47:15370 FilePath path;
initial.commit09911bf2008-07-26 23:55:29371 bool result = PathService::Get(chrome::DIR_USER_DATA, &path);
372 DCHECK(result);
[email protected]c870c762009-01-28 05:47:15373 path = path.Append(chrome::kSafeBrowsingFilename);
initial.commit09911bf2008-07-26 23:55:29374
375 Time before = Time::Now();
[email protected]54d80bb02008-09-20 02:03:08376 SafeBrowsingDatabase* database = SafeBrowsingDatabase::Create();
[email protected]613a03b2008-10-24 23:02:00377 Callback0::Type* chunk_callback =
initial.commit09911bf2008-07-26 23:55:29378 NewCallback(this, &SafeBrowsingService::ChunkInserted);
[email protected]613a03b2008-10-24 23:02:00379 bool init_success = database->Init(path, chunk_callback);
380
381 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
382 this, &SafeBrowsingService::DatabaseLoadComplete, !init_success));
383
384 if (!init_success) {
initial.commit09911bf2008-07-26 23:55:29385 NOTREACHED();
386 return NULL;
387 }
388
389 database_ = database;
390
391 TimeDelta open_time = Time::Now() - before;
392 SB_DLOG(INFO) << "SafeBrowsing database open took " <<
393 open_time.InMilliseconds() << " ms.";
394
395 return database_;
396}
397
398// Public API called only on the IO thread.
399// The SafeBrowsingProtocolManager has received the full hash results for
400// prefix hits detected in the database.
401void SafeBrowsingService::HandleGetHashResults(
402 SafeBrowsingCheck* check,
[email protected]200abc32008-09-05 01:44:33403 const std::vector<SBFullHashResult>& full_hashes,
404 bool can_cache) {
initial.commit09911bf2008-07-26 23:55:29405 if (checks_.find(check) == checks_.end())
406 return;
407
408 DCHECK(enabled_);
409
[email protected]484c57a2009-03-21 01:24:01410 UMA_HISTOGRAM_LONG_TIMES("SB2.Network", Time::Now() - check->start);
[email protected]22573822008-11-14 00:40:47411
[email protected]200abc32008-09-05 01:44:33412 std::vector<SBPrefix> prefixes = check->prefix_hits;
initial.commit09911bf2008-07-26 23:55:29413 OnHandleGetHashResults(check, full_hashes); // 'check' is deleted here.
414
[email protected]484c57a2009-03-21 01:24:01415 if (can_cache && database_) {
416 // Cache the GetHash results in memory:
417 database_->CacheHashResults(prefixes, full_hashes);
[email protected]613a03b2008-10-24 23:02:00418 }
initial.commit09911bf2008-07-26 23:55:29419}
420
421void SafeBrowsingService::OnHandleGetHashResults(
422 SafeBrowsingCheck* check,
423 const std::vector<SBFullHashResult>& full_hashes) {
424 SBPrefix prefix = check->prefix_hits[0];
425 GetHashRequests::iterator it = gethash_requests_.find(prefix);
426 if (check->prefix_hits.size() > 1 || it == gethash_requests_.end()) {
427 HandleOneCheck(check, full_hashes);
428 return;
429 }
430
431 // Call back all interested parties.
432 GetHashRequestors& requestors = it->second;
433 for (GetHashRequestors::iterator r = requestors.begin();
434 r != requestors.end(); ++r) {
435 HandleOneCheck(*r, full_hashes);
436 }
437
438 gethash_requests_.erase(it);
439}
440
441void SafeBrowsingService::HandleOneCheck(
442 SafeBrowsingCheck* check,
443 const std::vector<SBFullHashResult>& full_hashes) {
444 if (check->client) {
445 UrlCheckResult result = URL_SAFE;
446 int index = safe_browsing_util::CompareFullHashes(check->url, full_hashes);
447 if (index != -1)
448 result = GetResultFromListname(full_hashes[index].list_name);
449
450 // Let the client continue handling the original request.
451 check->client->OnUrlCheckResult(check->url, result);
452 }
453
454 checks_.erase(check);
455 delete check;
456}
457
[email protected]57119c3f2008-12-04 00:33:04458void SafeBrowsingService::UpdateStarted() {
initial.commit09911bf2008-07-26 23:55:29459 DCHECK(MessageLoop::current() == io_loop_);
460 DCHECK(enabled_);
[email protected]57119c3f2008-12-04 00:33:04461 DCHECK(!update_in_progress_);
462 update_in_progress_ = true;
initial.commit09911bf2008-07-26 23:55:29463 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
464 this, &SafeBrowsingService::GetAllChunksFromDatabase));
465}
466
[email protected]613a03b2008-10-24 23:02:00467void SafeBrowsingService::UpdateFinished(bool update_succeeded) {
[email protected]aad08752008-10-02 22:13:41468 DCHECK(MessageLoop::current() == io_loop_);
469 DCHECK(enabled_);
[email protected]57119c3f2008-12-04 00:33:04470 if (update_in_progress_) {
471 update_in_progress_ = false;
472 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
473 this, &SafeBrowsingService::DatabaseUpdateFinished, update_succeeded));
474 }
[email protected]aad08752008-10-02 22:13:41475}
476
[email protected]613a03b2008-10-24 23:02:00477void SafeBrowsingService::DatabaseUpdateFinished(bool update_succeeded) {
[email protected]aad08752008-10-02 22:13:41478 DCHECK(MessageLoop::current() == db_thread_->message_loop());
479 if (GetDatabase())
[email protected]613a03b2008-10-24 23:02:00480 GetDatabase()->UpdateFinished(update_succeeded);
[email protected]aad08752008-10-02 22:13:41481}
482
[email protected]1b277e72009-01-23 21:05:34483void SafeBrowsingService::OnBlockingPageDone(
484 const std::vector<UnsafeResource>& resources,
485 bool proceed) {
486 for (std::vector<UnsafeResource>::const_iterator iter = resources.begin();
487 iter != resources.end(); ++iter) {
488 const UnsafeResource& resource = *iter;
489 NotifyClientBlockingComplete(resource.client, proceed);
initial.commit09911bf2008-07-26 23:55:29490
[email protected]1b277e72009-01-23 21:05:34491 if (proceed) {
492 // Whitelist this domain and warning type for the given tab.
493 WhiteListedEntry entry;
494 entry.render_process_host_id = resource.render_process_host_id;
495 entry.render_view_id = resource.render_view_id;
496 entry.domain = net::RegistryControlledDomainService::GetDomainAndRegistry(
497 resource.url);
498 entry.result = resource.threat_type;
499 white_listed_entries_.push_back(entry);
500 }
initial.commit09911bf2008-07-26 23:55:29501 }
initial.commit09911bf2008-07-26 23:55:29502}
503
504void SafeBrowsingService::NotifyClientBlockingComplete(Client* client,
505 bool proceed) {
506 client->OnBlockingPageComplete(proceed);
507}
508
509// This method runs on the UI loop to access the prefs.
510void SafeBrowsingService::OnNewMacKeys(const std::string& client_key,
511 const std::string& wrapped_key) {
512 PrefService* prefs = g_browser_process->local_state();
513 if (prefs) {
514 prefs->SetString(prefs::kSafeBrowsingClientKey, ASCIIToWide(client_key));
515 prefs->SetString(prefs::kSafeBrowsingWrappedKey, ASCIIToWide(wrapped_key));
516 }
517}
518
519void SafeBrowsingService::ChunkInserted() {
[email protected]fbb2b7a2008-11-18 22:54:04520 DCHECK(MessageLoop::current() == db_thread_->message_loop());
initial.commit09911bf2008-07-26 23:55:29521 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
522 this, &SafeBrowsingService::OnChunkInserted));
523}
524
525void SafeBrowsingService::OnChunkInserted() {
526 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04527 if (enabled_)
528 protocol_manager_->OnChunkInserted();
initial.commit09911bf2008-07-26 23:55:29529}
530
[email protected]613a03b2008-10-24 23:02:00531void SafeBrowsingService::DatabaseLoadComplete(bool database_error) {
532 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04533 if (!enabled_)
534 return;
[email protected]613a03b2008-10-24 23:02:00535
536 database_loaded_ = true;
537
538 // TODO(paulg): More robust database initialization error handling.
539 if (protocol_manager_ && !database_error)
540 protocol_manager_->Initialize();
541
542 // If we have any queued requests, we can now check them.
543 if (!resetting_)
544 RunQueuedClients();
545}
546
initial.commit09911bf2008-07-26 23:55:29547// static
[email protected]919d77f02009-01-06 19:48:35548void SafeBrowsingService::RegisterPrefs(PrefService* prefs) {
initial.commit09911bf2008-07-26 23:55:29549 prefs->RegisterStringPref(prefs::kSafeBrowsingClientKey, L"");
550 prefs->RegisterStringPref(prefs::kSafeBrowsingWrappedKey, L"");
551}
552
553void SafeBrowsingService::ResetDatabase() {
554 DCHECK(MessageLoop::current() == io_loop_);
555 resetting_ = true;
556 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
557 this, &SafeBrowsingService::OnResetDatabase));
558}
559
560void SafeBrowsingService::OnResetDatabase() {
561 DCHECK(MessageLoop::current() == db_thread_->message_loop());
562 GetDatabase()->ResetDatabase();
563 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
564 this, &SafeBrowsingService::OnResetComplete));
565}
566
567void SafeBrowsingService::OnResetComplete() {
568 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04569 if (enabled_) {
570 resetting_ = false;
571 database_loaded_ = true;
572 RunQueuedClients();
573 }
initial.commit09911bf2008-07-26 23:55:29574}
575
576void SafeBrowsingService::HandleChunk(const std::string& list,
577 std::deque<SBChunk>* chunks) {
578 DCHECK(MessageLoop::current() == io_loop_);
579 DCHECK(enabled_);
580 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
581 this, &SafeBrowsingService::HandleChunkForDatabase, list, chunks));
582}
583
584void SafeBrowsingService::HandleChunkForDatabase(
585 const std::string& list_name,
586 std::deque<SBChunk>* chunks) {
587 DCHECK(MessageLoop::current() == db_thread_->message_loop());
588
589 GetDatabase()->InsertChunks(list_name, chunks);
590}
591
592void SafeBrowsingService::HandleChunkDelete(
593 std::vector<SBChunkDelete>* chunk_deletes) {
594 DCHECK(MessageLoop::current() == io_loop_);
595 DCHECK(enabled_);
596 db_thread_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
597 this, &SafeBrowsingService::DeleteChunks, chunk_deletes));
598}
599
600void SafeBrowsingService::DeleteChunks(
601 std::vector<SBChunkDelete>* chunk_deletes) {
602 DCHECK(MessageLoop::current() == db_thread_->message_loop());
603
604 GetDatabase()->DeleteChunks(chunk_deletes);
605}
606
607// Database worker function.
608void SafeBrowsingService::GetAllChunksFromDatabase() {
609 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]a5a37522008-11-11 21:49:56610 bool database_error = true;
initial.commit09911bf2008-07-26 23:55:29611 std::vector<SBListChunkRanges> lists;
[email protected]53ad8572008-11-13 21:50:34612 if (GetDatabase()) {
613 if (GetDatabase()->UpdateStarted()) {
614 GetDatabase()->GetListsInfo(&lists);
615 database_error = false;
616 } else {
617 GetDatabase()->UpdateFinished(false);
618 }
initial.commit09911bf2008-07-26 23:55:29619 }
620
621 io_loop_->PostTask(FROM_HERE, NewRunnableMethod(
622 this, &SafeBrowsingService::OnGetAllChunksFromDatabase, lists,
623 database_error));
624}
625
626// Called on the io thread with the results of all chunks.
627void SafeBrowsingService::OnGetAllChunksFromDatabase(
628 const std::vector<SBListChunkRanges>& lists, bool database_error) {
629 DCHECK(MessageLoop::current() == io_loop_);
[email protected]fbb2b7a2008-11-18 22:54:04630 if (enabled_)
631 protocol_manager_->OnGetChunksComplete(lists, database_error);
initial.commit09911bf2008-07-26 23:55:29632}
633
634SafeBrowsingService::UrlCheckResult SafeBrowsingService::GetResultFromListname(
635 const std::string& list_name) {
636 if (safe_browsing_util::IsPhishingList(list_name)) {
637 return URL_PHISHING;
638 }
639
640 if (safe_browsing_util::IsMalwareList(list_name)) {
641 return URL_MALWARE;
642 }
643
644 SB_DLOG(INFO) << "Unknown safe browsing list " << list_name;
645 return URL_SAFE;
646}
647
initial.commit09911bf2008-07-26 23:55:29648void SafeBrowsingService::LogPauseDelay(TimeDelta time) {
[email protected]484c57a2009-03-21 01:24:01649 UMA_HISTOGRAM_LONG_TIMES("SB2.Delay", time);
initial.commit09911bf2008-07-26 23:55:29650}
651
652void SafeBrowsingService::CacheHashResults(
[email protected]200abc32008-09-05 01:44:33653 const std::vector<SBPrefix>& prefixes,
initial.commit09911bf2008-07-26 23:55:29654 const std::vector<SBFullHashResult>& full_hashes) {
655 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]200abc32008-09-05 01:44:33656 GetDatabase()->CacheHashResults(prefixes, full_hashes);
initial.commit09911bf2008-07-26 23:55:29657}
658
[email protected]0a3076572008-12-13 20:48:36659void SafeBrowsingService::OnSuspend(base::SystemMonitor*) {
initial.commit09911bf2008-07-26 23:55:29660}
661
662// Tell the SafeBrowsing database not to do expensive disk operations for a few
663// minutes after waking up. It's quite likely that the act of resuming from a
664// low power state will involve much disk activity, which we don't want to
665// exacerbate.
[email protected]0a3076572008-12-13 20:48:36666void SafeBrowsingService::OnResume(base::SystemMonitor*) {
initial.commit09911bf2008-07-26 23:55:29667 if (enabled_) {
[email protected]0a3076572008-12-13 20:48:36668 ChromeThread::GetMessageLoop(ChromeThread::DB)->PostTask(FROM_HERE,
669 NewRunnableMethod(this, &SafeBrowsingService::HandleResume));
initial.commit09911bf2008-07-26 23:55:29670 }
671}
672
673void SafeBrowsingService::HandleResume() {
674 DCHECK(MessageLoop::current() == db_thread_->message_loop());
[email protected]53ad8572008-11-13 21:50:34675 // We don't call GetDatabase() here, since we want to avoid unnecessary calls
676 // to Open, Reset, etc, or reload the bloom filter while we're coming out of
677 // a suspended state.
678 if (database_)
679 database_->HandleResume();
license.botbf09a502008-08-24 00:55:55680}
[email protected]613a03b2008-10-24 23:02:00681
682void SafeBrowsingService::RunQueuedClients() {
683 DCHECK(MessageLoop::current() == io_loop_);
[email protected]553dba62009-02-24 19:08:23684 HISTOGRAM_COUNTS("SB.QueueDepth", queued_checks_.size());
[email protected]613a03b2008-10-24 23:02:00685 while (!queued_checks_.empty()) {
686 QueuedCheck check = queued_checks_.front();
[email protected]553dba62009-02-24 19:08:23687 HISTOGRAM_TIMES("SB.QueueDelay", Time::Now() - check.start);
[email protected]613a03b2008-10-24 23:02:00688 CheckUrl(check.url, check.client);
689 queued_checks_.pop_front();
690 }
691}
692
[email protected]dfdb0de72009-02-19 21:58:14693void SafeBrowsingService::ReportMalware(const GURL& malware_url,
694 const GURL& page_url,
695 const GURL& referrer_url) {
696 DCHECK(MessageLoop::current() == io_loop_);
697
[email protected]484c57a2009-03-21 01:24:01698 if (!enabled_ || !database_)
[email protected]dfdb0de72009-02-19 21:58:14699 return;
700
701 // Check if 'page_url' is already blacklisted (exists in our cache). Only
702 // report if it's not there.
703 std::string list;
704 std::vector<SBPrefix> prefix_hits;
705 std::vector<SBFullHashResult> full_hits;
706 database_->ContainsUrl(page_url, &list, &prefix_hits, &full_hits,
707 protocol_manager_->last_update());
708
709 if (full_hits.empty())
710 protocol_manager_->ReportMalware(malware_url, page_url, referrer_url);
711}