Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / net / chrome_network_delegate.cc
blob20372d3c5b61aef8f60ac93933cc25b3e083eea5
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.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/safe_search_util.h"
34 #include "chrome/browser/profiles/profile_manager.h"
35 #include "chrome/browser/task_manager/task_manager.h"
36 #include "chrome/common/pref_names.h"
37 #include "components/domain_reliability/monitor.h"
38 #include "content/public/browser/browser_thread.h"
39 #include "content/public/browser/render_frame_host.h"
40 #include "content/public/browser/render_view_host.h"
41 #include "content/public/browser/resource_request_info.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/process_type.h"
44 #include "net/base/host_port_pair.h"
45 #include "net/base/load_flags.h"
46 #include "net/base/net_errors.h"
47 #include "net/cookies/canonical_cookie.h"
48 #include "net/cookies/cookie_options.h"
49 #include "net/http/http_request_headers.h"
50 #include "net/http/http_response_headers.h"
51 #include "net/http/http_status_code.h"
52 #include "net/log/net_log.h"
53 #include "net/url_request/url_request.h"
55 #if defined(OS_ANDROID)
56 #include "chrome/browser/io_thread.h"
57 #include "components/precache/content/precache_manager.h"
58 #include "components/precache/content/precache_manager_factory.h"
59 #endif
61 #if defined(OS_CHROMEOS)
62 #include "base/sys_info.h"
63 #include "chrome/common/chrome_switches.h"
64 #endif
66 #if defined(ENABLE_CONFIGURATION_POLICY)
67 #include "components/policy/core/browser/url_blacklist_manager.h"
68 #endif
70 #if defined(ENABLE_EXTENSIONS)
71 #include "extensions/common/constants.h"
72 #endif
74 using content::BrowserThread;
75 using content::RenderViewHost;
76 using content::ResourceRequestInfo;
77 using content::ResourceType;
79 // By default we don't allow access to all file:// urls on ChromeOS and
80 // Android.
81 #if defined(OS_CHROMEOS) || defined(OS_ANDROID)
82 bool ChromeNetworkDelegate::g_allow_file_access_ = false;
83 #else
84 bool ChromeNetworkDelegate::g_allow_file_access_ = true;
85 #endif
87 #if defined(ENABLE_EXTENSIONS)
88 // This remains false unless the --disable-extensions-http-throttling
89 // flag is passed to the browser.
90 bool ChromeNetworkDelegate::g_never_throttle_requests_ = false;
91 #endif
93 namespace {
95 const char kDNTHeader[] = "DNT";
97 // Gets called when the extensions finish work on the URL. If the extensions
98 // did not do a redirect (so |new_url| is empty) then we enforce the
99 // SafeSearch parameters. Otherwise we will get called again after the
100 // redirect and we enforce SafeSearch then.
101 void ForceGoogleSafeSearchCallbackWrapper(
102 const net::CompletionCallback& callback,
103 net::URLRequest* request,
104 GURL* new_url,
105 int rv) {
106 if (rv == net::OK && new_url->is_empty())
107 safe_search_util::ForceGoogleSafeSearch(request, new_url);
108 callback.Run(rv);
111 #if defined(OS_ANDROID)
112 void RecordPrecacheStatsOnUIThread(const GURL& url,
113 const base::Time& fetch_time, int64 size,
114 bool was_cached, void* profile_id) {
115 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
117 Profile* profile = reinterpret_cast<Profile*>(profile_id);
118 if (!g_browser_process->profile_manager()->IsValidProfile(profile)) {
119 return;
122 precache::PrecacheManager* precache_manager =
123 precache::PrecacheManagerFactory::GetForBrowserContext(profile);
124 if (!precache_manager || !precache_manager->IsPrecachingAllowed()) {
125 // |precache_manager| could be NULL if the profile is off the record.
126 return;
129 precache_manager->RecordStatsForFetch(url, fetch_time, size, was_cached);
131 #endif // defined(OS_ANDROID)
133 void ReportInvalidReferrerSendOnUI() {
134 base::RecordAction(
135 base::UserMetricsAction("Net.URLRequest_StartJob_InvalidReferrer"));
138 void ReportInvalidReferrerSend(const GURL& target_url,
139 const GURL& referrer_url) {
140 // Record information to help debug http://crbug.com/422871
141 if (!target_url.SchemeIsHTTPOrHTTPS())
142 return;
143 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
144 base::Bind(&ReportInvalidReferrerSendOnUI));
145 base::debug::DumpWithoutCrashing();
146 NOTREACHED() << "Sending request to " << target_url
147 << " with invalid referrer " << referrer_url;
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" },
181 const bool kCaseSensitive = true;
183 std::string mime_type;
184 request->GetMimeType(&mime_type);
186 for (size_t i = 0; i < arraysize(kEligibleMasks); i++) {
187 const char *prefix = kEligibleMasks[i].prefix;
188 const char *suffix = kEligibleMasks[i].suffix;
189 if (prefix && !StartsWithASCII(mime_type, prefix, kCaseSensitive))
190 continue;
191 if (suffix && !EndsWith(mime_type, suffix, kCaseSensitive))
192 continue;
193 return true;
195 return false;
198 // Returns whether |request| was issued by a renderer process, as opposed to
199 // the browser process or a plugin process.
200 bool IsRendererInitiatedRequest(const net::URLRequest* request) {
201 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
202 return info && info->GetProcessType() == content::PROCESS_TYPE_RENDERER;
205 // Uploads UMA histograms for delta encoding eligibility. This method can only
206 // be safely called after the network stack has called both OnStarted and
207 // OnCompleted, since it needs the received response content length and the
208 // response headers.
209 void RecordCacheStateStats(const net::URLRequest* request) {
210 net::HttpRequestHeaders request_headers;
211 if (!request->GetFullRequestHeaders(&request_headers)) {
212 // GetFullRequestHeaders is guaranteed to succeed if OnResponseStarted() has
213 // been called on |request|, so if GetFullRequestHeaders() fails,
214 // RecordCacheStateStats must have been called before
215 // OnResponseStarted().
216 return;
219 if (!IsRendererInitiatedRequest(request)) {
220 // Ignore browser-initiated requests. These are internal requests like safe
221 // browsing and sync, and so on. Some of these could be eligible for
222 // delta-encoding, but to be conservative this function ignores all of them.
223 return;
226 const int kCacheAffectingFlags = net::LOAD_BYPASS_CACHE |
227 net::LOAD_DISABLE_CACHE |
228 net::LOAD_PREFERRING_CACHE;
230 if (request->load_flags() & kCacheAffectingFlags) {
231 // Ignore requests with cache-affecting flags, which would otherwise mess up
232 // these stats.
233 return;
236 enum {
237 CACHE_STATE_FROM_CACHE,
238 CACHE_STATE_STILL_VALID,
239 CACHE_STATE_NO_LONGER_VALID,
240 CACHE_STATE_NO_ENTRY,
241 CACHE_STATE_MAX,
242 } state = CACHE_STATE_NO_ENTRY;
243 bool had_cache_headers =
244 request_headers.HasHeader(net::HttpRequestHeaders::kIfModifiedSince) ||
245 request_headers.HasHeader(net::HttpRequestHeaders::kIfNoneMatch) ||
246 request_headers.HasHeader(net::HttpRequestHeaders::kIfRange);
247 if (request->was_cached() && !had_cache_headers) {
248 // Entry was served directly from cache.
249 state = CACHE_STATE_FROM_CACHE;
250 } else if (request->was_cached() && had_cache_headers) {
251 // Expired entry was present in cache, and server responded with NOT
252 // MODIFIED, indicating the expired entry is still valid.
253 state = CACHE_STATE_STILL_VALID;
254 } else if (!request->was_cached() && had_cache_headers) {
255 // Expired entry was present in cache, and server responded with something
256 // other than NOT MODIFIED, indicating the entry is no longer valid.
257 state = CACHE_STATE_NO_LONGER_VALID;
258 } else if (!request->was_cached() && !had_cache_headers) {
259 // Neither |was_cached| nor |had_cache_headers|, so there's no local cache
260 // entry for this content at all.
261 state = CACHE_STATE_NO_ENTRY;
264 UMA_HISTOGRAM_ENUMERATION("Net.CacheState.AllRequests", state,
265 CACHE_STATE_MAX);
266 if (CanRequestBeDeltaEncoded(request)) {
267 UMA_HISTOGRAM_ENUMERATION("Net.CacheState.EncodeableRequests", state,
268 CACHE_STATE_MAX);
271 int64 size = request->received_response_content_length();
272 if (size >= 0 && state == CACHE_STATE_NO_LONGER_VALID) {
273 UMA_HISTOGRAM_COUNTS("Net.CacheState.AllBytes", size);
274 if (CanRequestBeDeltaEncoded(request)) {
275 UMA_HISTOGRAM_COUNTS("Net.CacheState.EncodeableBytes", size);
280 } // namespace
282 ChromeNetworkDelegate::ChromeNetworkDelegate(
283 extensions::EventRouterForwarder* event_router,
284 BooleanPrefMember* enable_referrers)
285 : profile_(NULL),
286 enable_referrers_(enable_referrers),
287 enable_do_not_track_(NULL),
288 force_safe_search_(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 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 #if defined(ENABLE_EXTENSIONS)
328 void ChromeNetworkDelegate::NeverThrottleRequests() {
329 g_never_throttle_requests_ = true;
331 #endif
333 // static
334 void ChromeNetworkDelegate::InitializePrefsOnUIThread(
335 BooleanPrefMember* enable_referrers,
336 BooleanPrefMember* enable_do_not_track,
337 BooleanPrefMember* force_safe_search,
338 BooleanPrefMember* force_google_safe_search,
339 BooleanPrefMember* force_youtube_safety_mode,
340 PrefService* pref_service) {
341 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
342 enable_referrers->Init(prefs::kEnableReferrers, pref_service);
343 enable_referrers->MoveToThread(
344 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
345 if (enable_do_not_track) {
346 enable_do_not_track->Init(prefs::kEnableDoNotTrack, pref_service);
347 enable_do_not_track->MoveToThread(
348 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
350 if (force_safe_search) {
351 force_safe_search->Init(prefs::kForceSafeSearch, pref_service);
352 force_safe_search->MoveToThread(
353 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
355 if (force_google_safe_search) {
356 force_google_safe_search->Init(prefs::kForceGoogleSafeSearch, pref_service);
357 force_google_safe_search->MoveToThread(
358 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
360 if (force_youtube_safety_mode) {
361 force_youtube_safety_mode->Init(prefs::kForceYouTubeSafetyMode,
362 pref_service);
363 force_youtube_safety_mode->MoveToThread(
364 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
368 // static
369 void ChromeNetworkDelegate::AllowAccessToAllFiles() {
370 g_allow_file_access_ = true;
373 int ChromeNetworkDelegate::OnBeforeURLRequest(
374 net::URLRequest* request,
375 const net::CompletionCallback& callback,
376 GURL* new_url) {
377 #if defined(ENABLE_CONFIGURATION_POLICY)
378 // TODO(joaodasilva): This prevents extensions from seeing URLs that are
379 // blocked. However, an extension might redirect the request to another URL,
380 // which is not blocked.
381 int error = net::ERR_BLOCKED_BY_ADMINISTRATOR;
382 if (url_blacklist_manager_ &&
383 url_blacklist_manager_->IsRequestBlocked(*request, &error)) {
384 // URL access blocked by policy.
385 request->net_log().AddEvent(
386 net::NetLog::TYPE_CHROME_POLICY_ABORTED_REQUEST,
387 net::NetLog::StringCallback("url",
388 &request->url().possibly_invalid_spec()));
389 return error;
391 #endif
393 extensions_delegate_->ForwardStartRequestStatus(request);
395 if (!enable_referrers_->GetValue())
396 request->SetReferrer(std::string());
397 if (enable_do_not_track_ && enable_do_not_track_->GetValue())
398 request->SetExtraRequestHeaderByName(kDNTHeader, "1", true /* override */);
400 bool force_safe_search =
401 (force_safe_search_ && force_safe_search_->GetValue()) ||
402 (force_google_safe_search_ && force_google_safe_search_->GetValue());
404 net::CompletionCallback wrapped_callback = callback;
405 if (force_safe_search) {
406 wrapped_callback = base::Bind(&ForceGoogleSafeSearchCallbackWrapper,
407 callback,
408 base::Unretained(request),
409 base::Unretained(new_url));
412 int rv = extensions_delegate_->OnBeforeURLRequest(
413 request, wrapped_callback, new_url);
415 if (force_safe_search && rv == net::OK && new_url->is_empty())
416 safe_search_util::ForceGoogleSafeSearch(request, new_url);
418 if (connect_interceptor_)
419 connect_interceptor_->WitnessURLRequest(request);
421 return rv;
424 int ChromeNetworkDelegate::OnBeforeSendHeaders(
425 net::URLRequest* request,
426 const net::CompletionCallback& callback,
427 net::HttpRequestHeaders* headers) {
428 bool force_safety_mode =
429 (force_safe_search_ && force_safe_search_->GetValue()) ||
430 (force_youtube_safety_mode_ && force_youtube_safety_mode_->GetValue());
431 if (force_safety_mode)
432 safe_search_util::ForceYouTubeSafetyMode(request, headers);
434 return extensions_delegate_->OnBeforeSendHeaders(request, callback, headers);
437 void ChromeNetworkDelegate::OnSendHeaders(
438 net::URLRequest* request,
439 const net::HttpRequestHeaders& headers) {
440 extensions_delegate_->OnSendHeaders(request, headers);
443 int ChromeNetworkDelegate::OnHeadersReceived(
444 net::URLRequest* request,
445 const net::CompletionCallback& callback,
446 const net::HttpResponseHeaders* original_response_headers,
447 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
448 GURL* allowed_unsafe_redirect_url) {
449 return extensions_delegate_->OnHeadersReceived(
450 request,
451 callback,
452 original_response_headers,
453 override_response_headers,
454 allowed_unsafe_redirect_url);
457 void ChromeNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
458 const GURL& new_location) {
459 if (domain_reliability_monitor_)
460 domain_reliability_monitor_->OnBeforeRedirect(request);
461 extensions_delegate_->OnBeforeRedirect(request, new_location);
465 void ChromeNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
466 extensions_delegate_->OnResponseStarted(request);
469 void ChromeNetworkDelegate::OnRawBytesRead(const net::URLRequest& request,
470 int bytes_read) {
471 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
472 tracked_objects::ScopedTracker tracking_profile(
473 FROM_HERE_WITH_EXPLICIT_FUNCTION(
474 "423948 ChromeNetworkDelegate::OnRawBytesRead"));
476 #if defined(ENABLE_TASK_MANAGER)
477 // This is not completely accurate, but as a first approximation ignore
478 // requests that are served from the cache. See bug 330931 for more info.
479 if (!request.was_cached()) {
480 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
481 // I suspect that the jank is in creating a TaskManager instance. After the
482 // bug is fixed, rewrite the operators below as one line.
483 tracked_objects::ScopedTracker tracking_profile1(
484 FROM_HERE_WITH_EXPLICIT_FUNCTION(
485 "423948 ChromeNetworkDelegate::OnRawBytesRead1"));
487 TaskManager* task_manager = TaskManager::GetInstance();
489 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
490 tracked_objects::ScopedTracker tracking_profile2(
491 FROM_HERE_WITH_EXPLICIT_FUNCTION(
492 "423948 ChromeNetworkDelegate::OnRawBytesRead2"));
494 task_manager->model()->NotifyBytesRead(request, bytes_read);
496 #endif // defined(ENABLE_TASK_MANAGER)
499 void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request,
500 bool started) {
501 RecordNetworkErrorHistograms(request);
502 if (started) {
503 // Only call in for requests that were started, to obey the precondition
504 // that RecordCacheStateStats can only be called on requests for which
505 // OnResponseStarted was called.
506 RecordCacheStateStats(request);
509 if (request->status().status() == net::URLRequestStatus::SUCCESS) {
510 #if defined(OS_ANDROID)
511 // For better accuracy, we use the actual bytes read instead of the length
512 // specified with the Content-Length header, which may be inaccurate,
513 // or missing, as is the case with chunked encoding.
514 int64 received_content_length = request->received_response_content_length();
516 if (precache::PrecacheManager::IsPrecachingEnabled()) {
517 // Record precache metrics when a fetch is completed successfully, if
518 // precaching is enabled.
519 BrowserThread::PostTask(
520 BrowserThread::UI, FROM_HERE,
521 base::Bind(&RecordPrecacheStatsOnUIThread, request->url(),
522 base::Time::Now(), received_content_length,
523 request->was_cached(), profile_));
525 #endif // defined(OS_ANDROID)
526 extensions_delegate_->OnCompleted(request, started);
527 } else if (request->status().status() == net::URLRequestStatus::FAILED ||
528 request->status().status() == net::URLRequestStatus::CANCELED) {
529 extensions_delegate_->OnCompleted(request, started);
530 } else {
531 NOTREACHED();
533 if (domain_reliability_monitor_)
534 domain_reliability_monitor_->OnCompleted(request, started);
535 extensions_delegate_->ForwardProxyErrors(request);
536 extensions_delegate_->ForwardDoneRequestStatus(request);
539 void ChromeNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
540 extensions_delegate_->OnURLRequestDestroyed(request);
543 void ChromeNetworkDelegate::OnPACScriptError(int line_number,
544 const base::string16& error) {
545 extensions_delegate_->OnPACScriptError(line_number, error);
548 net::NetworkDelegate::AuthRequiredResponse
549 ChromeNetworkDelegate::OnAuthRequired(
550 net::URLRequest* request,
551 const net::AuthChallengeInfo& auth_info,
552 const AuthCallback& callback,
553 net::AuthCredentials* credentials) {
554 return extensions_delegate_->OnAuthRequired(
555 request, auth_info, callback, credentials);
558 bool ChromeNetworkDelegate::OnCanGetCookies(
559 const net::URLRequest& request,
560 const net::CookieList& cookie_list) {
561 // NULL during tests, or when we're running in the system context.
562 if (!cookie_settings_.get())
563 return true;
565 bool allow = cookie_settings_->IsReadingCookieAllowed(
566 request.url(), request.first_party_for_cookies());
568 int render_process_id = -1;
569 int render_frame_id = -1;
570 if (content::ResourceRequestInfo::GetRenderFrameForRequest(
571 &request, &render_process_id, &render_frame_id)) {
572 BrowserThread::PostTask(
573 BrowserThread::UI, FROM_HERE,
574 base::Bind(&TabSpecificContentSettings::CookiesRead,
575 render_process_id, render_frame_id,
576 request.url(), request.first_party_for_cookies(),
577 cookie_list, !allow));
580 return allow;
583 bool ChromeNetworkDelegate::OnCanSetCookie(const net::URLRequest& request,
584 const std::string& cookie_line,
585 net::CookieOptions* options) {
586 // NULL during tests, or when we're running in the system context.
587 if (!cookie_settings_.get())
588 return true;
590 bool allow = cookie_settings_->IsSettingCookieAllowed(
591 request.url(), request.first_party_for_cookies());
593 int render_process_id = -1;
594 int render_frame_id = -1;
595 if (content::ResourceRequestInfo::GetRenderFrameForRequest(
596 &request, &render_process_id, &render_frame_id)) {
597 BrowserThread::PostTask(
598 BrowserThread::UI, FROM_HERE,
599 base::Bind(&TabSpecificContentSettings::CookieChanged,
600 render_process_id, render_frame_id,
601 request.url(), request.first_party_for_cookies(),
602 cookie_line, *options, !allow));
605 return allow;
608 bool ChromeNetworkDelegate::OnCanAccessFile(const net::URLRequest& request,
609 const base::FilePath& path) const {
610 if (g_allow_file_access_)
611 return true;
613 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
614 return true;
615 #else
616 #if defined(OS_CHROMEOS)
617 // If we're running Chrome for ChromeOS on Linux, we want to allow file
618 // access.
619 if (!base::SysInfo::IsRunningOnChromeOS() ||
620 base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
621 return true;
624 // Use a whitelist to only allow access to files residing in the list of
625 // directories below.
626 static const char* const kLocalAccessWhiteList[] = {
627 "/home/chronos/user/Downloads",
628 "/home/chronos/user/log",
629 "/home/chronos/user/WebRTC Logs",
630 "/media",
631 "/opt/oem",
632 "/usr/share/chromeos-assets",
633 "/tmp",
634 "/var/log",
637 // The actual location of "/home/chronos/user/Xyz" is the Xyz directory under
638 // the profile path ("/home/chronos/user' is a hard link to current primary
639 // logged in profile.) For the support of multi-profile sessions, we are
640 // switching to use explicit "$PROFILE_PATH/Xyz" path and here whitelist such
641 // access.
642 if (!profile_path_.empty()) {
643 const base::FilePath downloads = profile_path_.AppendASCII("Downloads");
644 if (downloads == path.StripTrailingSeparators() || downloads.IsParent(path))
645 return true;
646 const base::FilePath webrtc_logs = profile_path_.AppendASCII("WebRTC Logs");
647 if (webrtc_logs == path.StripTrailingSeparators() ||
648 webrtc_logs.IsParent(path)) {
649 return true;
652 #elif defined(OS_ANDROID)
653 // Access to files in external storage is allowed.
654 base::FilePath external_storage_path;
655 PathService::Get(base::DIR_ANDROID_EXTERNAL_STORAGE, &external_storage_path);
656 if (external_storage_path.IsParent(path))
657 return true;
659 // Whitelist of other allowed directories.
660 static const char* const kLocalAccessWhiteList[] = {
661 "/sdcard",
662 "/mnt/sdcard",
664 #endif
666 for (size_t i = 0; i < arraysize(kLocalAccessWhiteList); ++i) {
667 const base::FilePath white_listed_path(kLocalAccessWhiteList[i]);
668 // base::FilePath::operator== should probably handle trailing separators.
669 if (white_listed_path == path.StripTrailingSeparators() ||
670 white_listed_path.IsParent(path)) {
671 return true;
675 DVLOG(1) << "File access denied - " << path.value().c_str();
676 return false;
677 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
680 bool ChromeNetworkDelegate::OnCanThrottleRequest(
681 const net::URLRequest& request) const {
682 #if defined(ENABLE_EXTENSIONS)
683 if (g_never_throttle_requests_)
684 return false;
685 return request.first_party_for_cookies().scheme() ==
686 extensions::kExtensionScheme;
687 #else
688 return false;
689 #endif
692 bool ChromeNetworkDelegate::OnCanEnablePrivacyMode(
693 const GURL& url,
694 const GURL& first_party_for_cookies) const {
695 // NULL during tests, or when we're running in the system context.
696 if (!cookie_settings_.get())
697 return false;
699 bool reading_cookie_allowed = cookie_settings_->IsReadingCookieAllowed(
700 url, first_party_for_cookies);
701 bool setting_cookie_allowed = cookie_settings_->IsSettingCookieAllowed(
702 url, first_party_for_cookies);
703 bool privacy_mode = !(reading_cookie_allowed && setting_cookie_allowed);
704 return privacy_mode;
707 bool ChromeNetworkDelegate::OnFirstPartyOnlyCookieExperimentEnabled() const {
708 return experimental_web_platform_features_enabled_;
711 bool ChromeNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
712 const net::URLRequest& request,
713 const GURL& target_url,
714 const GURL& referrer_url) const {
715 ReportInvalidReferrerSend(target_url, referrer_url);
716 return true;