Popular sites on the NTP: re-download popular suggestions once per Chrome run
[chromium-blink-merge.git] / chrome / browser / net / chrome_network_delegate.cc
blob8fd2976e149934d21be6e42ac73a1bc1ea23639f
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.
5 #include "chrome/browser/net/chrome_network_delegate.h"
7 #include <stdlib.h>
9 #include <vector>
11 #include "base/base_paths.h"
12 #include "base/command_line.h"
13 #include "base/debug/alias.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/debug/stack_trace.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/metrics/sparse_histogram.h"
19 #include "base/metrics/user_metrics.h"
20 #include "base/path_service.h"
21 #include "base/prefs/pref_member.h"
22 #include "base/prefs/pref_service.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/time/time.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/content_settings/cookie_settings_factory.h"
29 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
30 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
31 #include "chrome/browser/net/chrome_extensions_network_delegate.h"
32 #include "chrome/browser/net/connect_interceptor.h"
33 #include "chrome/browser/net/request_source_bandwidth_histograms.h"
34 #include "chrome/browser/net/safe_search_util.h"
35 #include "chrome/browser/profiles/profile_manager.h"
36 #include "chrome/browser/task_management/task_manager_interface.h"
37 #include "chrome/common/pref_names.h"
38 #include "components/content_settings/core/browser/cookie_settings.h"
39 #include "components/domain_reliability/monitor.h"
40 #include "content/public/browser/browser_thread.h"
41 #include "content/public/browser/render_frame_host.h"
42 #include "content/public/browser/render_view_host.h"
43 #include "content/public/browser/resource_request_info.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/process_type.h"
46 #include "net/base/host_port_pair.h"
47 #include "net/base/load_flags.h"
48 #include "net/base/net_errors.h"
49 #include "net/cookies/canonical_cookie.h"
50 #include "net/cookies/cookie_options.h"
51 #include "net/http/http_request_headers.h"
52 #include "net/http/http_response_headers.h"
53 #include "net/http/http_status_code.h"
54 #include "net/log/net_log.h"
55 #include "net/url_request/url_request.h"
57 #if defined(OS_ANDROID)
58 #include "chrome/browser/io_thread.h"
59 #include "chrome/browser/precache/precache_manager_factory.h"
60 #include "components/precache/content/precache_manager.h"
61 #endif
63 #if defined(OS_CHROMEOS)
64 #include "base/sys_info.h"
65 #include "chrome/common/chrome_switches.h"
66 #endif
68 #if defined(ENABLE_CONFIGURATION_POLICY)
69 #include "components/policy/core/browser/url_blacklist_manager.h"
70 #endif
72 #if defined(ENABLE_EXTENSIONS)
73 #include "extensions/common/constants.h"
74 #endif
76 using content::BrowserThread;
77 using content::RenderViewHost;
78 using content::ResourceRequestInfo;
79 using content::ResourceType;
81 // By default we don't allow access to all file:// urls on ChromeOS and
82 // Android.
83 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
84 bool ChromeNetworkDelegate::g_allow_file_access_ = false;
85 #else
86 bool ChromeNetworkDelegate::g_allow_file_access_ = true;
87 #endif
89 namespace {
91 const char kDNTHeader[] = "DNT";
93 // Gets called when the extensions finish work on the URL. If the extensions
94 // did not do a redirect (so |new_url| is empty) then we enforce the
95 // SafeSearch parameters. Otherwise we will get called again after the
96 // redirect and we enforce SafeSearch then.
97 void ForceGoogleSafeSearchCallbackWrapper(
98 const net::CompletionCallback& callback,
99 net::URLRequest* request,
100 GURL* new_url,
101 int rv) {
102 if (rv == net::OK && new_url->is_empty())
103 safe_search_util::ForceGoogleSafeSearch(request, new_url);
104 callback.Run(rv);
107 #if defined(OS_ANDROID)
108 void RecordPrecacheStatsOnUIThread(const GURL& url,
109 const GURL& referrer,
110 base::TimeDelta latency,
111 const base::Time& fetch_time,
112 int64 size,
113 bool was_cached,
114 void* profile_id) {
115 DCHECK_CURRENTLY_ON(BrowserThread::UI);
117 Profile* profile = reinterpret_cast<Profile*>(profile_id);
118 if (!g_browser_process->profile_manager()->IsValidProfile(profile))
119 return;
121 precache::PrecacheManager* precache_manager =
122 precache::PrecacheManagerFactory::GetForBrowserContext(profile);
123 // |precache_manager| could be NULL if the profile is off the record.
124 if (!precache_manager || !precache_manager->IsPrecachingAllowed())
125 return;
127 precache_manager->RecordStatsForFetch(url, referrer, latency, fetch_time,
128 size, was_cached);
130 #endif // defined(OS_ANDROID)
132 void ReportInvalidReferrerSendOnUI() {
133 base::RecordAction(
134 base::UserMetricsAction("Net.URLRequest_StartJob_InvalidReferrer"));
137 void ReportInvalidReferrerSend(const GURL& target_url,
138 const GURL& referrer_url) {
139 LOG(ERROR) << "Cancelling request to " << target_url
140 << " with invalid referrer " << referrer_url;
141 // Record information to help debug http://crbug.com/422871
142 if (!target_url.SchemeIsHTTPOrHTTPS())
143 return;
144 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
145 base::Bind(&ReportInvalidReferrerSendOnUI));
146 base::debug::DumpWithoutCrashing();
147 NOTREACHED();
150 // Record network errors that HTTP requests complete with, including OK and
151 // ABORTED.
152 void RecordNetworkErrorHistograms(const net::URLRequest* request) {
153 if (request->url().SchemeIs("http")) {
154 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.HttpRequestCompletionErrorCodes",
155 std::abs(request->status().error()));
157 if (request->load_flags() & net::LOAD_MAIN_FRAME) {
158 UMA_HISTOGRAM_SPARSE_SLOWLY(
159 "Net.HttpRequestCompletionErrorCodes.MainFrame",
160 std::abs(request->status().error()));
165 // Returns whether |request| is likely to be eligible for delta-encoding.
166 // This is only a rough approximation right now, based on MIME type.
167 bool CanRequestBeDeltaEncoded(const net::URLRequest* request) {
168 struct {
169 const char *prefix;
170 const char *suffix;
171 } kEligibleMasks[] = {
172 // All text/ types are eligible, even if not displayable.
173 { "text/", NULL },
174 // JSON (application/json and application/*+json) is eligible.
175 { "application/", "json" },
176 // Javascript is eligible.
177 { "application/", "javascript" },
178 // XML (application/xml and application/*+xml) is eligible.
179 { "application/", "xml" },
182 std::string mime_type;
183 request->GetMimeType(&mime_type);
185 for (size_t i = 0; i < arraysize(kEligibleMasks); i++) {
186 const char *prefix = kEligibleMasks[i].prefix;
187 const char *suffix = kEligibleMasks[i].suffix;
188 if (prefix &&
189 !base::StartsWith(mime_type, prefix, base::CompareCase::SENSITIVE))
190 continue;
191 if (suffix &&
192 !base::EndsWith(mime_type, suffix, base::CompareCase::SENSITIVE))
193 continue;
194 return true;
196 return false;
199 // Returns whether |request| was issued by a renderer process, as opposed to
200 // the browser process or a plugin process.
201 bool IsRendererInitiatedRequest(const net::URLRequest* request) {
202 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
203 return info && info->GetProcessType() == content::PROCESS_TYPE_RENDERER;
206 // Uploads UMA histograms for delta encoding eligibility. This method can only
207 // be safely called after the network stack has called both OnStarted and
208 // OnCompleted, since it needs the received response content length and the
209 // response headers.
210 void RecordCacheStateStats(const net::URLRequest* request) {
211 net::HttpRequestHeaders request_headers;
212 if (!request->GetFullRequestHeaders(&request_headers)) {
213 // GetFullRequestHeaders is guaranteed to succeed if OnResponseStarted() has
214 // been called on |request|, so if GetFullRequestHeaders() fails,
215 // RecordCacheStateStats must have been called before
216 // OnResponseStarted().
217 return;
220 if (!IsRendererInitiatedRequest(request)) {
221 // Ignore browser-initiated requests. These are internal requests like safe
222 // browsing and sync, and so on. Some of these could be eligible for
223 // delta-encoding, but to be conservative this function ignores all of them.
224 return;
227 const int kCacheAffectingFlags = net::LOAD_BYPASS_CACHE |
228 net::LOAD_DISABLE_CACHE |
229 net::LOAD_PREFERRING_CACHE;
231 if (request->load_flags() & kCacheAffectingFlags) {
232 // Ignore requests with cache-affecting flags, which would otherwise mess up
233 // these stats.
234 return;
237 enum {
238 CACHE_STATE_FROM_CACHE,
239 CACHE_STATE_STILL_VALID,
240 CACHE_STATE_NO_LONGER_VALID,
241 CACHE_STATE_NO_ENTRY,
242 CACHE_STATE_MAX,
243 } state = CACHE_STATE_NO_ENTRY;
244 bool had_cache_headers =
245 request_headers.HasHeader(net::HttpRequestHeaders::kIfModifiedSince) ||
246 request_headers.HasHeader(net::HttpRequestHeaders::kIfNoneMatch) ||
247 request_headers.HasHeader(net::HttpRequestHeaders::kIfRange);
248 if (request->was_cached() && !had_cache_headers) {
249 // Entry was served directly from cache.
250 state = CACHE_STATE_FROM_CACHE;
251 } else if (request->was_cached() && had_cache_headers) {
252 // Expired entry was present in cache, and server responded with NOT
253 // MODIFIED, indicating the expired entry is still valid.
254 state = CACHE_STATE_STILL_VALID;
255 } else if (!request->was_cached() && had_cache_headers) {
256 // Expired entry was present in cache, and server responded with something
257 // other than NOT MODIFIED, indicating the entry is no longer valid.
258 state = CACHE_STATE_NO_LONGER_VALID;
259 } else if (!request->was_cached() && !had_cache_headers) {
260 // Neither |was_cached| nor |had_cache_headers|, so there's no local cache
261 // entry for this content at all.
262 state = CACHE_STATE_NO_ENTRY;
265 UMA_HISTOGRAM_ENUMERATION("Net.CacheState.AllRequests", state,
266 CACHE_STATE_MAX);
267 if (CanRequestBeDeltaEncoded(request)) {
268 UMA_HISTOGRAM_ENUMERATION("Net.CacheState.EncodeableRequests", state,
269 CACHE_STATE_MAX);
272 int64 size = request->received_response_content_length();
273 if (size >= 0 && state == CACHE_STATE_NO_LONGER_VALID) {
274 UMA_HISTOGRAM_COUNTS("Net.CacheState.AllBytes", size);
275 if (CanRequestBeDeltaEncoded(request)) {
276 UMA_HISTOGRAM_COUNTS("Net.CacheState.EncodeableBytes", size);
281 } // namespace
283 ChromeNetworkDelegate::ChromeNetworkDelegate(
284 extensions::EventRouterForwarder* event_router,
285 BooleanPrefMember* enable_referrers)
286 : profile_(NULL),
287 enable_referrers_(enable_referrers),
288 enable_do_not_track_(NULL),
289 force_google_safe_search_(NULL),
290 force_youtube_safety_mode_(NULL),
291 #if defined(ENABLE_CONFIGURATION_POLICY)
292 url_blacklist_manager_(NULL),
293 #endif
294 domain_reliability_monitor_(NULL),
295 experimental_web_platform_features_enabled_(
296 base::CommandLine::ForCurrentProcess()->HasSwitch(
297 switches::kEnableExperimentalWebPlatformFeatures)) {
298 DCHECK(enable_referrers);
299 extensions_delegate_.reset(
300 ChromeExtensionsNetworkDelegate::Create(event_router));
303 ChromeNetworkDelegate::~ChromeNetworkDelegate() {}
305 void ChromeNetworkDelegate::set_extension_info_map(
306 extensions::InfoMap* extension_info_map) {
307 extensions_delegate_->set_extension_info_map(extension_info_map);
310 void ChromeNetworkDelegate::set_profile(void* profile) {
311 profile_ = profile;
312 extensions_delegate_->set_profile(profile);
315 void ChromeNetworkDelegate::set_cookie_settings(
316 content_settings::CookieSettings* cookie_settings) {
317 cookie_settings_ = cookie_settings;
320 void ChromeNetworkDelegate::set_predictor(
321 chrome_browser_net::Predictor* predictor) {
322 connect_interceptor_.reset(
323 new chrome_browser_net::ConnectInterceptor(predictor));
326 // static
327 void ChromeNetworkDelegate::InitializePrefsOnUIThread(
328 BooleanPrefMember* enable_referrers,
329 BooleanPrefMember* enable_do_not_track,
330 BooleanPrefMember* force_google_safe_search,
331 BooleanPrefMember* force_youtube_safety_mode,
332 PrefService* pref_service) {
333 DCHECK_CURRENTLY_ON(BrowserThread::UI);
334 enable_referrers->Init(prefs::kEnableReferrers, pref_service);
335 enable_referrers->MoveToThread(
336 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
337 if (enable_do_not_track) {
338 enable_do_not_track->Init(prefs::kEnableDoNotTrack, pref_service);
339 enable_do_not_track->MoveToThread(
340 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
342 if (force_google_safe_search) {
343 force_google_safe_search->Init(prefs::kForceGoogleSafeSearch, pref_service);
344 force_google_safe_search->MoveToThread(
345 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
347 if (force_youtube_safety_mode) {
348 force_youtube_safety_mode->Init(prefs::kForceYouTubeSafetyMode,
349 pref_service);
350 force_youtube_safety_mode->MoveToThread(
351 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
355 // static
356 void ChromeNetworkDelegate::AllowAccessToAllFiles() {
357 g_allow_file_access_ = true;
360 int ChromeNetworkDelegate::OnBeforeURLRequest(
361 net::URLRequest* request,
362 const net::CompletionCallback& callback,
363 GURL* new_url) {
364 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
365 tracked_objects::ScopedTracker tracking_profile1(
366 FROM_HERE_WITH_EXPLICIT_FUNCTION(
367 "456327 URLRequest::ChromeNetworkDelegate::OnBeforeURLRequest"));
369 #if defined(ENABLE_CONFIGURATION_POLICY)
370 // TODO(joaodasilva): This prevents extensions from seeing URLs that are
371 // blocked. However, an extension might redirect the request to another URL,
372 // which is not blocked.
374 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
375 int error = net::ERR_BLOCKED_BY_ADMINISTRATOR;
376 if (info && content::IsResourceTypeFrame(info->GetResourceType()) &&
377 url_blacklist_manager_ &&
378 url_blacklist_manager_->ShouldBlockRequestForFrame(
379 request->url(), &error)) {
380 // URL access blocked by policy.
381 request->net_log().AddEvent(
382 net::NetLog::TYPE_CHROME_POLICY_ABORTED_REQUEST,
383 net::NetLog::StringCallback("url",
384 &request->url().possibly_invalid_spec()));
385 return error;
387 #endif
389 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
390 tracked_objects::ScopedTracker tracking_profile2(
391 FROM_HERE_WITH_EXPLICIT_FUNCTION(
392 "456327 URLRequest::ChromeNetworkDelegate::OnBeforeURLRequest 2"));
394 extensions_delegate_->ForwardStartRequestStatus(request);
396 if (!enable_referrers_->GetValue())
397 request->SetReferrer(std::string());
398 if (enable_do_not_track_ && enable_do_not_track_->GetValue())
399 request->SetExtraRequestHeaderByName(kDNTHeader, "1", true /* override */);
401 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
402 tracked_objects::ScopedTracker tracking_profile3(
403 FROM_HERE_WITH_EXPLICIT_FUNCTION(
404 "456327 URLRequest::ChromeNetworkDelegate::OnBeforeURLRequest 3"));
406 bool force_safe_search =
407 (force_google_safe_search_ && force_google_safe_search_->GetValue());
409 net::CompletionCallback wrapped_callback = callback;
410 if (force_safe_search) {
411 wrapped_callback = base::Bind(&ForceGoogleSafeSearchCallbackWrapper,
412 callback,
413 base::Unretained(request),
414 base::Unretained(new_url));
417 int rv = extensions_delegate_->OnBeforeURLRequest(
418 request, wrapped_callback, new_url);
420 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
421 tracked_objects::ScopedTracker tracking_profile4(
422 FROM_HERE_WITH_EXPLICIT_FUNCTION(
423 "456327 URLRequest::ChromeNetworkDelegate::OnBeforeURLRequest 4"));
425 if (force_safe_search && rv == net::OK && new_url->is_empty())
426 safe_search_util::ForceGoogleSafeSearch(request, new_url);
428 // TODO(mmenke): Remove ScopedTracker below once crbug.com/456327 is fixed.
429 tracked_objects::ScopedTracker tracking_profile5(
430 FROM_HERE_WITH_EXPLICIT_FUNCTION(
431 "456327 URLRequest::ChromeNetworkDelegate::OnBeforeURLRequest 5"));
433 if (connect_interceptor_)
434 connect_interceptor_->WitnessURLRequest(request);
436 return rv;
439 int ChromeNetworkDelegate::OnBeforeSendHeaders(
440 net::URLRequest* request,
441 const net::CompletionCallback& callback,
442 net::HttpRequestHeaders* headers) {
443 if (force_youtube_safety_mode_ && force_youtube_safety_mode_->GetValue())
444 safe_search_util::ForceYouTubeSafetyMode(request, headers);
446 return extensions_delegate_->OnBeforeSendHeaders(request, callback, headers);
449 void ChromeNetworkDelegate::OnSendHeaders(
450 net::URLRequest* request,
451 const net::HttpRequestHeaders& headers) {
452 extensions_delegate_->OnSendHeaders(request, headers);
455 int ChromeNetworkDelegate::OnHeadersReceived(
456 net::URLRequest* request,
457 const net::CompletionCallback& callback,
458 const net::HttpResponseHeaders* original_response_headers,
459 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
460 GURL* allowed_unsafe_redirect_url) {
461 return extensions_delegate_->OnHeadersReceived(
462 request,
463 callback,
464 original_response_headers,
465 override_response_headers,
466 allowed_unsafe_redirect_url);
469 void ChromeNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
470 const GURL& new_location) {
471 // Recording data use of request on redirects.
472 #if !defined(OS_IOS)
473 data_use_measurement_.ReportDataUseUMA(request);
474 #endif
475 if (domain_reliability_monitor_)
476 domain_reliability_monitor_->OnBeforeRedirect(request);
477 extensions_delegate_->OnBeforeRedirect(request, new_location);
481 void ChromeNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
482 extensions_delegate_->OnResponseStarted(request);
485 void ChromeNetworkDelegate::OnNetworkBytesReceived(
486 const net::URLRequest& request,
487 int64_t bytes_received) {
488 #if defined(ENABLE_TASK_MANAGER)
489 // Note: Currently, OnNetworkBytesReceived is only implemented for HTTP jobs,
490 // not FTP or other types, so those kinds of bytes will not be reported here.
491 task_management::TaskManagerInterface::OnRawBytesRead(request,
492 bytes_received);
493 #endif // defined(ENABLE_TASK_MANAGER)
496 void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
497 bool started) {
498 #if !defined(OS_IOS)
499 // TODO(amohammadkhan): Verify that there is no double recording in data use
500 // of redirected requests.
501 data_use_measurement_.ReportDataUseUMA(request);
502 #endif
503 RecordNetworkErrorHistograms(request);
504 if (started) {
505 // Only call in for requests that were started, to obey the precondition
506 // that RecordCacheStateStats can only be called on requests for which
507 // OnResponseStarted was called.
508 RecordCacheStateStats(request);
511 if (request->status().status() == net::URLRequestStatus::SUCCESS) {
512 #if defined(OS_ANDROID)
513 // For better accuracy, we use the actual bytes read instead of the length
514 // specified with the Content-Length header, which may be inaccurate,
515 // or missing, as is the case with chunked encoding.
516 int64 received_content_length = request->received_response_content_length();
517 base::TimeDelta latency = base::TimeTicks::Now() - request->creation_time();
519 // Record precache metrics when a fetch is completed successfully, if
520 // precaching is allowed.
521 BrowserThread::PostTask(
522 BrowserThread::UI, FROM_HERE,
523 base::Bind(&RecordPrecacheStatsOnUIThread, request->url(),
524 GURL(request->referrer()), latency, base::Time::Now(),
525 received_content_length, request->was_cached(), profile_));
526 #endif // defined(OS_ANDROID)
527 extensions_delegate_->OnCompleted(request, started);
528 } else if (request->status().status() == net::URLRequestStatus::FAILED ||
529 request->status().status() == net::URLRequestStatus::CANCELED) {
530 extensions_delegate_->OnCompleted(request, started);
531 } else {
532 NOTREACHED();
534 if (domain_reliability_monitor_)
535 domain_reliability_monitor_->OnCompleted(request, started);
536 RecordRequestSourceBandwidth(request, started);
537 extensions_delegate_->ForwardProxyErrors(request);
538 extensions_delegate_->ForwardDoneRequestStatus(request);
541 void ChromeNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
542 extensions_delegate_->OnURLRequestDestroyed(request);
545 void ChromeNetworkDelegate::OnURLRequestJobOrphaned(net::URLRequest* request) {
546 extensions_delegate_->OnURLRequestJobOrphaned(request);
549 void ChromeNetworkDelegate::OnPACScriptError(int line_number,
550 const base::string16& error) {
551 extensions_delegate_->OnPACScriptError(line_number, error);
554 net::NetworkDelegate::AuthRequiredResponse
555 ChromeNetworkDelegate::OnAuthRequired(
556 net::URLRequest* request,
557 const net::AuthChallengeInfo& auth_info,
558 const AuthCallback& callback,
559 net::AuthCredentials* credentials) {
560 return extensions_delegate_->OnAuthRequired(
561 request, auth_info, callback, credentials);
564 bool ChromeNetworkDelegate::OnCanGetCookies(
565 const net::URLRequest& request,
566 const net::CookieList& cookie_list) {
567 // NULL during tests, or when we're running in the system context.
568 if (!cookie_settings_.get())
569 return true;
571 bool allow = cookie_settings_->IsReadingCookieAllowed(
572 request.url(), request.first_party_for_cookies());
574 int render_process_id = -1;
575 int render_frame_id = -1;
576 if (content::ResourceRequestInfo::GetRenderFrameForRequest(
577 &request, &render_process_id, &render_frame_id)) {
578 BrowserThread::PostTask(
579 BrowserThread::UI, FROM_HERE,
580 base::Bind(&TabSpecificContentSettings::CookiesRead,
581 render_process_id, render_frame_id,
582 request.url(), request.first_party_for_cookies(),
583 cookie_list, !allow));
586 return allow;
589 bool ChromeNetworkDelegate::OnCanSetCookie(const net::URLRequest& request,
590 const std::string& cookie_line,
591 net::CookieOptions* options) {
592 // NULL during tests, or when we're running in the system context.
593 if (!cookie_settings_.get())
594 return true;
596 bool allow = cookie_settings_->IsSettingCookieAllowed(
597 request.url(), request.first_party_for_cookies());
599 int render_process_id = -1;
600 int render_frame_id = -1;
601 if (content::ResourceRequestInfo::GetRenderFrameForRequest(
602 &request, &render_process_id, &render_frame_id)) {
603 BrowserThread::PostTask(
604 BrowserThread::UI, FROM_HERE,
605 base::Bind(&TabSpecificContentSettings::CookieChanged,
606 render_process_id, render_frame_id,
607 request.url(), request.first_party_for_cookies(),
608 cookie_line, *options, !allow));
611 return allow;
614 bool ChromeNetworkDelegate::OnCanAccessFile(const net::URLRequest& request,
615 const base::FilePath& path) const {
616 if (g_allow_file_access_)
617 return true;
619 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
620 return true;
621 #else
622 #if defined(OS_CHROMEOS)
623 // If we're running Chrome for ChromeOS on Linux, we want to allow file
624 // access.
625 if (!base::SysInfo::IsRunningOnChromeOS() ||
626 base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
627 return true;
630 // Use a whitelist to only allow access to files residing in the list of
631 // directories below.
632 static const char* const kLocalAccessWhiteList[] = {
633 "/home/chronos/user/Downloads",
634 "/home/chronos/user/log",
635 "/home/chronos/user/WebRTC Logs",
636 "/media",
637 "/opt/oem",
638 "/usr/share/chromeos-assets",
639 "/tmp",
640 "/var/log",
643 // The actual location of "/home/chronos/user/Xyz" is the Xyz directory under
644 // the profile path ("/home/chronos/user' is a hard link to current primary
645 // logged in profile.) For the support of multi-profile sessions, we are
646 // switching to use explicit "$PROFILE_PATH/Xyz" path and here whitelist such
647 // access.
648 if (!profile_path_.empty()) {
649 const base::FilePath downloads = profile_path_.AppendASCII("Downloads");
650 if (downloads == path.StripTrailingSeparators() || downloads.IsParent(path))
651 return true;
652 const base::FilePath webrtc_logs = profile_path_.AppendASCII("WebRTC Logs");
653 if (webrtc_logs == path.StripTrailingSeparators() ||
654 webrtc_logs.IsParent(path)) {
655 return true;
658 #elif defined(OS_ANDROID)
659 // Access to files in external storage is allowed.
660 base::FilePath external_storage_path;
661 PathService::Get(base::DIR_ANDROID_EXTERNAL_STORAGE, &external_storage_path);
662 if (external_storage_path.IsParent(path))
663 return true;
665 // Whitelist of other allowed directories.
666 static const char* const kLocalAccessWhiteList[] = {
667 "/sdcard",
668 "/mnt/sdcard",
670 #endif
672 for (size_t i = 0; i < arraysize(kLocalAccessWhiteList); ++i) {
673 const base::FilePath white_listed_path(kLocalAccessWhiteList[i]);
674 // base::FilePath::operator== should probably handle trailing separators.
675 if (white_listed_path == path.StripTrailingSeparators() ||
676 white_listed_path.IsParent(path)) {
677 return true;
681 DVLOG(1) << "File access denied - " << path.value().c_str();
682 return false;
683 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
686 bool ChromeNetworkDelegate::OnCanEnablePrivacyMode(
687 const GURL& url,
688 const GURL& first_party_for_cookies) const {
689 // NULL during tests, or when we're running in the system context.
690 if (!cookie_settings_.get())
691 return false;
693 bool reading_cookie_allowed = cookie_settings_->IsReadingCookieAllowed(
694 url, first_party_for_cookies);
695 bool setting_cookie_allowed = cookie_settings_->IsSettingCookieAllowed(
696 url, first_party_for_cookies);
697 bool privacy_mode = !(reading_cookie_allowed && setting_cookie_allowed);
698 return privacy_mode;
701 bool ChromeNetworkDelegate::OnFirstPartyOnlyCookieExperimentEnabled() const {
702 return experimental_web_platform_features_enabled_;
705 bool ChromeNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
706 const net::URLRequest& request,
707 const GURL& target_url,
708 const GURL& referrer_url) const {
709 ReportInvalidReferrerSend(target_url, referrer_url);
710 return true;