DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ContentBlockingLog.h"

#include "nsStringStream.h"
#include "nsTArray.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/HashFunctions.h"
#include "mozilla/RandomNum.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/StaticPrefs_telemetry.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Unused.h"
#include "mozilla/XorShift128PlusRNG.h"
#include "mozilla/ipc/IPCStreamUtils.h"

namespace mozilla {

using ipc::AutoIPCStream;

static LazyLogModule gContentBlockingLog("ContentBlockingLog");
#define LOG(fmt, ...) \
  MOZ_LOG(gContentBlockingLog, LogLevel::Debug, (fmt, ##__VA_ARGS__))

typedef Telemetry::OriginMetricID OriginMetricID;

namespace dom {

// sync with TelemetryOriginData.inc
NS_NAMED_LITERAL_CSTRING(ContentBlockingLog::kDummyOriginHash, "PAGELOAD");

// randomly choose 1% users included in the content blocking measurement
// based on their client id.
static constexpr double kRatioReportUser = 0.01;

// randomly choose 0.14% documents when the page is unload.
static constexpr double kRatioReportDocument = 0.0014;

static bool IsReportingPerUserEnabled() {
  MOZ_ASSERT(NS_IsMainThread());

  static Maybe<bool> sIsReportingEnabled;

  if (sIsReportingEnabled.isSome()) {
    return sIsReportingEnabled.value();
  }

  nsAutoCString cachedClientId;
  if (NS_FAILED(Preferences::GetCString("toolkit.telemetry.cachedClientID",
                                        cachedClientId))) {
    return false;
  }

  nsID clientId;
  if (!clientId.Parse(cachedClientId.get())) {
    return false;
  }

  /**
   * UUID might not be uniform-distributed (although some part of it could be).
   * In order to generate more random result, usually we use a hash function,
   * but here we hope it's fast and doesn't have to be cryptographic-safe.
   * |XorShift128PlusRNG| looks like a good alternative because it takes a
   * 128-bit data as its seed and always generate identical sequence if the
   * initial seed is the same.
   */
  static_assert(sizeof(nsID) == 16, "nsID is 128-bit");
  uint64_t* init = reinterpret_cast<uint64_t*>(&clientId);
  non_crypto::XorShift128PlusRNG rng(init[0], init[1]);
  sIsReportingEnabled.emplace(rng.nextDouble() <= kRatioReportUser);

  return sIsReportingEnabled.value();
}

static bool IsReportingPerDocumentEnabled() {
  constexpr double boundary =
      kRatioReportDocument * double(std::numeric_limits<uint64_t>::max());
  Maybe<uint64_t> randomNum = RandomUint64();
  return randomNum.isSome() && randomNum.value() <= boundary;
}

static bool IsReportingEnabled() {
  if (StaticPrefs::telemetry_origin_telemetry_test_mode_enabled()) {
    return true;
  } else if (!StaticPrefs::
                 privacy_trackingprotection_origin_telemetry_enabled()) {
    return false;
  }

  return IsReportingPerUserEnabled() && IsReportingPerDocumentEnabled();
}

static void ReportOriginSingleHash(OriginMetricID aId,
                                   const nsACString& aOrigin) {
  MOZ_ASSERT(NS_IsMainThread());

  LOG("ReportOriginSingleHash metric=%s",
      Telemetry::MetricIDToString[static_cast<uint32_t>(aId)]);
  LOG("ReportOriginSingleHash origin=%s", PromiseFlatCString(aOrigin).get());

  if (XRE_IsParentProcess()) {
    Telemetry::RecordOrigin(aId, aOrigin);
    return;
  }

  dom::ContentChild* contentChild = dom::ContentChild::GetSingleton();
  if (NS_WARN_IF(!contentChild)) {
    return;
  }

  Unused << contentChild->SendRecordOrigin(static_cast<uint32_t>(aId),
                                           nsCString(aOrigin));
}

void ContentBlockingLog::ReportLog(nsIPrincipal* aFirstPartyPrincipal) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aFirstPartyPrincipal);

  if (!StaticPrefs::browser_contentblocking_database_enabled()) {
    return;
  }

  if (mLog.IsEmpty()) {
    return;
  }

  dom::ContentChild* contentChild = dom::ContentChild::GetSingleton();
  if (NS_WARN_IF(!contentChild)) {
    return;
  }

  nsAutoCString json = Stringify();

  nsCOMPtr<nsIInputStream> stream;
  nsresult rv = NS_NewCStringInputStream(getter_AddRefs(stream), json);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  AutoIPCStream ipcStream;
  ipcStream.Serialize(stream, contentChild);

  Unused << contentChild->SendReportContentBlockingLog(ipcStream.TakeValue());
}

void ContentBlockingLog::ReportOrigins() {
  if (!IsReportingEnabled()) {
    return;
  }
  LOG("ContentBlockingLog::ReportOrigins [this=%p]", this);
  const bool testMode =
      StaticPrefs::telemetry_origin_telemetry_test_mode_enabled();
  OriginMetricID metricId =
      testMode ? OriginMetricID::ContentBlocking_Blocked_TestOnly
               : OriginMetricID::ContentBlocking_Blocked;
  ReportOriginSingleHash(metricId, kDummyOriginHash);

  nsTArray<HashNumber> lookupTable;
  for (const auto& originEntry : mLog) {
    if (!originEntry.mData) {
      continue;
    }

    for (const auto& logEntry : Reversed(originEntry.mData->mLogs)) {
      if (logEntry.mType !=
              nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER ||
          logEntry.mTrackingFullHashes.IsEmpty()) {
        continue;
      }

      const bool isBlocked = logEntry.mBlocked;
      Maybe<StorageAccessGrantedReason> reason = logEntry.mReason;

      metricId = testMode ? OriginMetricID::ContentBlocking_Blocked_TestOnly
                          : OriginMetricID::ContentBlocking_Blocked;
      if (!isBlocked) {
        MOZ_ASSERT(reason.isSome());
        switch (reason.value()) {
          case StorageAccessGrantedReason::eStorageAccessAPI:
            metricId =
                testMode
                    ? OriginMetricID::
                          ContentBlocking_StorageAccessAPIExempt_TestOnly
                    : OriginMetricID::ContentBlocking_StorageAccessAPIExempt;
            break;
          case StorageAccessGrantedReason::eOpenerAfterUserInteraction:
            metricId =
                testMode
                    ? OriginMetricID::
                          ContentBlocking_OpenerAfterUserInteractionExempt_TestOnly
                    : OriginMetricID::
                          ContentBlocking_OpenerAfterUserInteractionExempt;
            break;
          case StorageAccessGrantedReason::eOpener:
            metricId =
                testMode ? OriginMetricID::ContentBlocking_OpenerExempt_TestOnly
                         : OriginMetricID::ContentBlocking_OpenerExempt;
            break;
          default:
            MOZ_ASSERT_UNREACHABLE("Unknown StorageAccessGrantedReason");
        }
      }

      for (const auto& hash : logEntry.mTrackingFullHashes) {
        HashNumber key = AddToHash(HashString(hash.get(), hash.Length()),
                                   static_cast<uint32_t>(metricId));
        if (lookupTable.Contains(key)) {
          continue;
        }
        lookupTable.AppendElement(key);
        ReportOriginSingleHash(metricId, hash);
      }
      break;
    }
  }
}

}  // namespace dom
}  // namespace mozilla