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 "net/proxy/proxy_service.h"
10 #include "base/bind_helpers.h"
11 #include "base/compiler_specific.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/metrics/histogram_macros.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string_util.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/time/time.h"
20 #include "base/values.h"
21 #include "net/base/completion_callback.h"
22 #include "net/base/load_flags.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/log/net_log.h"
26 #include "net/proxy/dhcp_proxy_script_fetcher.h"
27 #include "net/proxy/multi_threaded_proxy_resolver.h"
28 #include "net/proxy/network_delegate_error_observer.h"
29 #include "net/proxy/proxy_config_service_fixed.h"
30 #include "net/proxy/proxy_resolver.h"
31 #include "net/proxy/proxy_resolver_factory.h"
32 #include "net/proxy/proxy_script_decider.h"
33 #include "net/proxy/proxy_script_fetcher.h"
34 #include "net/url_request/url_request_context.h"
38 #include "net/proxy/proxy_config_service_win.h"
39 #include "net/proxy/proxy_resolver_winhttp.h"
41 #include "net/proxy/proxy_config_service_ios.h"
42 #include "net/proxy/proxy_resolver_mac.h"
43 #elif defined(OS_MACOSX)
44 #include "net/proxy/proxy_config_service_mac.h"
45 #include "net/proxy/proxy_resolver_mac.h"
46 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
47 #include "net/proxy/proxy_config_service_linux.h"
48 #elif defined(OS_ANDROID)
49 #include "net/proxy/proxy_config_service_android.h"
52 using base::TimeDelta
;
53 using base::TimeTicks
;
59 // When the IP address changes we don't immediately re-run proxy auto-config.
60 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
61 // attempting to re-valuate proxy auto-config.
63 // During this time window, any resolve requests sent to the ProxyService will
64 // be queued. Once we have waited the required amount of them, the proxy
65 // auto-config step will be run, and the queued requests resumed.
67 // The reason we play this game is that our signal for detecting network
68 // changes (NetworkChangeNotifier) may fire *before* the system's networking
69 // dependencies are fully configured. This is a problem since it means if
70 // we were to run proxy auto-config right away, it could fail due to spurious
71 // DNS failures. (see http://crbug.com/50779 for more details.)
73 // By adding the wait window, we give things a better chance to get properly
74 // set up. Network failures can happen at any time though, so we additionally
75 // poll the PAC script for changes, which will allow us to recover from these
77 const int64 kDelayAfterNetworkChangesMs
= 2000;
79 // This is the default policy for polling the PAC script.
81 // In response to a failure, the poll intervals are:
82 // 0: 8 seconds (scheduled on timer)
87 // In response to a success, the poll intervals are:
90 // Only the 8 second poll is scheduled on a timer, the rest happen in response
91 // to network activity (and hence will take longer than the written time).
93 // Explanation for these values:
95 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
96 // using some histograms data. Trying to be conservative so as not to break
97 // existing setups when deployed. A simple exponential retry scheme would be
98 // more elegant, but places more load on server.
100 // The motivation for trying quickly after failures (8 seconds) is to recover
101 // from spurious network failures, which are common after the IP address has
102 // just changed (like DNS failing to resolve). The next 32 second boundary is
103 // to try and catch other VPN weirdness which anecdotally I have seen take
104 // 10+ seconds for some users.
106 // The motivation for re-trying after a success is to check for possible
107 // content changes to the script, or to the WPAD auto-discovery results. We are
108 // not very aggressive with these checks so as to minimize the risk of
109 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
110 // change very frequently in existing setups. More research is needed to
111 // motivate what safe values are here, and what other user agents do.
113 // Comparison to other browsers:
115 // In Firefox the PAC URL is re-tried on failures according to
116 // network.proxy.autoconfig_retry_interval_min and
117 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
118 // 5 minutes respectively. It doubles the interval at each attempt.
120 // TODO(eroman): Figure out what Internet Explorer does.
121 class DefaultPollPolicy
: public ProxyService::PacPollPolicy
{
123 DefaultPollPolicy() {}
125 Mode
GetNextDelay(int initial_error
,
126 TimeDelta current_delay
,
127 TimeDelta
* next_delay
) const override
{
128 if (initial_error
!= OK
) {
129 // Re-try policy for failures.
130 const int kDelay1Seconds
= 8;
131 const int kDelay2Seconds
= 32;
132 const int kDelay3Seconds
= 2 * 60; // 2 minutes
133 const int kDelay4Seconds
= 4 * 60 * 60; // 4 Hours
136 if (current_delay
< TimeDelta()) {
137 *next_delay
= TimeDelta::FromSeconds(kDelay1Seconds
);
138 return MODE_USE_TIMER
;
140 switch (current_delay
.InSeconds()) {
142 *next_delay
= TimeDelta::FromSeconds(kDelay2Seconds
);
143 return MODE_START_AFTER_ACTIVITY
;
145 *next_delay
= TimeDelta::FromSeconds(kDelay3Seconds
);
146 return MODE_START_AFTER_ACTIVITY
;
148 *next_delay
= TimeDelta::FromSeconds(kDelay4Seconds
);
149 return MODE_START_AFTER_ACTIVITY
;
152 // Re-try policy for succeses.
153 *next_delay
= TimeDelta::FromHours(12);
154 return MODE_START_AFTER_ACTIVITY
;
159 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy
);
162 // Config getter that always returns direct settings.
163 class ProxyConfigServiceDirect
: public ProxyConfigService
{
165 // ProxyConfigService implementation:
166 void AddObserver(Observer
* observer
) override
{}
167 void RemoveObserver(Observer
* observer
) override
{}
168 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
169 *config
= ProxyConfig::CreateDirect();
170 config
->set_source(PROXY_CONFIG_SOURCE_UNKNOWN
);
175 // Proxy resolver that fails every time.
176 class ProxyResolverNull
: public ProxyResolver
{
178 ProxyResolverNull() {}
180 // ProxyResolver implementation.
181 int GetProxyForURL(const GURL
& url
,
183 const CompletionCallback
& callback
,
184 RequestHandle
* request
,
185 const BoundNetLog
& net_log
) override
{
186 return ERR_NOT_IMPLEMENTED
;
189 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
191 LoadState
GetLoadState(RequestHandle request
) const override
{
193 return LOAD_STATE_IDLE
;
198 // ProxyResolver that simulates a PAC script which returns
199 // |pac_string| for every single URL.
200 class ProxyResolverFromPacString
: public ProxyResolver
{
202 explicit ProxyResolverFromPacString(const std::string
& pac_string
)
203 : pac_string_(pac_string
) {}
205 int GetProxyForURL(const GURL
& url
,
207 const CompletionCallback
& callback
,
208 RequestHandle
* request
,
209 const BoundNetLog
& net_log
) override
{
210 results
->UsePacString(pac_string_
);
214 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
216 LoadState
GetLoadState(RequestHandle request
) const override
{
218 return LOAD_STATE_IDLE
;
222 const std::string pac_string_
;
225 // Creates ProxyResolvers using a platform-specific implementation.
226 class ProxyResolverFactoryForSystem
: public MultiThreadedProxyResolverFactory
{
228 explicit ProxyResolverFactoryForSystem(size_t max_num_threads
)
229 : MultiThreadedProxyResolverFactory(max_num_threads
,
230 false /*expects_pac_bytes*/) {}
232 scoped_ptr
<ProxyResolverFactory
> CreateProxyResolverFactory() override
{
234 return make_scoped_ptr(new ProxyResolverFactoryWinHttp());
235 #elif defined(OS_MACOSX)
236 return make_scoped_ptr(new ProxyResolverFactoryMac());
243 static bool IsSupported() {
244 #if defined(OS_WIN) || defined(OS_MACOSX)
252 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForSystem
);
255 class ProxyResolverFactoryForNullResolver
: public ProxyResolverFactory
{
257 ProxyResolverFactoryForNullResolver() : ProxyResolverFactory(false) {}
259 // ProxyResolverFactory overrides.
260 int CreateProxyResolver(
261 const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
262 scoped_ptr
<ProxyResolver
>* resolver
,
263 const net::CompletionCallback
& callback
,
264 scoped_ptr
<Request
>* request
) override
{
265 resolver
->reset(new ProxyResolverNull());
270 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForNullResolver
);
273 class ProxyResolverFactoryForPacResult
: public ProxyResolverFactory
{
275 explicit ProxyResolverFactoryForPacResult(const std::string
& pac_string
)
276 : ProxyResolverFactory(false), pac_string_(pac_string
) {}
278 // ProxyResolverFactory override.
279 int CreateProxyResolver(
280 const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
281 scoped_ptr
<ProxyResolver
>* resolver
,
282 const net::CompletionCallback
& callback
,
283 scoped_ptr
<Request
>* request
) override
{
284 resolver
->reset(new ProxyResolverFromPacString(pac_string_
));
289 const std::string pac_string_
;
291 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForPacResult
);
294 // Returns NetLog parameters describing a proxy configuration change.
295 scoped_ptr
<base::Value
> NetLogProxyConfigChangedCallback(
296 const ProxyConfig
* old_config
,
297 const ProxyConfig
* new_config
,
298 NetLogCaptureMode
/* capture_mode */) {
299 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
300 // The "old_config" is optional -- the first notification will not have
301 // any "previous" configuration.
302 if (old_config
->is_valid())
303 dict
->Set("old_config", old_config
->ToValue());
304 dict
->Set("new_config", new_config
->ToValue());
308 scoped_ptr
<base::Value
> NetLogBadProxyListCallback(
309 const ProxyRetryInfoMap
* retry_info
,
310 NetLogCaptureMode
/* capture_mode */) {
311 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
312 base::ListValue
* list
= new base::ListValue();
314 for (ProxyRetryInfoMap::const_iterator iter
= retry_info
->begin();
315 iter
!= retry_info
->end(); ++iter
) {
316 list
->Append(new base::StringValue(iter
->first
));
318 dict
->Set("bad_proxy_list", list
);
322 // Returns NetLog parameters on a successfuly proxy resolution.
323 scoped_ptr
<base::Value
> NetLogFinishedResolvingProxyCallback(
324 const ProxyInfo
* result
,
325 NetLogCaptureMode
/* capture_mode */) {
326 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
327 dict
->SetString("pac_string", result
->ToPacString());
331 #if defined(OS_CHROMEOS)
332 class UnsetProxyConfigService
: public ProxyConfigService
{
334 UnsetProxyConfigService() {}
335 ~UnsetProxyConfigService() override
{}
337 void AddObserver(Observer
* observer
) override
{}
338 void RemoveObserver(Observer
* observer
) override
{}
339 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
347 // ProxyService::InitProxyResolver --------------------------------------------
349 // This glues together two asynchronous steps:
350 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
351 // to figure out what we should configure against.
352 // (2) Feed the fetched PAC script into the ProxyResolver.
354 // InitProxyResolver is a single-use class which encapsulates cancellation as
355 // part of its destructor. Start() or StartSkipDecider() should be called just
356 // once. The instance can be destroyed at any time, and the request will be
359 class ProxyService::InitProxyResolver
{
362 : proxy_resolver_factory_(nullptr),
363 proxy_resolver_(NULL
),
364 next_state_(STATE_NONE
),
365 quick_check_enabled_(true) {}
367 ~InitProxyResolver() {
368 // Note that the destruction of ProxyScriptDecider will automatically cancel
369 // any outstanding work.
372 // Begins initializing the proxy resolver; calls |callback| when done. A
373 // ProxyResolver instance will be created using |proxy_resolver_factory| and
374 // returned via |proxy_resolver| if the final result is OK.
375 int Start(scoped_ptr
<ProxyResolver
>* proxy_resolver
,
376 ProxyResolverFactory
* proxy_resolver_factory
,
377 ProxyScriptFetcher
* proxy_script_fetcher
,
378 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
380 const ProxyConfig
& config
,
381 TimeDelta wait_delay
,
382 const CompletionCallback
& callback
) {
383 DCHECK_EQ(STATE_NONE
, next_state_
);
384 proxy_resolver_
= proxy_resolver
;
385 proxy_resolver_factory_
= proxy_resolver_factory
;
387 decider_
.reset(new ProxyScriptDecider(
388 proxy_script_fetcher
, dhcp_proxy_script_fetcher
, net_log
));
389 decider_
->set_quick_check_enabled(quick_check_enabled_
);
391 wait_delay_
= wait_delay
;
392 callback_
= callback
;
394 next_state_
= STATE_DECIDE_PROXY_SCRIPT
;
398 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
399 // |effective_config|, |decider_result| and |script_data| will be used as the
400 // inputs for initializing the ProxyResolver. A ProxyResolver instance will
401 // be created using |proxy_resolver_factory| and returned via
402 // |proxy_resolver| if the final result is OK.
403 int StartSkipDecider(scoped_ptr
<ProxyResolver
>* proxy_resolver
,
404 ProxyResolverFactory
* proxy_resolver_factory
,
405 const ProxyConfig
& effective_config
,
407 ProxyResolverScriptData
* script_data
,
408 const CompletionCallback
& callback
) {
409 DCHECK_EQ(STATE_NONE
, next_state_
);
410 proxy_resolver_
= proxy_resolver
;
411 proxy_resolver_factory_
= proxy_resolver_factory
;
413 effective_config_
= effective_config
;
414 script_data_
= script_data
;
415 callback_
= callback
;
417 if (decider_result
!= OK
)
418 return decider_result
;
420 next_state_
= STATE_CREATE_RESOLVER
;
424 // Returns the proxy configuration that was selected by ProxyScriptDecider.
425 // Should only be called upon completion of the initialization.
426 const ProxyConfig
& effective_config() const {
427 DCHECK_EQ(STATE_NONE
, next_state_
);
428 return effective_config_
;
431 // Returns the PAC script data that was selected by ProxyScriptDecider.
432 // Should only be called upon completion of the initialization.
433 const scoped_refptr
<ProxyResolverScriptData
>& script_data() {
434 DCHECK_EQ(STATE_NONE
, next_state_
);
438 LoadState
GetLoadState() const {
439 if (next_state_
== STATE_DECIDE_PROXY_SCRIPT_COMPLETE
) {
440 // In addition to downloading, this state may also include the stall time
441 // after network change events (kDelayAfterNetworkChangesMs).
442 return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT
;
444 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
447 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
448 bool quick_check_enabled() const { return quick_check_enabled_
; }
453 STATE_DECIDE_PROXY_SCRIPT
,
454 STATE_DECIDE_PROXY_SCRIPT_COMPLETE
,
455 STATE_CREATE_RESOLVER
,
456 STATE_CREATE_RESOLVER_COMPLETE
,
459 int DoLoop(int result
) {
460 DCHECK_NE(next_state_
, STATE_NONE
);
463 State state
= next_state_
;
464 next_state_
= STATE_NONE
;
466 case STATE_DECIDE_PROXY_SCRIPT
:
468 rv
= DoDecideProxyScript();
470 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE
:
471 rv
= DoDecideProxyScriptComplete(rv
);
473 case STATE_CREATE_RESOLVER
:
475 rv
= DoCreateResolver();
477 case STATE_CREATE_RESOLVER_COMPLETE
:
478 rv
= DoCreateResolverComplete(rv
);
481 NOTREACHED() << "bad state: " << state
;
485 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
489 int DoDecideProxyScript() {
490 next_state_
= STATE_DECIDE_PROXY_SCRIPT_COMPLETE
;
492 return decider_
->Start(
493 config_
, wait_delay_
, proxy_resolver_factory_
->expects_pac_bytes(),
494 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
497 int DoDecideProxyScriptComplete(int result
) {
501 effective_config_
= decider_
->effective_config();
502 script_data_
= decider_
->script_data();
504 next_state_
= STATE_CREATE_RESOLVER
;
508 int DoCreateResolver() {
509 DCHECK(script_data_
.get());
510 // TODO(eroman): Should log this latency to the NetLog.
511 next_state_
= STATE_CREATE_RESOLVER_COMPLETE
;
512 return proxy_resolver_factory_
->CreateProxyResolver(
513 script_data_
, proxy_resolver_
,
514 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)),
515 &create_resolver_request_
);
518 int DoCreateResolverComplete(int result
) {
520 proxy_resolver_
->reset();
524 void OnIOCompletion(int result
) {
525 DCHECK_NE(STATE_NONE
, next_state_
);
526 int rv
= DoLoop(result
);
527 if (rv
!= ERR_IO_PENDING
)
531 void DoCallback(int result
) {
532 DCHECK_NE(ERR_IO_PENDING
, result
);
533 callback_
.Run(result
);
537 ProxyConfig effective_config_
;
538 scoped_refptr
<ProxyResolverScriptData
> script_data_
;
539 TimeDelta wait_delay_
;
540 scoped_ptr
<ProxyScriptDecider
> decider_
;
541 ProxyResolverFactory
* proxy_resolver_factory_
;
542 scoped_ptr
<ProxyResolverFactory::Request
> create_resolver_request_
;
543 scoped_ptr
<ProxyResolver
>* proxy_resolver_
;
544 CompletionCallback callback_
;
546 bool quick_check_enabled_
;
548 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver
);
551 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
553 // This helper class encapsulates the logic to schedule and run periodic
554 // background checks to see if the PAC script (or effective proxy configuration)
555 // has changed. If a change is detected, then the caller will be notified via
556 // the ChangeCallback.
557 class ProxyService::ProxyScriptDeciderPoller
{
559 typedef base::Callback
<void(int, ProxyResolverScriptData
*,
560 const ProxyConfig
&)> ChangeCallback
;
562 // Builds a poller helper, and starts polling for updates. Whenever a change
563 // is observed, |callback| will be invoked with the details.
565 // |config| specifies the (unresolved) proxy configuration to poll.
566 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
567 // to use the resulting script data with
568 // (so it can choose the right format).
569 // |proxy_script_fetcher| this pointer must remain alive throughout our
570 // lifetime. It is the dependency that will be used
571 // for downloading proxy scripts.
572 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
573 // the DHCP dependency.
574 // |init_net_error| This is the initial network error (possibly success)
575 // encountered by the first PAC fetch attempt. We use it
576 // to schedule updates more aggressively if the initial
577 // fetch resulted in an error.
578 // |init_script_data| the initial script data from the PAC fetch attempt.
579 // This is the baseline used to determine when the
580 // script's contents have changed.
581 // |net_log| the NetLog to log progress into.
582 ProxyScriptDeciderPoller(ChangeCallback callback
,
583 const ProxyConfig
& config
,
584 bool proxy_resolver_expects_pac_bytes
,
585 ProxyScriptFetcher
* proxy_script_fetcher
,
586 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
588 const scoped_refptr
<ProxyResolverScriptData
>&
591 : change_callback_(callback
),
593 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes
),
594 proxy_script_fetcher_(proxy_script_fetcher
),
595 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher
),
596 last_error_(init_net_error
),
597 last_script_data_(init_script_data
),
598 last_poll_time_(TimeTicks::Now()),
599 weak_factory_(this) {
600 // Set the initial poll delay.
601 next_poll_mode_
= poll_policy()->GetNextDelay(
602 last_error_
, TimeDelta::FromSeconds(-1), &next_poll_delay_
);
603 TryToStartNextPoll(false);
607 // We have just been notified of network activity. Use this opportunity to
608 // see if we can start our next poll.
609 TryToStartNextPoll(true);
612 static const PacPollPolicy
* set_policy(const PacPollPolicy
* policy
) {
613 const PacPollPolicy
* prev
= poll_policy_
;
614 poll_policy_
= policy
;
618 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
619 bool quick_check_enabled() const { return quick_check_enabled_
; }
622 // Returns the effective poll policy (the one injected by unit-tests, or the
624 const PacPollPolicy
* poll_policy() {
627 return &default_poll_policy_
;
630 void StartPollTimer() {
631 DCHECK(!decider_
.get());
633 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
634 FROM_HERE
, base::Bind(&ProxyScriptDeciderPoller::DoPoll
,
635 weak_factory_
.GetWeakPtr()),
639 void TryToStartNextPoll(bool triggered_by_activity
) {
640 switch (next_poll_mode_
) {
641 case PacPollPolicy::MODE_USE_TIMER
:
642 if (!triggered_by_activity
)
646 case PacPollPolicy::MODE_START_AFTER_ACTIVITY
:
647 if (triggered_by_activity
&& !decider_
.get()) {
648 TimeDelta elapsed_time
= TimeTicks::Now() - last_poll_time_
;
649 if (elapsed_time
>= next_poll_delay_
)
657 last_poll_time_
= TimeTicks::Now();
659 // Start the proxy script decider to see if anything has changed.
660 // TODO(eroman): Pass a proper NetLog rather than NULL.
661 decider_
.reset(new ProxyScriptDecider(
662 proxy_script_fetcher_
, dhcp_proxy_script_fetcher_
, NULL
));
663 decider_
->set_quick_check_enabled(quick_check_enabled_
);
664 int result
= decider_
->Start(
665 config_
, TimeDelta(), proxy_resolver_expects_pac_bytes_
,
666 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted
,
667 base::Unretained(this)));
669 if (result
!= ERR_IO_PENDING
)
670 OnProxyScriptDeciderCompleted(result
);
673 void OnProxyScriptDeciderCompleted(int result
) {
674 if (HasScriptDataChanged(result
, decider_
->script_data())) {
675 // Something has changed, we must notify the ProxyService so it can
676 // re-initialize its ProxyResolver. Note that we post a notification task
677 // rather than calling it directly -- this is done to avoid an ugly
678 // destruction sequence, since |this| might be destroyed as a result of
680 base::ThreadTaskRunnerHandle::Get()->PostTask(
682 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange
,
683 weak_factory_
.GetWeakPtr(), result
,
684 decider_
->script_data(),
685 decider_
->effective_config()));
691 // Decide when the next poll should take place, and possibly start the
693 next_poll_mode_
= poll_policy()->GetNextDelay(
694 last_error_
, next_poll_delay_
, &next_poll_delay_
);
695 TryToStartNextPoll(false);
698 bool HasScriptDataChanged(int result
,
699 const scoped_refptr
<ProxyResolverScriptData
>& script_data
) {
700 if (result
!= last_error_
) {
701 // Something changed -- it was failing before and now it succeeded, or
702 // conversely it succeeded before and now it failed. Or it failed in
703 // both cases, however the specific failure error codes differ.
708 // If it failed last time and failed again with the same error code this
709 // time, then nothing has actually changed.
713 // Otherwise if it succeeded both this time and last time, we need to look
714 // closer and see if we ended up downloading different content for the PAC
716 return !script_data
->Equals(last_script_data_
.get());
719 void NotifyProxyServiceOfChange(
721 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
722 const ProxyConfig
& effective_config
) {
723 // Note that |this| may be deleted after calling into the ProxyService.
724 change_callback_
.Run(result
, script_data
.get(), effective_config
);
727 ChangeCallback change_callback_
;
729 bool proxy_resolver_expects_pac_bytes_
;
730 ProxyScriptFetcher
* proxy_script_fetcher_
;
731 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher_
;
734 scoped_refptr
<ProxyResolverScriptData
> last_script_data_
;
736 scoped_ptr
<ProxyScriptDecider
> decider_
;
737 TimeDelta next_poll_delay_
;
738 PacPollPolicy::Mode next_poll_mode_
;
740 TimeTicks last_poll_time_
;
742 // Polling policy injected by unit-tests. Otherwise this is NULL and the
743 // default policy will be used.
744 static const PacPollPolicy
* poll_policy_
;
746 const DefaultPollPolicy default_poll_policy_
;
748 bool quick_check_enabled_
;
750 base::WeakPtrFactory
<ProxyScriptDeciderPoller
> weak_factory_
;
752 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller
);
756 const ProxyService::PacPollPolicy
*
757 ProxyService::ProxyScriptDeciderPoller::poll_policy_
= NULL
;
759 // ProxyService::PacRequest ---------------------------------------------------
761 class ProxyService::PacRequest
762 : public base::RefCounted
<ProxyService::PacRequest
> {
764 PacRequest(ProxyService
* service
,
767 NetworkDelegate
* network_delegate
,
769 const CompletionCallback
& user_callback
,
770 const BoundNetLog
& net_log
)
772 user_callback_(user_callback
),
775 load_flags_(load_flags
),
776 network_delegate_(network_delegate
),
778 config_id_(ProxyConfig::kInvalidConfigID
),
779 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN
),
781 creation_time_(TimeTicks::Now()) {
782 DCHECK(!user_callback
.is_null());
785 // Starts the resolve proxy request.
787 DCHECK(!was_cancelled());
788 DCHECK(!is_started());
790 DCHECK(service_
->config_
.is_valid());
792 config_id_
= service_
->config_
.id();
793 config_source_
= service_
->config_
.source();
795 return resolver()->GetProxyForURL(
797 base::Bind(&PacRequest::QueryComplete
, base::Unretained(this)),
798 &resolve_job_
, net_log_
);
801 bool is_started() const {
802 // Note that !! casts to bool. (VS gives a warning otherwise).
803 return !!resolve_job_
;
806 void StartAndCompleteCheckingForSynchronous() {
807 int rv
= service_
->TryToCompleteSynchronously(url_
, load_flags_
,
808 network_delegate_
, results_
);
809 if (rv
== ERR_IO_PENDING
)
811 if (rv
!= ERR_IO_PENDING
)
815 void CancelResolveJob() {
816 DCHECK(is_started());
817 // The request may already be running in the resolver.
818 resolver()->CancelRequest(resolve_job_
);
820 DCHECK(!is_started());
824 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
829 // Mark as cancelled, to prevent accessing this again later.
831 user_callback_
.Reset();
834 net_log_
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
837 // Returns true if Cancel() has been called.
838 bool was_cancelled() const {
839 return user_callback_
.is_null();
842 // Helper to call after ProxyResolver completion (both synchronous and
843 // asynchronous). Fixes up the result that is to be returned to user.
844 int QueryDidComplete(int result_code
) {
845 DCHECK(!was_cancelled());
847 // This state is cleared when resolve_job_ is set to nullptr below.
848 bool script_executed
= is_started();
850 // Clear |resolve_job_| so is_started() returns false while
851 // DidFinishResolvingProxy() runs.
852 resolve_job_
= nullptr;
854 // Note that DidFinishResolvingProxy might modify |results_|.
855 int rv
= service_
->DidFinishResolvingProxy(
856 url_
, load_flags_
, network_delegate_
, results_
, result_code
, net_log_
,
857 creation_time_
, script_executed
);
859 // Make a note in the results which configuration was in use at the
860 // time of the resolve.
861 results_
->config_id_
= config_id_
;
862 results_
->config_source_
= config_source_
;
863 results_
->did_use_pac_script_
= true;
864 results_
->proxy_resolve_start_time_
= creation_time_
;
865 results_
->proxy_resolve_end_time_
= TimeTicks::Now();
867 // Reset the state associated with in-progress-resolve.
868 config_id_
= ProxyConfig::kInvalidConfigID
;
869 config_source_
= PROXY_CONFIG_SOURCE_UNKNOWN
;
874 BoundNetLog
* net_log() { return &net_log_
; }
876 LoadState
GetLoadState() const {
878 return resolver()->GetLoadState(resolve_job_
);
879 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
883 friend class base::RefCounted
<ProxyService::PacRequest
>;
887 // Callback for when the ProxyResolver request has completed.
888 void QueryComplete(int result_code
) {
889 result_code
= QueryDidComplete(result_code
);
891 // Remove this completed PacRequest from the service's pending list.
892 /// (which will probably cause deletion of |this|).
893 if (!user_callback_
.is_null()) {
894 CompletionCallback callback
= user_callback_
;
895 service_
->RemovePendingRequest(this);
896 callback
.Run(result_code
);
900 ProxyResolver
* resolver() const { return service_
->resolver_
.get(); }
902 // Note that we don't hold a reference to the ProxyService. Outstanding
903 // requests are cancelled during ~ProxyService, so this is guaranteed
904 // to be valid throughout our lifetime.
905 ProxyService
* service_
;
906 CompletionCallback user_callback_
;
910 NetworkDelegate
* network_delegate_
;
911 ProxyResolver::RequestHandle resolve_job_
;
912 ProxyConfig::ID config_id_
; // The config id when the resolve was started.
913 ProxyConfigSource config_source_
; // The source of proxy settings.
914 BoundNetLog net_log_
;
915 // Time when the request was created. Stored here rather than in |results_|
916 // because the time in |results_| will be cleared.
917 TimeTicks creation_time_
;
920 // ProxyService ---------------------------------------------------------------
922 ProxyService::ProxyService(ProxyConfigService
* config_service
,
923 scoped_ptr
<ProxyResolverFactory
> resolver_factory
,
925 : resolver_factory_(resolver_factory
.Pass()),
927 current_state_(STATE_NONE
),
929 stall_proxy_auto_config_delay_(
930 TimeDelta::FromMilliseconds(kDelayAfterNetworkChangesMs
)),
931 quick_check_enabled_(true) {
932 NetworkChangeNotifier::AddIPAddressObserver(this);
933 NetworkChangeNotifier::AddDNSObserver(this);
934 ResetConfigService(config_service
);
938 ProxyService
* ProxyService::CreateUsingSystemProxyResolver(
939 ProxyConfigService
* proxy_config_service
,
940 size_t num_pac_threads
,
942 DCHECK(proxy_config_service
);
944 if (!ProxyResolverFactoryForSystem::IsSupported()) {
945 VLOG(1) << "PAC support disabled because there is no system implementation";
946 return CreateWithoutProxyResolver(proxy_config_service
, net_log
);
949 if (num_pac_threads
== 0)
950 num_pac_threads
= kDefaultNumPacThreads
;
952 return new ProxyService(
953 proxy_config_service
,
954 make_scoped_ptr(new ProxyResolverFactoryForSystem(num_pac_threads
)),
959 ProxyService
* ProxyService::CreateWithoutProxyResolver(
960 ProxyConfigService
* proxy_config_service
,
962 return new ProxyService(
963 proxy_config_service
,
964 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
968 ProxyService
* ProxyService::CreateFixed(const ProxyConfig
& pc
) {
969 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
971 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc
),
976 ProxyService
* ProxyService::CreateFixed(const std::string
& proxy
) {
977 ProxyConfig proxy_config
;
978 proxy_config
.proxy_rules().ParseFromString(proxy
);
979 return ProxyService::CreateFixed(proxy_config
);
983 ProxyService
* ProxyService::CreateDirect() {
984 return CreateDirectWithNetLog(NULL
);
987 ProxyService
* ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
988 // Use direct connections.
989 return new ProxyService(
990 new ProxyConfigServiceDirect
,
991 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
995 ProxyService
* ProxyService::CreateFixedFromPacResult(
996 const std::string
& pac_string
) {
998 // We need the settings to contain an "automatic" setting, otherwise the
999 // ProxyResolver dependency we give it will never be used.
1000 scoped_ptr
<ProxyConfigService
> proxy_config_service(
1001 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
1003 return new ProxyService(
1004 proxy_config_service
.release(),
1005 make_scoped_ptr(new ProxyResolverFactoryForPacResult(pac_string
)), NULL
);
1008 int ProxyService::ResolveProxy(const GURL
& raw_url
,
1011 const CompletionCallback
& callback
,
1012 PacRequest
** pac_request
,
1013 NetworkDelegate
* network_delegate
,
1014 const BoundNetLog
& net_log
) {
1015 DCHECK(!callback
.is_null());
1016 return ResolveProxyHelper(raw_url
,
1025 int ProxyService::ResolveProxyHelper(const GURL
& raw_url
,
1028 const CompletionCallback
& callback
,
1029 PacRequest
** pac_request
,
1030 NetworkDelegate
* network_delegate
,
1031 const BoundNetLog
& net_log
) {
1032 DCHECK(CalledOnValidThread());
1034 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
1036 // Notify our polling-based dependencies that a resolve is taking place.
1037 // This way they can schedule their polls in response to network activity.
1038 config_service_
->OnLazyPoll();
1039 if (script_poller_
.get())
1040 script_poller_
->OnLazyPoll();
1042 if (current_state_
== STATE_NONE
)
1043 ApplyProxyConfigIfAvailable();
1045 // Strip away any reference fragments and the username/password, as they
1046 // are not relevant to proxy resolution.
1047 GURL url
= SimplifyUrlForRequest(raw_url
);
1049 // Check if the request can be completed right away. (This is the case when
1050 // using a direct connection for example).
1051 int rv
= TryToCompleteSynchronously(url
, load_flags
,
1052 network_delegate
, result
);
1053 if (rv
!= ERR_IO_PENDING
) {
1054 rv
= DidFinishResolvingProxy(
1055 url
, load_flags
, network_delegate
, result
, rv
, net_log
,
1056 callback
.is_null() ? TimeTicks() : TimeTicks::Now(), false);
1060 if (callback
.is_null())
1061 return ERR_IO_PENDING
;
1063 scoped_refptr
<PacRequest
> req(
1064 new PacRequest(this, url
, load_flags
, network_delegate
,
1065 result
, callback
, net_log
));
1067 if (current_state_
== STATE_READY
) {
1068 // Start the resolve request.
1070 if (rv
!= ERR_IO_PENDING
)
1071 return req
->QueryDidComplete(rv
);
1073 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1076 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1077 DCHECK(!ContainsPendingRequest(req
.get()));
1078 pending_requests_
.insert(req
);
1080 // Completion will be notified through |callback|, unless the caller cancels
1081 // the request using |pac_request|.
1083 *pac_request
= req
.get();
1084 return rv
; // ERR_IO_PENDING
1087 bool ProxyService:: TryResolveProxySynchronously(
1088 const GURL
& raw_url
,
1091 NetworkDelegate
* network_delegate
,
1092 const BoundNetLog
& net_log
) {
1093 CompletionCallback null_callback
;
1094 return ResolveProxyHelper(raw_url
,
1098 NULL
/* pac_request*/,
1103 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1105 NetworkDelegate
* network_delegate
,
1106 ProxyInfo
* result
) {
1107 DCHECK_NE(STATE_NONE
, current_state_
);
1109 if (current_state_
!= STATE_READY
)
1110 return ERR_IO_PENDING
; // Still initializing.
1112 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1114 // If it was impossible to fetch or parse the PAC script, we cannot complete
1115 // the request here and bail out.
1116 if (permanent_error_
!= OK
)
1117 return permanent_error_
;
1119 if (config_
.HasAutomaticSettings())
1120 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1122 // Use the manual proxy settings.
1123 config_
.proxy_rules().Apply(url
, result
);
1124 result
->config_source_
= config_
.source();
1125 result
->config_id_
= config_
.id();
1130 ProxyService::~ProxyService() {
1131 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1132 NetworkChangeNotifier::RemoveDNSObserver(this);
1133 config_service_
->RemoveObserver(this);
1135 // Cancel any inprogress requests.
1136 for (PendingRequests::iterator it
= pending_requests_
.begin();
1137 it
!= pending_requests_
.end();
1143 void ProxyService::SuspendAllPendingRequests() {
1144 for (PendingRequests::iterator it
= pending_requests_
.begin();
1145 it
!= pending_requests_
.end();
1147 PacRequest
* req
= it
->get();
1148 if (req
->is_started()) {
1149 req
->CancelResolveJob();
1151 req
->net_log()->BeginEvent(
1152 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1157 void ProxyService::SetReady() {
1158 DCHECK(!init_proxy_resolver_
.get());
1159 current_state_
= STATE_READY
;
1161 // Make a copy in case |this| is deleted during the synchronous completion
1162 // of one of the requests. If |this| is deleted then all of the PacRequest
1163 // instances will be Cancel()-ed.
1164 PendingRequests pending_copy
= pending_requests_
;
1166 for (PendingRequests::iterator it
= pending_copy
.begin();
1167 it
!= pending_copy
.end();
1169 PacRequest
* req
= it
->get();
1170 if (!req
->is_started() && !req
->was_cancelled()) {
1171 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1173 // Note that we re-check for synchronous completion, in case we are
1174 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1175 req
->StartAndCompleteCheckingForSynchronous();
1180 void ProxyService::ApplyProxyConfigIfAvailable() {
1181 DCHECK_EQ(STATE_NONE
, current_state_
);
1183 config_service_
->OnLazyPoll();
1185 // If we have already fetched the configuration, start applying it.
1186 if (fetched_config_
.is_valid()) {
1187 InitializeUsingLastFetchedConfig();
1191 // Otherwise we need to first fetch the configuration.
1192 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1194 // Retrieve the current proxy configuration from the ProxyConfigService.
1195 // If a configuration is not available yet, we will get called back later
1196 // by our ProxyConfigService::Observer once it changes.
1198 ProxyConfigService::ConfigAvailability availability
=
1199 config_service_
->GetLatestProxyConfig(&config
);
1200 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1201 OnProxyConfigChanged(config
, availability
);
1204 void ProxyService::OnInitProxyResolverComplete(int result
) {
1205 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1206 DCHECK(init_proxy_resolver_
.get());
1207 DCHECK(fetched_config_
.HasAutomaticSettings());
1208 config_
= init_proxy_resolver_
->effective_config();
1210 // At this point we have decided which proxy settings to use (i.e. which PAC
1211 // script if any). We start up a background poller to periodically revisit
1212 // this decision. If the contents of the PAC script change, or if the
1213 // result of proxy auto-discovery changes, this poller will notice it and
1214 // will trigger a re-initialization using the newly discovered PAC.
1215 script_poller_
.reset(new ProxyScriptDeciderPoller(
1216 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1217 base::Unretained(this)),
1218 fetched_config_
, resolver_factory_
->expects_pac_bytes(),
1219 proxy_script_fetcher_
.get(), dhcp_proxy_script_fetcher_
.get(), result
,
1220 init_proxy_resolver_
->script_data(), NULL
));
1221 script_poller_
->set_quick_check_enabled(quick_check_enabled_
);
1223 init_proxy_resolver_
.reset();
1225 // When using the out-of-process resolver, creating the resolver can complete
1226 // with the ERR_PAC_SCRIPT_TERMINATED result code, which indicates the
1227 // resolver process crashed.
1228 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminatedOnInit",
1229 result
== ERR_PAC_SCRIPT_TERMINATED
);
1232 if (fetched_config_
.pac_mandatory()) {
1233 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1235 config_
= fetched_config_
;
1236 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1238 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1240 config_
= fetched_config_
;
1241 config_
.ClearAutomaticSettings();
1245 permanent_error_
= result
;
1247 // TODO(eroman): Make this ID unique in the case where configuration changed
1248 // due to ProxyScriptDeciderPoller.
1249 config_
.set_id(fetched_config_
.id());
1250 config_
.set_source(fetched_config_
.source());
1252 // Resume any requests which we had to defer until the PAC script was
1257 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1261 const CompletionCallback
& callback
,
1262 PacRequest
** pac_request
,
1263 NetworkDelegate
* network_delegate
,
1264 const BoundNetLog
& net_log
) {
1265 DCHECK(CalledOnValidThread());
1267 // Check to see if we have a new config since ResolveProxy was called. We
1268 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1269 // direct connection failed and we never tried the current config.
1272 bool re_resolve
= result
->config_id_
!= config_
.id();
1275 // If we have a new config or the config was never tried, we delete the
1276 // list of bad proxies and we try again.
1277 proxy_retry_info_
.clear();
1278 return ResolveProxy(url
, load_flags
, result
, callback
, pac_request
,
1279 network_delegate
, net_log
);
1282 DCHECK(!result
->is_empty());
1283 ProxyServer bad_proxy
= result
->proxy_server();
1285 // We don't have new proxy settings to try, try to fallback to the next proxy
1287 bool did_fallback
= result
->Fallback(net_error
, net_log
);
1289 // Return synchronous failure if there is nothing left to fall-back to.
1290 // TODO(eroman): This is a yucky API, clean it up.
1291 return did_fallback
? OK
: ERR_FAILED
;
1294 bool ProxyService::MarkProxiesAsBadUntil(
1295 const ProxyInfo
& result
,
1296 base::TimeDelta retry_delay
,
1297 const std::vector
<ProxyServer
>& additional_bad_proxies
,
1298 const BoundNetLog
& net_log
) {
1299 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
, retry_delay
,
1300 false, additional_bad_proxies
,
1302 return result
.proxy_list_
.size() > (additional_bad_proxies
.size() + 1);
1305 void ProxyService::ReportSuccess(const ProxyInfo
& result
,
1306 NetworkDelegate
* network_delegate
) {
1307 DCHECK(CalledOnValidThread());
1309 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1310 if (new_retry_info
.empty())
1313 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1314 iter
!= new_retry_info
.end(); ++iter
) {
1315 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1316 if (existing
== proxy_retry_info_
.end()) {
1317 proxy_retry_info_
[iter
->first
] = iter
->second
;
1318 if (network_delegate
) {
1319 const ProxyServer
& bad_proxy
=
1320 ProxyServer::FromURI(iter
->first
, ProxyServer::SCHEME_HTTP
);
1321 const ProxyRetryInfo
& proxy_retry_info
= iter
->second
;
1322 network_delegate
->NotifyProxyFallback(bad_proxy
,
1323 proxy_retry_info
.net_error
);
1326 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1327 existing
->second
.bad_until
= iter
->second
.bad_until
;
1330 net_log_
->AddGlobalEntry(
1331 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1332 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1336 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1337 DCHECK(CalledOnValidThread());
1340 RemovePendingRequest(req
);
1343 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1345 if (current_state_
== STATE_WAITING_FOR_INIT_PROXY_RESOLVER
)
1346 return init_proxy_resolver_
->GetLoadState();
1347 return req
->GetLoadState();
1350 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1351 return pending_requests_
.count(req
) == 1;
1354 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1355 DCHECK(ContainsPendingRequest(req
));
1356 pending_requests_
.erase(req
);
1359 int ProxyService::DidFinishResolvingProxy(const GURL
& url
,
1361 NetworkDelegate
* network_delegate
,
1364 const BoundNetLog
& net_log
,
1365 base::TimeTicks start_time
,
1366 bool script_executed
) {
1367 // Don't track any metrics if start_time is 0, which will happen when the user
1368 // calls |TryResolveProxySynchronously|.
1369 if (!start_time
.is_null()) {
1370 TimeDelta diff
= TimeTicks::Now() - start_time
;
1371 if (script_executed
) {
1372 // This function "fixes" the result code, so make sure script terminated
1373 // errors are tracked. Only track result codes that were a result of
1374 // script execution.
1375 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminated",
1376 result_code
== ERR_PAC_SCRIPT_TERMINATED
);
1377 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.GetProxyUsingScriptTime",
1378 diff
, base::TimeDelta::FromMicroseconds(100),
1379 base::TimeDelta::FromSeconds(20), 50);
1381 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ResolvedUsingScript",
1383 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.ResolveProxyTime", diff
,
1384 base::TimeDelta::FromMicroseconds(100),
1385 base::TimeDelta::FromSeconds(20), 50);
1388 // Log the result of the proxy resolution.
1389 if (result_code
== OK
) {
1390 // Allow the network delegate to interpose on the resolution decision,
1391 // possibly modifying the ProxyInfo.
1392 if (network_delegate
)
1393 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1395 // When logging all events is enabled, dump the proxy list.
1396 if (net_log
.IsCapturing()) {
1398 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1399 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1401 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1403 net_log
.AddEventWithNetErrorCode(
1404 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1406 bool reset_config
= result_code
== ERR_PAC_SCRIPT_TERMINATED
;
1407 if (!config_
.pac_mandatory()) {
1408 // Fall-back to direct when the proxy resolver fails. This corresponds
1409 // with a javascript runtime error in the PAC script.
1411 // This implicit fall-back to direct matches Firefox 3.5 and
1412 // Internet Explorer 8. For more information, see:
1414 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1415 result
->UseDirect();
1418 // Allow the network delegate to interpose on the resolution decision,
1419 // possibly modifying the ProxyInfo.
1420 if (network_delegate
)
1421 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1423 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1426 ResetProxyConfig(false);
1427 // If the ProxyResolver crashed, force it to be re-initialized for the
1428 // next request by resetting the proxy config. If there are other pending
1429 // requests, trigger the recreation immediately so those requests retry.
1430 if (pending_requests_
.size() > 1)
1431 ApplyProxyConfigIfAvailable();
1435 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1439 void ProxyService::SetProxyScriptFetchers(
1440 ProxyScriptFetcher
* proxy_script_fetcher
,
1441 scoped_ptr
<DhcpProxyScriptFetcher
> dhcp_proxy_script_fetcher
) {
1442 DCHECK(CalledOnValidThread());
1443 State previous_state
= ResetProxyConfig(false);
1444 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1445 dhcp_proxy_script_fetcher_
= dhcp_proxy_script_fetcher
.Pass();
1446 if (previous_state
!= STATE_NONE
)
1447 ApplyProxyConfigIfAvailable();
1450 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1451 DCHECK(CalledOnValidThread());
1452 return proxy_script_fetcher_
.get();
1455 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1456 DCHECK(CalledOnValidThread());
1457 State previous_state
= current_state_
;
1459 permanent_error_
= OK
;
1460 proxy_retry_info_
.clear();
1461 script_poller_
.reset();
1462 init_proxy_resolver_
.reset();
1463 SuspendAllPendingRequests();
1465 config_
= ProxyConfig();
1466 if (reset_fetched_config
)
1467 fetched_config_
= ProxyConfig();
1468 current_state_
= STATE_NONE
;
1470 return previous_state
;
1473 void ProxyService::ResetConfigService(
1474 ProxyConfigService
* new_proxy_config_service
) {
1475 DCHECK(CalledOnValidThread());
1476 State previous_state
= ResetProxyConfig(true);
1478 // Release the old configuration service.
1479 if (config_service_
.get())
1480 config_service_
->RemoveObserver(this);
1482 // Set the new configuration service.
1483 config_service_
.reset(new_proxy_config_service
);
1484 config_service_
->AddObserver(this);
1486 if (previous_state
!= STATE_NONE
)
1487 ApplyProxyConfigIfAvailable();
1490 void ProxyService::ForceReloadProxyConfig() {
1491 DCHECK(CalledOnValidThread());
1492 ResetProxyConfig(false);
1493 ApplyProxyConfigIfAvailable();
1497 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1498 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
1499 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_task_runner
) {
1501 return new ProxyConfigServiceWin();
1502 #elif defined(OS_IOS)
1503 return new ProxyConfigServiceIOS();
1504 #elif defined(OS_MACOSX)
1505 return new ProxyConfigServiceMac(io_task_runner
);
1506 #elif defined(OS_CHROMEOS)
1507 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1508 << "profile_io_data.cc::CreateProxyConfigService and this should "
1509 << "be used only for examples.";
1510 return new UnsetProxyConfigService
;
1511 #elif defined(OS_LINUX)
1512 ProxyConfigServiceLinux
* linux_config_service
=
1513 new ProxyConfigServiceLinux();
1515 // Assume we got called on the thread that runs the default glib
1516 // main loop, so the current thread is where we should be running
1517 // gconf calls from.
1518 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1519 base::ThreadTaskRunnerHandle::Get();
1521 // Synchronously fetch the current proxy config (since we are running on
1522 // glib_default_loop). Additionally register for notifications (delivered in
1523 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1524 // the proxy config changes.
1525 linux_config_service
->SetupAndFetchInitialConfig(
1526 glib_thread_task_runner
, io_task_runner
, file_task_runner
);
1528 return linux_config_service
;
1529 #elif defined(OS_ANDROID)
1530 return new ProxyConfigServiceAndroid(io_task_runner
,
1531 base::ThreadTaskRunnerHandle::Get());
1533 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1534 "for this platform.";
1535 return new ProxyConfigServiceDirect();
1540 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1541 const PacPollPolicy
* policy
) {
1542 return ProxyScriptDeciderPoller::set_policy(policy
);
1546 scoped_ptr
<ProxyService::PacPollPolicy
>
1547 ProxyService::CreateDefaultPacPollPolicy() {
1548 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1551 void ProxyService::OnProxyConfigChanged(
1552 const ProxyConfig
& config
,
1553 ProxyConfigService::ConfigAvailability availability
) {
1554 // Retrieve the current proxy configuration from the ProxyConfigService.
1555 // If a configuration is not available yet, we will get called back later
1556 // by our ProxyConfigService::Observer once it changes.
1557 ProxyConfig effective_config
;
1558 switch (availability
) {
1559 case ProxyConfigService::CONFIG_PENDING
:
1560 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1561 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1563 case ProxyConfigService::CONFIG_VALID
:
1564 effective_config
= config
;
1566 case ProxyConfigService::CONFIG_UNSET
:
1567 effective_config
= ProxyConfig::CreateDirect();
1571 // Emit the proxy settings change to the NetLog stream.
1573 net_log_
->AddGlobalEntry(NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1574 base::Bind(&NetLogProxyConfigChangedCallback
,
1575 &fetched_config_
, &effective_config
));
1578 // Set the new configuration as the most recently fetched one.
1579 fetched_config_
= effective_config
;
1580 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1582 InitializeUsingLastFetchedConfig();
1585 void ProxyService::InitializeUsingLastFetchedConfig() {
1586 ResetProxyConfig(false);
1588 DCHECK(fetched_config_
.is_valid());
1590 // Increment the ID to reflect that the config has changed.
1591 fetched_config_
.set_id(next_config_id_
++);
1593 if (!fetched_config_
.HasAutomaticSettings()) {
1594 config_
= fetched_config_
;
1599 // Start downloading + testing the PAC scripts for this new configuration.
1600 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1602 // If we changed networks recently, we should delay running proxy auto-config.
1603 TimeDelta wait_delay
=
1604 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1606 init_proxy_resolver_
.reset(new InitProxyResolver());
1607 init_proxy_resolver_
->set_quick_check_enabled(quick_check_enabled_
);
1608 int rv
= init_proxy_resolver_
->Start(
1609 &resolver_
, resolver_factory_
.get(), proxy_script_fetcher_
.get(),
1610 dhcp_proxy_script_fetcher_
.get(), net_log_
, fetched_config_
, wait_delay
,
1611 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1612 base::Unretained(this)));
1614 if (rv
!= ERR_IO_PENDING
)
1615 OnInitProxyResolverComplete(rv
);
1618 void ProxyService::InitializeUsingDecidedConfig(
1620 ProxyResolverScriptData
* script_data
,
1621 const ProxyConfig
& effective_config
) {
1622 DCHECK(fetched_config_
.is_valid());
1623 DCHECK(fetched_config_
.HasAutomaticSettings());
1625 ResetProxyConfig(false);
1627 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1629 init_proxy_resolver_
.reset(new InitProxyResolver());
1630 int rv
= init_proxy_resolver_
->StartSkipDecider(
1631 &resolver_
, resolver_factory_
.get(), effective_config
, decider_result
,
1632 script_data
, base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1633 base::Unretained(this)));
1635 if (rv
!= ERR_IO_PENDING
)
1636 OnInitProxyResolverComplete(rv
);
1639 void ProxyService::OnIPAddressChanged() {
1640 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1641 stall_proxy_autoconfig_until_
=
1642 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1644 State previous_state
= ResetProxyConfig(false);
1645 if (previous_state
!= STATE_NONE
)
1646 ApplyProxyConfigIfAvailable();
1649 void ProxyService::OnDNSChanged() {
1650 OnIPAddressChanged();