[M85 Dev][EFL] Fix errors to generate ninja files
[platform/framework/web/chromium-efl.git] / chrome / browser / intranet_redirect_detector.cc
1 // Copyright (c) 2012 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/intranet_redirect_detector.h"
6
7 #include <stddef.h>
8
9 #include <utility>
10
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/location.h"
14 #include "base/rand_util.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/stl_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/threading/thread_task_runner_handle.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/net/system_network_context_manager.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/common/pref_names.h"
23 #include "components/prefs/pref_registry_simple.h"
24 #include "components/prefs/pref_service.h"
25 #include "content/public/browser/browser_context.h"
26 #include "content/public/browser/browser_thread.h"
27 #include "content/public/browser/network_service_instance.h"
28 #include "content/public/browser/storage_partition.h"
29 #include "mojo/public/cpp/bindings/remote.h"
30 #include "net/base/load_flags.h"
31 #include "net/base/net_errors.h"
32 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
33 #include "net/traffic_annotation/network_traffic_annotation.h"
34 #include "services/network/public/cpp/resource_request.h"
35 #include "services/network/public/cpp/simple_url_loader.h"
36 #include "services/network/public/mojom/network_service.mojom.h"
37
38 // TODO(crbug.com/181671): Write test to verify we handle the policy toggling.
39 IntranetRedirectDetector::IntranetRedirectDetector()
40     : redirect_origin_(g_browser_process->local_state()->GetString(
41           prefs::kLastKnownIntranetRedirectOrigin)) {
42   // Because this function can be called during startup, when kicking off a URL
43   // fetch can eat up 20 ms of time, we delay seven seconds, which is hopefully
44   // long enough to be after startup, but still get results back quickly.
45   // Ideally, instead of this timer, we'd do something like "check if the
46   // browser is starting up, and if so, come back later", but there is currently
47   // no function to do this.
48   static constexpr base::TimeDelta kStartFetchDelay =
49       base::TimeDelta::FromSeconds(7);
50   base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
51       FROM_HERE,
52       base::BindOnce(&IntranetRedirectDetector::FinishSleep,
53                      weak_ptr_factory_.GetWeakPtr()),
54       kStartFetchDelay);
55
56   content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this);
57   SetupDnsConfigClient();
58 }
59
60 IntranetRedirectDetector::~IntranetRedirectDetector() {
61   content::GetNetworkConnectionTracker()->RemoveNetworkConnectionObserver(this);
62 }
63
64 // static
65 GURL IntranetRedirectDetector::RedirectOrigin() {
66   const IntranetRedirectDetector* const detector =
67       g_browser_process->intranet_redirect_detector();
68   return detector ? detector->redirect_origin_ : GURL();
69 }
70
71 // static
72 void IntranetRedirectDetector::RegisterPrefs(PrefRegistrySimple* registry) {
73   registry->RegisterStringPref(prefs::kLastKnownIntranetRedirectOrigin,
74                                std::string());
75   registry->RegisterBooleanPref(prefs::kDNSInterceptionChecksEnabled, true);
76 }
77
78 void IntranetRedirectDetector::Restart() {
79   if (!IsEnabledByPolicy()) {
80     if (redirect_origin_.is_valid()) {
81       g_browser_process->local_state()->SetString(
82           prefs::kLastKnownIntranetRedirectOrigin, std::string());
83     }
84     redirect_origin_ = GURL();
85     return;
86   }
87   // If a request is already scheduled, do not scheduled yet another one.
88   if (in_sleep_)
89     return;
90
91   // Since presumably many programs open connections after network changes,
92   // delay this a little bit.
93   in_sleep_ = true;
94   static constexpr base::TimeDelta kRestartDelay =
95       base::TimeDelta::FromSeconds(1);
96   base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
97       FROM_HERE,
98       base::BindOnce(&IntranetRedirectDetector::FinishSleep,
99                      weak_ptr_factory_.GetWeakPtr()),
100       kRestartDelay);
101 }
102
103 void IntranetRedirectDetector::FinishSleep() {
104   in_sleep_ = false;
105   if (!IsEnabledByPolicy()) {
106     if (redirect_origin_.is_valid()) {
107       g_browser_process->local_state()->SetString(
108           prefs::kLastKnownIntranetRedirectOrigin, std::string());
109     }
110     redirect_origin_ = GURL();
111     return;
112   }
113
114   // If another fetch operation is still running, cancel it.
115   simple_loaders_.clear();
116   resulting_origins_.clear();
117
118   const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
119   if (cmd_line->HasSwitch(switches::kDisableBackgroundNetworking))
120     return;
121
122   DCHECK(simple_loaders_.empty() && resulting_origins_.empty());
123
124   // Create traffic annotation tag.
125   net::NetworkTrafficAnnotationTag traffic_annotation =
126       net::DefineNetworkTrafficAnnotation("intranet_redirect_detector", R"(
127         semantics {
128           sender: "Intranet Redirect Detector"
129           description:
130             "This component sends requests to three randomly generated, and "
131             "thus likely nonexistent, hostnames.  If at least two redirect to "
132             "the same hostname, this suggests the ISP is hijacking NXDOMAIN, "
133             "and the omnibox should treat similar redirected navigations as "
134             "'failed' when deciding whether to prompt the user with a 'did you "
135             "mean to navigate' infobar for certain search inputs."
136           trigger: "On startup and when IP address of the computer changes."
137           data: "None, this is just an empty request."
138           destination: OTHER
139         }
140         policy {
141           cookies_allowed: NO
142           setting: "This feature cannot be disabled by settings."
143           policy_exception_justification:
144               "Not implemented, considered not useful."
145         })");
146
147   // Start three loaders on random hostnames.
148   for (size_t i = 0; i < 3; ++i) {
149     std::string url_string("http://");
150     // We generate a random hostname with between 7 and 15 characters.
151     const int num_chars = base::RandInt(7, 15);
152     for (int j = 0; j < num_chars; ++j)
153       url_string += ('a' + base::RandInt(0, 'z' - 'a'));
154     GURL random_url(url_string + '/');
155
156     auto resource_request = std::make_unique<network::ResourceRequest>();
157     resource_request->url = random_url;
158     resource_request->method = "HEAD";
159     // We don't want these fetches to affect existing state in the profile.
160     resource_request->load_flags = net::LOAD_DISABLE_CACHE;
161     resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
162     network::mojom::URLLoaderFactory* loader_factory =
163         g_browser_process->system_network_context_manager()
164             ->GetURLLoaderFactory();
165     std::unique_ptr<network::SimpleURLLoader> simple_loader =
166         network::SimpleURLLoader::Create(std::move(resource_request),
167                                          traffic_annotation);
168     network::SimpleURLLoader* simple_loader_ptr = simple_loader.get();
169     simple_loader->DownloadToString(
170         loader_factory,
171         base::BindOnce(&IntranetRedirectDetector::OnSimpleLoaderComplete,
172                        base::Unretained(this), simple_loader_ptr),
173         /*max_body_size=*/1);
174     simple_loaders_[simple_loader_ptr] = std::move(simple_loader);
175   }
176 }
177
178 void IntranetRedirectDetector::OnSimpleLoaderComplete(
179     network::SimpleURLLoader* source,
180     std::unique_ptr<std::string> response_body) {
181   // Delete the loader on this function's exit.
182   auto it = simple_loaders_.find(source);
183   DCHECK(it != simple_loaders_.end());
184   std::unique_ptr<network::SimpleURLLoader> simple_loader =
185       std::move(it->second);
186   simple_loaders_.erase(it);
187
188   // If any two loaders result in the same domain/host, we set the redirect
189   // origin to that; otherwise we set it to nothing.
190   if (response_body) {
191     DCHECK(source->GetFinalURL().is_valid());
192     GURL origin(source->GetFinalURL().GetOrigin());
193     if (resulting_origins_.empty()) {
194       resulting_origins_.push_back(origin);
195       return;
196     }
197     if (net::registry_controlled_domains::SameDomainOrHost(
198         resulting_origins_.front(),
199         origin,
200         net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)) {
201       redirect_origin_ = origin;
202       if (!simple_loaders_.empty()) {
203         // Cancel remaining loader, we don't need it.
204         DCHECK(simple_loaders_.size() == 1);
205         simple_loaders_.clear();
206       }
207     }
208     if (resulting_origins_.size() == 1) {
209       resulting_origins_.push_back(origin);
210       return;
211     }
212     DCHECK(resulting_origins_.size() == 2);
213     const bool same_domain_or_host =
214         net::registry_controlled_domains::SameDomainOrHost(
215             resulting_origins_.back(),
216             origin,
217             net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
218     redirect_origin_ = same_domain_or_host ? origin : GURL();
219   } else {
220     if (resulting_origins_.empty() || (resulting_origins_.size() == 1 &&
221                                        resulting_origins_.front().is_valid())) {
222       resulting_origins_.push_back(GURL());
223       return;
224     }
225     redirect_origin_ = GURL();
226   }
227
228   g_browser_process->local_state()->SetString(
229       prefs::kLastKnownIntranetRedirectOrigin, redirect_origin_.is_valid() ?
230           redirect_origin_.spec() : std::string());
231 }
232
233 void IntranetRedirectDetector::OnConnectionChanged(
234     network::mojom::ConnectionType type) {
235   if (type != network::mojom::ConnectionType::CONNECTION_NONE)
236     Restart();
237 }
238
239 void IntranetRedirectDetector::OnDnsConfigChanged() {
240   Restart();
241 }
242
243 void IntranetRedirectDetector::SetupDnsConfigClient() {
244   DCHECK(!dns_config_client_receiver_.is_bound());
245
246   mojo::Remote<network::mojom::DnsConfigChangeManager> manager_remote;
247   content::GetNetworkService()->GetDnsConfigChangeManager(
248       manager_remote.BindNewPipeAndPassReceiver());
249   manager_remote->RequestNotifications(
250       dns_config_client_receiver_.BindNewPipeAndPassRemote());
251   dns_config_client_receiver_.set_disconnect_handler(base::BindOnce(
252       &IntranetRedirectDetector::OnDnsConfigClientConnectionError,
253       base::Unretained(this)));
254 }
255
256 void IntranetRedirectDetector::OnDnsConfigClientConnectionError() {
257   dns_config_client_receiver_.reset();
258   SetupDnsConfigClient();
259 }
260
261 bool IntranetRedirectDetector::IsEnabledByPolicy() {
262   return g_browser_process->local_state()->GetBoolean(
263       prefs::kDNSInterceptionChecksEnabled);
264 }