Home | History | Annotate | Download | only in rappor
      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 "components/rappor/rappor_service.h"
      6 
      7 #include "base/base64.h"
      8 #include "base/metrics/field_trial.h"
      9 #include "base/prefs/pref_registry_simple.h"
     10 #include "base/prefs/pref_service.h"
     11 #include "base/rand_util.h"
     12 #include "base/stl_util.h"
     13 #include "base/time/time.h"
     14 #include "components/metrics/metrics_hashes.h"
     15 #include "components/rappor/log_uploader.h"
     16 #include "components/rappor/proto/rappor_metric.pb.h"
     17 #include "components/rappor/rappor_metric.h"
     18 #include "components/rappor/rappor_pref_names.h"
     19 #include "components/variations/variations_associated_data.h"
     20 
     21 namespace rappor {
     22 
     23 namespace {
     24 
     25 // Seconds before the initial log is generated.
     26 const int kInitialLogIntervalSeconds = 15;
     27 // Interval between ongoing logs.
     28 const int kLogIntervalSeconds = 30 * 60;
     29 
     30 const char kMimeType[] = "application/vnd.chrome.rappor";
     31 
     32 // Constants for the RAPPOR rollout field trial.
     33 const char kRapporRolloutFieldTrialName[] = "RapporRollout";
     34 
     35 // Constant for the finch parameter name for the server URL
     36 const char kRapporRolloutServerUrlParam[] = "ServerUrl";
     37 
     38 GURL GetServerUrl() {
     39   return GURL(chrome_variations::GetVariationParamValue(
     40       kRapporRolloutFieldTrialName,
     41       kRapporRolloutServerUrlParam));
     42 }
     43 
     44 const RapporParameters kRapporParametersForType[NUM_RAPPOR_TYPES] = {
     45     // ETLD_PLUS_ONE_RAPPOR_TYPE
     46     {128 /* Num cohorts */,
     47      16 /* Bloom filter size bytes */,
     48      2 /* Bloom filter hash count */,
     49      rappor::PROBABILITY_50 /* Fake data probability */,
     50      rappor::PROBABILITY_50 /* Fake one probability */,
     51      rappor::PROBABILITY_75 /* One coin probability */,
     52      rappor::PROBABILITY_25 /* Zero coin probability */},
     53 };
     54 
     55 }  // namespace
     56 
     57 RapporService::RapporService() : cohort_(-1) {}
     58 
     59 RapporService::~RapporService() {
     60   STLDeleteValues(&metrics_map_);
     61 }
     62 
     63 void RapporService::Start(PrefService* pref_service,
     64                           net::URLRequestContextGetter* request_context) {
     65   const GURL server_url = GetServerUrl();
     66   if (!server_url.is_valid())
     67     return;
     68   DCHECK(!uploader_);
     69   LoadSecret(pref_service);
     70   LoadCohort(pref_service);
     71   uploader_.reset(new LogUploader(server_url, kMimeType, request_context));
     72   log_rotation_timer_.Start(
     73       FROM_HERE,
     74       base::TimeDelta::FromSeconds(kInitialLogIntervalSeconds),
     75       this,
     76       &RapporService::OnLogInterval);
     77 }
     78 
     79 void RapporService::OnLogInterval() {
     80   DCHECK(uploader_);
     81   RapporReports reports;
     82   if (ExportMetrics(&reports)) {
     83     std::string log_text;
     84     bool success = reports.SerializeToString(&log_text);
     85     DCHECK(success);
     86     uploader_->QueueLog(log_text);
     87   }
     88   log_rotation_timer_.Start(FROM_HERE,
     89                             base::TimeDelta::FromSeconds(kLogIntervalSeconds),
     90                             this,
     91                             &RapporService::OnLogInterval);
     92 }
     93 
     94 // static
     95 void RapporService::RegisterPrefs(PrefRegistrySimple* registry) {
     96   registry->RegisterStringPref(prefs::kRapporSecret, std::string());
     97   registry->RegisterIntegerPref(prefs::kRapporCohortDeprecated, -1);
     98   registry->RegisterIntegerPref(prefs::kRapporCohortSeed, -1);
     99 }
    100 
    101 void RapporService::LoadCohort(PrefService* pref_service) {
    102   DCHECK(!IsInitialized());
    103   // Ignore and delete old cohort parameter.
    104   pref_service->ClearPref(prefs::kRapporCohortDeprecated);
    105 
    106   cohort_ = pref_service->GetInteger(prefs::kRapporCohortSeed);
    107   // If the user is already assigned to a valid cohort, we're done.
    108   if (cohort_ >= 0 && cohort_ < RapporParameters::kMaxCohorts)
    109     return;
    110 
    111   // This is the first time the client has started the service (or their
    112   // preferences were corrupted).  Randomly assign them to a cohort.
    113   cohort_ = base::RandGenerator(RapporParameters::kMaxCohorts);
    114   pref_service->SetInteger(prefs::kRapporCohortSeed, cohort_);
    115 }
    116 
    117 void RapporService::LoadSecret(PrefService* pref_service) {
    118   DCHECK(secret_.empty());
    119   std::string secret_base64 = pref_service->GetString(prefs::kRapporSecret);
    120   if (!secret_base64.empty()) {
    121     bool decoded = base::Base64Decode(secret_base64, &secret_);
    122     if (decoded && secret_.size() == HmacByteVectorGenerator::kEntropyInputSize)
    123       return;
    124     // If the preference fails to decode, or is the wrong size, it must be
    125     // corrupt, so continue as though it didn't exist yet and generate a new
    126     // one.
    127   }
    128 
    129   secret_ = HmacByteVectorGenerator::GenerateEntropyInput();
    130   base::Base64Encode(secret_, &secret_base64);
    131   pref_service->SetString(prefs::kRapporSecret, secret_base64);
    132 }
    133 
    134 bool RapporService::ExportMetrics(RapporReports* reports) {
    135   if (metrics_map_.empty())
    136     return false;
    137 
    138   DCHECK_GE(cohort_, 0);
    139   reports->set_cohort(cohort_);
    140 
    141   for (std::map<std::string, RapporMetric*>::const_iterator it =
    142            metrics_map_.begin();
    143        it != metrics_map_.end();
    144        ++it) {
    145     const RapporMetric* metric = it->second;
    146     RapporReports::Report* report = reports->add_report();
    147     report->set_name_hash(metrics::HashMetricName(it->first));
    148     ByteVector bytes = metric->GetReport(secret_);
    149     report->set_bits(std::string(bytes.begin(), bytes.end()));
    150   }
    151   STLDeleteValues(&metrics_map_);
    152   return true;
    153 }
    154 
    155 bool RapporService::IsInitialized() const {
    156   return cohort_ >= 0;
    157 }
    158 
    159 void RapporService::RecordSample(const std::string& metric_name,
    160                                  RapporType type,
    161                                  const std::string& sample) {
    162   // Ignore the sample if the service hasn't started yet.
    163   if (!IsInitialized())
    164     return;
    165   DCHECK_LT(type, NUM_RAPPOR_TYPES);
    166   RecordSampleInternal(metric_name, kRapporParametersForType[type], sample);
    167 }
    168 
    169 void RapporService::RecordSampleInternal(const std::string& metric_name,
    170                                          const RapporParameters& parameters,
    171                                          const std::string& sample) {
    172   DCHECK(IsInitialized());
    173   RapporMetric* metric = LookUpMetric(metric_name, parameters);
    174   metric->AddSample(sample);
    175 }
    176 
    177 RapporMetric* RapporService::LookUpMetric(const std::string& metric_name,
    178                                           const RapporParameters& parameters) {
    179   DCHECK(IsInitialized());
    180   std::map<std::string, RapporMetric*>::const_iterator it =
    181       metrics_map_.find(metric_name);
    182   if (it != metrics_map_.end()) {
    183     RapporMetric* metric = it->second;
    184     DCHECK_EQ(parameters.ToString(), metric->parameters().ToString());
    185     return metric;
    186   }
    187 
    188   RapporMetric* new_metric = new RapporMetric(metric_name, parameters, cohort_);
    189   metrics_map_[metric_name] = new_metric;
    190   return new_metric;
    191 }
    192 
    193 }  // namespace rappor
    194