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/logging.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/strings/string_util.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/values.h"
19 #include "net/base/completion_callback.h"
20 #include "net/base/load_flags.h"
21 #include "net/base/net_errors.h"
22 #include "net/base/net_util.h"
23 #include "net/log/net_log.h"
24 #include "net/proxy/dhcp_proxy_script_fetcher.h"
25 #include "net/proxy/multi_threaded_proxy_resolver.h"
26 #include "net/proxy/network_delegate_error_observer.h"
27 #include "net/proxy/proxy_config_service_fixed.h"
28 #include "net/proxy/proxy_resolver.h"
29 #include "net/proxy/proxy_resolver_factory.h"
30 #include "net/proxy/proxy_script_decider.h"
31 #include "net/proxy/proxy_script_fetcher.h"
32 #include "net/url_request/url_request_context.h"
36 #include "net/proxy/proxy_config_service_win.h"
37 #include "net/proxy/proxy_resolver_winhttp.h"
39 #include "net/proxy/proxy_config_service_ios.h"
40 #include "net/proxy/proxy_resolver_mac.h"
41 #elif defined(OS_MACOSX)
42 #include "net/proxy/proxy_config_service_mac.h"
43 #include "net/proxy/proxy_resolver_mac.h"
44 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
45 #include "net/proxy/proxy_config_service_linux.h"
46 #elif defined(OS_ANDROID)
47 #include "net/proxy/proxy_config_service_android.h"
50 using base::TimeDelta
;
51 using base::TimeTicks
;
57 // When the IP address changes we don't immediately re-run proxy auto-config.
58 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
59 // attempting to re-valuate proxy auto-config.
61 // During this time window, any resolve requests sent to the ProxyService will
62 // be queued. Once we have waited the required amount of them, the proxy
63 // auto-config step will be run, and the queued requests resumed.
65 // The reason we play this game is that our signal for detecting network
66 // changes (NetworkChangeNotifier) may fire *before* the system's networking
67 // dependencies are fully configured. This is a problem since it means if
68 // we were to run proxy auto-config right away, it could fail due to spurious
69 // DNS failures. (see http://crbug.com/50779 for more details.)
71 // By adding the wait window, we give things a better chance to get properly
72 // set up. Network failures can happen at any time though, so we additionally
73 // poll the PAC script for changes, which will allow us to recover from these
75 const int64 kDelayAfterNetworkChangesMs
= 2000;
77 // This is the default policy for polling the PAC script.
79 // In response to a failure, the poll intervals are:
80 // 0: 8 seconds (scheduled on timer)
85 // In response to a success, the poll intervals are:
88 // Only the 8 second poll is scheduled on a timer, the rest happen in response
89 // to network activity (and hence will take longer than the written time).
91 // Explanation for these values:
93 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
94 // using some histograms data. Trying to be conservative so as not to break
95 // existing setups when deployed. A simple exponential retry scheme would be
96 // more elegant, but places more load on server.
98 // The motivation for trying quickly after failures (8 seconds) is to recover
99 // from spurious network failures, which are common after the IP address has
100 // just changed (like DNS failing to resolve). The next 32 second boundary is
101 // to try and catch other VPN weirdness which anecdotally I have seen take
102 // 10+ seconds for some users.
104 // The motivation for re-trying after a success is to check for possible
105 // content changes to the script, or to the WPAD auto-discovery results. We are
106 // not very aggressive with these checks so as to minimize the risk of
107 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
108 // change very frequently in existing setups. More research is needed to
109 // motivate what safe values are here, and what other user agents do.
111 // Comparison to other browsers:
113 // In Firefox the PAC URL is re-tried on failures according to
114 // network.proxy.autoconfig_retry_interval_min and
115 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
116 // 5 minutes respectively. It doubles the interval at each attempt.
118 // TODO(eroman): Figure out what Internet Explorer does.
119 class DefaultPollPolicy
: public ProxyService::PacPollPolicy
{
121 DefaultPollPolicy() {}
123 Mode
GetNextDelay(int initial_error
,
124 TimeDelta current_delay
,
125 TimeDelta
* next_delay
) const override
{
126 if (initial_error
!= OK
) {
127 // Re-try policy for failures.
128 const int kDelay1Seconds
= 8;
129 const int kDelay2Seconds
= 32;
130 const int kDelay3Seconds
= 2 * 60; // 2 minutes
131 const int kDelay4Seconds
= 4 * 60 * 60; // 4 Hours
134 if (current_delay
< TimeDelta()) {
135 *next_delay
= TimeDelta::FromSeconds(kDelay1Seconds
);
136 return MODE_USE_TIMER
;
138 switch (current_delay
.InSeconds()) {
140 *next_delay
= TimeDelta::FromSeconds(kDelay2Seconds
);
141 return MODE_START_AFTER_ACTIVITY
;
143 *next_delay
= TimeDelta::FromSeconds(kDelay3Seconds
);
144 return MODE_START_AFTER_ACTIVITY
;
146 *next_delay
= TimeDelta::FromSeconds(kDelay4Seconds
);
147 return MODE_START_AFTER_ACTIVITY
;
150 // Re-try policy for succeses.
151 *next_delay
= TimeDelta::FromHours(12);
152 return MODE_START_AFTER_ACTIVITY
;
157 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy
);
160 // Config getter that always returns direct settings.
161 class ProxyConfigServiceDirect
: public ProxyConfigService
{
163 // ProxyConfigService implementation:
164 void AddObserver(Observer
* observer
) override
{}
165 void RemoveObserver(Observer
* observer
) override
{}
166 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
167 *config
= ProxyConfig::CreateDirect();
168 config
->set_source(PROXY_CONFIG_SOURCE_UNKNOWN
);
173 // Proxy resolver that fails every time.
174 class ProxyResolverNull
: public ProxyResolver
{
176 ProxyResolverNull() : ProxyResolver(false /*expects_pac_bytes*/) {}
178 // ProxyResolver implementation.
179 int GetProxyForURL(const GURL
& url
,
181 const CompletionCallback
& callback
,
182 RequestHandle
* request
,
183 const BoundNetLog
& net_log
) override
{
184 return ERR_NOT_IMPLEMENTED
;
187 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
189 LoadState
GetLoadState(RequestHandle request
) const override
{
191 return LOAD_STATE_IDLE
;
194 void CancelSetPacScript() override
{ NOTREACHED(); }
197 const scoped_refptr
<ProxyResolverScriptData
>& /*script_data*/,
198 const CompletionCallback
& /*callback*/) override
{
199 return ERR_NOT_IMPLEMENTED
;
203 // ProxyResolver that simulates a PAC script which returns
204 // |pac_string| for every single URL.
205 class ProxyResolverFromPacString
: public ProxyResolver
{
207 explicit ProxyResolverFromPacString(const std::string
& pac_string
)
208 : ProxyResolver(false /*expects_pac_bytes*/),
209 pac_string_(pac_string
) {}
211 int GetProxyForURL(const GURL
& url
,
213 const CompletionCallback
& callback
,
214 RequestHandle
* request
,
215 const BoundNetLog
& net_log
) override
{
216 results
->UsePacString(pac_string_
);
220 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
222 LoadState
GetLoadState(RequestHandle request
) const override
{
224 return LOAD_STATE_IDLE
;
227 void CancelSetPacScript() override
{ NOTREACHED(); }
229 int SetPacScript(const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
230 const CompletionCallback
& callback
) override
{
235 const std::string pac_string_
;
238 // Creates ProxyResolvers using a platform-specific implementation.
239 class ProxyResolverFactoryForSystem
: public MultiThreadedProxyResolverFactory
{
241 explicit ProxyResolverFactoryForSystem(size_t max_num_threads
)
242 : MultiThreadedProxyResolverFactory(max_num_threads
,
243 false /*expects_pac_bytes*/) {}
245 scoped_ptr
<ProxyResolverFactory
> CreateProxyResolverFactory() override
{
247 return make_scoped_ptr(new ProxyResolverFactoryWinHttp());
248 #elif defined(OS_MACOSX)
249 return make_scoped_ptr(new ProxyResolverFactoryMac());
256 static bool IsSupported() {
257 #if defined(OS_WIN) || defined(OS_MACOSX)
265 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForSystem
);
268 class ProxyResolverFactoryForNullResolver
: public ProxyResolverFactory
{
270 ProxyResolverFactoryForNullResolver() : ProxyResolverFactory(false) {}
272 // ProxyResolverFactory overrides.
273 int CreateProxyResolver(
274 const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
275 scoped_ptr
<ProxyResolver
>* resolver
,
276 const net::CompletionCallback
& callback
,
277 scoped_ptr
<Request
>* request
) override
{
278 resolver
->reset(new ProxyResolverNull());
283 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForNullResolver
);
286 class ProxyResolverFactoryForPacResult
: public ProxyResolverFactory
{
288 explicit ProxyResolverFactoryForPacResult(const std::string
& pac_string
)
289 : ProxyResolverFactory(false), pac_string_(pac_string
) {}
291 // ProxyResolverFactory override.
292 int CreateProxyResolver(
293 const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
294 scoped_ptr
<ProxyResolver
>* resolver
,
295 const net::CompletionCallback
& callback
,
296 scoped_ptr
<Request
>* request
) override
{
297 resolver
->reset(new ProxyResolverFromPacString(pac_string_
));
302 const std::string pac_string_
;
304 DISALLOW_COPY_AND_ASSIGN(ProxyResolverFactoryForPacResult
);
307 // Returns NetLog parameters describing a proxy configuration change.
308 base::Value
* NetLogProxyConfigChangedCallback(
309 const ProxyConfig
* old_config
,
310 const ProxyConfig
* new_config
,
311 NetLogCaptureMode
/* capture_mode */) {
312 base::DictionaryValue
* dict
= new base::DictionaryValue();
313 // The "old_config" is optional -- the first notification will not have
314 // any "previous" configuration.
315 if (old_config
->is_valid())
316 dict
->Set("old_config", old_config
->ToValue());
317 dict
->Set("new_config", new_config
->ToValue());
321 base::Value
* NetLogBadProxyListCallback(const ProxyRetryInfoMap
* retry_info
,
322 NetLogCaptureMode
/* capture_mode */) {
323 base::DictionaryValue
* dict
= new base::DictionaryValue();
324 base::ListValue
* list
= new base::ListValue();
326 for (ProxyRetryInfoMap::const_iterator iter
= retry_info
->begin();
327 iter
!= retry_info
->end(); ++iter
) {
328 list
->Append(new base::StringValue(iter
->first
));
330 dict
->Set("bad_proxy_list", list
);
334 // Returns NetLog parameters on a successfuly proxy resolution.
335 base::Value
* NetLogFinishedResolvingProxyCallback(
336 const ProxyInfo
* result
,
337 NetLogCaptureMode
/* capture_mode */) {
338 base::DictionaryValue
* dict
= new base::DictionaryValue();
339 dict
->SetString("pac_string", result
->ToPacString());
343 #if defined(OS_CHROMEOS)
344 class UnsetProxyConfigService
: public ProxyConfigService
{
346 UnsetProxyConfigService() {}
347 ~UnsetProxyConfigService() override
{}
349 void AddObserver(Observer
* observer
) override
{}
350 void RemoveObserver(Observer
* observer
) override
{}
351 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
359 // ProxyService::InitProxyResolver --------------------------------------------
361 // This glues together two asynchronous steps:
362 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
363 // to figure out what we should configure against.
364 // (2) Feed the fetched PAC script into the ProxyResolver.
366 // InitProxyResolver is a single-use class which encapsulates cancellation as
367 // part of its destructor. Start() or StartSkipDecider() should be called just
368 // once. The instance can be destroyed at any time, and the request will be
371 class ProxyService::InitProxyResolver
{
374 : proxy_resolver_factory_(nullptr),
375 proxy_resolver_(NULL
),
376 next_state_(STATE_NONE
),
377 quick_check_enabled_(true) {}
379 ~InitProxyResolver() {
380 // Note that the destruction of ProxyScriptDecider will automatically cancel
381 // any outstanding work.
384 // Begins initializing the proxy resolver; calls |callback| when done. A
385 // ProxyResolver instance will be created using |proxy_resolver_factory| and
386 // returned via |proxy_resolver| if the final result is OK.
387 int Start(scoped_ptr
<ProxyResolver
>* proxy_resolver
,
388 ProxyResolverFactory
* proxy_resolver_factory
,
389 ProxyScriptFetcher
* proxy_script_fetcher
,
390 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
392 const ProxyConfig
& config
,
393 TimeDelta wait_delay
,
394 const CompletionCallback
& callback
) {
395 DCHECK_EQ(STATE_NONE
, next_state_
);
396 proxy_resolver_
= proxy_resolver
;
397 proxy_resolver_factory_
= proxy_resolver_factory
;
399 decider_
.reset(new ProxyScriptDecider(
400 proxy_script_fetcher
, dhcp_proxy_script_fetcher
, net_log
));
401 decider_
->set_quick_check_enabled(quick_check_enabled_
);
403 wait_delay_
= wait_delay
;
404 callback_
= callback
;
406 next_state_
= STATE_DECIDE_PROXY_SCRIPT
;
410 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
411 // |effective_config|, |decider_result| and |script_data| will be used as the
412 // inputs for initializing the ProxyResolver. A ProxyResolver instance will
413 // be created using |proxy_resolver_factory| and returned via
414 // |proxy_resolver| if the final result is OK.
415 int StartSkipDecider(scoped_ptr
<ProxyResolver
>* proxy_resolver
,
416 ProxyResolverFactory
* proxy_resolver_factory
,
417 const ProxyConfig
& effective_config
,
419 ProxyResolverScriptData
* script_data
,
420 const CompletionCallback
& callback
) {
421 DCHECK_EQ(STATE_NONE
, next_state_
);
422 proxy_resolver_
= proxy_resolver
;
423 proxy_resolver_factory_
= proxy_resolver_factory
;
425 effective_config_
= effective_config
;
426 script_data_
= script_data
;
427 callback_
= callback
;
429 if (decider_result
!= OK
)
430 return decider_result
;
432 next_state_
= STATE_CREATE_RESOLVER
;
436 // Returns the proxy configuration that was selected by ProxyScriptDecider.
437 // Should only be called upon completion of the initialization.
438 const ProxyConfig
& effective_config() const {
439 DCHECK_EQ(STATE_NONE
, next_state_
);
440 return effective_config_
;
443 // Returns the PAC script data that was selected by ProxyScriptDecider.
444 // Should only be called upon completion of the initialization.
445 ProxyResolverScriptData
* script_data() {
446 DCHECK_EQ(STATE_NONE
, next_state_
);
447 return script_data_
.get();
450 LoadState
GetLoadState() const {
451 if (next_state_
== STATE_DECIDE_PROXY_SCRIPT_COMPLETE
) {
452 // In addition to downloading, this state may also include the stall time
453 // after network change events (kDelayAfterNetworkChangesMs).
454 return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT
;
456 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
459 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
460 bool quick_check_enabled() const { return quick_check_enabled_
; }
465 STATE_DECIDE_PROXY_SCRIPT
,
466 STATE_DECIDE_PROXY_SCRIPT_COMPLETE
,
467 STATE_CREATE_RESOLVER
,
468 STATE_CREATE_RESOLVER_COMPLETE
,
471 int DoLoop(int result
) {
472 DCHECK_NE(next_state_
, STATE_NONE
);
475 State state
= next_state_
;
476 next_state_
= STATE_NONE
;
478 case STATE_DECIDE_PROXY_SCRIPT
:
480 rv
= DoDecideProxyScript();
482 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE
:
483 rv
= DoDecideProxyScriptComplete(rv
);
485 case STATE_CREATE_RESOLVER
:
487 rv
= DoCreateResolver();
489 case STATE_CREATE_RESOLVER_COMPLETE
:
490 rv
= DoCreateResolverComplete(rv
);
493 NOTREACHED() << "bad state: " << state
;
497 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
501 int DoDecideProxyScript() {
502 next_state_
= STATE_DECIDE_PROXY_SCRIPT_COMPLETE
;
504 return decider_
->Start(
505 config_
, wait_delay_
, proxy_resolver_factory_
->expects_pac_bytes(),
506 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
509 int DoDecideProxyScriptComplete(int result
) {
513 effective_config_
= decider_
->effective_config();
514 script_data_
= decider_
->script_data();
516 next_state_
= STATE_CREATE_RESOLVER
;
520 int DoCreateResolver() {
521 DCHECK(script_data_
.get());
522 // TODO(eroman): Should log this latency to the NetLog.
523 next_state_
= STATE_CREATE_RESOLVER_COMPLETE
;
524 return proxy_resolver_factory_
->CreateProxyResolver(
525 script_data_
, proxy_resolver_
,
526 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)),
527 &create_resolver_request_
);
530 int DoCreateResolverComplete(int result
) {
532 proxy_resolver_
->reset();
536 void OnIOCompletion(int result
) {
537 DCHECK_NE(STATE_NONE
, next_state_
);
538 int rv
= DoLoop(result
);
539 if (rv
!= ERR_IO_PENDING
)
543 void DoCallback(int result
) {
544 DCHECK_NE(ERR_IO_PENDING
, result
);
545 callback_
.Run(result
);
549 ProxyConfig effective_config_
;
550 scoped_refptr
<ProxyResolverScriptData
> script_data_
;
551 TimeDelta wait_delay_
;
552 scoped_ptr
<ProxyScriptDecider
> decider_
;
553 ProxyResolverFactory
* proxy_resolver_factory_
;
554 scoped_ptr
<ProxyResolverFactory::Request
> create_resolver_request_
;
555 scoped_ptr
<ProxyResolver
>* proxy_resolver_
;
556 CompletionCallback callback_
;
558 bool quick_check_enabled_
;
560 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver
);
563 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
565 // This helper class encapsulates the logic to schedule and run periodic
566 // background checks to see if the PAC script (or effective proxy configuration)
567 // has changed. If a change is detected, then the caller will be notified via
568 // the ChangeCallback.
569 class ProxyService::ProxyScriptDeciderPoller
{
571 typedef base::Callback
<void(int, ProxyResolverScriptData
*,
572 const ProxyConfig
&)> ChangeCallback
;
574 // Builds a poller helper, and starts polling for updates. Whenever a change
575 // is observed, |callback| will be invoked with the details.
577 // |config| specifies the (unresolved) proxy configuration to poll.
578 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
579 // to use the resulting script data with
580 // (so it can choose the right format).
581 // |proxy_script_fetcher| this pointer must remain alive throughout our
582 // lifetime. It is the dependency that will be used
583 // for downloading proxy scripts.
584 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
585 // the DHCP dependency.
586 // |init_net_error| This is the initial network error (possibly success)
587 // encountered by the first PAC fetch attempt. We use it
588 // to schedule updates more aggressively if the initial
589 // fetch resulted in an error.
590 // |init_script_data| the initial script data from the PAC fetch attempt.
591 // This is the baseline used to determine when the
592 // script's contents have changed.
593 // |net_log| the NetLog to log progress into.
594 ProxyScriptDeciderPoller(ChangeCallback callback
,
595 const ProxyConfig
& config
,
596 bool proxy_resolver_expects_pac_bytes
,
597 ProxyScriptFetcher
* proxy_script_fetcher
,
598 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
600 ProxyResolverScriptData
* init_script_data
,
602 : change_callback_(callback
),
604 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes
),
605 proxy_script_fetcher_(proxy_script_fetcher
),
606 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher
),
607 last_error_(init_net_error
),
608 last_script_data_(init_script_data
),
609 last_poll_time_(TimeTicks::Now()),
610 weak_factory_(this) {
611 // Set the initial poll delay.
612 next_poll_mode_
= poll_policy()->GetNextDelay(
613 last_error_
, TimeDelta::FromSeconds(-1), &next_poll_delay_
);
614 TryToStartNextPoll(false);
618 // We have just been notified of network activity. Use this opportunity to
619 // see if we can start our next poll.
620 TryToStartNextPoll(true);
623 static const PacPollPolicy
* set_policy(const PacPollPolicy
* policy
) {
624 const PacPollPolicy
* prev
= poll_policy_
;
625 poll_policy_
= policy
;
629 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
630 bool quick_check_enabled() const { return quick_check_enabled_
; }
633 // Returns the effective poll policy (the one injected by unit-tests, or the
635 const PacPollPolicy
* poll_policy() {
638 return &default_poll_policy_
;
641 void StartPollTimer() {
642 DCHECK(!decider_
.get());
644 base::MessageLoop::current()->PostDelayedTask(
646 base::Bind(&ProxyScriptDeciderPoller::DoPoll
,
647 weak_factory_
.GetWeakPtr()),
651 void TryToStartNextPoll(bool triggered_by_activity
) {
652 switch (next_poll_mode_
) {
653 case PacPollPolicy::MODE_USE_TIMER
:
654 if (!triggered_by_activity
)
658 case PacPollPolicy::MODE_START_AFTER_ACTIVITY
:
659 if (triggered_by_activity
&& !decider_
.get()) {
660 TimeDelta elapsed_time
= TimeTicks::Now() - last_poll_time_
;
661 if (elapsed_time
>= next_poll_delay_
)
669 last_poll_time_
= TimeTicks::Now();
671 // Start the proxy script decider to see if anything has changed.
672 // TODO(eroman): Pass a proper NetLog rather than NULL.
673 decider_
.reset(new ProxyScriptDecider(
674 proxy_script_fetcher_
, dhcp_proxy_script_fetcher_
, NULL
));
675 decider_
->set_quick_check_enabled(quick_check_enabled_
);
676 int result
= decider_
->Start(
677 config_
, TimeDelta(), proxy_resolver_expects_pac_bytes_
,
678 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted
,
679 base::Unretained(this)));
681 if (result
!= ERR_IO_PENDING
)
682 OnProxyScriptDeciderCompleted(result
);
685 void OnProxyScriptDeciderCompleted(int result
) {
686 if (HasScriptDataChanged(result
, decider_
->script_data())) {
687 // Something has changed, we must notify the ProxyService so it can
688 // re-initialize its ProxyResolver. Note that we post a notification task
689 // rather than calling it directly -- this is done to avoid an ugly
690 // destruction sequence, since |this| might be destroyed as a result of
692 base::MessageLoop::current()->PostTask(
694 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange
,
695 weak_factory_
.GetWeakPtr(),
697 make_scoped_refptr(decider_
->script_data()),
698 decider_
->effective_config()));
704 // Decide when the next poll should take place, and possibly start the
706 next_poll_mode_
= poll_policy()->GetNextDelay(
707 last_error_
, next_poll_delay_
, &next_poll_delay_
);
708 TryToStartNextPoll(false);
711 bool HasScriptDataChanged(int result
, ProxyResolverScriptData
* script_data
) {
712 if (result
!= last_error_
) {
713 // Something changed -- it was failing before and now it succeeded, or
714 // conversely it succeeded before and now it failed. Or it failed in
715 // both cases, however the specific failure error codes differ.
720 // If it failed last time and failed again with the same error code this
721 // time, then nothing has actually changed.
725 // Otherwise if it succeeded both this time and last time, we need to look
726 // closer and see if we ended up downloading different content for the PAC
728 return !script_data
->Equals(last_script_data_
.get());
731 void NotifyProxyServiceOfChange(
733 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
734 const ProxyConfig
& effective_config
) {
735 // Note that |this| may be deleted after calling into the ProxyService.
736 change_callback_
.Run(result
, script_data
.get(), effective_config
);
739 ChangeCallback change_callback_
;
741 bool proxy_resolver_expects_pac_bytes_
;
742 ProxyScriptFetcher
* proxy_script_fetcher_
;
743 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher_
;
746 scoped_refptr
<ProxyResolverScriptData
> last_script_data_
;
748 scoped_ptr
<ProxyScriptDecider
> decider_
;
749 TimeDelta next_poll_delay_
;
750 PacPollPolicy::Mode next_poll_mode_
;
752 TimeTicks last_poll_time_
;
754 // Polling policy injected by unit-tests. Otherwise this is NULL and the
755 // default policy will be used.
756 static const PacPollPolicy
* poll_policy_
;
758 const DefaultPollPolicy default_poll_policy_
;
760 bool quick_check_enabled_
;
762 base::WeakPtrFactory
<ProxyScriptDeciderPoller
> weak_factory_
;
764 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller
);
768 const ProxyService::PacPollPolicy
*
769 ProxyService::ProxyScriptDeciderPoller::poll_policy_
= NULL
;
771 // ProxyService::PacRequest ---------------------------------------------------
773 class ProxyService::PacRequest
774 : public base::RefCounted
<ProxyService::PacRequest
> {
776 PacRequest(ProxyService
* service
,
779 NetworkDelegate
* network_delegate
,
781 const CompletionCallback
& user_callback
,
782 const BoundNetLog
& net_log
)
784 user_callback_(user_callback
),
787 load_flags_(load_flags
),
788 network_delegate_(network_delegate
),
790 config_id_(ProxyConfig::kInvalidConfigID
),
791 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN
),
793 creation_time_(TimeTicks::Now()) {
794 DCHECK(!user_callback
.is_null());
797 // Starts the resolve proxy request.
799 DCHECK(!was_cancelled());
800 DCHECK(!is_started());
802 DCHECK(service_
->config_
.is_valid());
804 config_id_
= service_
->config_
.id();
805 config_source_
= service_
->config_
.source();
807 return resolver()->GetProxyForURL(
809 base::Bind(&PacRequest::QueryComplete
, base::Unretained(this)),
810 &resolve_job_
, net_log_
);
813 bool is_started() const {
814 // Note that !! casts to bool. (VS gives a warning otherwise).
815 return !!resolve_job_
;
818 void StartAndCompleteCheckingForSynchronous() {
819 int rv
= service_
->TryToCompleteSynchronously(url_
, load_flags_
,
820 network_delegate_
, results_
);
821 if (rv
== ERR_IO_PENDING
)
823 if (rv
!= ERR_IO_PENDING
)
827 void CancelResolveJob() {
828 DCHECK(is_started());
829 // The request may already be running in the resolver.
830 resolver()->CancelRequest(resolve_job_
);
832 DCHECK(!is_started());
836 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
841 // Mark as cancelled, to prevent accessing this again later.
843 user_callback_
.Reset();
846 net_log_
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
849 // Returns true if Cancel() has been called.
850 bool was_cancelled() const {
851 return user_callback_
.is_null();
854 // Helper to call after ProxyResolver completion (both synchronous and
855 // asynchronous). Fixes up the result that is to be returned to user.
856 int QueryDidComplete(int result_code
) {
857 DCHECK(!was_cancelled());
859 // Clear |resolve_job_| so is_started() returns false while
860 // DidFinishResolvingProxy() runs.
861 resolve_job_
= nullptr;
863 // Note that DidFinishResolvingProxy might modify |results_|.
864 int rv
= service_
->DidFinishResolvingProxy(url_
, load_flags_
,
865 network_delegate_
, results_
,
866 result_code
, net_log_
);
868 // Make a note in the results which configuration was in use at the
869 // time of the resolve.
870 results_
->config_id_
= config_id_
;
871 results_
->config_source_
= config_source_
;
872 results_
->did_use_pac_script_
= true;
873 results_
->proxy_resolve_start_time_
= creation_time_
;
874 results_
->proxy_resolve_end_time_
= TimeTicks::Now();
876 // Reset the state associated with in-progress-resolve.
877 config_id_
= ProxyConfig::kInvalidConfigID
;
878 config_source_
= PROXY_CONFIG_SOURCE_UNKNOWN
;
883 BoundNetLog
* net_log() { return &net_log_
; }
885 LoadState
GetLoadState() const {
887 return resolver()->GetLoadState(resolve_job_
);
888 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
892 friend class base::RefCounted
<ProxyService::PacRequest
>;
896 // Callback for when the ProxyResolver request has completed.
897 void QueryComplete(int result_code
) {
898 result_code
= QueryDidComplete(result_code
);
900 // Remove this completed PacRequest from the service's pending list.
901 /// (which will probably cause deletion of |this|).
902 if (!user_callback_
.is_null()) {
903 CompletionCallback callback
= user_callback_
;
904 service_
->RemovePendingRequest(this);
905 callback
.Run(result_code
);
909 ProxyResolver
* resolver() const { return service_
->resolver_
.get(); }
911 // Note that we don't hold a reference to the ProxyService. Outstanding
912 // requests are cancelled during ~ProxyService, so this is guaranteed
913 // to be valid throughout our lifetime.
914 ProxyService
* service_
;
915 CompletionCallback user_callback_
;
919 NetworkDelegate
* network_delegate_
;
920 ProxyResolver::RequestHandle resolve_job_
;
921 ProxyConfig::ID config_id_
; // The config id when the resolve was started.
922 ProxyConfigSource config_source_
; // The source of proxy settings.
923 BoundNetLog net_log_
;
924 // Time when the request was created. Stored here rather than in |results_|
925 // because the time in |results_| will be cleared.
926 TimeTicks creation_time_
;
929 // ProxyService ---------------------------------------------------------------
931 ProxyService::ProxyService(ProxyConfigService
* config_service
,
932 scoped_ptr
<ProxyResolverFactory
> resolver_factory
,
934 : resolver_factory_(resolver_factory
.Pass()),
936 current_state_(STATE_NONE
),
938 stall_proxy_auto_config_delay_(
939 TimeDelta::FromMilliseconds(kDelayAfterNetworkChangesMs
)),
940 quick_check_enabled_(true) {
941 NetworkChangeNotifier::AddIPAddressObserver(this);
942 NetworkChangeNotifier::AddDNSObserver(this);
943 ResetConfigService(config_service
);
947 ProxyService
* ProxyService::CreateUsingSystemProxyResolver(
948 ProxyConfigService
* proxy_config_service
,
949 size_t num_pac_threads
,
951 DCHECK(proxy_config_service
);
953 if (!ProxyResolverFactoryForSystem::IsSupported()) {
954 VLOG(1) << "PAC support disabled because there is no system implementation";
955 return CreateWithoutProxyResolver(proxy_config_service
, net_log
);
958 if (num_pac_threads
== 0)
959 num_pac_threads
= kDefaultNumPacThreads
;
961 return new ProxyService(
962 proxy_config_service
,
963 make_scoped_ptr(new ProxyResolverFactoryForSystem(num_pac_threads
)),
968 ProxyService
* ProxyService::CreateWithoutProxyResolver(
969 ProxyConfigService
* proxy_config_service
,
971 return new ProxyService(
972 proxy_config_service
,
973 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
977 ProxyService
* ProxyService::CreateFixed(const ProxyConfig
& pc
) {
978 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
980 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc
),
985 ProxyService
* ProxyService::CreateFixed(const std::string
& proxy
) {
986 ProxyConfig proxy_config
;
987 proxy_config
.proxy_rules().ParseFromString(proxy
);
988 return ProxyService::CreateFixed(proxy_config
);
992 ProxyService
* ProxyService::CreateDirect() {
993 return CreateDirectWithNetLog(NULL
);
996 ProxyService
* ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
997 // Use direct connections.
998 return new ProxyService(
999 new ProxyConfigServiceDirect
,
1000 make_scoped_ptr(new ProxyResolverFactoryForNullResolver
), net_log
);
1004 ProxyService
* ProxyService::CreateFixedFromPacResult(
1005 const std::string
& pac_string
) {
1007 // We need the settings to contain an "automatic" setting, otherwise the
1008 // ProxyResolver dependency we give it will never be used.
1009 scoped_ptr
<ProxyConfigService
> proxy_config_service(
1010 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
1012 return new ProxyService(
1013 proxy_config_service
.release(),
1014 make_scoped_ptr(new ProxyResolverFactoryForPacResult(pac_string
)), NULL
);
1017 int ProxyService::ResolveProxy(const GURL
& raw_url
,
1020 const CompletionCallback
& callback
,
1021 PacRequest
** pac_request
,
1022 NetworkDelegate
* network_delegate
,
1023 const BoundNetLog
& net_log
) {
1024 DCHECK(!callback
.is_null());
1025 return ResolveProxyHelper(raw_url
,
1034 int ProxyService::ResolveProxyHelper(const GURL
& raw_url
,
1037 const CompletionCallback
& callback
,
1038 PacRequest
** pac_request
,
1039 NetworkDelegate
* network_delegate
,
1040 const BoundNetLog
& net_log
) {
1041 DCHECK(CalledOnValidThread());
1043 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
1045 // Notify our polling-based dependencies that a resolve is taking place.
1046 // This way they can schedule their polls in response to network activity.
1047 config_service_
->OnLazyPoll();
1048 if (script_poller_
.get())
1049 script_poller_
->OnLazyPoll();
1051 if (current_state_
== STATE_NONE
)
1052 ApplyProxyConfigIfAvailable();
1054 // Strip away any reference fragments and the username/password, as they
1055 // are not relevant to proxy resolution.
1056 GURL url
= SimplifyUrlForRequest(raw_url
);
1058 // Check if the request can be completed right away. (This is the case when
1059 // using a direct connection for example).
1060 int rv
= TryToCompleteSynchronously(url
, load_flags
,
1061 network_delegate
, result
);
1062 if (rv
!= ERR_IO_PENDING
)
1063 return DidFinishResolvingProxy(url
, load_flags
, network_delegate
,
1064 result
, rv
, net_log
);
1066 if (callback
.is_null())
1067 return ERR_IO_PENDING
;
1069 scoped_refptr
<PacRequest
> req(
1070 new PacRequest(this, url
, load_flags
, network_delegate
,
1071 result
, callback
, net_log
));
1073 if (current_state_
== STATE_READY
) {
1074 // Start the resolve request.
1076 if (rv
!= ERR_IO_PENDING
)
1077 return req
->QueryDidComplete(rv
);
1079 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1082 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1083 DCHECK(!ContainsPendingRequest(req
.get()));
1084 pending_requests_
.push_back(req
);
1086 // Completion will be notified through |callback|, unless the caller cancels
1087 // the request using |pac_request|.
1089 *pac_request
= req
.get();
1090 return rv
; // ERR_IO_PENDING
1093 bool ProxyService:: TryResolveProxySynchronously(
1094 const GURL
& raw_url
,
1097 NetworkDelegate
* network_delegate
,
1098 const BoundNetLog
& net_log
) {
1099 CompletionCallback null_callback
;
1100 return ResolveProxyHelper(raw_url
,
1104 NULL
/* pac_request*/,
1109 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1111 NetworkDelegate
* network_delegate
,
1112 ProxyInfo
* result
) {
1113 DCHECK_NE(STATE_NONE
, current_state_
);
1115 if (current_state_
!= STATE_READY
)
1116 return ERR_IO_PENDING
; // Still initializing.
1118 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1120 // If it was impossible to fetch or parse the PAC script, we cannot complete
1121 // the request here and bail out.
1122 if (permanent_error_
!= OK
)
1123 return permanent_error_
;
1125 if (config_
.HasAutomaticSettings())
1126 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1128 // Use the manual proxy settings.
1129 config_
.proxy_rules().Apply(url
, result
);
1130 result
->config_source_
= config_
.source();
1131 result
->config_id_
= config_
.id();
1136 ProxyService::~ProxyService() {
1137 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1138 NetworkChangeNotifier::RemoveDNSObserver(this);
1139 config_service_
->RemoveObserver(this);
1141 // Cancel any inprogress requests.
1142 for (PendingRequests::iterator it
= pending_requests_
.begin();
1143 it
!= pending_requests_
.end();
1149 void ProxyService::SuspendAllPendingRequests() {
1150 for (PendingRequests::iterator it
= pending_requests_
.begin();
1151 it
!= pending_requests_
.end();
1153 PacRequest
* req
= it
->get();
1154 if (req
->is_started()) {
1155 req
->CancelResolveJob();
1157 req
->net_log()->BeginEvent(
1158 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1163 void ProxyService::SetReady() {
1164 DCHECK(!init_proxy_resolver_
.get());
1165 current_state_
= STATE_READY
;
1167 // Make a copy in case |this| is deleted during the synchronous completion
1168 // of one of the requests. If |this| is deleted then all of the PacRequest
1169 // instances will be Cancel()-ed.
1170 PendingRequests pending_copy
= pending_requests_
;
1172 for (PendingRequests::iterator it
= pending_copy
.begin();
1173 it
!= pending_copy
.end();
1175 PacRequest
* req
= it
->get();
1176 if (!req
->is_started() && !req
->was_cancelled()) {
1177 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1179 // Note that we re-check for synchronous completion, in case we are
1180 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1181 req
->StartAndCompleteCheckingForSynchronous();
1186 void ProxyService::ApplyProxyConfigIfAvailable() {
1187 DCHECK_EQ(STATE_NONE
, current_state_
);
1189 config_service_
->OnLazyPoll();
1191 // If we have already fetched the configuration, start applying it.
1192 if (fetched_config_
.is_valid()) {
1193 InitializeUsingLastFetchedConfig();
1197 // Otherwise we need to first fetch the configuration.
1198 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1200 // Retrieve the current proxy configuration from the ProxyConfigService.
1201 // If a configuration is not available yet, we will get called back later
1202 // by our ProxyConfigService::Observer once it changes.
1204 ProxyConfigService::ConfigAvailability availability
=
1205 config_service_
->GetLatestProxyConfig(&config
);
1206 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1207 OnProxyConfigChanged(config
, availability
);
1210 void ProxyService::OnInitProxyResolverComplete(int result
) {
1211 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1212 DCHECK(init_proxy_resolver_
.get());
1213 DCHECK(fetched_config_
.HasAutomaticSettings());
1214 config_
= init_proxy_resolver_
->effective_config();
1216 // At this point we have decided which proxy settings to use (i.e. which PAC
1217 // script if any). We start up a background poller to periodically revisit
1218 // this decision. If the contents of the PAC script change, or if the
1219 // result of proxy auto-discovery changes, this poller will notice it and
1220 // will trigger a re-initialization using the newly discovered PAC.
1221 script_poller_
.reset(new ProxyScriptDeciderPoller(
1222 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1223 base::Unretained(this)),
1224 fetched_config_
, resolver_factory_
->expects_pac_bytes(),
1225 proxy_script_fetcher_
.get(), dhcp_proxy_script_fetcher_
.get(), result
,
1226 init_proxy_resolver_
->script_data(), NULL
));
1227 script_poller_
->set_quick_check_enabled(quick_check_enabled_
);
1229 init_proxy_resolver_
.reset();
1232 if (fetched_config_
.pac_mandatory()) {
1233 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1235 config_
= fetched_config_
;
1236 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1238 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1240 config_
= fetched_config_
;
1241 config_
.ClearAutomaticSettings();
1245 permanent_error_
= result
;
1247 // TODO(eroman): Make this ID unique in the case where configuration changed
1248 // due to ProxyScriptDeciderPoller.
1249 config_
.set_id(fetched_config_
.id());
1250 config_
.set_source(fetched_config_
.source());
1252 // Resume any requests which we had to defer until the PAC script was
1257 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1261 const CompletionCallback
& callback
,
1262 PacRequest
** pac_request
,
1263 NetworkDelegate
* network_delegate
,
1264 const BoundNetLog
& net_log
) {
1265 DCHECK(CalledOnValidThread());
1267 // Check to see if we have a new config since ResolveProxy was called. We
1268 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1269 // direct connection failed and we never tried the current config.
1272 bool re_resolve
= result
->config_id_
!= config_
.id();
1275 // If we have a new config or the config was never tried, we delete the
1276 // list of bad proxies and we try again.
1277 proxy_retry_info_
.clear();
1278 return ResolveProxy(url
, load_flags
, result
, callback
, pac_request
,
1279 network_delegate
, net_log
);
1282 DCHECK(!result
->is_empty());
1283 ProxyServer bad_proxy
= result
->proxy_server();
1285 // We don't have new proxy settings to try, try to fallback to the next proxy
1287 bool did_fallback
= result
->Fallback(net_error
, net_log
);
1289 // Return synchronous failure if there is nothing left to fall-back to.
1290 // TODO(eroman): This is a yucky API, clean it up.
1291 return did_fallback
? OK
: ERR_FAILED
;
1294 bool ProxyService::MarkProxiesAsBadUntil(
1295 const ProxyInfo
& result
,
1296 base::TimeDelta retry_delay
,
1297 const ProxyServer
& another_bad_proxy
,
1298 const BoundNetLog
& net_log
) {
1299 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
,
1305 if (another_bad_proxy
.is_valid())
1306 return result
.proxy_list_
.size() > 2;
1308 return result
.proxy_list_
.size() > 1;
1311 void ProxyService::ReportSuccess(const ProxyInfo
& result
,
1312 NetworkDelegate
* network_delegate
) {
1313 DCHECK(CalledOnValidThread());
1315 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1316 if (new_retry_info
.empty())
1319 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1320 iter
!= new_retry_info
.end(); ++iter
) {
1321 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1322 if (existing
== proxy_retry_info_
.end()) {
1323 proxy_retry_info_
[iter
->first
] = iter
->second
;
1324 if (network_delegate
) {
1325 const ProxyServer
& bad_proxy
=
1326 ProxyServer::FromURI(iter
->first
, ProxyServer::SCHEME_HTTP
);
1327 const ProxyRetryInfo
& proxy_retry_info
= iter
->second
;
1328 network_delegate
->NotifyProxyFallback(bad_proxy
,
1329 proxy_retry_info
.net_error
);
1332 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1333 existing
->second
.bad_until
= iter
->second
.bad_until
;
1336 net_log_
->AddGlobalEntry(
1337 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1338 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1342 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1343 DCHECK(CalledOnValidThread());
1346 RemovePendingRequest(req
);
1349 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1351 if (current_state_
== STATE_WAITING_FOR_INIT_PROXY_RESOLVER
)
1352 return init_proxy_resolver_
->GetLoadState();
1353 return req
->GetLoadState();
1356 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1357 PendingRequests::iterator it
= std::find(
1358 pending_requests_
.begin(), pending_requests_
.end(), req
);
1359 return pending_requests_
.end() != it
;
1362 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1363 DCHECK(ContainsPendingRequest(req
));
1364 PendingRequests::iterator it
= std::find(
1365 pending_requests_
.begin(), pending_requests_
.end(), req
);
1366 pending_requests_
.erase(it
);
1369 int ProxyService::DidFinishResolvingProxy(const GURL
& url
,
1371 NetworkDelegate
* network_delegate
,
1374 const BoundNetLog
& net_log
) {
1375 // Log the result of the proxy resolution.
1376 if (result_code
== OK
) {
1377 // Allow the network delegate to interpose on the resolution decision,
1378 // possibly modifying the ProxyInfo.
1379 if (network_delegate
)
1380 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1382 // When logging all events is enabled, dump the proxy list.
1383 if (net_log
.IsCapturing()) {
1385 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1386 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1388 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1390 net_log
.AddEventWithNetErrorCode(
1391 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1393 bool reset_config
= result_code
== ERR_PAC_SCRIPT_TERMINATED
;
1394 if (!config_
.pac_mandatory()) {
1395 // Fall-back to direct when the proxy resolver fails. This corresponds
1396 // with a javascript runtime error in the PAC script.
1398 // This implicit fall-back to direct matches Firefox 3.5 and
1399 // Internet Explorer 8. For more information, see:
1401 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1402 result
->UseDirect();
1405 // Allow the network delegate to interpose on the resolution decision,
1406 // possibly modifying the ProxyInfo.
1407 if (network_delegate
)
1408 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1410 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1413 ResetProxyConfig(false);
1414 // If the ProxyResolver crashed, force it to be re-initialized for the
1415 // next request by resetting the proxy config. If there are other pending
1416 // requests, trigger the recreation immediately so those requests retry.
1417 if (pending_requests_
.size() > 1)
1418 ApplyProxyConfigIfAvailable();
1422 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1426 void ProxyService::SetProxyScriptFetchers(
1427 ProxyScriptFetcher
* proxy_script_fetcher
,
1428 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
) {
1429 DCHECK(CalledOnValidThread());
1430 State previous_state
= ResetProxyConfig(false);
1431 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1432 dhcp_proxy_script_fetcher_
.reset(dhcp_proxy_script_fetcher
);
1433 if (previous_state
!= STATE_NONE
)
1434 ApplyProxyConfigIfAvailable();
1437 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1438 DCHECK(CalledOnValidThread());
1439 return proxy_script_fetcher_
.get();
1442 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1443 DCHECK(CalledOnValidThread());
1444 State previous_state
= current_state_
;
1446 permanent_error_
= OK
;
1447 proxy_retry_info_
.clear();
1448 script_poller_
.reset();
1449 init_proxy_resolver_
.reset();
1450 SuspendAllPendingRequests();
1452 config_
= ProxyConfig();
1453 if (reset_fetched_config
)
1454 fetched_config_
= ProxyConfig();
1455 current_state_
= STATE_NONE
;
1457 return previous_state
;
1460 void ProxyService::ResetConfigService(
1461 ProxyConfigService
* new_proxy_config_service
) {
1462 DCHECK(CalledOnValidThread());
1463 State previous_state
= ResetProxyConfig(true);
1465 // Release the old configuration service.
1466 if (config_service_
.get())
1467 config_service_
->RemoveObserver(this);
1469 // Set the new configuration service.
1470 config_service_
.reset(new_proxy_config_service
);
1471 config_service_
->AddObserver(this);
1473 if (previous_state
!= STATE_NONE
)
1474 ApplyProxyConfigIfAvailable();
1477 void ProxyService::ForceReloadProxyConfig() {
1478 DCHECK(CalledOnValidThread());
1479 ResetProxyConfig(false);
1480 ApplyProxyConfigIfAvailable();
1484 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1485 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
1486 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_task_runner
) {
1488 return new ProxyConfigServiceWin();
1489 #elif defined(OS_IOS)
1490 return new ProxyConfigServiceIOS();
1491 #elif defined(OS_MACOSX)
1492 return new ProxyConfigServiceMac(io_task_runner
);
1493 #elif defined(OS_CHROMEOS)
1494 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1495 << "profile_io_data.cc::CreateProxyConfigService and this should "
1496 << "be used only for examples.";
1497 return new UnsetProxyConfigService
;
1498 #elif defined(OS_LINUX)
1499 ProxyConfigServiceLinux
* linux_config_service
=
1500 new ProxyConfigServiceLinux();
1502 // Assume we got called on the thread that runs the default glib
1503 // main loop, so the current thread is where we should be running
1504 // gconf calls from.
1505 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1506 base::ThreadTaskRunnerHandle::Get();
1508 // Synchronously fetch the current proxy config (since we are running on
1509 // glib_default_loop). Additionally register for notifications (delivered in
1510 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1511 // the proxy config changes.
1512 linux_config_service
->SetupAndFetchInitialConfig(
1513 glib_thread_task_runner
, io_task_runner
, file_task_runner
);
1515 return linux_config_service
;
1516 #elif defined(OS_ANDROID)
1517 return new ProxyConfigServiceAndroid(
1518 io_task_runner
, base::MessageLoop::current()->message_loop_proxy());
1520 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1521 "for this platform.";
1522 return new ProxyConfigServiceDirect();
1527 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1528 const PacPollPolicy
* policy
) {
1529 return ProxyScriptDeciderPoller::set_policy(policy
);
1533 scoped_ptr
<ProxyService::PacPollPolicy
>
1534 ProxyService::CreateDefaultPacPollPolicy() {
1535 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1538 void ProxyService::OnProxyConfigChanged(
1539 const ProxyConfig
& config
,
1540 ProxyConfigService::ConfigAvailability availability
) {
1541 // Retrieve the current proxy configuration from the ProxyConfigService.
1542 // If a configuration is not available yet, we will get called back later
1543 // by our ProxyConfigService::Observer once it changes.
1544 ProxyConfig effective_config
;
1545 switch (availability
) {
1546 case ProxyConfigService::CONFIG_PENDING
:
1547 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1548 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1550 case ProxyConfigService::CONFIG_VALID
:
1551 effective_config
= config
;
1553 case ProxyConfigService::CONFIG_UNSET
:
1554 effective_config
= ProxyConfig::CreateDirect();
1558 // Emit the proxy settings change to the NetLog stream.
1560 net_log_
->AddGlobalEntry(NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1561 base::Bind(&NetLogProxyConfigChangedCallback
,
1562 &fetched_config_
, &effective_config
));
1565 // Set the new configuration as the most recently fetched one.
1566 fetched_config_
= effective_config
;
1567 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1569 InitializeUsingLastFetchedConfig();
1572 void ProxyService::InitializeUsingLastFetchedConfig() {
1573 ResetProxyConfig(false);
1575 DCHECK(fetched_config_
.is_valid());
1577 // Increment the ID to reflect that the config has changed.
1578 fetched_config_
.set_id(next_config_id_
++);
1580 if (!fetched_config_
.HasAutomaticSettings()) {
1581 config_
= fetched_config_
;
1586 // Start downloading + testing the PAC scripts for this new configuration.
1587 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1589 // If we changed networks recently, we should delay running proxy auto-config.
1590 TimeDelta wait_delay
=
1591 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1593 init_proxy_resolver_
.reset(new InitProxyResolver());
1594 init_proxy_resolver_
->set_quick_check_enabled(quick_check_enabled_
);
1595 int rv
= init_proxy_resolver_
->Start(
1596 &resolver_
, resolver_factory_
.get(), proxy_script_fetcher_
.get(),
1597 dhcp_proxy_script_fetcher_
.get(), net_log_
, fetched_config_
, wait_delay
,
1598 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1599 base::Unretained(this)));
1601 if (rv
!= ERR_IO_PENDING
)
1602 OnInitProxyResolverComplete(rv
);
1605 void ProxyService::InitializeUsingDecidedConfig(
1607 ProxyResolverScriptData
* script_data
,
1608 const ProxyConfig
& effective_config
) {
1609 DCHECK(fetched_config_
.is_valid());
1610 DCHECK(fetched_config_
.HasAutomaticSettings());
1612 ResetProxyConfig(false);
1614 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1616 init_proxy_resolver_
.reset(new InitProxyResolver());
1617 int rv
= init_proxy_resolver_
->StartSkipDecider(
1618 &resolver_
, resolver_factory_
.get(), effective_config
, decider_result
,
1619 script_data
, base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1620 base::Unretained(this)));
1622 if (rv
!= ERR_IO_PENDING
)
1623 OnInitProxyResolverComplete(rv
);
1626 void ProxyService::OnIPAddressChanged() {
1627 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1628 stall_proxy_autoconfig_until_
=
1629 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1631 State previous_state
= ResetProxyConfig(false);
1632 if (previous_state
!= STATE_NONE
)
1633 ApplyProxyConfigIfAvailable();
1636 void ProxyService::OnDNSChanged() {
1637 OnIPAddressChanged();