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.h"
15 #include "base/message_loop_proxy.h"
16 #include "base/string_util.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/values.h"
19 #include "googleurl/src/gurl.h"
20 #include "net/base/completion_callback.h"
21 #include "net/base/net_errors.h"
22 #include "net/base/net_log.h"
23 #include "net/base/net_util.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_script_decider.h"
30 #include "net/proxy/proxy_script_fetcher.h"
31 #include "net/proxy/sync_host_resolver_bridge.h"
32 #include "net/url_request/url_request_context.h"
35 #include "net/proxy/proxy_config_service_win.h"
36 #include "net/proxy/proxy_resolver_winhttp.h"
38 #include "net/proxy/proxy_config_service_ios.h"
39 #include "net/proxy/proxy_resolver_mac.h"
40 #elif defined(OS_MACOSX)
41 #include "net/proxy/proxy_config_service_mac.h"
42 #include "net/proxy/proxy_resolver_mac.h"
43 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
44 #include "net/proxy/proxy_config_service_linux.h"
45 #elif defined(OS_ANDROID)
46 #include "net/proxy/proxy_config_service_android.h"
49 using base::TimeDelta
;
50 using base::TimeTicks
;
56 const size_t kMaxNumNetLogEntries
= 100;
58 // When the IP address changes we don't immediately re-run proxy auto-config.
59 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
60 // attempting to re-valuate proxy auto-config.
62 // During this time window, any resolve requests sent to the ProxyService will
63 // be queued. Once we have waited the required amount of them, the proxy
64 // auto-config step will be run, and the queued requests resumed.
66 // The reason we play this game is that our signal for detecting network
67 // changes (NetworkChangeNotifier) may fire *before* the system's networking
68 // dependencies are fully configured. This is a problem since it means if
69 // we were to run proxy auto-config right away, it could fail due to spurious
70 // DNS failures. (see http://crbug.com/50779 for more details.)
72 // By adding the wait window, we give things a better chance to get properly
73 // set up. Network failures can happen at any time though, so we additionally
74 // poll the PAC script for changes, which will allow us to recover from these
76 const int64 kDelayAfterNetworkChangesMs
= 2000;
78 // This is the default policy for polling the PAC script.
80 // In response to a failure, the poll intervals are:
81 // 0: 8 seconds (scheduled on timer)
86 // In response to a success, the poll intervals are:
89 // Only the 8 second poll is scheduled on a timer, the rest happen in response
90 // to network activity (and hence will take longer than the written time).
92 // Explanation for these values:
94 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
95 // using some histograms data. Trying to be conservative so as not to break
96 // existing setups when deployed. A simple exponential retry scheme would be
97 // more elegant, but places more load on server.
99 // The motivation for trying quickly after failures (8 seconds) is to recover
100 // from spurious network failures, which are common after the IP address has
101 // just changed (like DNS failing to resolve). The next 32 second boundary is
102 // to try and catch other VPN weirdness which anecdotally I have seen take
103 // 10+ seconds for some users.
105 // The motivation for re-trying after a success is to check for possible
106 // content changes to the script, or to the WPAD auto-discovery results. We are
107 // not very aggressive with these checks so as to minimize the risk of
108 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
109 // change very frequently in existing setups. More research is needed to
110 // motivate what safe values are here, and what other user agents do.
112 // Comparison to other browsers:
114 // In Firefox the PAC URL is re-tried on failures according to
115 // network.proxy.autoconfig_retry_interval_min and
116 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
117 // 5 minutes respectively. It doubles the interval at each attempt.
119 // TODO(eroman): Figure out what Internet Explorer does.
120 class DefaultPollPolicy
: public ProxyService::PacPollPolicy
{
122 DefaultPollPolicy() {}
124 virtual Mode
GetNextDelay(int initial_error
,
125 TimeDelta current_delay
,
126 TimeDelta
* next_delay
) const OVERRIDE
{
127 if (initial_error
!= OK
) {
128 // Re-try policy for failures.
129 const int kDelay1Seconds
= 8;
130 const int kDelay2Seconds
= 32;
131 const int kDelay3Seconds
= 2 * 60; // 2 minutes
132 const int kDelay4Seconds
= 4 * 60 * 60; // 4 Hours
135 if (current_delay
< TimeDelta()) {
136 *next_delay
= TimeDelta::FromSeconds(kDelay1Seconds
);
137 return MODE_USE_TIMER
;
139 switch (current_delay
.InSeconds()) {
141 *next_delay
= TimeDelta::FromSeconds(kDelay2Seconds
);
142 return MODE_START_AFTER_ACTIVITY
;
144 *next_delay
= TimeDelta::FromSeconds(kDelay3Seconds
);
145 return MODE_START_AFTER_ACTIVITY
;
147 *next_delay
= TimeDelta::FromSeconds(kDelay4Seconds
);
148 return MODE_START_AFTER_ACTIVITY
;
151 // Re-try policy for succeses.
152 *next_delay
= TimeDelta::FromHours(12);
153 return MODE_START_AFTER_ACTIVITY
;
158 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy
);
161 // Config getter that always returns direct settings.
162 class ProxyConfigServiceDirect
: public ProxyConfigService
{
164 // ProxyConfigService implementation:
165 virtual void AddObserver(Observer
* observer
) OVERRIDE
{}
166 virtual void RemoveObserver(Observer
* observer
) OVERRIDE
{}
167 virtual ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
)
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() : ProxyResolver(false /*expects_pac_bytes*/) {}
180 // ProxyResolver implementation.
181 virtual int GetProxyForURL(const GURL
& url
,
183 const CompletionCallback
& callback
,
184 RequestHandle
* request
,
185 const BoundNetLog
& net_log
) OVERRIDE
{
186 return ERR_NOT_IMPLEMENTED
;
189 virtual void CancelRequest(RequestHandle request
) OVERRIDE
{
193 virtual LoadState
GetLoadState(RequestHandle request
) const OVERRIDE
{
195 return LOAD_STATE_IDLE
;
198 virtual LoadState
GetLoadStateThreadSafe(
199 RequestHandle request
) const OVERRIDE
{
201 return LOAD_STATE_IDLE
;
204 virtual void CancelSetPacScript() OVERRIDE
{
208 virtual int SetPacScript(
209 const scoped_refptr
<ProxyResolverScriptData
>& /*script_data*/,
210 const CompletionCallback
& /*callback*/) OVERRIDE
{
211 return ERR_NOT_IMPLEMENTED
;
215 // ProxyResolver that simulates a PAC script which returns
216 // |pac_string| for every single URL.
217 class ProxyResolverFromPacString
: public ProxyResolver
{
219 ProxyResolverFromPacString(const std::string
& pac_string
)
220 : ProxyResolver(false /*expects_pac_bytes*/),
221 pac_string_(pac_string
) {}
223 virtual int GetProxyForURL(const GURL
& url
,
225 const CompletionCallback
& callback
,
226 RequestHandle
* request
,
227 const BoundNetLog
& net_log
) OVERRIDE
{
228 results
->UsePacString(pac_string_
);
232 virtual void CancelRequest(RequestHandle request
) OVERRIDE
{
236 virtual LoadState
GetLoadState(RequestHandle request
) const OVERRIDE
{
238 return LOAD_STATE_IDLE
;
241 virtual LoadState
GetLoadStateThreadSafe(
242 RequestHandle request
) const OVERRIDE
{
244 return LOAD_STATE_IDLE
;
247 virtual void CancelSetPacScript() OVERRIDE
{
251 virtual int SetPacScript(
252 const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
253 const CompletionCallback
& callback
) OVERRIDE
{
258 const std::string pac_string_
;
261 // Creates ProxyResolvers using a platform-specific implementation.
262 class ProxyResolverFactoryForSystem
: public ProxyResolverFactory
{
264 ProxyResolverFactoryForSystem()
265 : ProxyResolverFactory(false /*expects_pac_bytes*/) {}
267 virtual ProxyResolver
* CreateProxyResolver() OVERRIDE
{
268 DCHECK(IsSupported());
270 return new ProxyResolverWinHttp();
271 #elif defined(OS_MACOSX)
272 return new ProxyResolverMac();
279 static bool IsSupported() {
280 #if defined(OS_WIN) || defined(OS_MACOSX)
288 // Returns NetLog parameters describing a proxy configuration change.
289 Value
* NetLogProxyConfigChangedCallback(const ProxyConfig
* old_config
,
290 const ProxyConfig
* new_config
,
291 NetLog::LogLevel
/* log_level */) {
292 DictionaryValue
* dict
= new DictionaryValue();
293 // The "old_config" is optional -- the first notification will not have
294 // any "previous" configuration.
295 if (old_config
->is_valid())
296 dict
->Set("old_config", old_config
->ToValue());
297 dict
->Set("new_config", new_config
->ToValue());
301 Value
* NetLogBadProxyListCallback(const ProxyRetryInfoMap
* retry_info
,
302 NetLog::LogLevel
/* log_level */) {
303 DictionaryValue
* dict
= new DictionaryValue();
304 ListValue
* list
= new ListValue();
306 for (ProxyRetryInfoMap::const_iterator iter
= retry_info
->begin();
307 iter
!= retry_info
->end(); ++iter
) {
308 list
->Append(Value::CreateStringValue(iter
->first
));
310 dict
->Set("bad_proxy_list", list
);
314 // Returns NetLog parameters on a successfuly proxy resolution.
315 Value
* NetLogFinishedResolvingProxyCallback(ProxyInfo
* result
,
316 NetLog::LogLevel
/* log_level */) {
317 DictionaryValue
* dict
= new DictionaryValue();
318 dict
->SetString("pac_string", result
->ToPacString());
322 #if defined(OS_CHROMEOS)
323 class UnsetProxyConfigService
: public ProxyConfigService
{
325 UnsetProxyConfigService() {}
326 virtual ~UnsetProxyConfigService() {}
328 virtual void AddObserver(Observer
* observer
) OVERRIDE
{}
329 virtual void RemoveObserver(Observer
* observer
) OVERRIDE
{}
330 virtual ConfigAvailability
GetLatestProxyConfig(
331 ProxyConfig
* config
) OVERRIDE
{
339 // ProxyService::InitProxyResolver --------------------------------------------
341 // This glues together two asynchronous steps:
342 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
343 // to figure out what we should configure against.
344 // (2) Feed the fetched PAC script into the ProxyResolver.
346 // InitProxyResolver is a single-use class which encapsulates cancellation as
347 // part of its destructor. Start() or StartSkipDecider() should be called just
348 // once. The instance can be destroyed at any time, and the request will be
351 class ProxyService::InitProxyResolver
{
354 : proxy_resolver_(NULL
),
355 next_state_(STATE_NONE
) {
358 ~InitProxyResolver() {
359 // Note that the destruction of ProxyScriptDecider will automatically cancel
360 // any outstanding work.
361 if (next_state_
== STATE_SET_PAC_SCRIPT_COMPLETE
) {
362 proxy_resolver_
->CancelSetPacScript();
366 // Begins initializing the proxy resolver; calls |callback| when done.
367 int Start(ProxyResolver
* proxy_resolver
,
368 ProxyScriptFetcher
* proxy_script_fetcher
,
369 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
371 const ProxyConfig
& config
,
372 TimeDelta wait_delay
,
373 const CompletionCallback
& callback
) {
374 DCHECK_EQ(STATE_NONE
, next_state_
);
375 proxy_resolver_
= proxy_resolver
;
377 decider_
.reset(new ProxyScriptDecider(
378 proxy_script_fetcher
, dhcp_proxy_script_fetcher
, net_log
));
380 wait_delay_
= wait_delay
;
381 callback_
= callback
;
383 next_state_
= STATE_DECIDE_PROXY_SCRIPT
;
387 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
388 // |effective_config|, |decider_result| and |script_data| will be used as the
389 // inputs for initializing the ProxyResolver.
390 int StartSkipDecider(ProxyResolver
* proxy_resolver
,
391 const ProxyConfig
& effective_config
,
393 ProxyResolverScriptData
* script_data
,
394 const CompletionCallback
& callback
) {
395 DCHECK_EQ(STATE_NONE
, next_state_
);
396 proxy_resolver_
= proxy_resolver
;
398 effective_config_
= effective_config
;
399 script_data_
= script_data
;
400 callback_
= callback
;
402 if (decider_result
!= OK
)
403 return decider_result
;
405 next_state_
= STATE_SET_PAC_SCRIPT
;
409 // Returns the proxy configuration that was selected by ProxyScriptDecider.
410 // Should only be called upon completion of the initialization.
411 const ProxyConfig
& effective_config() const {
412 DCHECK_EQ(STATE_NONE
, next_state_
);
413 return effective_config_
;
416 // Returns the PAC script data that was selected by ProxyScriptDecider.
417 // Should only be called upon completion of the initialization.
418 ProxyResolverScriptData
* script_data() {
419 DCHECK_EQ(STATE_NONE
, next_state_
);
420 return script_data_
.get();
426 STATE_DECIDE_PROXY_SCRIPT
,
427 STATE_DECIDE_PROXY_SCRIPT_COMPLETE
,
428 STATE_SET_PAC_SCRIPT
,
429 STATE_SET_PAC_SCRIPT_COMPLETE
,
432 int DoLoop(int result
) {
433 DCHECK_NE(next_state_
, STATE_NONE
);
436 State state
= next_state_
;
437 next_state_
= STATE_NONE
;
439 case STATE_DECIDE_PROXY_SCRIPT
:
441 rv
= DoDecideProxyScript();
443 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE
:
444 rv
= DoDecideProxyScriptComplete(rv
);
446 case STATE_SET_PAC_SCRIPT
:
448 rv
= DoSetPacScript();
450 case STATE_SET_PAC_SCRIPT_COMPLETE
:
451 rv
= DoSetPacScriptComplete(rv
);
454 NOTREACHED() << "bad state: " << state
;
458 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
462 int DoDecideProxyScript() {
463 next_state_
= STATE_DECIDE_PROXY_SCRIPT_COMPLETE
;
465 return decider_
->Start(
466 config_
, wait_delay_
, proxy_resolver_
->expects_pac_bytes(),
467 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
470 int DoDecideProxyScriptComplete(int result
) {
474 effective_config_
= decider_
->effective_config();
475 script_data_
= decider_
->script_data();
477 next_state_
= STATE_SET_PAC_SCRIPT
;
481 int DoSetPacScript() {
482 DCHECK(script_data_
);
483 // TODO(eroman): Should log this latency to the NetLog.
484 next_state_
= STATE_SET_PAC_SCRIPT_COMPLETE
;
485 return proxy_resolver_
->SetPacScript(
487 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
490 int DoSetPacScriptComplete(int result
) {
494 void OnIOCompletion(int result
) {
495 DCHECK_NE(STATE_NONE
, next_state_
);
496 int rv
= DoLoop(result
);
497 if (rv
!= ERR_IO_PENDING
)
501 void DoCallback(int result
) {
502 DCHECK_NE(ERR_IO_PENDING
, result
);
503 callback_
.Run(result
);
507 ProxyConfig effective_config_
;
508 scoped_refptr
<ProxyResolverScriptData
> script_data_
;
509 TimeDelta wait_delay_
;
510 scoped_ptr
<ProxyScriptDecider
> decider_
;
511 ProxyResolver
* proxy_resolver_
;
512 CompletionCallback callback_
;
515 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver
);
518 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
520 // This helper class encapsulates the logic to schedule and run periodic
521 // background checks to see if the PAC script (or effective proxy configuration)
522 // has changed. If a change is detected, then the caller will be notified via
523 // the ChangeCallback.
524 class ProxyService::ProxyScriptDeciderPoller
{
526 typedef base::Callback
<void(int, ProxyResolverScriptData
*,
527 const ProxyConfig
&)> ChangeCallback
;
529 // Builds a poller helper, and starts polling for updates. Whenever a change
530 // is observed, |callback| will be invoked with the details.
532 // |config| specifies the (unresolved) proxy configuration to poll.
533 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
534 // to use the resulting script data with
535 // (so it can choose the right format).
536 // |proxy_script_fetcher| this pointer must remain alive throughout our
537 // lifetime. It is the dependency that will be used
538 // for downloading proxy scripts.
539 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
540 // the DHCP dependency.
541 // |init_net_error| This is the initial network error (possibly success)
542 // encountered by the first PAC fetch attempt. We use it
543 // to schedule updates more aggressively if the initial
544 // fetch resulted in an error.
545 // |init_script_data| the initial script data from the PAC fetch attempt.
546 // This is the baseline used to determine when the
547 // script's contents have changed.
548 // |net_log| the NetLog to log progress into.
549 ProxyScriptDeciderPoller(ChangeCallback callback
,
550 const ProxyConfig
& config
,
551 bool proxy_resolver_expects_pac_bytes
,
552 ProxyScriptFetcher
* proxy_script_fetcher
,
553 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
555 ProxyResolverScriptData
* init_script_data
,
557 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
558 change_callback_(callback
),
560 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes
),
561 proxy_script_fetcher_(proxy_script_fetcher
),
562 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher
),
563 last_error_(init_net_error
),
564 last_script_data_(init_script_data
),
565 last_poll_time_(TimeTicks::Now()) {
566 // Set the initial poll delay.
567 next_poll_mode_
= poll_policy()->GetNextDelay(
568 last_error_
, TimeDelta::FromSeconds(-1), &next_poll_delay_
);
569 TryToStartNextPoll(false);
573 // We have just been notified of network activity. Use this opportunity to
574 // see if we can start our next poll.
575 TryToStartNextPoll(true);
578 static const PacPollPolicy
* set_policy(const PacPollPolicy
* policy
) {
579 const PacPollPolicy
* prev
= poll_policy_
;
580 poll_policy_
= policy
;
585 // Returns the effective poll policy (the one injected by unit-tests, or the
587 const PacPollPolicy
* poll_policy() {
590 return &default_poll_policy_
;
593 void StartPollTimer() {
594 DCHECK(!decider_
.get());
596 MessageLoop::current()->PostDelayedTask(
598 base::Bind(&ProxyScriptDeciderPoller::DoPoll
,
599 weak_factory_
.GetWeakPtr()),
603 void TryToStartNextPoll(bool triggered_by_activity
) {
604 switch (next_poll_mode_
) {
605 case PacPollPolicy::MODE_USE_TIMER
:
606 if (!triggered_by_activity
)
610 case PacPollPolicy::MODE_START_AFTER_ACTIVITY
:
611 if (triggered_by_activity
&& !decider_
.get()) {
612 TimeDelta elapsed_time
= TimeTicks::Now() - last_poll_time_
;
613 if (elapsed_time
>= next_poll_delay_
)
621 last_poll_time_
= TimeTicks::Now();
623 // Start the proxy script decider to see if anything has changed.
624 // TODO(eroman): Pass a proper NetLog rather than NULL.
625 decider_
.reset(new ProxyScriptDecider(
626 proxy_script_fetcher_
, dhcp_proxy_script_fetcher_
, NULL
));
627 int result
= decider_
->Start(
628 config_
, TimeDelta(), proxy_resolver_expects_pac_bytes_
,
629 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted
,
630 base::Unretained(this)));
632 if (result
!= ERR_IO_PENDING
)
633 OnProxyScriptDeciderCompleted(result
);
636 void OnProxyScriptDeciderCompleted(int result
) {
637 if (HasScriptDataChanged(result
, decider_
->script_data())) {
638 // Something has changed, we must notify the ProxyService so it can
639 // re-initialize its ProxyResolver. Note that we post a notification task
640 // rather than calling it directly -- this is done to avoid an ugly
641 // destruction sequence, since |this| might be destroyed as a result of
643 MessageLoop::current()->PostTask(
646 &ProxyScriptDeciderPoller::NotifyProxyServiceOfChange
,
647 weak_factory_
.GetWeakPtr(),
649 make_scoped_refptr(decider_
->script_data()),
650 decider_
->effective_config()));
656 // Decide when the next poll should take place, and possibly start the
658 next_poll_mode_
= poll_policy()->GetNextDelay(
659 last_error_
, next_poll_delay_
, &next_poll_delay_
);
660 TryToStartNextPoll(false);
663 bool HasScriptDataChanged(int result
, ProxyResolverScriptData
* script_data
) {
664 if (result
!= last_error_
) {
665 // Something changed -- it was failing before and now it succeeded, or
666 // conversely it succeeded before and now it failed. Or it failed in
667 // both cases, however the specific failure error codes differ.
672 // If it failed last time and failed again with the same error code this
673 // time, then nothing has actually changed.
677 // Otherwise if it succeeded both this time and last time, we need to look
678 // closer and see if we ended up downloading different content for the PAC
680 return !script_data
->Equals(last_script_data_
);
683 void NotifyProxyServiceOfChange(
685 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
686 const ProxyConfig
& effective_config
) {
687 // Note that |this| may be deleted after calling into the ProxyService.
688 change_callback_
.Run(result
, script_data
, effective_config
);
691 base::WeakPtrFactory
<ProxyScriptDeciderPoller
> weak_factory_
;
693 ChangeCallback change_callback_
;
695 bool proxy_resolver_expects_pac_bytes_
;
696 ProxyScriptFetcher
* proxy_script_fetcher_
;
697 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher_
;
700 scoped_refptr
<ProxyResolverScriptData
> last_script_data_
;
702 scoped_ptr
<ProxyScriptDecider
> decider_
;
703 TimeDelta next_poll_delay_
;
704 PacPollPolicy::Mode next_poll_mode_
;
706 TimeTicks last_poll_time_
;
708 // Polling policy injected by unit-tests. Otherwise this is NULL and the
709 // default policy will be used.
710 static const PacPollPolicy
* poll_policy_
;
712 const DefaultPollPolicy default_poll_policy_
;
714 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller
);
718 const ProxyService::PacPollPolicy
*
719 ProxyService::ProxyScriptDeciderPoller::poll_policy_
= NULL
;
721 // ProxyService::PacRequest ---------------------------------------------------
723 class ProxyService::PacRequest
724 : public base::RefCounted
<ProxyService::PacRequest
> {
726 PacRequest(ProxyService
* service
,
729 const net::CompletionCallback
& user_callback
,
730 const BoundNetLog
& net_log
)
732 user_callback_(user_callback
),
736 config_id_(ProxyConfig::kInvalidConfigID
),
737 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN
),
739 DCHECK(!user_callback
.is_null());
742 // Starts the resolve proxy request.
744 DCHECK(!was_cancelled());
745 DCHECK(!is_started());
747 DCHECK(service_
->config_
.is_valid());
749 config_id_
= service_
->config_
.id();
750 config_source_
= service_
->config_
.source();
752 return resolver()->GetProxyForURL(
754 base::Bind(&PacRequest::QueryComplete
, base::Unretained(this)),
755 &resolve_job_
, net_log_
);
758 bool is_started() const {
759 // Note that !! casts to bool. (VS gives a warning otherwise).
760 return !!resolve_job_
;
763 void StartAndCompleteCheckingForSynchronous() {
764 int rv
= service_
->TryToCompleteSynchronously(url_
, results_
);
765 if (rv
== ERR_IO_PENDING
)
767 if (rv
!= ERR_IO_PENDING
)
771 void CancelResolveJob() {
772 DCHECK(is_started());
773 // The request may already be running in the resolver.
774 resolver()->CancelRequest(resolve_job_
);
776 DCHECK(!is_started());
780 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
785 // Mark as cancelled, to prevent accessing this again later.
787 user_callback_
.Reset();
790 net_log_
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
793 // Returns true if Cancel() has been called.
794 bool was_cancelled() const {
795 return user_callback_
.is_null();
798 // Helper to call after ProxyResolver completion (both synchronous and
799 // asynchronous). Fixes up the result that is to be returned to user.
800 int QueryDidComplete(int result_code
) {
801 DCHECK(!was_cancelled());
803 // Note that DidFinishResolvingProxy might modify |results_|.
804 int rv
= service_
->DidFinishResolvingProxy(results_
, result_code
, net_log_
);
806 // Make a note in the results which configuration was in use at the
807 // time of the resolve.
808 results_
->config_id_
= config_id_
;
809 results_
->config_source_
= config_source_
;
810 results_
->did_use_pac_script_
= true;
812 // Reset the state associated with in-progress-resolve.
814 config_id_
= ProxyConfig::kInvalidConfigID
;
815 config_source_
= PROXY_CONFIG_SOURCE_UNKNOWN
;
820 BoundNetLog
* net_log() { return &net_log_
; }
822 LoadState
GetLoadState() const {
824 return resolver()->GetLoadState(resolve_job_
);
825 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
829 friend class base::RefCounted
<ProxyService::PacRequest
>;
833 // Callback for when the ProxyResolver request has completed.
834 void QueryComplete(int result_code
) {
835 result_code
= QueryDidComplete(result_code
);
837 // Remove this completed PacRequest from the service's pending list.
838 /// (which will probably cause deletion of |this|).
839 if (!user_callback_
.is_null()){
840 net::CompletionCallback callback
= user_callback_
;
841 service_
->RemovePendingRequest(this);
842 callback
.Run(result_code
);
846 ProxyResolver
* resolver() const { return service_
->resolver_
.get(); }
848 // Note that we don't hold a reference to the ProxyService. Outstanding
849 // requests are cancelled during ~ProxyService, so this is guaranteed
850 // to be valid throughout our lifetime.
851 ProxyService
* service_
;
852 net::CompletionCallback user_callback_
;
855 ProxyResolver::RequestHandle resolve_job_
;
856 ProxyConfig::ID config_id_
; // The config id when the resolve was started.
857 ProxyConfigSource config_source_
; // The source of proxy settings.
858 BoundNetLog net_log_
;
861 // ProxyService ---------------------------------------------------------------
863 ProxyService::ProxyService(ProxyConfigService
* config_service
,
864 ProxyResolver
* resolver
,
866 : resolver_(resolver
),
868 current_state_(STATE_NONE
) ,
870 stall_proxy_auto_config_delay_(TimeDelta::FromMilliseconds(
871 kDelayAfterNetworkChangesMs
)) {
872 NetworkChangeNotifier::AddIPAddressObserver(this);
873 NetworkChangeNotifier::AddDNSObserver(this);
874 ResetConfigService(config_service
);
878 ProxyService
* ProxyService::CreateUsingSystemProxyResolver(
879 ProxyConfigService
* proxy_config_service
,
880 size_t num_pac_threads
,
882 DCHECK(proxy_config_service
);
884 if (!ProxyResolverFactoryForSystem::IsSupported()) {
885 LOG(WARNING
) << "PAC support disabled because there is no "
886 "system implementation";
887 return CreateWithoutProxyResolver(proxy_config_service
, net_log
);
890 if (num_pac_threads
== 0)
891 num_pac_threads
= kDefaultNumPacThreads
;
893 ProxyResolver
* proxy_resolver
= new MultiThreadedProxyResolver(
894 new ProxyResolverFactoryForSystem(), num_pac_threads
);
896 return new ProxyService(proxy_config_service
, proxy_resolver
, net_log
);
900 ProxyService
* ProxyService::CreateWithoutProxyResolver(
901 ProxyConfigService
* proxy_config_service
,
903 return new ProxyService(proxy_config_service
,
904 new ProxyResolverNull(),
909 ProxyService
* ProxyService::CreateFixed(const ProxyConfig
& pc
) {
910 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
912 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc
),
917 ProxyService
* ProxyService::CreateFixed(const std::string
& proxy
) {
918 net::ProxyConfig proxy_config
;
919 proxy_config
.proxy_rules().ParseFromString(proxy
);
920 return ProxyService::CreateFixed(proxy_config
);
924 ProxyService
* ProxyService::CreateDirect() {
925 return CreateDirectWithNetLog(NULL
);
928 ProxyService
* ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
929 // Use direct connections.
930 return new ProxyService(new ProxyConfigServiceDirect
, new ProxyResolverNull
,
935 ProxyService
* ProxyService::CreateFixedFromPacResult(
936 const std::string
& pac_string
) {
938 // We need the settings to contain an "automatic" setting, otherwise the
939 // ProxyResolver dependency we give it will never be used.
940 scoped_ptr
<ProxyConfigService
> proxy_config_service(
941 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
943 scoped_ptr
<ProxyResolver
> proxy_resolver(
944 new ProxyResolverFromPacString(pac_string
));
946 return new ProxyService(proxy_config_service
.release(),
947 proxy_resolver
.release(),
951 int ProxyService::ResolveProxy(const GURL
& raw_url
,
953 const net::CompletionCallback
& callback
,
954 PacRequest
** pac_request
,
955 const BoundNetLog
& net_log
) {
956 DCHECK(CalledOnValidThread());
957 DCHECK(!callback
.is_null());
959 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
961 // Notify our polling-based dependencies that a resolve is taking place.
962 // This way they can schedule their polls in response to network activity.
963 config_service_
->OnLazyPoll();
964 if (script_poller_
.get())
965 script_poller_
->OnLazyPoll();
967 if (current_state_
== STATE_NONE
)
968 ApplyProxyConfigIfAvailable();
970 // Strip away any reference fragments and the username/password, as they
971 // are not relevant to proxy resolution.
972 GURL url
= SimplifyUrlForRequest(raw_url
);
974 // Check if the request can be completed right away. (This is the case when
975 // using a direct connection for example).
976 int rv
= TryToCompleteSynchronously(url
, result
);
977 if (rv
!= ERR_IO_PENDING
)
978 return DidFinishResolvingProxy(result
, rv
, net_log
);
980 scoped_refptr
<PacRequest
> req(
981 new PacRequest(this, url
, result
, callback
, net_log
));
983 if (current_state_
== STATE_READY
) {
984 // Start the resolve request.
986 if (rv
!= ERR_IO_PENDING
)
987 return req
->QueryDidComplete(rv
);
989 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
992 DCHECK_EQ(ERR_IO_PENDING
, rv
);
993 DCHECK(!ContainsPendingRequest(req
));
994 pending_requests_
.push_back(req
);
996 // Completion will be notified through |callback|, unless the caller cancels
997 // the request using |pac_request|.
999 *pac_request
= req
.get();
1000 return rv
; // ERR_IO_PENDING
1003 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1004 ProxyInfo
* result
) {
1005 DCHECK_NE(STATE_NONE
, current_state_
);
1007 if (current_state_
!= STATE_READY
)
1008 return ERR_IO_PENDING
; // Still initializing.
1010 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1012 // If it was impossible to fetch or parse the PAC script, we cannot complete
1013 // the request here and bail out.
1014 if (permanent_error_
!= OK
)
1015 return permanent_error_
;
1017 if (config_
.HasAutomaticSettings())
1018 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1020 // Use the manual proxy settings.
1021 config_
.proxy_rules().Apply(url
, result
);
1022 result
->config_source_
= config_
.source();
1023 result
->config_id_
= config_
.id();
1027 ProxyService::~ProxyService() {
1028 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1029 NetworkChangeNotifier::RemoveDNSObserver(this);
1030 config_service_
->RemoveObserver(this);
1032 // Cancel any inprogress requests.
1033 for (PendingRequests::iterator it
= pending_requests_
.begin();
1034 it
!= pending_requests_
.end();
1040 void ProxyService::SuspendAllPendingRequests() {
1041 for (PendingRequests::iterator it
= pending_requests_
.begin();
1042 it
!= pending_requests_
.end();
1044 PacRequest
* req
= it
->get();
1045 if (req
->is_started()) {
1046 req
->CancelResolveJob();
1048 req
->net_log()->BeginEvent(
1049 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1054 void ProxyService::SetReady() {
1055 DCHECK(!init_proxy_resolver_
.get());
1056 current_state_
= STATE_READY
;
1058 // Make a copy in case |this| is deleted during the synchronous completion
1059 // of one of the requests. If |this| is deleted then all of the PacRequest
1060 // instances will be Cancel()-ed.
1061 PendingRequests pending_copy
= pending_requests_
;
1063 for (PendingRequests::iterator it
= pending_copy
.begin();
1064 it
!= pending_copy
.end();
1066 PacRequest
* req
= it
->get();
1067 if (!req
->is_started() && !req
->was_cancelled()) {
1068 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1070 // Note that we re-check for synchronous completion, in case we are
1071 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1072 req
->StartAndCompleteCheckingForSynchronous();
1077 void ProxyService::ApplyProxyConfigIfAvailable() {
1078 DCHECK_EQ(STATE_NONE
, current_state_
);
1080 config_service_
->OnLazyPoll();
1082 // If we have already fetched the configuration, start applying it.
1083 if (fetched_config_
.is_valid()) {
1084 InitializeUsingLastFetchedConfig();
1088 // Otherwise we need to first fetch the configuration.
1089 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1091 // Retrieve the current proxy configuration from the ProxyConfigService.
1092 // If a configuration is not available yet, we will get called back later
1093 // by our ProxyConfigService::Observer once it changes.
1095 ProxyConfigService::ConfigAvailability availability
=
1096 config_service_
->GetLatestProxyConfig(&config
);
1097 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1098 OnProxyConfigChanged(config
, availability
);
1101 void ProxyService::OnInitProxyResolverComplete(int result
) {
1102 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1103 DCHECK(init_proxy_resolver_
.get());
1104 DCHECK(fetched_config_
.HasAutomaticSettings());
1105 config_
= init_proxy_resolver_
->effective_config();
1107 // At this point we have decided which proxy settings to use (i.e. which PAC
1108 // script if any). We start up a background poller to periodically revisit
1109 // this decision. If the contents of the PAC script change, or if the
1110 // result of proxy auto-discovery changes, this poller will notice it and
1111 // will trigger a re-initialization using the newly discovered PAC.
1112 script_poller_
.reset(new ProxyScriptDeciderPoller(
1113 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1114 base::Unretained(this)),
1116 resolver_
->expects_pac_bytes(),
1117 proxy_script_fetcher_
.get(),
1118 dhcp_proxy_script_fetcher_
.get(),
1120 init_proxy_resolver_
->script_data(),
1123 init_proxy_resolver_
.reset();
1126 if (fetched_config_
.pac_mandatory()) {
1127 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1129 config_
= fetched_config_
;
1130 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1132 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1134 config_
= fetched_config_
;
1135 config_
.ClearAutomaticSettings();
1139 permanent_error_
= result
;
1141 // TODO(eroman): Make this ID unique in the case where configuration changed
1142 // due to ProxyScriptDeciderPoller.
1143 config_
.set_id(fetched_config_
.id());
1144 config_
.set_source(fetched_config_
.source());
1146 // Resume any requests which we had to defer until the PAC script was
1151 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1153 const CompletionCallback
& callback
,
1154 PacRequest
** pac_request
,
1155 const BoundNetLog
& net_log
) {
1156 DCHECK(CalledOnValidThread());
1158 // Check to see if we have a new config since ResolveProxy was called. We
1159 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1160 // direct connection failed and we never tried the current config.
1162 bool re_resolve
= result
->config_id_
!= config_
.id();
1165 // If we have a new config or the config was never tried, we delete the
1166 // list of bad proxies and we try again.
1167 proxy_retry_info_
.clear();
1168 return ResolveProxy(url
, result
, callback
, pac_request
, net_log
);
1171 // We don't have new proxy settings to try, try to fallback to the next proxy
1173 bool did_fallback
= result
->Fallback(net_log
);
1175 // Return synchronous failure if there is nothing left to fall-back to.
1176 // TODO(eroman): This is a yucky API, clean it up.
1177 return did_fallback
? OK
: ERR_FAILED
;
1180 bool ProxyService::MarkProxyAsBad(const ProxyInfo
& result
,
1181 const BoundNetLog
& net_log
) {
1182 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
, net_log
);
1183 return result
.proxy_list_
.HasUntriedProxies(proxy_retry_info_
);
1186 void ProxyService::ReportSuccess(const ProxyInfo
& result
) {
1187 DCHECK(CalledOnValidThread());
1189 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1190 if (new_retry_info
.empty())
1193 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1194 iter
!= new_retry_info
.end(); ++iter
) {
1195 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1196 if (existing
== proxy_retry_info_
.end())
1197 proxy_retry_info_
[iter
->first
] = iter
->second
;
1198 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1199 existing
->second
.bad_until
= iter
->second
.bad_until
;
1202 net_log_
->AddGlobalEntry(
1203 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1204 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1208 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1209 DCHECK(CalledOnValidThread());
1212 RemovePendingRequest(req
);
1215 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1217 return req
->GetLoadState();
1220 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1221 PendingRequests::iterator it
= std::find(
1222 pending_requests_
.begin(), pending_requests_
.end(), req
);
1223 return pending_requests_
.end() != it
;
1226 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1227 DCHECK(ContainsPendingRequest(req
));
1228 PendingRequests::iterator it
= std::find(
1229 pending_requests_
.begin(), pending_requests_
.end(), req
);
1230 pending_requests_
.erase(it
);
1233 int ProxyService::DidFinishResolvingProxy(ProxyInfo
* result
,
1235 const BoundNetLog
& net_log
) {
1236 // Log the result of the proxy resolution.
1237 if (result_code
== OK
) {
1238 // When logging all events is enabled, dump the proxy list.
1239 if (net_log
.IsLoggingAllEvents()) {
1241 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1242 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1244 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1246 net_log
.AddEventWithNetErrorCode(
1247 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1249 if (!config_
.pac_mandatory()) {
1250 // Fall-back to direct when the proxy resolver fails. This corresponds
1251 // with a javascript runtime error in the PAC script.
1253 // This implicit fall-back to direct matches Firefox 3.5 and
1254 // Internet Explorer 8. For more information, see:
1256 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1257 result
->UseDirect();
1260 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1264 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1268 void ProxyService::SetProxyScriptFetchers(
1269 ProxyScriptFetcher
* proxy_script_fetcher
,
1270 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
) {
1271 DCHECK(CalledOnValidThread());
1272 State previous_state
= ResetProxyConfig(false);
1273 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1274 dhcp_proxy_script_fetcher_
.reset(dhcp_proxy_script_fetcher
);
1275 if (previous_state
!= STATE_NONE
)
1276 ApplyProxyConfigIfAvailable();
1279 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1280 DCHECK(CalledOnValidThread());
1281 return proxy_script_fetcher_
.get();
1284 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1285 DCHECK(CalledOnValidThread());
1286 State previous_state
= current_state_
;
1288 permanent_error_
= OK
;
1289 proxy_retry_info_
.clear();
1290 script_poller_
.reset();
1291 init_proxy_resolver_
.reset();
1292 SuspendAllPendingRequests();
1293 config_
= ProxyConfig();
1294 if (reset_fetched_config
)
1295 fetched_config_
= ProxyConfig();
1296 current_state_
= STATE_NONE
;
1298 return previous_state
;
1301 void ProxyService::ResetConfigService(
1302 ProxyConfigService
* new_proxy_config_service
) {
1303 DCHECK(CalledOnValidThread());
1304 State previous_state
= ResetProxyConfig(true);
1306 // Release the old configuration service.
1307 if (config_service_
.get())
1308 config_service_
->RemoveObserver(this);
1310 // Set the new configuration service.
1311 config_service_
.reset(new_proxy_config_service
);
1312 config_service_
->AddObserver(this);
1314 if (previous_state
!= STATE_NONE
)
1315 ApplyProxyConfigIfAvailable();
1318 void ProxyService::PurgeMemory() {
1319 DCHECK(CalledOnValidThread());
1320 if (resolver_
.get())
1321 resolver_
->PurgeMemory();
1324 void ProxyService::ForceReloadProxyConfig() {
1325 DCHECK(CalledOnValidThread());
1326 ResetProxyConfig(false);
1327 ApplyProxyConfigIfAvailable();
1331 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1332 base::SingleThreadTaskRunner
* io_thread_task_runner
,
1333 MessageLoop
* file_loop
) {
1335 return new ProxyConfigServiceWin();
1336 #elif defined(OS_IOS)
1337 return new ProxyConfigServiceIOS();
1338 #elif defined(OS_MACOSX)
1339 return new ProxyConfigServiceMac(io_thread_task_runner
);
1340 #elif defined(OS_CHROMEOS)
1341 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1342 << "profile_io_data.cc::CreateProxyConfigService and this should "
1343 << "be used only for examples.";
1344 return new UnsetProxyConfigService
;
1345 #elif defined(OS_LINUX)
1346 ProxyConfigServiceLinux
* linux_config_service
=
1347 new ProxyConfigServiceLinux();
1349 // Assume we got called on the thread that runs the default glib
1350 // main loop, so the current thread is where we should be running
1351 // gconf calls from.
1352 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1353 base::ThreadTaskRunnerHandle::Get();
1355 // The file loop should be a MessageLoopForIO on Linux.
1356 DCHECK_EQ(MessageLoop::TYPE_IO
, file_loop
->type());
1358 // Synchronously fetch the current proxy config (since we are
1359 // running on glib_default_loop). Additionally register for
1360 // notifications (delivered in either |glib_default_loop| or
1361 // |file_loop|) to keep us updated when the proxy config changes.
1362 linux_config_service
->SetupAndFetchInitialConfig(
1363 glib_thread_task_runner
, io_thread_task_runner
,
1364 static_cast<MessageLoopForIO
*>(file_loop
));
1366 return linux_config_service
;
1367 #elif defined(OS_ANDROID)
1368 return new ProxyConfigServiceAndroid(
1369 io_thread_task_runner
,
1370 MessageLoop::current()->message_loop_proxy());
1372 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1373 "for this platform.";
1374 return new ProxyConfigServiceDirect();
1379 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1380 const PacPollPolicy
* policy
) {
1381 return ProxyScriptDeciderPoller::set_policy(policy
);
1385 scoped_ptr
<ProxyService::PacPollPolicy
>
1386 ProxyService::CreateDefaultPacPollPolicy() {
1387 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1390 void ProxyService::OnProxyConfigChanged(
1391 const ProxyConfig
& config
,
1392 ProxyConfigService::ConfigAvailability availability
) {
1393 // Retrieve the current proxy configuration from the ProxyConfigService.
1394 // If a configuration is not available yet, we will get called back later
1395 // by our ProxyConfigService::Observer once it changes.
1396 ProxyConfig effective_config
;
1397 switch (availability
) {
1398 case ProxyConfigService::CONFIG_PENDING
:
1399 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1400 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1402 case ProxyConfigService::CONFIG_VALID
:
1403 effective_config
= config
;
1405 case ProxyConfigService::CONFIG_UNSET
:
1406 effective_config
= ProxyConfig::CreateDirect();
1410 // Emit the proxy settings change to the NetLog stream.
1412 net_log_
->AddGlobalEntry(
1413 net::NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1414 base::Bind(&NetLogProxyConfigChangedCallback
,
1415 &fetched_config_
, &effective_config
));
1418 // Set the new configuration as the most recently fetched one.
1419 fetched_config_
= effective_config
;
1420 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1422 InitializeUsingLastFetchedConfig();
1425 void ProxyService::InitializeUsingLastFetchedConfig() {
1426 ResetProxyConfig(false);
1428 DCHECK(fetched_config_
.is_valid());
1430 // Increment the ID to reflect that the config has changed.
1431 fetched_config_
.set_id(next_config_id_
++);
1433 if (!fetched_config_
.HasAutomaticSettings()) {
1434 config_
= fetched_config_
;
1439 // Start downloading + testing the PAC scripts for this new configuration.
1440 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1442 // If we changed networks recently, we should delay running proxy auto-config.
1443 TimeDelta wait_delay
=
1444 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1446 init_proxy_resolver_
.reset(new InitProxyResolver());
1447 int rv
= init_proxy_resolver_
->Start(
1449 proxy_script_fetcher_
.get(),
1450 dhcp_proxy_script_fetcher_
.get(),
1454 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1455 base::Unretained(this)));
1457 if (rv
!= ERR_IO_PENDING
)
1458 OnInitProxyResolverComplete(rv
);
1461 void ProxyService::InitializeUsingDecidedConfig(
1463 ProxyResolverScriptData
* script_data
,
1464 const ProxyConfig
& effective_config
) {
1465 DCHECK(fetched_config_
.is_valid());
1466 DCHECK(fetched_config_
.HasAutomaticSettings());
1468 ResetProxyConfig(false);
1470 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1472 init_proxy_resolver_
.reset(new InitProxyResolver());
1473 int rv
= init_proxy_resolver_
->StartSkipDecider(
1478 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1479 base::Unretained(this)));
1481 if (rv
!= ERR_IO_PENDING
)
1482 OnInitProxyResolverComplete(rv
);
1485 void ProxyService::OnIPAddressChanged() {
1486 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1487 stall_proxy_autoconfig_until_
=
1488 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1490 State previous_state
= ResetProxyConfig(false);
1491 if (previous_state
!= STATE_NONE
)
1492 ApplyProxyConfigIfAvailable();
1495 void ProxyService::OnDNSChanged() {
1496 OnIPAddressChanged();
1499 SyncProxyServiceHelper::SyncProxyServiceHelper(MessageLoop
* io_message_loop
,
1500 ProxyService
* proxy_service
)
1501 : io_message_loop_(io_message_loop
),
1502 proxy_service_(proxy_service
),
1503 event_(false, false),
1504 ALLOW_THIS_IN_INITIALIZER_LIST(callback_(
1505 base::Bind(&SyncProxyServiceHelper::OnCompletion
,
1506 base::Unretained(this)))) {
1507 DCHECK(io_message_loop_
!= MessageLoop::current());
1510 int SyncProxyServiceHelper::ResolveProxy(const GURL
& url
,
1511 ProxyInfo
* proxy_info
,
1512 const BoundNetLog
& net_log
) {
1513 DCHECK(io_message_loop_
!= MessageLoop::current());
1515 io_message_loop_
->PostTask(
1517 base::Bind(&SyncProxyServiceHelper::StartAsyncResolve
, this, url
,
1522 if (result_
== net::OK
) {
1523 *proxy_info
= proxy_info_
;
1528 int SyncProxyServiceHelper::ReconsiderProxyAfterError(
1529 const GURL
& url
, ProxyInfo
* proxy_info
, const BoundNetLog
& net_log
) {
1530 DCHECK(io_message_loop_
!= MessageLoop::current());
1532 io_message_loop_
->PostTask(
1534 base::Bind(&SyncProxyServiceHelper::StartAsyncReconsider
, this, url
,
1539 if (result_
== net::OK
) {
1540 *proxy_info
= proxy_info_
;
1545 SyncProxyServiceHelper::~SyncProxyServiceHelper() {}
1547 void SyncProxyServiceHelper::StartAsyncResolve(const GURL
& url
,
1548 const BoundNetLog
& net_log
) {
1549 result_
= proxy_service_
->ResolveProxy(
1550 url
, &proxy_info_
, callback_
, NULL
, net_log
);
1551 if (result_
!= net::ERR_IO_PENDING
) {
1552 OnCompletion(result_
);
1556 void SyncProxyServiceHelper::StartAsyncReconsider(const GURL
& url
,
1557 const BoundNetLog
& net_log
) {
1558 result_
= proxy_service_
->ReconsiderProxyAfterError(
1559 url
, &proxy_info_
, callback_
, NULL
, net_log
);
1560 if (result_
!= net::ERR_IO_PENDING
) {
1561 OnCompletion(result_
);
1565 void SyncProxyServiceHelper::OnCompletion(int rv
) {