Backed out changeset f594e6f00208 (bug 1940883) for causing crashes in bug 1941164.
[gecko.git] / toolkit / components / antitracking / URLDecorationStripper.cpp
blobfc94fe8ed5805e37aeff3af35543936a616a4b42
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "URLDecorationStripper.h"
9 #include "mozilla/Preferences.h"
10 #include "nsCharSeparatedTokenizer.h"
11 #include "nsEffectiveTLDService.h"
12 #include "nsIURI.h"
13 #include "nsIURIMutator.h"
14 #include "nsURLHelper.h"
16 namespace {
17 static const char* kPrefName =
18 "privacy.restrict3rdpartystorage.url_decorations";
19 } // namespace
21 namespace mozilla {
23 nsresult URLDecorationStripper::StripTrackingIdentifiers(nsIURI* aURI,
24 nsACString& aOutSpec) {
25 nsAutoCString tokenList;
26 nsresult rv = Preferences::GetCString(kPrefName, tokenList);
27 ToLowerCase(tokenList);
29 nsAutoCString path;
30 rv = aURI->GetPathQueryRef(path);
31 NS_ENSURE_SUCCESS(rv, rv);
32 ToLowerCase(path);
34 int32_t queryBegins = path.FindChar('?');
35 // Only positive values are valid since the path must begin with a '/'.
36 if (queryBegins > 0) {
37 for (const nsACString& token : tokenList.Split(' ')) {
38 if (token.IsEmpty()) {
39 continue;
42 nsAutoCString value;
43 if (URLParams::Extract(Substring(path, queryBegins + 1), token, value) &&
44 !value.IsVoid()) {
45 // Tracking identifier found in the URL!
46 return StripToRegistrableDomain(aURI, aOutSpec);
51 return aURI->GetSpec(aOutSpec);
54 nsresult URLDecorationStripper::StripToRegistrableDomain(nsIURI* aURI,
55 nsACString& aOutSpec) {
56 NS_MutateURI mutator(aURI);
57 mutator.SetPathQueryRef(""_ns).SetUserPass(""_ns);
59 RefPtr<nsEffectiveTLDService> etldService =
60 nsEffectiveTLDService::GetInstance();
61 NS_ENSURE_TRUE(etldService, NS_ERROR_FAILURE);
62 nsAutoCString baseDomain;
63 nsresult rv = etldService->GetBaseDomain(aURI, 0, baseDomain);
64 if (NS_SUCCEEDED(rv)) {
65 mutator.SetHost(baseDomain);
66 } else {
67 // If this is an IP address or something like "localhost", ignore the error.
68 if (rv != NS_ERROR_HOST_IS_IP_ADDRESS &&
69 rv != NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
70 return rv;
74 nsCOMPtr<nsIURI> uri;
75 rv = mutator.Finalize(uri);
76 NS_ENSURE_SUCCESS(rv, rv);
77 return uri->GetSpec(aOutSpec);
80 } // namespace mozilla