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_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/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 // When the IP address changes we don't immediately re-run proxy auto-config.
57 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
58 // attempting to re-valuate proxy auto-config.
60 // During this time window, any resolve requests sent to the ProxyService will
61 // be queued. Once we have waited the required amount of them, the proxy
62 // auto-config step will be run, and the queued requests resumed.
64 // The reason we play this game is that our signal for detecting network
65 // changes (NetworkChangeNotifier) may fire *before* the system's networking
66 // dependencies are fully configured. This is a problem since it means if
67 // we were to run proxy auto-config right away, it could fail due to spurious
68 // DNS failures. (see http://crbug.com/50779 for more details.)
70 // By adding the wait window, we give things a better chance to get properly
71 // set up. Network failures can happen at any time though, so we additionally
72 // poll the PAC script for changes, which will allow us to recover from these
74 const int64 kDelayAfterNetworkChangesMs
= 2000;
76 // This is the default policy for polling the PAC script.
78 // In response to a failure, the poll intervals are:
79 // 0: 8 seconds (scheduled on timer)
84 // In response to a success, the poll intervals are:
87 // Only the 8 second poll is scheduled on a timer, the rest happen in response
88 // to network activity (and hence will take longer than the written time).
90 // Explanation for these values:
92 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
93 // using some histograms data. Trying to be conservative so as not to break
94 // existing setups when deployed. A simple exponential retry scheme would be
95 // more elegant, but places more load on server.
97 // The motivation for trying quickly after failures (8 seconds) is to recover
98 // from spurious network failures, which are common after the IP address has
99 // just changed (like DNS failing to resolve). The next 32 second boundary is
100 // to try and catch other VPN weirdness which anecdotally I have seen take
101 // 10+ seconds for some users.
103 // The motivation for re-trying after a success is to check for possible
104 // content changes to the script, or to the WPAD auto-discovery results. We are
105 // not very aggressive with these checks so as to minimize the risk of
106 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
107 // change very frequently in existing setups. More research is needed to
108 // motivate what safe values are here, and what other user agents do.
110 // Comparison to other browsers:
112 // In Firefox the PAC URL is re-tried on failures according to
113 // network.proxy.autoconfig_retry_interval_min and
114 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
115 // 5 minutes respectively. It doubles the interval at each attempt.
117 // TODO(eroman): Figure out what Internet Explorer does.
118 class DefaultPollPolicy
: public ProxyService::PacPollPolicy
{
120 DefaultPollPolicy() {}
122 Mode
GetNextDelay(int initial_error
,
123 TimeDelta current_delay
,
124 TimeDelta
* next_delay
) const override
{
125 if (initial_error
!= OK
) {
126 // Re-try policy for failures.
127 const int kDelay1Seconds
= 8;
128 const int kDelay2Seconds
= 32;
129 const int kDelay3Seconds
= 2 * 60; // 2 minutes
130 const int kDelay4Seconds
= 4 * 60 * 60; // 4 Hours
133 if (current_delay
< TimeDelta()) {
134 *next_delay
= TimeDelta::FromSeconds(kDelay1Seconds
);
135 return MODE_USE_TIMER
;
137 switch (current_delay
.InSeconds()) {
139 *next_delay
= TimeDelta::FromSeconds(kDelay2Seconds
);
140 return MODE_START_AFTER_ACTIVITY
;
142 *next_delay
= TimeDelta::FromSeconds(kDelay3Seconds
);
143 return MODE_START_AFTER_ACTIVITY
;
145 *next_delay
= TimeDelta::FromSeconds(kDelay4Seconds
);
146 return MODE_START_AFTER_ACTIVITY
;
149 // Re-try policy for succeses.
150 *next_delay
= TimeDelta::FromHours(12);
151 return MODE_START_AFTER_ACTIVITY
;
156 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy
);
159 // Config getter that always returns direct settings.
160 class ProxyConfigServiceDirect
: public ProxyConfigService
{
162 // ProxyConfigService implementation:
163 void AddObserver(Observer
* observer
) override
{}
164 void RemoveObserver(Observer
* observer
) override
{}
165 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
166 *config
= ProxyConfig::CreateDirect();
167 config
->set_source(PROXY_CONFIG_SOURCE_UNKNOWN
);
172 // Proxy resolver that fails every time.
173 class ProxyResolverNull
: public ProxyResolver
{
175 ProxyResolverNull() : ProxyResolver(false /*expects_pac_bytes*/) {}
177 // ProxyResolver implementation.
178 int GetProxyForURL(const GURL
& url
,
180 const CompletionCallback
& callback
,
181 RequestHandle
* request
,
182 const BoundNetLog
& net_log
) override
{
183 return ERR_NOT_IMPLEMENTED
;
186 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
188 LoadState
GetLoadState(RequestHandle request
) const override
{
190 return LOAD_STATE_IDLE
;
193 void CancelSetPacScript() override
{ NOTREACHED(); }
196 const scoped_refptr
<ProxyResolverScriptData
>& /*script_data*/,
197 const CompletionCallback
& /*callback*/) override
{
198 return ERR_NOT_IMPLEMENTED
;
202 // ProxyResolver that simulates a PAC script which returns
203 // |pac_string| for every single URL.
204 class ProxyResolverFromPacString
: public ProxyResolver
{
206 explicit ProxyResolverFromPacString(const std::string
& pac_string
)
207 : ProxyResolver(false /*expects_pac_bytes*/),
208 pac_string_(pac_string
) {}
210 int GetProxyForURL(const GURL
& url
,
212 const CompletionCallback
& callback
,
213 RequestHandle
* request
,
214 const BoundNetLog
& net_log
) override
{
215 results
->UsePacString(pac_string_
);
219 void CancelRequest(RequestHandle request
) override
{ NOTREACHED(); }
221 LoadState
GetLoadState(RequestHandle request
) const override
{
223 return LOAD_STATE_IDLE
;
226 void CancelSetPacScript() override
{ NOTREACHED(); }
228 int SetPacScript(const scoped_refptr
<ProxyResolverScriptData
>& pac_script
,
229 const CompletionCallback
& callback
) override
{
234 const std::string pac_string_
;
237 // Creates ProxyResolvers using a platform-specific implementation.
238 class ProxyResolverFactoryForSystem
: public ProxyResolverFactory
{
240 ProxyResolverFactoryForSystem()
241 : ProxyResolverFactory(false /*expects_pac_bytes*/) {}
243 ProxyResolver
* CreateProxyResolver() override
{
244 DCHECK(IsSupported());
246 return new ProxyResolverWinHttp();
247 #elif defined(OS_MACOSX)
248 return new ProxyResolverMac();
255 static bool IsSupported() {
256 #if defined(OS_WIN) || defined(OS_MACOSX)
264 // Returns NetLog parameters describing a proxy configuration change.
265 base::Value
* NetLogProxyConfigChangedCallback(
266 const ProxyConfig
* old_config
,
267 const ProxyConfig
* new_config
,
268 NetLog::LogLevel
/* log_level */) {
269 base::DictionaryValue
* dict
= new base::DictionaryValue();
270 // The "old_config" is optional -- the first notification will not have
271 // any "previous" configuration.
272 if (old_config
->is_valid())
273 dict
->Set("old_config", old_config
->ToValue());
274 dict
->Set("new_config", new_config
->ToValue());
278 base::Value
* NetLogBadProxyListCallback(const ProxyRetryInfoMap
* retry_info
,
279 NetLog::LogLevel
/* log_level */) {
280 base::DictionaryValue
* dict
= new base::DictionaryValue();
281 base::ListValue
* list
= new base::ListValue();
283 for (ProxyRetryInfoMap::const_iterator iter
= retry_info
->begin();
284 iter
!= retry_info
->end(); ++iter
) {
285 list
->Append(new base::StringValue(iter
->first
));
287 dict
->Set("bad_proxy_list", list
);
291 // Returns NetLog parameters on a successfuly proxy resolution.
292 base::Value
* NetLogFinishedResolvingProxyCallback(
293 const ProxyInfo
* result
,
294 NetLog::LogLevel
/* log_level */) {
295 base::DictionaryValue
* dict
= new base::DictionaryValue();
296 dict
->SetString("pac_string", result
->ToPacString());
300 #if defined(OS_CHROMEOS)
301 class UnsetProxyConfigService
: public ProxyConfigService
{
303 UnsetProxyConfigService() {}
304 ~UnsetProxyConfigService() override
{}
306 void AddObserver(Observer
* observer
) override
{}
307 void RemoveObserver(Observer
* observer
) override
{}
308 ConfigAvailability
GetLatestProxyConfig(ProxyConfig
* config
) override
{
316 // ProxyService::InitProxyResolver --------------------------------------------
318 // This glues together two asynchronous steps:
319 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
320 // to figure out what we should configure against.
321 // (2) Feed the fetched PAC script into the ProxyResolver.
323 // InitProxyResolver is a single-use class which encapsulates cancellation as
324 // part of its destructor. Start() or StartSkipDecider() should be called just
325 // once. The instance can be destroyed at any time, and the request will be
328 class ProxyService::InitProxyResolver
{
331 : proxy_resolver_(NULL
),
332 next_state_(STATE_NONE
),
333 quick_check_enabled_(true) {
336 ~InitProxyResolver() {
337 // Note that the destruction of ProxyScriptDecider will automatically cancel
338 // any outstanding work.
339 if (next_state_
== STATE_SET_PAC_SCRIPT_COMPLETE
) {
340 proxy_resolver_
->CancelSetPacScript();
344 // Begins initializing the proxy resolver; calls |callback| when done.
345 int Start(ProxyResolver
* proxy_resolver
,
346 ProxyScriptFetcher
* proxy_script_fetcher
,
347 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
349 const ProxyConfig
& config
,
350 TimeDelta wait_delay
,
351 const CompletionCallback
& callback
) {
352 DCHECK_EQ(STATE_NONE
, next_state_
);
353 proxy_resolver_
= proxy_resolver
;
355 decider_
.reset(new ProxyScriptDecider(
356 proxy_script_fetcher
, dhcp_proxy_script_fetcher
, net_log
));
357 decider_
->set_quick_check_enabled(quick_check_enabled_
);
359 wait_delay_
= wait_delay
;
360 callback_
= callback
;
362 next_state_
= STATE_DECIDE_PROXY_SCRIPT
;
366 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
367 // |effective_config|, |decider_result| and |script_data| will be used as the
368 // inputs for initializing the ProxyResolver.
369 int StartSkipDecider(ProxyResolver
* proxy_resolver
,
370 const ProxyConfig
& effective_config
,
372 ProxyResolverScriptData
* script_data
,
373 const CompletionCallback
& callback
) {
374 DCHECK_EQ(STATE_NONE
, next_state_
);
375 proxy_resolver_
= proxy_resolver
;
377 effective_config_
= effective_config
;
378 script_data_
= script_data
;
379 callback_
= callback
;
381 if (decider_result
!= OK
)
382 return decider_result
;
384 next_state_
= STATE_SET_PAC_SCRIPT
;
388 // Returns the proxy configuration that was selected by ProxyScriptDecider.
389 // Should only be called upon completion of the initialization.
390 const ProxyConfig
& effective_config() const {
391 DCHECK_EQ(STATE_NONE
, next_state_
);
392 return effective_config_
;
395 // Returns the PAC script data that was selected by ProxyScriptDecider.
396 // Should only be called upon completion of the initialization.
397 ProxyResolverScriptData
* script_data() {
398 DCHECK_EQ(STATE_NONE
, next_state_
);
399 return script_data_
.get();
402 LoadState
GetLoadState() const {
403 if (next_state_
== STATE_DECIDE_PROXY_SCRIPT_COMPLETE
) {
404 // In addition to downloading, this state may also include the stall time
405 // after network change events (kDelayAfterNetworkChangesMs).
406 return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT
;
408 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
411 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
412 bool quick_check_enabled() const { return quick_check_enabled_
; }
417 STATE_DECIDE_PROXY_SCRIPT
,
418 STATE_DECIDE_PROXY_SCRIPT_COMPLETE
,
419 STATE_SET_PAC_SCRIPT
,
420 STATE_SET_PAC_SCRIPT_COMPLETE
,
423 int DoLoop(int result
) {
424 DCHECK_NE(next_state_
, STATE_NONE
);
427 State state
= next_state_
;
428 next_state_
= STATE_NONE
;
430 case STATE_DECIDE_PROXY_SCRIPT
:
432 rv
= DoDecideProxyScript();
434 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE
:
435 rv
= DoDecideProxyScriptComplete(rv
);
437 case STATE_SET_PAC_SCRIPT
:
439 rv
= DoSetPacScript();
441 case STATE_SET_PAC_SCRIPT_COMPLETE
:
442 rv
= DoSetPacScriptComplete(rv
);
445 NOTREACHED() << "bad state: " << state
;
449 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
453 int DoDecideProxyScript() {
454 next_state_
= STATE_DECIDE_PROXY_SCRIPT_COMPLETE
;
456 return decider_
->Start(
457 config_
, wait_delay_
, proxy_resolver_
->expects_pac_bytes(),
458 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
461 int DoDecideProxyScriptComplete(int result
) {
465 effective_config_
= decider_
->effective_config();
466 script_data_
= decider_
->script_data();
468 next_state_
= STATE_SET_PAC_SCRIPT
;
472 int DoSetPacScript() {
473 DCHECK(script_data_
.get());
474 // TODO(eroman): Should log this latency to the NetLog.
475 next_state_
= STATE_SET_PAC_SCRIPT_COMPLETE
;
476 return proxy_resolver_
->SetPacScript(
478 base::Bind(&InitProxyResolver::OnIOCompletion
, base::Unretained(this)));
481 int DoSetPacScriptComplete(int result
) {
485 void OnIOCompletion(int result
) {
486 DCHECK_NE(STATE_NONE
, next_state_
);
487 int rv
= DoLoop(result
);
488 if (rv
!= ERR_IO_PENDING
)
492 void DoCallback(int result
) {
493 DCHECK_NE(ERR_IO_PENDING
, result
);
494 callback_
.Run(result
);
498 ProxyConfig effective_config_
;
499 scoped_refptr
<ProxyResolverScriptData
> script_data_
;
500 TimeDelta wait_delay_
;
501 scoped_ptr
<ProxyScriptDecider
> decider_
;
502 ProxyResolver
* proxy_resolver_
;
503 CompletionCallback callback_
;
505 bool quick_check_enabled_
;
507 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver
);
510 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
512 // This helper class encapsulates the logic to schedule and run periodic
513 // background checks to see if the PAC script (or effective proxy configuration)
514 // has changed. If a change is detected, then the caller will be notified via
515 // the ChangeCallback.
516 class ProxyService::ProxyScriptDeciderPoller
{
518 typedef base::Callback
<void(int, ProxyResolverScriptData
*,
519 const ProxyConfig
&)> ChangeCallback
;
521 // Builds a poller helper, and starts polling for updates. Whenever a change
522 // is observed, |callback| will be invoked with the details.
524 // |config| specifies the (unresolved) proxy configuration to poll.
525 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
526 // to use the resulting script data with
527 // (so it can choose the right format).
528 // |proxy_script_fetcher| this pointer must remain alive throughout our
529 // lifetime. It is the dependency that will be used
530 // for downloading proxy scripts.
531 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
532 // the DHCP dependency.
533 // |init_net_error| This is the initial network error (possibly success)
534 // encountered by the first PAC fetch attempt. We use it
535 // to schedule updates more aggressively if the initial
536 // fetch resulted in an error.
537 // |init_script_data| the initial script data from the PAC fetch attempt.
538 // This is the baseline used to determine when the
539 // script's contents have changed.
540 // |net_log| the NetLog to log progress into.
541 ProxyScriptDeciderPoller(ChangeCallback callback
,
542 const ProxyConfig
& config
,
543 bool proxy_resolver_expects_pac_bytes
,
544 ProxyScriptFetcher
* proxy_script_fetcher
,
545 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
,
547 ProxyResolverScriptData
* init_script_data
,
549 : change_callback_(callback
),
551 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes
),
552 proxy_script_fetcher_(proxy_script_fetcher
),
553 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher
),
554 last_error_(init_net_error
),
555 last_script_data_(init_script_data
),
556 last_poll_time_(TimeTicks::Now()),
557 weak_factory_(this) {
558 // Set the initial poll delay.
559 next_poll_mode_
= poll_policy()->GetNextDelay(
560 last_error_
, TimeDelta::FromSeconds(-1), &next_poll_delay_
);
561 TryToStartNextPoll(false);
565 // We have just been notified of network activity. Use this opportunity to
566 // see if we can start our next poll.
567 TryToStartNextPoll(true);
570 static const PacPollPolicy
* set_policy(const PacPollPolicy
* policy
) {
571 const PacPollPolicy
* prev
= poll_policy_
;
572 poll_policy_
= policy
;
576 void set_quick_check_enabled(bool enabled
) { quick_check_enabled_
= enabled
; }
577 bool quick_check_enabled() const { return quick_check_enabled_
; }
580 // Returns the effective poll policy (the one injected by unit-tests, or the
582 const PacPollPolicy
* poll_policy() {
585 return &default_poll_policy_
;
588 void StartPollTimer() {
589 DCHECK(!decider_
.get());
591 base::MessageLoop::current()->PostDelayedTask(
593 base::Bind(&ProxyScriptDeciderPoller::DoPoll
,
594 weak_factory_
.GetWeakPtr()),
598 void TryToStartNextPoll(bool triggered_by_activity
) {
599 switch (next_poll_mode_
) {
600 case PacPollPolicy::MODE_USE_TIMER
:
601 if (!triggered_by_activity
)
605 case PacPollPolicy::MODE_START_AFTER_ACTIVITY
:
606 if (triggered_by_activity
&& !decider_
.get()) {
607 TimeDelta elapsed_time
= TimeTicks::Now() - last_poll_time_
;
608 if (elapsed_time
>= next_poll_delay_
)
616 last_poll_time_
= TimeTicks::Now();
618 // Start the proxy script decider to see if anything has changed.
619 // TODO(eroman): Pass a proper NetLog rather than NULL.
620 decider_
.reset(new ProxyScriptDecider(
621 proxy_script_fetcher_
, dhcp_proxy_script_fetcher_
, NULL
));
622 decider_
->set_quick_check_enabled(quick_check_enabled_
);
623 int result
= decider_
->Start(
624 config_
, TimeDelta(), proxy_resolver_expects_pac_bytes_
,
625 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted
,
626 base::Unretained(this)));
628 if (result
!= ERR_IO_PENDING
)
629 OnProxyScriptDeciderCompleted(result
);
632 void OnProxyScriptDeciderCompleted(int result
) {
633 if (HasScriptDataChanged(result
, decider_
->script_data())) {
634 // Something has changed, we must notify the ProxyService so it can
635 // re-initialize its ProxyResolver. Note that we post a notification task
636 // rather than calling it directly -- this is done to avoid an ugly
637 // destruction sequence, since |this| might be destroyed as a result of
639 base::MessageLoop::current()->PostTask(
641 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange
,
642 weak_factory_
.GetWeakPtr(),
644 make_scoped_refptr(decider_
->script_data()),
645 decider_
->effective_config()));
651 // Decide when the next poll should take place, and possibly start the
653 next_poll_mode_
= poll_policy()->GetNextDelay(
654 last_error_
, next_poll_delay_
, &next_poll_delay_
);
655 TryToStartNextPoll(false);
658 bool HasScriptDataChanged(int result
, ProxyResolverScriptData
* script_data
) {
659 if (result
!= last_error_
) {
660 // Something changed -- it was failing before and now it succeeded, or
661 // conversely it succeeded before and now it failed. Or it failed in
662 // both cases, however the specific failure error codes differ.
667 // If it failed last time and failed again with the same error code this
668 // time, then nothing has actually changed.
672 // Otherwise if it succeeded both this time and last time, we need to look
673 // closer and see if we ended up downloading different content for the PAC
675 return !script_data
->Equals(last_script_data_
.get());
678 void NotifyProxyServiceOfChange(
680 const scoped_refptr
<ProxyResolverScriptData
>& script_data
,
681 const ProxyConfig
& effective_config
) {
682 // Note that |this| may be deleted after calling into the ProxyService.
683 change_callback_
.Run(result
, script_data
.get(), effective_config
);
686 ChangeCallback change_callback_
;
688 bool proxy_resolver_expects_pac_bytes_
;
689 ProxyScriptFetcher
* proxy_script_fetcher_
;
690 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher_
;
693 scoped_refptr
<ProxyResolverScriptData
> last_script_data_
;
695 scoped_ptr
<ProxyScriptDecider
> decider_
;
696 TimeDelta next_poll_delay_
;
697 PacPollPolicy::Mode next_poll_mode_
;
699 TimeTicks last_poll_time_
;
701 // Polling policy injected by unit-tests. Otherwise this is NULL and the
702 // default policy will be used.
703 static const PacPollPolicy
* poll_policy_
;
705 const DefaultPollPolicy default_poll_policy_
;
707 bool quick_check_enabled_
;
709 base::WeakPtrFactory
<ProxyScriptDeciderPoller
> weak_factory_
;
711 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller
);
715 const ProxyService::PacPollPolicy
*
716 ProxyService::ProxyScriptDeciderPoller::poll_policy_
= NULL
;
718 // ProxyService::PacRequest ---------------------------------------------------
720 class ProxyService::PacRequest
721 : public base::RefCounted
<ProxyService::PacRequest
> {
723 PacRequest(ProxyService
* service
,
726 NetworkDelegate
* network_delegate
,
728 const net::CompletionCallback
& user_callback
,
729 const BoundNetLog
& net_log
)
731 user_callback_(user_callback
),
734 load_flags_(load_flags
),
735 network_delegate_(network_delegate
),
737 config_id_(ProxyConfig::kInvalidConfigID
),
738 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN
),
740 DCHECK(!user_callback
.is_null());
743 // Starts the resolve proxy request.
745 DCHECK(!was_cancelled());
746 DCHECK(!is_started());
748 DCHECK(service_
->config_
.is_valid());
750 config_id_
= service_
->config_
.id();
751 config_source_
= service_
->config_
.source();
752 proxy_resolve_start_time_
= TimeTicks::Now();
754 return resolver()->GetProxyForURL(
756 base::Bind(&PacRequest::QueryComplete
, base::Unretained(this)),
757 &resolve_job_
, net_log_
);
760 bool is_started() const {
761 // Note that !! casts to bool. (VS gives a warning otherwise).
762 return !!resolve_job_
;
765 void StartAndCompleteCheckingForSynchronous() {
766 int rv
= service_
->TryToCompleteSynchronously(url_
, load_flags_
,
767 network_delegate_
, results_
);
768 if (rv
== ERR_IO_PENDING
)
770 if (rv
!= ERR_IO_PENDING
)
774 void CancelResolveJob() {
775 DCHECK(is_started());
776 // The request may already be running in the resolver.
777 resolver()->CancelRequest(resolve_job_
);
779 DCHECK(!is_started());
783 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
788 // Mark as cancelled, to prevent accessing this again later.
790 user_callback_
.Reset();
793 net_log_
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
796 // Returns true if Cancel() has been called.
797 bool was_cancelled() const {
798 return user_callback_
.is_null();
801 // Helper to call after ProxyResolver completion (both synchronous and
802 // asynchronous). Fixes up the result that is to be returned to user.
803 int QueryDidComplete(int result_code
) {
804 DCHECK(!was_cancelled());
806 // Note that DidFinishResolvingProxy might modify |results_|.
807 int rv
= service_
->DidFinishResolvingProxy(url_
, load_flags_
,
808 network_delegate_
, results_
,
809 result_code
, net_log_
);
811 // Make a note in the results which configuration was in use at the
812 // time of the resolve.
813 results_
->config_id_
= config_id_
;
814 results_
->config_source_
= config_source_
;
815 results_
->did_use_pac_script_
= true;
816 results_
->proxy_resolve_start_time_
= proxy_resolve_start_time_
;
817 results_
->proxy_resolve_end_time_
= TimeTicks::Now();
819 // Reset the state associated with in-progress-resolve.
821 config_id_
= ProxyConfig::kInvalidConfigID
;
822 config_source_
= PROXY_CONFIG_SOURCE_UNKNOWN
;
827 BoundNetLog
* net_log() { return &net_log_
; }
829 LoadState
GetLoadState() const {
831 return resolver()->GetLoadState(resolve_job_
);
832 return LOAD_STATE_RESOLVING_PROXY_FOR_URL
;
836 friend class base::RefCounted
<ProxyService::PacRequest
>;
840 // Callback for when the ProxyResolver request has completed.
841 void QueryComplete(int result_code
) {
842 result_code
= QueryDidComplete(result_code
);
844 // Remove this completed PacRequest from the service's pending list.
845 /// (which will probably cause deletion of |this|).
846 if (!user_callback_
.is_null()) {
847 net::CompletionCallback callback
= user_callback_
;
848 service_
->RemovePendingRequest(this);
849 callback
.Run(result_code
);
853 ProxyResolver
* resolver() const { return service_
->resolver_
.get(); }
855 // Note that we don't hold a reference to the ProxyService. Outstanding
856 // requests are cancelled during ~ProxyService, so this is guaranteed
857 // to be valid throughout our lifetime.
858 ProxyService
* service_
;
859 net::CompletionCallback user_callback_
;
863 NetworkDelegate
* network_delegate_
;
864 ProxyResolver::RequestHandle resolve_job_
;
865 ProxyConfig::ID config_id_
; // The config id when the resolve was started.
866 ProxyConfigSource config_source_
; // The source of proxy settings.
867 BoundNetLog net_log_
;
868 // Time when the PAC is started. Cached here since resetting ProxyInfo also
869 // clears the proxy times.
870 TimeTicks proxy_resolve_start_time_
;
873 // ProxyService ---------------------------------------------------------------
875 ProxyService::ProxyService(ProxyConfigService
* config_service
,
876 ProxyResolver
* resolver
,
878 : resolver_(resolver
),
880 current_state_(STATE_NONE
),
882 stall_proxy_auto_config_delay_(TimeDelta::FromMilliseconds(
883 kDelayAfterNetworkChangesMs
)),
884 quick_check_enabled_(true) {
885 NetworkChangeNotifier::AddIPAddressObserver(this);
886 NetworkChangeNotifier::AddDNSObserver(this);
887 ResetConfigService(config_service
);
891 ProxyService
* ProxyService::CreateUsingSystemProxyResolver(
892 ProxyConfigService
* proxy_config_service
,
893 size_t num_pac_threads
,
895 DCHECK(proxy_config_service
);
897 if (!ProxyResolverFactoryForSystem::IsSupported()) {
898 LOG(WARNING
) << "PAC support disabled because there is no "
899 "system implementation";
900 return CreateWithoutProxyResolver(proxy_config_service
, net_log
);
903 if (num_pac_threads
== 0)
904 num_pac_threads
= kDefaultNumPacThreads
;
906 ProxyResolver
* proxy_resolver
= new MultiThreadedProxyResolver(
907 new ProxyResolverFactoryForSystem(), num_pac_threads
);
909 return new ProxyService(proxy_config_service
, proxy_resolver
, net_log
);
913 ProxyService
* ProxyService::CreateWithoutProxyResolver(
914 ProxyConfigService
* proxy_config_service
,
916 return new ProxyService(proxy_config_service
,
917 new ProxyResolverNull(),
922 ProxyService
* ProxyService::CreateFixed(const ProxyConfig
& pc
) {
923 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
925 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc
),
930 ProxyService
* ProxyService::CreateFixed(const std::string
& proxy
) {
931 net::ProxyConfig proxy_config
;
932 proxy_config
.proxy_rules().ParseFromString(proxy
);
933 return ProxyService::CreateFixed(proxy_config
);
937 ProxyService
* ProxyService::CreateDirect() {
938 return CreateDirectWithNetLog(NULL
);
941 ProxyService
* ProxyService::CreateDirectWithNetLog(NetLog
* net_log
) {
942 // Use direct connections.
943 return new ProxyService(new ProxyConfigServiceDirect
, new ProxyResolverNull
,
948 ProxyService
* ProxyService::CreateFixedFromPacResult(
949 const std::string
& pac_string
) {
951 // We need the settings to contain an "automatic" setting, otherwise the
952 // ProxyResolver dependency we give it will never be used.
953 scoped_ptr
<ProxyConfigService
> proxy_config_service(
954 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
956 scoped_ptr
<ProxyResolver
> proxy_resolver(
957 new ProxyResolverFromPacString(pac_string
));
959 return new ProxyService(proxy_config_service
.release(),
960 proxy_resolver
.release(),
964 int ProxyService::ResolveProxy(const GURL
& raw_url
,
967 const net::CompletionCallback
& callback
,
968 PacRequest
** pac_request
,
969 NetworkDelegate
* network_delegate
,
970 const BoundNetLog
& net_log
) {
971 DCHECK(!callback
.is_null());
972 return ResolveProxyHelper(raw_url
,
981 int ProxyService::ResolveProxyHelper(const GURL
& raw_url
,
984 const net::CompletionCallback
& callback
,
985 PacRequest
** pac_request
,
986 NetworkDelegate
* network_delegate
,
987 const BoundNetLog
& net_log
) {
988 DCHECK(CalledOnValidThread());
990 net_log
.BeginEvent(NetLog::TYPE_PROXY_SERVICE
);
992 // Notify our polling-based dependencies that a resolve is taking place.
993 // This way they can schedule their polls in response to network activity.
994 config_service_
->OnLazyPoll();
995 if (script_poller_
.get())
996 script_poller_
->OnLazyPoll();
998 if (current_state_
== STATE_NONE
)
999 ApplyProxyConfigIfAvailable();
1001 // Strip away any reference fragments and the username/password, as they
1002 // are not relevant to proxy resolution.
1003 GURL url
= SimplifyUrlForRequest(raw_url
);
1005 // Check if the request can be completed right away. (This is the case when
1006 // using a direct connection for example).
1007 int rv
= TryToCompleteSynchronously(url
, load_flags
,
1008 network_delegate
, result
);
1009 if (rv
!= ERR_IO_PENDING
)
1010 return DidFinishResolvingProxy(url
, load_flags
, network_delegate
,
1011 result
, rv
, net_log
);
1013 if (callback
.is_null())
1014 return ERR_IO_PENDING
;
1016 scoped_refptr
<PacRequest
> req(
1017 new PacRequest(this, url
, load_flags
, network_delegate
,
1018 result
, callback
, net_log
));
1020 if (current_state_
== STATE_READY
) {
1021 // Start the resolve request.
1023 if (rv
!= ERR_IO_PENDING
)
1024 return req
->QueryDidComplete(rv
);
1026 req
->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1029 DCHECK_EQ(ERR_IO_PENDING
, rv
);
1030 DCHECK(!ContainsPendingRequest(req
.get()));
1031 pending_requests_
.push_back(req
);
1033 // Completion will be notified through |callback|, unless the caller cancels
1034 // the request using |pac_request|.
1036 *pac_request
= req
.get();
1037 return rv
; // ERR_IO_PENDING
1040 bool ProxyService:: TryResolveProxySynchronously(
1041 const GURL
& raw_url
,
1044 NetworkDelegate
* network_delegate
,
1045 const BoundNetLog
& net_log
) {
1046 net::CompletionCallback null_callback
;
1047 return ResolveProxyHelper(raw_url
,
1051 NULL
/* pac_request*/,
1056 int ProxyService::TryToCompleteSynchronously(const GURL
& url
,
1058 NetworkDelegate
* network_delegate
,
1059 ProxyInfo
* result
) {
1060 DCHECK_NE(STATE_NONE
, current_state_
);
1062 if (current_state_
!= STATE_READY
)
1063 return ERR_IO_PENDING
; // Still initializing.
1065 DCHECK_NE(config_
.id(), ProxyConfig::kInvalidConfigID
);
1067 // If it was impossible to fetch or parse the PAC script, we cannot complete
1068 // the request here and bail out.
1069 if (permanent_error_
!= OK
)
1070 return permanent_error_
;
1072 if (config_
.HasAutomaticSettings())
1073 return ERR_IO_PENDING
; // Must submit the request to the proxy resolver.
1075 // Use the manual proxy settings.
1076 config_
.proxy_rules().Apply(url
, result
);
1077 result
->config_source_
= config_
.source();
1078 result
->config_id_
= config_
.id();
1083 ProxyService::~ProxyService() {
1084 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1085 NetworkChangeNotifier::RemoveDNSObserver(this);
1086 config_service_
->RemoveObserver(this);
1088 // Cancel any inprogress requests.
1089 for (PendingRequests::iterator it
= pending_requests_
.begin();
1090 it
!= pending_requests_
.end();
1096 void ProxyService::SuspendAllPendingRequests() {
1097 for (PendingRequests::iterator it
= pending_requests_
.begin();
1098 it
!= pending_requests_
.end();
1100 PacRequest
* req
= it
->get();
1101 if (req
->is_started()) {
1102 req
->CancelResolveJob();
1104 req
->net_log()->BeginEvent(
1105 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1110 void ProxyService::SetReady() {
1111 DCHECK(!init_proxy_resolver_
.get());
1112 current_state_
= STATE_READY
;
1114 // Make a copy in case |this| is deleted during the synchronous completion
1115 // of one of the requests. If |this| is deleted then all of the PacRequest
1116 // instances will be Cancel()-ed.
1117 PendingRequests pending_copy
= pending_requests_
;
1119 for (PendingRequests::iterator it
= pending_copy
.begin();
1120 it
!= pending_copy
.end();
1122 PacRequest
* req
= it
->get();
1123 if (!req
->is_started() && !req
->was_cancelled()) {
1124 req
->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC
);
1126 // Note that we re-check for synchronous completion, in case we are
1127 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1128 req
->StartAndCompleteCheckingForSynchronous();
1133 void ProxyService::ApplyProxyConfigIfAvailable() {
1134 DCHECK_EQ(STATE_NONE
, current_state_
);
1136 config_service_
->OnLazyPoll();
1138 // If we have already fetched the configuration, start applying it.
1139 if (fetched_config_
.is_valid()) {
1140 InitializeUsingLastFetchedConfig();
1144 // Otherwise we need to first fetch the configuration.
1145 current_state_
= STATE_WAITING_FOR_PROXY_CONFIG
;
1147 // Retrieve the current proxy configuration from the ProxyConfigService.
1148 // If a configuration is not available yet, we will get called back later
1149 // by our ProxyConfigService::Observer once it changes.
1151 ProxyConfigService::ConfigAvailability availability
=
1152 config_service_
->GetLatestProxyConfig(&config
);
1153 if (availability
!= ProxyConfigService::CONFIG_PENDING
)
1154 OnProxyConfigChanged(config
, availability
);
1157 void ProxyService::OnInitProxyResolverComplete(int result
) {
1158 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER
, current_state_
);
1159 DCHECK(init_proxy_resolver_
.get());
1160 DCHECK(fetched_config_
.HasAutomaticSettings());
1161 config_
= init_proxy_resolver_
->effective_config();
1163 // At this point we have decided which proxy settings to use (i.e. which PAC
1164 // script if any). We start up a background poller to periodically revisit
1165 // this decision. If the contents of the PAC script change, or if the
1166 // result of proxy auto-discovery changes, this poller will notice it and
1167 // will trigger a re-initialization using the newly discovered PAC.
1168 script_poller_
.reset(new ProxyScriptDeciderPoller(
1169 base::Bind(&ProxyService::InitializeUsingDecidedConfig
,
1170 base::Unretained(this)),
1172 resolver_
->expects_pac_bytes(),
1173 proxy_script_fetcher_
.get(),
1174 dhcp_proxy_script_fetcher_
.get(),
1176 init_proxy_resolver_
->script_data(),
1178 script_poller_
->set_quick_check_enabled(quick_check_enabled_
);
1180 init_proxy_resolver_
.reset();
1183 if (fetched_config_
.pac_mandatory()) {
1184 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1186 config_
= fetched_config_
;
1187 result
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1189 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1191 config_
= fetched_config_
;
1192 config_
.ClearAutomaticSettings();
1196 permanent_error_
= result
;
1198 // TODO(eroman): Make this ID unique in the case where configuration changed
1199 // due to ProxyScriptDeciderPoller.
1200 config_
.set_id(fetched_config_
.id());
1201 config_
.set_source(fetched_config_
.source());
1203 // Resume any requests which we had to defer until the PAC script was
1208 int ProxyService::ReconsiderProxyAfterError(const GURL
& url
,
1212 const CompletionCallback
& callback
,
1213 PacRequest
** pac_request
,
1214 NetworkDelegate
* network_delegate
,
1215 const BoundNetLog
& net_log
) {
1216 DCHECK(CalledOnValidThread());
1218 // Check to see if we have a new config since ResolveProxy was called. We
1219 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1220 // direct connection failed and we never tried the current config.
1223 bool re_resolve
= result
->config_id_
!= config_
.id();
1226 // If we have a new config or the config was never tried, we delete the
1227 // list of bad proxies and we try again.
1228 proxy_retry_info_
.clear();
1229 return ResolveProxy(url
, load_flags
, result
, callback
, pac_request
,
1230 network_delegate
, net_log
);
1233 DCHECK(!result
->is_empty());
1234 ProxyServer bad_proxy
= result
->proxy_server();
1236 // We don't have new proxy settings to try, try to fallback to the next proxy
1238 bool did_fallback
= result
->Fallback(net_error
, net_log
);
1240 // Return synchronous failure if there is nothing left to fall-back to.
1241 // TODO(eroman): This is a yucky API, clean it up.
1242 return did_fallback
? OK
: ERR_FAILED
;
1245 bool ProxyService::MarkProxiesAsBadUntil(
1246 const ProxyInfo
& result
,
1247 base::TimeDelta retry_delay
,
1248 const ProxyServer
& another_bad_proxy
,
1249 const BoundNetLog
& net_log
) {
1250 result
.proxy_list_
.UpdateRetryInfoOnFallback(&proxy_retry_info_
,
1256 if (another_bad_proxy
.is_valid())
1257 return result
.proxy_list_
.size() > 2;
1259 return result
.proxy_list_
.size() > 1;
1262 void ProxyService::ReportSuccess(const ProxyInfo
& result
,
1263 NetworkDelegate
* network_delegate
) {
1264 DCHECK(CalledOnValidThread());
1266 const ProxyRetryInfoMap
& new_retry_info
= result
.proxy_retry_info();
1267 if (new_retry_info
.empty())
1270 for (ProxyRetryInfoMap::const_iterator iter
= new_retry_info
.begin();
1271 iter
!= new_retry_info
.end(); ++iter
) {
1272 ProxyRetryInfoMap::iterator existing
= proxy_retry_info_
.find(iter
->first
);
1273 if (existing
== proxy_retry_info_
.end()) {
1274 proxy_retry_info_
[iter
->first
] = iter
->second
;
1275 if (network_delegate
) {
1276 const ProxyServer
& bad_proxy
=
1277 ProxyServer::FromURI(iter
->first
, ProxyServer::SCHEME_HTTP
);
1278 const ProxyRetryInfo
& proxy_retry_info
= iter
->second
;
1279 network_delegate
->NotifyProxyFallback(bad_proxy
,
1280 proxy_retry_info
.net_error
);
1283 else if (existing
->second
.bad_until
< iter
->second
.bad_until
)
1284 existing
->second
.bad_until
= iter
->second
.bad_until
;
1287 net_log_
->AddGlobalEntry(
1288 NetLog::TYPE_BAD_PROXY_LIST_REPORTED
,
1289 base::Bind(&NetLogBadProxyListCallback
, &new_retry_info
));
1293 void ProxyService::CancelPacRequest(PacRequest
* req
) {
1294 DCHECK(CalledOnValidThread());
1297 RemovePendingRequest(req
);
1300 LoadState
ProxyService::GetLoadState(const PacRequest
* req
) const {
1302 if (current_state_
== STATE_WAITING_FOR_INIT_PROXY_RESOLVER
)
1303 return init_proxy_resolver_
->GetLoadState();
1304 return req
->GetLoadState();
1307 bool ProxyService::ContainsPendingRequest(PacRequest
* req
) {
1308 PendingRequests::iterator it
= std::find(
1309 pending_requests_
.begin(), pending_requests_
.end(), req
);
1310 return pending_requests_
.end() != it
;
1313 void ProxyService::RemovePendingRequest(PacRequest
* req
) {
1314 DCHECK(ContainsPendingRequest(req
));
1315 PendingRequests::iterator it
= std::find(
1316 pending_requests_
.begin(), pending_requests_
.end(), req
);
1317 pending_requests_
.erase(it
);
1320 int ProxyService::DidFinishResolvingProxy(const GURL
& url
,
1322 NetworkDelegate
* network_delegate
,
1325 const BoundNetLog
& net_log
) {
1326 // Log the result of the proxy resolution.
1327 if (result_code
== OK
) {
1328 // Allow the network delegate to interpose on the resolution decision,
1329 // possibly modifying the ProxyInfo.
1330 if (network_delegate
)
1331 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1333 // When logging all events is enabled, dump the proxy list.
1334 if (net_log
.IsLogging()) {
1336 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
,
1337 base::Bind(&NetLogFinishedResolvingProxyCallback
, result
));
1339 result
->DeprioritizeBadProxies(proxy_retry_info_
);
1341 net_log
.AddEventWithNetErrorCode(
1342 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST
, result_code
);
1344 if (!config_
.pac_mandatory()) {
1345 // Fall-back to direct when the proxy resolver fails. This corresponds
1346 // with a javascript runtime error in the PAC script.
1348 // This implicit fall-back to direct matches Firefox 3.5 and
1349 // Internet Explorer 8. For more information, see:
1351 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1352 result
->UseDirect();
1355 // Allow the network delegate to interpose on the resolution decision,
1356 // possibly modifying the ProxyInfo.
1357 if (network_delegate
)
1358 network_delegate
->NotifyResolveProxy(url
, load_flags
, *this, result
);
1360 result_code
= ERR_MANDATORY_PROXY_CONFIGURATION_FAILED
;
1364 net_log
.EndEvent(NetLog::TYPE_PROXY_SERVICE
);
1368 void ProxyService::SetProxyScriptFetchers(
1369 ProxyScriptFetcher
* proxy_script_fetcher
,
1370 DhcpProxyScriptFetcher
* dhcp_proxy_script_fetcher
) {
1371 DCHECK(CalledOnValidThread());
1372 State previous_state
= ResetProxyConfig(false);
1373 proxy_script_fetcher_
.reset(proxy_script_fetcher
);
1374 dhcp_proxy_script_fetcher_
.reset(dhcp_proxy_script_fetcher
);
1375 if (previous_state
!= STATE_NONE
)
1376 ApplyProxyConfigIfAvailable();
1379 ProxyScriptFetcher
* ProxyService::GetProxyScriptFetcher() const {
1380 DCHECK(CalledOnValidThread());
1381 return proxy_script_fetcher_
.get();
1384 ProxyService::State
ProxyService::ResetProxyConfig(bool reset_fetched_config
) {
1385 DCHECK(CalledOnValidThread());
1386 State previous_state
= current_state_
;
1388 permanent_error_
= OK
;
1389 proxy_retry_info_
.clear();
1390 script_poller_
.reset();
1391 init_proxy_resolver_
.reset();
1392 SuspendAllPendingRequests();
1393 config_
= ProxyConfig();
1394 if (reset_fetched_config
)
1395 fetched_config_
= ProxyConfig();
1396 current_state_
= STATE_NONE
;
1398 return previous_state
;
1401 void ProxyService::ResetConfigService(
1402 ProxyConfigService
* new_proxy_config_service
) {
1403 DCHECK(CalledOnValidThread());
1404 State previous_state
= ResetProxyConfig(true);
1406 // Release the old configuration service.
1407 if (config_service_
.get())
1408 config_service_
->RemoveObserver(this);
1410 // Set the new configuration service.
1411 config_service_
.reset(new_proxy_config_service
);
1412 config_service_
->AddObserver(this);
1414 if (previous_state
!= STATE_NONE
)
1415 ApplyProxyConfigIfAvailable();
1418 void ProxyService::ForceReloadProxyConfig() {
1419 DCHECK(CalledOnValidThread());
1420 ResetProxyConfig(false);
1421 ApplyProxyConfigIfAvailable();
1425 ProxyConfigService
* ProxyService::CreateSystemProxyConfigService(
1426 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
,
1427 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_task_runner
) {
1429 return new ProxyConfigServiceWin();
1430 #elif defined(OS_IOS)
1431 return new ProxyConfigServiceIOS();
1432 #elif defined(OS_MACOSX)
1433 return new ProxyConfigServiceMac(io_task_runner
);
1434 #elif defined(OS_CHROMEOS)
1435 LOG(ERROR
) << "ProxyConfigService for ChromeOS should be created in "
1436 << "profile_io_data.cc::CreateProxyConfigService and this should "
1437 << "be used only for examples.";
1438 return new UnsetProxyConfigService
;
1439 #elif defined(OS_LINUX)
1440 ProxyConfigServiceLinux
* linux_config_service
=
1441 new ProxyConfigServiceLinux();
1443 // Assume we got called on the thread that runs the default glib
1444 // main loop, so the current thread is where we should be running
1445 // gconf calls from.
1446 scoped_refptr
<base::SingleThreadTaskRunner
> glib_thread_task_runner
=
1447 base::ThreadTaskRunnerHandle::Get();
1449 // Synchronously fetch the current proxy config (since we are running on
1450 // glib_default_loop). Additionally register for notifications (delivered in
1451 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1452 // the proxy config changes.
1453 linux_config_service
->SetupAndFetchInitialConfig(
1454 glib_thread_task_runner
, io_task_runner
, file_task_runner
);
1456 return linux_config_service
;
1457 #elif defined(OS_ANDROID)
1458 return new ProxyConfigServiceAndroid(
1459 io_task_runner
, base::MessageLoop::current()->message_loop_proxy());
1461 LOG(WARNING
) << "Failed to choose a system proxy settings fetcher "
1462 "for this platform.";
1463 return new ProxyConfigServiceDirect();
1468 const ProxyService::PacPollPolicy
* ProxyService::set_pac_script_poll_policy(
1469 const PacPollPolicy
* policy
) {
1470 return ProxyScriptDeciderPoller::set_policy(policy
);
1474 scoped_ptr
<ProxyService::PacPollPolicy
>
1475 ProxyService::CreateDefaultPacPollPolicy() {
1476 return scoped_ptr
<PacPollPolicy
>(new DefaultPollPolicy());
1479 void ProxyService::OnProxyConfigChanged(
1480 const ProxyConfig
& config
,
1481 ProxyConfigService::ConfigAvailability availability
) {
1482 // Retrieve the current proxy configuration from the ProxyConfigService.
1483 // If a configuration is not available yet, we will get called back later
1484 // by our ProxyConfigService::Observer once it changes.
1485 ProxyConfig effective_config
;
1486 switch (availability
) {
1487 case ProxyConfigService::CONFIG_PENDING
:
1488 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1489 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1491 case ProxyConfigService::CONFIG_VALID
:
1492 effective_config
= config
;
1494 case ProxyConfigService::CONFIG_UNSET
:
1495 effective_config
= ProxyConfig::CreateDirect();
1499 // Emit the proxy settings change to the NetLog stream.
1501 net_log_
->AddGlobalEntry(
1502 net::NetLog::TYPE_PROXY_CONFIG_CHANGED
,
1503 base::Bind(&NetLogProxyConfigChangedCallback
,
1504 &fetched_config_
, &effective_config
));
1507 // Set the new configuration as the most recently fetched one.
1508 fetched_config_
= effective_config
;
1509 fetched_config_
.set_id(1); // Needed for a later DCHECK of is_valid().
1511 InitializeUsingLastFetchedConfig();
1514 void ProxyService::InitializeUsingLastFetchedConfig() {
1515 ResetProxyConfig(false);
1517 DCHECK(fetched_config_
.is_valid());
1519 // Increment the ID to reflect that the config has changed.
1520 fetched_config_
.set_id(next_config_id_
++);
1522 if (!fetched_config_
.HasAutomaticSettings()) {
1523 config_
= fetched_config_
;
1528 // Start downloading + testing the PAC scripts for this new configuration.
1529 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1531 // If we changed networks recently, we should delay running proxy auto-config.
1532 TimeDelta wait_delay
=
1533 stall_proxy_autoconfig_until_
- TimeTicks::Now();
1535 init_proxy_resolver_
.reset(new InitProxyResolver());
1536 init_proxy_resolver_
->set_quick_check_enabled(quick_check_enabled_
);
1537 int rv
= init_proxy_resolver_
->Start(
1539 proxy_script_fetcher_
.get(),
1540 dhcp_proxy_script_fetcher_
.get(),
1544 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1545 base::Unretained(this)));
1547 if (rv
!= ERR_IO_PENDING
)
1548 OnInitProxyResolverComplete(rv
);
1551 void ProxyService::InitializeUsingDecidedConfig(
1553 ProxyResolverScriptData
* script_data
,
1554 const ProxyConfig
& effective_config
) {
1555 DCHECK(fetched_config_
.is_valid());
1556 DCHECK(fetched_config_
.HasAutomaticSettings());
1558 ResetProxyConfig(false);
1560 current_state_
= STATE_WAITING_FOR_INIT_PROXY_RESOLVER
;
1562 init_proxy_resolver_
.reset(new InitProxyResolver());
1563 int rv
= init_proxy_resolver_
->StartSkipDecider(
1568 base::Bind(&ProxyService::OnInitProxyResolverComplete
,
1569 base::Unretained(this)));
1571 if (rv
!= ERR_IO_PENDING
)
1572 OnInitProxyResolverComplete(rv
);
1575 void ProxyService::OnIPAddressChanged() {
1576 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1577 stall_proxy_autoconfig_until_
=
1578 TimeTicks::Now() + stall_proxy_auto_config_delay_
;
1580 State previous_state
= ResetProxyConfig(false);
1581 if (previous_state
!= STATE_NONE
)
1582 ApplyProxyConfigIfAvailable();
1585 void ProxyService::OnDNSChanged() {
1586 OnIPAddressChanged();