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 scoped_ptr
<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 make_scoped_ptr(new ProxyService(
953 proxy_config_service
,
954 make_scoped_ptr(new ProxyResolverFactoryForSystem(num_pac_threads
)),
959 scoped_ptr
<ProxyService
> ProxyService::CreateWithoutProxyResolver(
960 ProxyConfigService
* proxy_config_service
,
962 return make_scoped_ptr(new ProxyService(
963 proxy_config_service
,
964 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
));
968 scoped_ptr
<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 scoped_ptr
<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 scoped_ptr
<ProxyService
> ProxyService::CreateDirect() {
984 return CreateDirectWithNetLog(NULL
);
987 scoped_ptr
<ProxyService
> ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
988 // Use direct connections.
989 return make_scoped_ptr(new ProxyService(
990 new ProxyConfigServiceDirect
,
991 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
));
995 scoped_ptr
<ProxyService
> ProxyService::CreateFixedFromPacResult(
996 const std::string
& pac_string
) {
997 // We need the settings to contain an "automatic" setting, otherwise the
998 // ProxyResolver dependency we give it will never be used.
999 scoped_ptr
<ProxyConfigService
> proxy_config_service(
1000 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
1002 return make_scoped_ptr(new ProxyService(
1003 proxy_config_service
.release(),
1004 make_scoped_ptr(new ProxyResolverFactoryForPacResult(pac_string
)), NULL
));
1007 int ProxyService::ResolveProxy(const GURL
& raw_url
,
1010 const CompletionCallback
& callback
,
1011 PacRequest
** pac_request
,
1012 NetworkDelegate
* network_delegate
,
1013 const BoundNetLog
& net_log
) {
1014 DCHECK(!callback
.is_null());
1015 return ResolveProxyHelper(raw_url
,
1024 int ProxyService::ResolveProxyHelper(const GURL
& raw_url
,
1027 const CompletionCallback
& callback
,
1028 PacRequest
** pac_request
,
1029 NetworkDelegate
* network_delegate
,
1030 const BoundNetLog
& net_log
) {
1031 DCHECK(CalledOnValidThread());
1033 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
1035 // Notify our polling-based dependencies that a resolve is taking place.
1036 // This way they can schedule their polls in response to network activity.
1037 config_service_
->OnLazyPoll();
1038 if (script_poller_
.get())
1039 script_poller_
->OnLazyPoll();
1041 if (current_state_
== STATE_NONE
)
1042 ApplyProxyConfigIfAvailable();
1044 // Strip away any reference fragments and the username/password, as they
1045 // are not relevant to proxy resolution.
1046 GURL url
= SimplifyUrlForRequest(raw_url
);
1048 // Check if the request can be completed right away. (This is the case when
1049 // using a direct connection for example).
1050 int rv
= TryToCompleteSynchronously(url
, load_flags
,
1051 network_delegate
, result
);
1052 if (rv
!= ERR_IO_PENDING
) {
1053 rv
= DidFinishResolvingProxy(
1054 url
, load_flags
, network_delegate
, result
, rv
, net_log
,
1055 callback
.is_null() ? TimeTicks() : TimeTicks::Now(), false);
1059 if (callback
.is_null())
1060 return ERR_IO_PENDING
;
1062 scoped_refptr
<PacRequest
> req(
1063 new PacRequest(this, url
, load_flags
, network_delegate
,
1064 result
, callback
, net_log
));
1066 if (current_state_
== STATE_READY
) {
1067 // Start the resolve request.
1069 if (rv
!= ERR_IO_PENDING
)
1070 return req
->QueryDidComplete(rv
);
1072 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1075 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1076 DCHECK(!ContainsPendingRequest(req
.get()));
1077 pending_requests_
.insert(req
);
1079 // Completion will be notified through |callback|, unless the caller cancels
1080 // the request using |pac_request|.
1082 *pac_request
= req
.get();
1083 return rv
; // ERR_IO_PENDING
1086 bool ProxyService:: TryResolveProxySynchronously(
1087 const GURL
& raw_url
,
1090 NetworkDelegate
* network_delegate
,
1091 const BoundNetLog
& net_log
) {
1092 CompletionCallback null_callback
;
1093 return ResolveProxyHelper(raw_url
,
1097 NULL
/* pac_request*/,
1102 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1104 NetworkDelegate
* network_delegate
,
1105 ProxyInfo
* result
) {
1106 DCHECK_NE(STATE_NONE
, current_state_
);
1108 if (current_state_
!= STATE_READY
)
1109 return ERR_IO_PENDING
; // Still initializing.
1111 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1113 // If it was impossible to fetch or parse the PAC script, we cannot complete
1114 // the request here and bail out.
1115 if (permanent_error_
!= OK
)
1116 return permanent_error_
;
1118 if (config_
.HasAutomaticSettings())
1119 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1121 // Use the manual proxy settings.
1122 config_
.proxy_rules().Apply(url
, result
);
1123 result
->config_source_
= config_
.source();
1124 result
->config_id_
= config_
.id();
1129 ProxyService::~ProxyService() {
1130 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1131 NetworkChangeNotifier::RemoveDNSObserver(this);
1132 config_service_
->RemoveObserver(this);
1134 // Cancel any inprogress requests.
1135 for (PendingRequests::iterator it
= pending_requests_
.begin();
1136 it
!= pending_requests_
.end();
1142 void ProxyService::SuspendAllPendingRequests() {
1143 for (PendingRequests::iterator it
= pending_requests_
.begin();
1144 it
!= pending_requests_
.end();
1146 PacRequest
* req
= it
->get();
1147 if (req
->is_started()) {
1148 req
->CancelResolveJob();
1150 req
->net_log()->BeginEvent(
1151 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1156 void ProxyService::SetReady() {
1157 DCHECK(!init_proxy_resolver_
.get());
1158 current_state_
= STATE_READY
;
1160 // Make a copy in case |this| is deleted during the synchronous completion
1161 // of one of the requests. If |this| is deleted then all of the PacRequest
1162 // instances will be Cancel()-ed.
1163 PendingRequests pending_copy
= pending_requests_
;
1165 for (PendingRequests::iterator it
= pending_copy
.begin();
1166 it
!= pending_copy
.end();
1168 PacRequest
* req
= it
->get();
1169 if (!req
->is_started() && !req
->was_cancelled()) {
1170 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1172 // Note that we re-check for synchronous completion, in case we are
1173 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1174 req
->StartAndCompleteCheckingForSynchronous();
1179 void ProxyService::ApplyProxyConfigIfAvailable() {
1180 DCHECK_EQ(STATE_NONE
, current_state_
);
1182 config_service_
->OnLazyPoll();
1184 // If we have already fetched the configuration, start applying it.
1185 if (fetched_config_
.is_valid()) {
1186 InitializeUsingLastFetchedConfig();
1190 // Otherwise we need to first fetch the configuration.
1191 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1193 // Retrieve the current proxy configuration from the ProxyConfigService.
1194 // If a configuration is not available yet, we will get called back later
1195 // by our ProxyConfigService::Observer once it changes.
1197 ProxyConfigService::ConfigAvailability availability
=
1198 config_service_
->GetLatestProxyConfig(&config
);
1199 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1200 OnProxyConfigChanged(config
, availability
);
1203 void ProxyService::OnInitProxyResolverComplete(int result
) {
1204 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1205 DCHECK(init_proxy_resolver_
.get());
1206 DCHECK(fetched_config_
.HasAutomaticSettings());
1207 config_
= init_proxy_resolver_
->effective_config();
1209 // At this point we have decided which proxy settings to use (i.e. which PAC
1210 // script if any). We start up a background poller to periodically revisit
1211 // this decision. If the contents of the PAC script change, or if the
1212 // result of proxy auto-discovery changes, this poller will notice it and
1213 // will trigger a re-initialization using the newly discovered PAC.
1214 script_poller_
.reset(new ProxyScriptDeciderPoller(
1215 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1216 base::Unretained(this)),
1217 fetched_config_
, resolver_factory_
->expects_pac_bytes(),
1218 proxy_script_fetcher_
.get(), dhcp_proxy_script_fetcher_
.get(), result
,
1219 init_proxy_resolver_
->script_data(), NULL
));
1220 script_poller_
->set_quick_check_enabled(quick_check_enabled_
);
1222 init_proxy_resolver_
.reset();
1224 // When using the out-of-process resolver, creating the resolver can complete
1225 // with the ERR_PAC_SCRIPT_TERMINATED result code, which indicates the
1226 // resolver process crashed.
1227 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminatedOnInit",
1228 result
== ERR_PAC_SCRIPT_TERMINATED
);
1231 if (fetched_config_
.pac_mandatory()) {
1232 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1234 config_
= fetched_config_
;
1235 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1237 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1239 config_
= fetched_config_
;
1240 config_
.ClearAutomaticSettings();
1244 permanent_error_
= result
;
1246 // TODO(eroman): Make this ID unique in the case where configuration changed
1247 // due to ProxyScriptDeciderPoller.
1248 config_
.set_id(fetched_config_
.id());
1249 config_
.set_source(fetched_config_
.source());
1251 // Resume any requests which we had to defer until the PAC script was
1256 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1260 const CompletionCallback
& callback
,
1261 PacRequest
** pac_request
,
1262 NetworkDelegate
* network_delegate
,
1263 const BoundNetLog
& net_log
) {
1264 DCHECK(CalledOnValidThread());
1266 // Check to see if we have a new config since ResolveProxy was called. We
1267 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1268 // direct connection failed and we never tried the current config.
1271 bool re_resolve
= result
->config_id_
!= config_
.id();
1274 // If we have a new config or the config was never tried, we delete the
1275 // list of bad proxies and we try again.
1276 proxy_retry_info_
.clear();
1277 return ResolveProxy(url
, load_flags
, result
, callback
, pac_request
,
1278 network_delegate
, net_log
);
1281 DCHECK(!result
->is_empty());
1282 ProxyServer bad_proxy
= result
->proxy_server();
1284 // We don't have new proxy settings to try, try to fallback to the next proxy
1286 bool did_fallback
= result
->Fallback(net_error
, net_log
);
1288 // Return synchronous failure if there is nothing left to fall-back to.
1289 // TODO(eroman): This is a yucky API, clean it up.
1290 return did_fallback
? OK
: ERR_FAILED
;
1293 bool ProxyService::MarkProxiesAsBadUntil(
1294 const ProxyInfo
& result
,
1295 base::TimeDelta retry_delay
,
1296 const std::vector
<ProxyServer
>& additional_bad_proxies
,
1297 const BoundNetLog
& net_log
) {
1298 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
, retry_delay
,
1299 false, additional_bad_proxies
,
1301 return result
.proxy_list_
.size() > (additional_bad_proxies
.size() + 1);
1304 void ProxyService::ReportSuccess(const ProxyInfo
& result
,
1305 NetworkDelegate
* network_delegate
) {
1306 DCHECK(CalledOnValidThread());
1308 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1309 if (new_retry_info
.empty())
1312 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1313 iter
!= new_retry_info
.end(); ++iter
) {
1314 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1315 if (existing
== proxy_retry_info_
.end()) {
1316 proxy_retry_info_
[iter
->first
] = iter
->second
;
1317 if (network_delegate
) {
1318 const ProxyServer
& bad_proxy
=
1319 ProxyServer::FromURI(iter
->first
, ProxyServer::SCHEME_HTTP
);
1320 const ProxyRetryInfo
& proxy_retry_info
= iter
->second
;
1321 network_delegate
->NotifyProxyFallback(bad_proxy
,
1322 proxy_retry_info
.net_error
);
1325 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1326 existing
->second
.bad_until
= iter
->second
.bad_until
;
1329 net_log_
->AddGlobalEntry(
1330 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1331 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1335 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1336 DCHECK(CalledOnValidThread());
1339 RemovePendingRequest(req
);
1342 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1344 if (current_state_
== STATE_WAITING_FOR_INIT_PROXY_RESOLVER
)
1345 return init_proxy_resolver_
->GetLoadState();
1346 return req
->GetLoadState();
1349 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1350 return pending_requests_
.count(req
) == 1;
1353 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1354 DCHECK(ContainsPendingRequest(req
));
1355 pending_requests_
.erase(req
);
1358 int ProxyService::DidFinishResolvingProxy(const GURL
& url
,
1360 NetworkDelegate
* network_delegate
,
1363 const BoundNetLog
& net_log
,
1364 base::TimeTicks start_time
,
1365 bool script_executed
) {
1366 // Don't track any metrics if start_time is 0, which will happen when the user
1367 // calls |TryResolveProxySynchronously|.
1368 if (!start_time
.is_null()) {
1369 TimeDelta diff
= TimeTicks::Now() - start_time
;
1370 if (script_executed
) {
1371 // This function "fixes" the result code, so make sure script terminated
1372 // errors are tracked. Only track result codes that were a result of
1373 // script execution.
1374 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminated",
1375 result_code
== ERR_PAC_SCRIPT_TERMINATED
);
1376 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.GetProxyUsingScriptTime",
1377 diff
, base::TimeDelta::FromMicroseconds(100),
1378 base::TimeDelta::FromSeconds(20), 50);
1380 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ResolvedUsingScript",
1382 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.ResolveProxyTime", diff
,
1383 base::TimeDelta::FromMicroseconds(100),
1384 base::TimeDelta::FromSeconds(20), 50);
1387 // Log the result of the proxy resolution.
1388 if (result_code
== OK
) {
1389 // Allow the network delegate to interpose on the resolution decision,
1390 // possibly modifying the ProxyInfo.
1391 if (network_delegate
)
1392 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1394 // When logging all events is enabled, dump the proxy list.
1395 if (net_log
.IsCapturing()) {
1397 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1398 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1400 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1402 net_log
.AddEventWithNetErrorCode(
1403 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1405 bool reset_config
= result_code
== ERR_PAC_SCRIPT_TERMINATED
;
1406 if (!config_
.pac_mandatory()) {
1407 // Fall-back to direct when the proxy resolver fails. This corresponds
1408 // with a javascript runtime error in the PAC script.
1410 // This implicit fall-back to direct matches Firefox 3.5 and
1411 // Internet Explorer 8. For more information, see:
1413 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1414 result
->UseDirect();
1417 // Allow the network delegate to interpose on the resolution decision,
1418 // possibly modifying the ProxyInfo.
1419 if (network_delegate
)
1420 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1422 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1425 ResetProxyConfig(false);
1426 // If the ProxyResolver crashed, force it to be re-initialized for the
1427 // next request by resetting the proxy config. If there are other pending
1428 // requests, trigger the recreation immediately so those requests retry.
1429 if (pending_requests_
.size() > 1)
1430 ApplyProxyConfigIfAvailable();
1434 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1438 void ProxyService::SetProxyScriptFetchers(
1439 ProxyScriptFetcher
* proxy_script_fetcher
,
1440 scoped_ptr
<DhcpProxyScriptFetcher
> dhcp_proxy_script_fetcher
) {
1441 DCHECK(CalledOnValidThread());
1442 State previous_state
= ResetProxyConfig(false);
1443 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1444 dhcp_proxy_script_fetcher_
= dhcp_proxy_script_fetcher
.Pass();
1445 if (previous_state
!= STATE_NONE
)
1446 ApplyProxyConfigIfAvailable();
1449 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1450 DCHECK(CalledOnValidThread());
1451 return proxy_script_fetcher_
.get();
1454 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1455 DCHECK(CalledOnValidThread());
1456 State previous_state
= current_state_
;
1458 permanent_error_
= OK
;
1459 proxy_retry_info_
.clear();
1460 script_poller_
.reset();
1461 init_proxy_resolver_
.reset();
1462 SuspendAllPendingRequests();
1464 config_
= ProxyConfig();
1465 if (reset_fetched_config
)
1466 fetched_config_
= ProxyConfig();
1467 current_state_
= STATE_NONE
;
1469 return previous_state
;
1472 void ProxyService::ResetConfigService(
1473 ProxyConfigService
* new_proxy_config_service
) {
1474 DCHECK(CalledOnValidThread());
1475 State previous_state
= ResetProxyConfig(true);
1477 // Release the old configuration service.
1478 if (config_service_
.get())
1479 config_service_
->RemoveObserver(this);
1481 // Set the new configuration service.
1482 config_service_
.reset(new_proxy_config_service
);
1483 config_service_
->AddObserver(this);
1485 if (previous_state
!= STATE_NONE
)
1486 ApplyProxyConfigIfAvailable();
1489 void ProxyService::ForceReloadProxyConfig() {
1490 DCHECK(CalledOnValidThread());
1491 ResetProxyConfig(false);
1492 ApplyProxyConfigIfAvailable();
1496 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1497 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
1498 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_task_runner
) {
1500 return new ProxyConfigServiceWin();
1501 #elif defined(OS_IOS)
1502 return new ProxyConfigServiceIOS();
1503 #elif defined(OS_MACOSX)
1504 return new ProxyConfigServiceMac(io_task_runner
);
1505 #elif defined(OS_CHROMEOS)
1506 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1507 << "profile_io_data.cc::CreateProxyConfigService and this should "
1508 << "be used only for examples.";
1509 return new UnsetProxyConfigService
;
1510 #elif defined(OS_LINUX)
1511 ProxyConfigServiceLinux
* linux_config_service
=
1512 new ProxyConfigServiceLinux();
1514 // Assume we got called on the thread that runs the default glib
1515 // main loop, so the current thread is where we should be running
1516 // gconf calls from.
1517 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1518 base::ThreadTaskRunnerHandle::Get();
1520 // Synchronously fetch the current proxy config (since we are running on
1521 // glib_default_loop). Additionally register for notifications (delivered in
1522 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1523 // the proxy config changes.
1524 linux_config_service
->SetupAndFetchInitialConfig(
1525 glib_thread_task_runner
, io_task_runner
, file_task_runner
);
1527 return linux_config_service
;
1528 #elif defined(OS_ANDROID)
1529 return new ProxyConfigServiceAndroid(io_task_runner
,
1530 base::ThreadTaskRunnerHandle::Get());
1532 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1533 "for this platform.";
1534 return new ProxyConfigServiceDirect();
1539 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1540 const PacPollPolicy
* policy
) {
1541 return ProxyScriptDeciderPoller::set_policy(policy
);
1545 scoped_ptr
<ProxyService::PacPollPolicy
>
1546 ProxyService::CreateDefaultPacPollPolicy() {
1547 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1550 void ProxyService::OnProxyConfigChanged(
1551 const ProxyConfig
& config
,
1552 ProxyConfigService::ConfigAvailability availability
) {
1553 // Retrieve the current proxy configuration from the ProxyConfigService.
1554 // If a configuration is not available yet, we will get called back later
1555 // by our ProxyConfigService::Observer once it changes.
1556 ProxyConfig effective_config
;
1557 switch (availability
) {
1558 case ProxyConfigService::CONFIG_PENDING
:
1559 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1560 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1562 case ProxyConfigService::CONFIG_VALID
:
1563 effective_config
= config
;
1565 case ProxyConfigService::CONFIG_UNSET
:
1566 effective_config
= ProxyConfig::CreateDirect();
1570 // Emit the proxy settings change to the NetLog stream.
1572 net_log_
->AddGlobalEntry(NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1573 base::Bind(&NetLogProxyConfigChangedCallback
,
1574 &fetched_config_
, &effective_config
));
1577 // Set the new configuration as the most recently fetched one.
1578 fetched_config_
= effective_config
;
1579 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1581 InitializeUsingLastFetchedConfig();
1584 void ProxyService::InitializeUsingLastFetchedConfig() {
1585 ResetProxyConfig(false);
1587 DCHECK(fetched_config_
.is_valid());
1589 // Increment the ID to reflect that the config has changed.
1590 fetched_config_
.set_id(next_config_id_
++);
1592 if (!fetched_config_
.HasAutomaticSettings()) {
1593 config_
= fetched_config_
;
1598 // Start downloading + testing the PAC scripts for this new configuration.
1599 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1601 // If we changed networks recently, we should delay running proxy auto-config.
1602 TimeDelta wait_delay
=
1603 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1605 init_proxy_resolver_
.reset(new InitProxyResolver());
1606 init_proxy_resolver_
->set_quick_check_enabled(quick_check_enabled_
);
1607 int rv
= init_proxy_resolver_
->Start(
1608 &resolver_
, resolver_factory_
.get(), proxy_script_fetcher_
.get(),
1609 dhcp_proxy_script_fetcher_
.get(), net_log_
, fetched_config_
, wait_delay
,
1610 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1611 base::Unretained(this)));
1613 if (rv
!= ERR_IO_PENDING
)
1614 OnInitProxyResolverComplete(rv
);
1617 void ProxyService::InitializeUsingDecidedConfig(
1619 ProxyResolverScriptData
* script_data
,
1620 const ProxyConfig
& effective_config
) {
1621 DCHECK(fetched_config_
.is_valid());
1622 DCHECK(fetched_config_
.HasAutomaticSettings());
1624 ResetProxyConfig(false);
1626 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1628 init_proxy_resolver_
.reset(new InitProxyResolver());
1629 int rv
= init_proxy_resolver_
->StartSkipDecider(
1630 &resolver_
, resolver_factory_
.get(), effective_config
, decider_result
,
1631 script_data
, base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1632 base::Unretained(this)));
1634 if (rv
!= ERR_IO_PENDING
)
1635 OnInitProxyResolverComplete(rv
);
1638 void ProxyService::OnIPAddressChanged() {
1639 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1640 stall_proxy_autoconfig_until_
=
1641 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1643 State previous_state
= ResetProxyConfig(false);
1644 if (previous_state
!= STATE_NONE
)
1645 ApplyProxyConfigIfAvailable();
1648 void ProxyService::OnDNSChanged() {
1649 OnIPAddressChanged();