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 ProxyResolverScriptData
* script_data() {
434 DCHECK_EQ(STATE_NONE
, next_state_
);
435 return script_data_
.get();
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 ProxyResolverScriptData
* init_script_data
,
590 : change_callback_(callback
),
592 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes
),
593 proxy_script_fetcher_(proxy_script_fetcher
),
594 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher
),
595 last_error_(init_net_error
),
596 last_script_data_(init_script_data
),
597 last_poll_time_(TimeTicks::Now()),
598 weak_factory_(this) {
599 // Set the initial poll delay.
600 next_poll_mode_
= poll_policy()->GetNextDelay(
601 last_error_
, TimeDelta::FromSeconds(-1), &next_poll_delay_
);
602 TryToStartNextPoll(false);
606 // We have just been notified of network activity. Use this opportunity to
607 // see if we can start our next poll.
608 TryToStartNextPoll(true);
611 static const PacPollPolicy
* set_policy(const PacPollPolicy
* policy
) {
612 const PacPollPolicy
* prev
= poll_policy_
;
613 poll_policy_
= policy
;
617 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
618 bool quick_check_enabled() const { return quick_check_enabled_
; }
621 // Returns the effective poll policy (the one injected by unit-tests, or the
623 const PacPollPolicy
* poll_policy() {
626 return &default_poll_policy_
;
629 void StartPollTimer() {
630 DCHECK(!decider_
.get());
632 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
633 FROM_HERE
, base::Bind(&ProxyScriptDeciderPoller::DoPoll
,
634 weak_factory_
.GetWeakPtr()),
638 void TryToStartNextPoll(bool triggered_by_activity
) {
639 switch (next_poll_mode_
) {
640 case PacPollPolicy::MODE_USE_TIMER
:
641 if (!triggered_by_activity
)
645 case PacPollPolicy::MODE_START_AFTER_ACTIVITY
:
646 if (triggered_by_activity
&& !decider_
.get()) {
647 TimeDelta elapsed_time
= TimeTicks::Now() - last_poll_time_
;
648 if (elapsed_time
>= next_poll_delay_
)
656 last_poll_time_
= TimeTicks::Now();
658 // Start the proxy script decider to see if anything has changed.
659 // TODO(eroman): Pass a proper NetLog rather than NULL.
660 decider_
.reset(new ProxyScriptDecider(
661 proxy_script_fetcher_
, dhcp_proxy_script_fetcher_
, NULL
));
662 decider_
->set_quick_check_enabled(quick_check_enabled_
);
663 int result
= decider_
->Start(
664 config_
, TimeDelta(), proxy_resolver_expects_pac_bytes_
,
665 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted
,
666 base::Unretained(this)));
668 if (result
!= ERR_IO_PENDING
)
669 OnProxyScriptDeciderCompleted(result
);
672 void OnProxyScriptDeciderCompleted(int result
) {
673 if (HasScriptDataChanged(result
, decider_
->script_data())) {
674 // Something has changed, we must notify the ProxyService so it can
675 // re-initialize its ProxyResolver. Note that we post a notification task
676 // rather than calling it directly -- this is done to avoid an ugly
677 // destruction sequence, since |this| might be destroyed as a result of
679 base::ThreadTaskRunnerHandle::Get()->PostTask(
681 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange
,
682 weak_factory_
.GetWeakPtr(), result
,
683 make_scoped_refptr(decider_
->script_data()),
684 decider_
->effective_config()));
690 // Decide when the next poll should take place, and possibly start the
692 next_poll_mode_
= poll_policy()->GetNextDelay(
693 last_error_
, next_poll_delay_
, &next_poll_delay_
);
694 TryToStartNextPoll(false);
697 bool HasScriptDataChanged(int result
, ProxyResolverScriptData
* script_data
) {
698 if (result
!= last_error_
) {
699 // Something changed -- it was failing before and now it succeeded, or
700 // conversely it succeeded before and now it failed. Or it failed in
701 // both cases, however the specific failure error codes differ.
706 // If it failed last time and failed again with the same error code this
707 // time, then nothing has actually changed.
711 // Otherwise if it succeeded both this time and last time, we need to look
712 // closer and see if we ended up downloading different content for the PAC
714 return !script_data
->Equals(last_script_data_
.get());
717 void NotifyProxyServiceOfChange(
719 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
720 const ProxyConfig
& effective_config
) {
721 // Note that |this| may be deleted after calling into the ProxyService.
722 change_callback_
.Run(result
, script_data
.get(), effective_config
);
725 ChangeCallback change_callback_
;
727 bool proxy_resolver_expects_pac_bytes_
;
728 ProxyScriptFetcher
* proxy_script_fetcher_
;
729 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher_
;
732 scoped_refptr
<ProxyResolverScriptData
> last_script_data_
;
734 scoped_ptr
<ProxyScriptDecider
> decider_
;
735 TimeDelta next_poll_delay_
;
736 PacPollPolicy::Mode next_poll_mode_
;
738 TimeTicks last_poll_time_
;
740 // Polling policy injected by unit-tests. Otherwise this is NULL and the
741 // default policy will be used.
742 static const PacPollPolicy
* poll_policy_
;
744 const DefaultPollPolicy default_poll_policy_
;
746 bool quick_check_enabled_
;
748 base::WeakPtrFactory
<ProxyScriptDeciderPoller
> weak_factory_
;
750 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller
);
754 const ProxyService::PacPollPolicy
*
755 ProxyService::ProxyScriptDeciderPoller::poll_policy_
= NULL
;
757 // ProxyService::PacRequest ---------------------------------------------------
759 class ProxyService::PacRequest
760 : public base::RefCounted
<ProxyService::PacRequest
> {
762 PacRequest(ProxyService
* service
,
765 NetworkDelegate
* network_delegate
,
767 const CompletionCallback
& user_callback
,
768 const BoundNetLog
& net_log
)
770 user_callback_(user_callback
),
773 load_flags_(load_flags
),
774 network_delegate_(network_delegate
),
776 config_id_(ProxyConfig::kInvalidConfigID
),
777 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN
),
779 creation_time_(TimeTicks::Now()) {
780 DCHECK(!user_callback
.is_null());
783 // Starts the resolve proxy request.
785 DCHECK(!was_cancelled());
786 DCHECK(!is_started());
788 DCHECK(service_
->config_
.is_valid());
790 config_id_
= service_
->config_
.id();
791 config_source_
= service_
->config_
.source();
793 return resolver()->GetProxyForURL(
795 base::Bind(&PacRequest::QueryComplete
, base::Unretained(this)),
796 &resolve_job_
, net_log_
);
799 bool is_started() const {
800 // Note that !! casts to bool. (VS gives a warning otherwise).
801 return !!resolve_job_
;
804 void StartAndCompleteCheckingForSynchronous() {
805 int rv
= service_
->TryToCompleteSynchronously(url_
, load_flags_
,
806 network_delegate_
, results_
);
807 if (rv
== ERR_IO_PENDING
)
809 if (rv
!= ERR_IO_PENDING
)
813 void CancelResolveJob() {
814 DCHECK(is_started());
815 // The request may already be running in the resolver.
816 resolver()->CancelRequest(resolve_job_
);
818 DCHECK(!is_started());
822 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
827 // Mark as cancelled, to prevent accessing this again later.
829 user_callback_
.Reset();
832 net_log_
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
835 // Returns true if Cancel() has been called.
836 bool was_cancelled() const {
837 return user_callback_
.is_null();
840 // Helper to call after ProxyResolver completion (both synchronous and
841 // asynchronous). Fixes up the result that is to be returned to user.
842 int QueryDidComplete(int result_code
) {
843 DCHECK(!was_cancelled());
845 // This state is cleared when resolve_job_ is set to nullptr below.
846 bool script_executed
= is_started();
848 // Clear |resolve_job_| so is_started() returns false while
849 // DidFinishResolvingProxy() runs.
850 resolve_job_
= nullptr;
852 // Note that DidFinishResolvingProxy might modify |results_|.
853 int rv
= service_
->DidFinishResolvingProxy(
854 url_
, load_flags_
, network_delegate_
, results_
, result_code
, net_log_
,
855 creation_time_
, script_executed
);
857 // Make a note in the results which configuration was in use at the
858 // time of the resolve.
859 results_
->config_id_
= config_id_
;
860 results_
->config_source_
= config_source_
;
861 results_
->did_use_pac_script_
= true;
862 results_
->proxy_resolve_start_time_
= creation_time_
;
863 results_
->proxy_resolve_end_time_
= TimeTicks::Now();
865 // Reset the state associated with in-progress-resolve.
866 config_id_
= ProxyConfig::kInvalidConfigID
;
867 config_source_
= PROXY_CONFIG_SOURCE_UNKNOWN
;
872 BoundNetLog
* net_log() { return &net_log_
; }
874 LoadState
GetLoadState() const {
876 return resolver()->GetLoadState(resolve_job_
);
877 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
881 friend class base::RefCounted
<ProxyService::PacRequest
>;
885 // Callback for when the ProxyResolver request has completed.
886 void QueryComplete(int result_code
) {
887 result_code
= QueryDidComplete(result_code
);
889 // Remove this completed PacRequest from the service's pending list.
890 /// (which will probably cause deletion of |this|).
891 if (!user_callback_
.is_null()) {
892 CompletionCallback callback
= user_callback_
;
893 service_
->RemovePendingRequest(this);
894 callback
.Run(result_code
);
898 ProxyResolver
* resolver() const { return service_
->resolver_
.get(); }
900 // Note that we don't hold a reference to the ProxyService. Outstanding
901 // requests are cancelled during ~ProxyService, so this is guaranteed
902 // to be valid throughout our lifetime.
903 ProxyService
* service_
;
904 CompletionCallback user_callback_
;
908 NetworkDelegate
* network_delegate_
;
909 ProxyResolver::RequestHandle resolve_job_
;
910 ProxyConfig::ID config_id_
; // The config id when the resolve was started.
911 ProxyConfigSource config_source_
; // The source of proxy settings.
912 BoundNetLog net_log_
;
913 // Time when the request was created. Stored here rather than in |results_|
914 // because the time in |results_| will be cleared.
915 TimeTicks creation_time_
;
918 // ProxyService ---------------------------------------------------------------
920 ProxyService::ProxyService(ProxyConfigService
* config_service
,
921 scoped_ptr
<ProxyResolverFactory
> resolver_factory
,
923 : resolver_factory_(resolver_factory
.Pass()),
925 current_state_(STATE_NONE
),
927 stall_proxy_auto_config_delay_(
928 TimeDelta::FromMilliseconds(kDelayAfterNetworkChangesMs
)),
929 quick_check_enabled_(true) {
930 NetworkChangeNotifier::AddIPAddressObserver(this);
931 NetworkChangeNotifier::AddDNSObserver(this);
932 ResetConfigService(config_service
);
936 ProxyService
* ProxyService::CreateUsingSystemProxyResolver(
937 ProxyConfigService
* proxy_config_service
,
938 size_t num_pac_threads
,
940 DCHECK(proxy_config_service
);
942 if (!ProxyResolverFactoryForSystem::IsSupported()) {
943 VLOG(1) << "PAC support disabled because there is no system implementation";
944 return CreateWithoutProxyResolver(proxy_config_service
, net_log
);
947 if (num_pac_threads
== 0)
948 num_pac_threads
= kDefaultNumPacThreads
;
950 return new ProxyService(
951 proxy_config_service
,
952 make_scoped_ptr(new ProxyResolverFactoryForSystem(num_pac_threads
)),
957 ProxyService
* ProxyService::CreateWithoutProxyResolver(
958 ProxyConfigService
* proxy_config_service
,
960 return new ProxyService(
961 proxy_config_service
,
962 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
966 ProxyService
* ProxyService::CreateFixed(const ProxyConfig
& pc
) {
967 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
969 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc
),
974 ProxyService
* ProxyService::CreateFixed(const std::string
& proxy
) {
975 ProxyConfig proxy_config
;
976 proxy_config
.proxy_rules().ParseFromString(proxy
);
977 return ProxyService::CreateFixed(proxy_config
);
981 ProxyService
* ProxyService::CreateDirect() {
982 return CreateDirectWithNetLog(NULL
);
985 ProxyService
* ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
986 // Use direct connections.
987 return new ProxyService(
988 new ProxyConfigServiceDirect
,
989 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
993 ProxyService
* ProxyService::CreateFixedFromPacResult(
994 const std::string
& pac_string
) {
996 // We need the settings to contain an "automatic" setting, otherwise the
997 // ProxyResolver dependency we give it will never be used.
998 scoped_ptr
<ProxyConfigService
> proxy_config_service(
999 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
1001 return new ProxyService(
1002 proxy_config_service
.release(),
1003 make_scoped_ptr(new ProxyResolverFactoryForPacResult(pac_string
)), NULL
);
1006 int ProxyService::ResolveProxy(const GURL
& raw_url
,
1009 const CompletionCallback
& callback
,
1010 PacRequest
** pac_request
,
1011 NetworkDelegate
* network_delegate
,
1012 const BoundNetLog
& net_log
) {
1013 DCHECK(!callback
.is_null());
1014 return ResolveProxyHelper(raw_url
,
1023 int ProxyService::ResolveProxyHelper(const GURL
& raw_url
,
1026 const CompletionCallback
& callback
,
1027 PacRequest
** pac_request
,
1028 NetworkDelegate
* network_delegate
,
1029 const BoundNetLog
& net_log
) {
1030 DCHECK(CalledOnValidThread());
1032 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
1034 // Notify our polling-based dependencies that a resolve is taking place.
1035 // This way they can schedule their polls in response to network activity.
1036 config_service_
->OnLazyPoll();
1037 if (script_poller_
.get())
1038 script_poller_
->OnLazyPoll();
1040 if (current_state_
== STATE_NONE
)
1041 ApplyProxyConfigIfAvailable();
1043 // Strip away any reference fragments and the username/password, as they
1044 // are not relevant to proxy resolution.
1045 GURL url
= SimplifyUrlForRequest(raw_url
);
1047 // Check if the request can be completed right away. (This is the case when
1048 // using a direct connection for example).
1049 int rv
= TryToCompleteSynchronously(url
, load_flags
,
1050 network_delegate
, result
);
1051 if (rv
!= ERR_IO_PENDING
) {
1052 rv
= DidFinishResolvingProxy(
1053 url
, load_flags
, network_delegate
, result
, rv
, net_log
,
1054 callback
.is_null() ? TimeTicks() : TimeTicks::Now(), false);
1058 if (callback
.is_null())
1059 return ERR_IO_PENDING
;
1061 scoped_refptr
<PacRequest
> req(
1062 new PacRequest(this, url
, load_flags
, network_delegate
,
1063 result
, callback
, net_log
));
1065 if (current_state_
== STATE_READY
) {
1066 // Start the resolve request.
1068 if (rv
!= ERR_IO_PENDING
)
1069 return req
->QueryDidComplete(rv
);
1071 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1074 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1075 DCHECK(!ContainsPendingRequest(req
.get()));
1076 pending_requests_
.push_back(req
);
1078 // Completion will be notified through |callback|, unless the caller cancels
1079 // the request using |pac_request|.
1081 *pac_request
= req
.get();
1082 return rv
; // ERR_IO_PENDING
1085 bool ProxyService:: TryResolveProxySynchronously(
1086 const GURL
& raw_url
,
1089 NetworkDelegate
* network_delegate
,
1090 const BoundNetLog
& net_log
) {
1091 CompletionCallback null_callback
;
1092 return ResolveProxyHelper(raw_url
,
1096 NULL
/* pac_request*/,
1101 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1103 NetworkDelegate
* network_delegate
,
1104 ProxyInfo
* result
) {
1105 DCHECK_NE(STATE_NONE
, current_state_
);
1107 if (current_state_
!= STATE_READY
)
1108 return ERR_IO_PENDING
; // Still initializing.
1110 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1112 // If it was impossible to fetch or parse the PAC script, we cannot complete
1113 // the request here and bail out.
1114 if (permanent_error_
!= OK
)
1115 return permanent_error_
;
1117 if (config_
.HasAutomaticSettings())
1118 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1120 // Use the manual proxy settings.
1121 config_
.proxy_rules().Apply(url
, result
);
1122 result
->config_source_
= config_
.source();
1123 result
->config_id_
= config_
.id();
1128 ProxyService::~ProxyService() {
1129 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1130 NetworkChangeNotifier::RemoveDNSObserver(this);
1131 config_service_
->RemoveObserver(this);
1133 // Cancel any inprogress requests.
1134 for (PendingRequests::iterator it
= pending_requests_
.begin();
1135 it
!= pending_requests_
.end();
1141 void ProxyService::SuspendAllPendingRequests() {
1142 for (PendingRequests::iterator it
= pending_requests_
.begin();
1143 it
!= pending_requests_
.end();
1145 PacRequest
* req
= it
->get();
1146 if (req
->is_started()) {
1147 req
->CancelResolveJob();
1149 req
->net_log()->BeginEvent(
1150 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1155 void ProxyService::SetReady() {
1156 DCHECK(!init_proxy_resolver_
.get());
1157 current_state_
= STATE_READY
;
1159 // Make a copy in case |this| is deleted during the synchronous completion
1160 // of one of the requests. If |this| is deleted then all of the PacRequest
1161 // instances will be Cancel()-ed.
1162 PendingRequests pending_copy
= pending_requests_
;
1164 for (PendingRequests::iterator it
= pending_copy
.begin();
1165 it
!= pending_copy
.end();
1167 PacRequest
* req
= it
->get();
1168 if (!req
->is_started() && !req
->was_cancelled()) {
1169 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1171 // Note that we re-check for synchronous completion, in case we are
1172 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1173 req
->StartAndCompleteCheckingForSynchronous();
1178 void ProxyService::ApplyProxyConfigIfAvailable() {
1179 DCHECK_EQ(STATE_NONE
, current_state_
);
1181 config_service_
->OnLazyPoll();
1183 // If we have already fetched the configuration, start applying it.
1184 if (fetched_config_
.is_valid()) {
1185 InitializeUsingLastFetchedConfig();
1189 // Otherwise we need to first fetch the configuration.
1190 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1192 // Retrieve the current proxy configuration from the ProxyConfigService.
1193 // If a configuration is not available yet, we will get called back later
1194 // by our ProxyConfigService::Observer once it changes.
1196 ProxyConfigService::ConfigAvailability availability
=
1197 config_service_
->GetLatestProxyConfig(&config
);
1198 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1199 OnProxyConfigChanged(config
, availability
);
1202 void ProxyService::OnInitProxyResolverComplete(int result
) {
1203 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1204 DCHECK(init_proxy_resolver_
.get());
1205 DCHECK(fetched_config_
.HasAutomaticSettings());
1206 config_
= init_proxy_resolver_
->effective_config();
1208 // At this point we have decided which proxy settings to use (i.e. which PAC
1209 // script if any). We start up a background poller to periodically revisit
1210 // this decision. If the contents of the PAC script change, or if the
1211 // result of proxy auto-discovery changes, this poller will notice it and
1212 // will trigger a re-initialization using the newly discovered PAC.
1213 script_poller_
.reset(new ProxyScriptDeciderPoller(
1214 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1215 base::Unretained(this)),
1216 fetched_config_
, resolver_factory_
->expects_pac_bytes(),
1217 proxy_script_fetcher_
.get(), dhcp_proxy_script_fetcher_
.get(), result
,
1218 init_proxy_resolver_
->script_data(), NULL
));
1219 script_poller_
->set_quick_check_enabled(quick_check_enabled_
);
1221 init_proxy_resolver_
.reset();
1223 // When using the out-of-process resolver, creating the resolver can complete
1224 // with the ERR_PAC_SCRIPT_TERMINATED result code, which indicates the
1225 // resolver process crashed.
1226 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminatedOnInit",
1227 result
== ERR_PAC_SCRIPT_TERMINATED
);
1230 if (fetched_config_
.pac_mandatory()) {
1231 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1233 config_
= fetched_config_
;
1234 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1236 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1238 config_
= fetched_config_
;
1239 config_
.ClearAutomaticSettings();
1243 permanent_error_
= result
;
1245 // TODO(eroman): Make this ID unique in the case where configuration changed
1246 // due to ProxyScriptDeciderPoller.
1247 config_
.set_id(fetched_config_
.id());
1248 config_
.set_source(fetched_config_
.source());
1250 // Resume any requests which we had to defer until the PAC script was
1255 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1259 const CompletionCallback
& callback
,
1260 PacRequest
** pac_request
,
1261 NetworkDelegate
* network_delegate
,
1262 const BoundNetLog
& net_log
) {
1263 DCHECK(CalledOnValidThread());
1265 // Check to see if we have a new config since ResolveProxy was called. We
1266 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1267 // direct connection failed and we never tried the current config.
1270 bool re_resolve
= result
->config_id_
!= config_
.id();
1273 // If we have a new config or the config was never tried, we delete the
1274 // list of bad proxies and we try again.
1275 proxy_retry_info_
.clear();
1276 return ResolveProxy(url
, load_flags
, result
, callback
, pac_request
,
1277 network_delegate
, net_log
);
1280 DCHECK(!result
->is_empty());
1281 ProxyServer bad_proxy
= result
->proxy_server();
1283 // We don't have new proxy settings to try, try to fallback to the next proxy
1285 bool did_fallback
= result
->Fallback(net_error
, net_log
);
1287 // Return synchronous failure if there is nothing left to fall-back to.
1288 // TODO(eroman): This is a yucky API, clean it up.
1289 return did_fallback
? OK
: ERR_FAILED
;
1292 bool ProxyService::MarkProxiesAsBadUntil(
1293 const ProxyInfo
& result
,
1294 base::TimeDelta retry_delay
,
1295 const std::vector
<ProxyServer
>& additional_bad_proxies
,
1296 const BoundNetLog
& net_log
) {
1297 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
, retry_delay
,
1298 false, additional_bad_proxies
,
1300 return result
.proxy_list_
.size() > (additional_bad_proxies
.size() + 1);
1303 void ProxyService::ReportSuccess(const ProxyInfo
& result
,
1304 NetworkDelegate
* network_delegate
) {
1305 DCHECK(CalledOnValidThread());
1307 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1308 if (new_retry_info
.empty())
1311 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1312 iter
!= new_retry_info
.end(); ++iter
) {
1313 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1314 if (existing
== proxy_retry_info_
.end()) {
1315 proxy_retry_info_
[iter
->first
] = iter
->second
;
1316 if (network_delegate
) {
1317 const ProxyServer
& bad_proxy
=
1318 ProxyServer::FromURI(iter
->first
, ProxyServer::SCHEME_HTTP
);
1319 const ProxyRetryInfo
& proxy_retry_info
= iter
->second
;
1320 network_delegate
->NotifyProxyFallback(bad_proxy
,
1321 proxy_retry_info
.net_error
);
1324 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1325 existing
->second
.bad_until
= iter
->second
.bad_until
;
1328 net_log_
->AddGlobalEntry(
1329 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1330 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1334 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1335 DCHECK(CalledOnValidThread());
1338 RemovePendingRequest(req
);
1341 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1343 if (current_state_
== STATE_WAITING_FOR_INIT_PROXY_RESOLVER
)
1344 return init_proxy_resolver_
->GetLoadState();
1345 return req
->GetLoadState();
1348 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1349 PendingRequests::iterator it
= std::find(
1350 pending_requests_
.begin(), pending_requests_
.end(), req
);
1351 return pending_requests_
.end() != it
;
1354 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1355 DCHECK(ContainsPendingRequest(req
));
1356 PendingRequests::iterator it
= std::find(
1357 pending_requests_
.begin(), pending_requests_
.end(), req
);
1358 pending_requests_
.erase(it
);
1361 int ProxyService::DidFinishResolvingProxy(const GURL
& url
,
1363 NetworkDelegate
* network_delegate
,
1366 const BoundNetLog
& net_log
,
1367 base::TimeTicks start_time
,
1368 bool script_executed
) {
1369 // Don't track any metrics if start_time is 0, which will happen when the user
1370 // calls |TryResolveProxySynchronously|.
1371 if (!start_time
.is_null()) {
1372 TimeDelta diff
= TimeTicks::Now() - start_time
;
1373 if (script_executed
) {
1374 // This function "fixes" the result code, so make sure script terminated
1375 // errors are tracked. Only track result codes that were a result of
1376 // script execution.
1377 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ScriptTerminated",
1378 result_code
== ERR_PAC_SCRIPT_TERMINATED
);
1379 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.GetProxyUsingScriptTime",
1380 diff
, base::TimeDelta::FromMicroseconds(100),
1381 base::TimeDelta::FromSeconds(20), 50);
1383 UMA_HISTOGRAM_BOOLEAN("Net.ProxyService.ResolvedUsingScript",
1385 UMA_HISTOGRAM_CUSTOM_TIMES("Net.ProxyService.ResolveProxyTime", diff
,
1386 base::TimeDelta::FromMicroseconds(100),
1387 base::TimeDelta::FromSeconds(20), 50);
1390 // Log the result of the proxy resolution.
1391 if (result_code
== OK
) {
1392 // Allow the network delegate to interpose on the resolution decision,
1393 // possibly modifying the ProxyInfo.
1394 if (network_delegate
)
1395 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1397 // When logging all events is enabled, dump the proxy list.
1398 if (net_log
.IsCapturing()) {
1400 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1401 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1403 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1405 net_log
.AddEventWithNetErrorCode(
1406 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1408 bool reset_config
= result_code
== ERR_PAC_SCRIPT_TERMINATED
;
1409 if (!config_
.pac_mandatory()) {
1410 // Fall-back to direct when the proxy resolver fails. This corresponds
1411 // with a javascript runtime error in the PAC script.
1413 // This implicit fall-back to direct matches Firefox 3.5 and
1414 // Internet Explorer 8. For more information, see:
1416 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1417 result
->UseDirect();
1420 // Allow the network delegate to interpose on the resolution decision,
1421 // possibly modifying the ProxyInfo.
1422 if (network_delegate
)
1423 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1425 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1428 ResetProxyConfig(false);
1429 // If the ProxyResolver crashed, force it to be re-initialized for the
1430 // next request by resetting the proxy config. If there are other pending
1431 // requests, trigger the recreation immediately so those requests retry.
1432 if (pending_requests_
.size() > 1)
1433 ApplyProxyConfigIfAvailable();
1437 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1441 void ProxyService::SetProxyScriptFetchers(
1442 ProxyScriptFetcher
* proxy_script_fetcher
,
1443 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
) {
1444 DCHECK(CalledOnValidThread());
1445 State previous_state
= ResetProxyConfig(false);
1446 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1447 dhcp_proxy_script_fetcher_
.reset(dhcp_proxy_script_fetcher
);
1448 if (previous_state
!= STATE_NONE
)
1449 ApplyProxyConfigIfAvailable();
1452 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1453 DCHECK(CalledOnValidThread());
1454 return proxy_script_fetcher_
.get();
1457 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1458 DCHECK(CalledOnValidThread());
1459 State previous_state
= current_state_
;
1461 permanent_error_
= OK
;
1462 proxy_retry_info_
.clear();
1463 script_poller_
.reset();
1464 init_proxy_resolver_
.reset();
1465 SuspendAllPendingRequests();
1467 config_
= ProxyConfig();
1468 if (reset_fetched_config
)
1469 fetched_config_
= ProxyConfig();
1470 current_state_
= STATE_NONE
;
1472 return previous_state
;
1475 void ProxyService::ResetConfigService(
1476 ProxyConfigService
* new_proxy_config_service
) {
1477 DCHECK(CalledOnValidThread());
1478 State previous_state
= ResetProxyConfig(true);
1480 // Release the old configuration service.
1481 if (config_service_
.get())
1482 config_service_
->RemoveObserver(this);
1484 // Set the new configuration service.
1485 config_service_
.reset(new_proxy_config_service
);
1486 config_service_
->AddObserver(this);
1488 if (previous_state
!= STATE_NONE
)
1489 ApplyProxyConfigIfAvailable();
1492 void ProxyService::ForceReloadProxyConfig() {
1493 DCHECK(CalledOnValidThread());
1494 ResetProxyConfig(false);
1495 ApplyProxyConfigIfAvailable();
1499 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1500 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
1501 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_task_runner
) {
1503 return new ProxyConfigServiceWin();
1504 #elif defined(OS_IOS)
1505 return new ProxyConfigServiceIOS();
1506 #elif defined(OS_MACOSX)
1507 return new ProxyConfigServiceMac(io_task_runner
);
1508 #elif defined(OS_CHROMEOS)
1509 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1510 << "profile_io_data.cc::CreateProxyConfigService and this should "
1511 << "be used only for examples.";
1512 return new UnsetProxyConfigService
;
1513 #elif defined(OS_LINUX)
1514 ProxyConfigServiceLinux
* linux_config_service
=
1515 new ProxyConfigServiceLinux();
1517 // Assume we got called on the thread that runs the default glib
1518 // main loop, so the current thread is where we should be running
1519 // gconf calls from.
1520 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1521 base::ThreadTaskRunnerHandle::Get();
1523 // Synchronously fetch the current proxy config (since we are running on
1524 // glib_default_loop). Additionally register for notifications (delivered in
1525 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1526 // the proxy config changes.
1527 linux_config_service
->SetupAndFetchInitialConfig(
1528 glib_thread_task_runner
, io_task_runner
, file_task_runner
);
1530 return linux_config_service
;
1531 #elif defined(OS_ANDROID)
1532 return new ProxyConfigServiceAndroid(io_task_runner
,
1533 base::ThreadTaskRunnerHandle::Get());
1535 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1536 "for this platform.";
1537 return new ProxyConfigServiceDirect();
1542 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1543 const PacPollPolicy
* policy
) {
1544 return ProxyScriptDeciderPoller::set_policy(policy
);
1548 scoped_ptr
<ProxyService::PacPollPolicy
>
1549 ProxyService::CreateDefaultPacPollPolicy() {
1550 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1553 void ProxyService::OnProxyConfigChanged(
1554 const ProxyConfig
& config
,
1555 ProxyConfigService::ConfigAvailability availability
) {
1556 // Retrieve the current proxy configuration from the ProxyConfigService.
1557 // If a configuration is not available yet, we will get called back later
1558 // by our ProxyConfigService::Observer once it changes.
1559 ProxyConfig effective_config
;
1560 switch (availability
) {
1561 case ProxyConfigService::CONFIG_PENDING
:
1562 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1563 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1565 case ProxyConfigService::CONFIG_VALID
:
1566 effective_config
= config
;
1568 case ProxyConfigService::CONFIG_UNSET
:
1569 effective_config
= ProxyConfig::CreateDirect();
1573 // Emit the proxy settings change to the NetLog stream.
1575 net_log_
->AddGlobalEntry(NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1576 base::Bind(&NetLogProxyConfigChangedCallback
,
1577 &fetched_config_
, &effective_config
));
1580 // Set the new configuration as the most recently fetched one.
1581 fetched_config_
= effective_config
;
1582 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1584 InitializeUsingLastFetchedConfig();
1587 void ProxyService::InitializeUsingLastFetchedConfig() {
1588 ResetProxyConfig(false);
1590 DCHECK(fetched_config_
.is_valid());
1592 // Increment the ID to reflect that the config has changed.
1593 fetched_config_
.set_id(next_config_id_
++);
1595 if (!fetched_config_
.HasAutomaticSettings()) {
1596 config_
= fetched_config_
;
1601 // Start downloading + testing the PAC scripts for this new configuration.
1602 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1604 // If we changed networks recently, we should delay running proxy auto-config.
1605 TimeDelta wait_delay
=
1606 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1608 init_proxy_resolver_
.reset(new InitProxyResolver());
1609 init_proxy_resolver_
->set_quick_check_enabled(quick_check_enabled_
);
1610 int rv
= init_proxy_resolver_
->Start(
1611 &resolver_
, resolver_factory_
.get(), proxy_script_fetcher_
.get(),
1612 dhcp_proxy_script_fetcher_
.get(), net_log_
, fetched_config_
, wait_delay
,
1613 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1614 base::Unretained(this)));
1616 if (rv
!= ERR_IO_PENDING
)
1617 OnInitProxyResolverComplete(rv
);
1620 void ProxyService::InitializeUsingDecidedConfig(
1622 ProxyResolverScriptData
* script_data
,
1623 const ProxyConfig
& effective_config
) {
1624 DCHECK(fetched_config_
.is_valid());
1625 DCHECK(fetched_config_
.HasAutomaticSettings());
1627 ResetProxyConfig(false);
1629 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1631 init_proxy_resolver_
.reset(new InitProxyResolver());
1632 int rv
= init_proxy_resolver_
->StartSkipDecider(
1633 &resolver_
, resolver_factory_
.get(), effective_config
, decider_result
,
1634 script_data
, base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1635 base::Unretained(this)));
1637 if (rv
!= ERR_IO_PENDING
)
1638 OnInitProxyResolverComplete(rv
);
1641 void ProxyService::OnIPAddressChanged() {
1642 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1643 stall_proxy_autoconfig_until_
=
1644 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1646 State previous_state
= ResetProxyConfig(false);
1647 if (previous_state
!= STATE_NONE
)
1648 ApplyProxyConfigIfAvailable();
1651 void ProxyService::OnDNSChanged() {
1652 OnIPAddressChanged();