• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/extensions/activity_log/hashed_ad_network_database.h"
6 
7 #include <algorithm>  // std::binary_search
8 #include <vector>
9 
10 #include "base/basictypes.h"
11 #include "base/logging.h"
12 #include "base/macros.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "chrome/browser/extensions/activity_log/hashed_ad_networks.h"
16 #include "crypto/sha2.h"
17 #include "url/gurl.h"
18 
19 namespace extensions {
20 
21 namespace {
22 
23 typedef char shorthash[8];
24 
CompareEntries(const char * entry1,const char * entry2)25 bool CompareEntries(const char* entry1, const char* entry2) {
26   return strcmp(entry1, entry2) < 0;
27 }
28 
29 }
30 
HashedAdNetworkDatabase()31 HashedAdNetworkDatabase::HashedAdNetworkDatabase()
32     : entries_(kHashedAdNetworks),
33       num_entries_(kNumHashedAdNetworks) {
34 }
35 
~HashedAdNetworkDatabase()36 HashedAdNetworkDatabase::~HashedAdNetworkDatabase() {
37 }
38 
IsAdNetwork(const GURL & url) const39 bool HashedAdNetworkDatabase::IsAdNetwork(const GURL& url) const {
40 // The list should be sorted. Check once in debug builds.
41 #if DCHECK_IS_ON
42   static bool is_sorted = false;
43   if (!is_sorted) {
44     std::vector<std::string> list;
45     for (int i = 0; i < num_entries_; ++i)
46       list.push_back(std::string(entries_[i]));
47     is_sorted = base::STLIsSorted(list);
48   }
49   DCHECK(is_sorted);
50 #endif
51 
52   shorthash hash;
53   crypto::SHA256HashString(url.host(), hash, sizeof(shorthash));
54   std::string hex_encoded = base::HexEncode(hash, sizeof(shorthash));
55   return std::binary_search(entries_,
56                             entries_ + num_entries_,
57                             hex_encoded.c_str(),
58                             CompareEntries);
59 }
60 
61 }  // namespace extensions
62