GoogleURLTrackerInfoBarDelegate: Initialize uninitialized member in constructor.
[chromium-blink-merge.git] / net / proxy / proxy_service.cc
blobb70ea2c8525b416995fc1bf00e031b7922d5b628
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"
7 #include <algorithm>
9 #include "base/bind.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/net_errors.h"
21 #include "net/base/net_log.h"
22 #include "net/base/net_util.h"
23 #include "net/proxy/dhcp_proxy_script_fetcher.h"
24 #include "net/proxy/multi_threaded_proxy_resolver.h"
25 #include "net/proxy/network_delegate_error_observer.h"
26 #include "net/proxy/proxy_config_service_fixed.h"
27 #include "net/proxy/proxy_resolver.h"
28 #include "net/proxy/proxy_script_decider.h"
29 #include "net/proxy/proxy_script_fetcher.h"
30 #include "net/url_request/url_request_context.h"
31 #include "url/gurl.h"
33 #if defined(OS_WIN)
34 #include "net/proxy/proxy_config_service_win.h"
35 #include "net/proxy/proxy_resolver_winhttp.h"
36 #elif defined(OS_IOS)
37 #include "net/proxy/proxy_config_service_ios.h"
38 #include "net/proxy/proxy_resolver_mac.h"
39 #elif defined(OS_MACOSX)
40 #include "net/proxy/proxy_config_service_mac.h"
41 #include "net/proxy/proxy_resolver_mac.h"
42 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
43 #include "net/proxy/proxy_config_service_linux.h"
44 #elif defined(OS_ANDROID)
45 #include "net/proxy/proxy_config_service_android.h"
46 #endif
48 #if defined(SPDY_PROXY_AUTH_ORIGIN)
49 #include "base/metrics/histogram.h"
50 #include "base/metrics/sparse_histogram.h"
51 #endif
53 using base::TimeDelta;
54 using base::TimeTicks;
56 namespace net {
58 namespace {
60 // When the IP address changes we don't immediately re-run proxy auto-config.
61 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
62 // attempting to re-valuate proxy auto-config.
64 // During this time window, any resolve requests sent to the ProxyService will
65 // be queued. Once we have waited the required amount of them, the proxy
66 // auto-config step will be run, and the queued requests resumed.
68 // The reason we play this game is that our signal for detecting network
69 // changes (NetworkChangeNotifier) may fire *before* the system's networking
70 // dependencies are fully configured. This is a problem since it means if
71 // we were to run proxy auto-config right away, it could fail due to spurious
72 // DNS failures. (see http://crbug.com/50779 for more details.)
74 // By adding the wait window, we give things a better chance to get properly
75 // set up. Network failures can happen at any time though, so we additionally
76 // poll the PAC script for changes, which will allow us to recover from these
77 // sorts of problems.
78 const int64 kDelayAfterNetworkChangesMs = 2000;
80 // This is the default policy for polling the PAC script.
82 // In response to a failure, the poll intervals are:
83 // 0: 8 seconds (scheduled on timer)
84 // 1: 32 seconds
85 // 2: 2 minutes
86 // 3+: 4 hours
88 // In response to a success, the poll intervals are:
89 // 0+: 12 hours
91 // Only the 8 second poll is scheduled on a timer, the rest happen in response
92 // to network activity (and hence will take longer than the written time).
94 // Explanation for these values:
96 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
97 // using some histograms data. Trying to be conservative so as not to break
98 // existing setups when deployed. A simple exponential retry scheme would be
99 // more elegant, but places more load on server.
101 // The motivation for trying quickly after failures (8 seconds) is to recover
102 // from spurious network failures, which are common after the IP address has
103 // just changed (like DNS failing to resolve). The next 32 second boundary is
104 // to try and catch other VPN weirdness which anecdotally I have seen take
105 // 10+ seconds for some users.
107 // The motivation for re-trying after a success is to check for possible
108 // content changes to the script, or to the WPAD auto-discovery results. We are
109 // not very aggressive with these checks so as to minimize the risk of
110 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
111 // change very frequently in existing setups. More research is needed to
112 // motivate what safe values are here, and what other user agents do.
114 // Comparison to other browsers:
116 // In Firefox the PAC URL is re-tried on failures according to
117 // network.proxy.autoconfig_retry_interval_min and
118 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
119 // 5 minutes respectively. It doubles the interval at each attempt.
121 // TODO(eroman): Figure out what Internet Explorer does.
122 class DefaultPollPolicy : public ProxyService::PacPollPolicy {
123 public:
124 DefaultPollPolicy() {}
126 virtual Mode GetNextDelay(int initial_error,
127 TimeDelta current_delay,
128 TimeDelta* next_delay) const OVERRIDE {
129 if (initial_error != OK) {
130 // Re-try policy for failures.
131 const int kDelay1Seconds = 8;
132 const int kDelay2Seconds = 32;
133 const int kDelay3Seconds = 2 * 60; // 2 minutes
134 const int kDelay4Seconds = 4 * 60 * 60; // 4 Hours
136 // Initial poll.
137 if (current_delay < TimeDelta()) {
138 *next_delay = TimeDelta::FromSeconds(kDelay1Seconds);
139 return MODE_USE_TIMER;
141 switch (current_delay.InSeconds()) {
142 case kDelay1Seconds:
143 *next_delay = TimeDelta::FromSeconds(kDelay2Seconds);
144 return MODE_START_AFTER_ACTIVITY;
145 case kDelay2Seconds:
146 *next_delay = TimeDelta::FromSeconds(kDelay3Seconds);
147 return MODE_START_AFTER_ACTIVITY;
148 default:
149 *next_delay = TimeDelta::FromSeconds(kDelay4Seconds);
150 return MODE_START_AFTER_ACTIVITY;
152 } else {
153 // Re-try policy for succeses.
154 *next_delay = TimeDelta::FromHours(12);
155 return MODE_START_AFTER_ACTIVITY;
159 private:
160 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy);
163 // Config getter that always returns direct settings.
164 class ProxyConfigServiceDirect : public ProxyConfigService {
165 public:
166 // ProxyConfigService implementation:
167 virtual void AddObserver(Observer* observer) OVERRIDE {}
168 virtual void RemoveObserver(Observer* observer) OVERRIDE {}
169 virtual ConfigAvailability GetLatestProxyConfig(ProxyConfig* config)
170 OVERRIDE {
171 *config = ProxyConfig::CreateDirect();
172 config->set_source(PROXY_CONFIG_SOURCE_UNKNOWN);
173 return CONFIG_VALID;
177 // Proxy resolver that fails every time.
178 class ProxyResolverNull : public ProxyResolver {
179 public:
180 ProxyResolverNull() : ProxyResolver(false /*expects_pac_bytes*/) {}
182 // ProxyResolver implementation.
183 virtual int GetProxyForURL(const GURL& url,
184 ProxyInfo* results,
185 const CompletionCallback& callback,
186 RequestHandle* request,
187 const BoundNetLog& net_log) OVERRIDE {
188 return ERR_NOT_IMPLEMENTED;
191 virtual void CancelRequest(RequestHandle request) OVERRIDE {
192 NOTREACHED();
195 virtual LoadState GetLoadState(RequestHandle request) const OVERRIDE {
196 NOTREACHED();
197 return LOAD_STATE_IDLE;
200 virtual void CancelSetPacScript() OVERRIDE {
201 NOTREACHED();
204 virtual int SetPacScript(
205 const scoped_refptr<ProxyResolverScriptData>& /*script_data*/,
206 const CompletionCallback& /*callback*/) OVERRIDE {
207 return ERR_NOT_IMPLEMENTED;
211 // ProxyResolver that simulates a PAC script which returns
212 // |pac_string| for every single URL.
213 class ProxyResolverFromPacString : public ProxyResolver {
214 public:
215 explicit ProxyResolverFromPacString(const std::string& pac_string)
216 : ProxyResolver(false /*expects_pac_bytes*/),
217 pac_string_(pac_string) {}
219 virtual int GetProxyForURL(const GURL& url,
220 ProxyInfo* results,
221 const CompletionCallback& callback,
222 RequestHandle* request,
223 const BoundNetLog& net_log) OVERRIDE {
224 results->UsePacString(pac_string_);
225 return OK;
228 virtual void CancelRequest(RequestHandle request) OVERRIDE {
229 NOTREACHED();
232 virtual LoadState GetLoadState(RequestHandle request) const OVERRIDE {
233 NOTREACHED();
234 return LOAD_STATE_IDLE;
237 virtual void CancelSetPacScript() OVERRIDE {
238 NOTREACHED();
241 virtual int SetPacScript(
242 const scoped_refptr<ProxyResolverScriptData>& pac_script,
243 const CompletionCallback& callback) OVERRIDE {
244 return OK;
247 private:
248 const std::string pac_string_;
251 // Creates ProxyResolvers using a platform-specific implementation.
252 class ProxyResolverFactoryForSystem : public ProxyResolverFactory {
253 public:
254 ProxyResolverFactoryForSystem()
255 : ProxyResolverFactory(false /*expects_pac_bytes*/) {}
257 virtual ProxyResolver* CreateProxyResolver() OVERRIDE {
258 DCHECK(IsSupported());
259 #if defined(OS_WIN)
260 return new ProxyResolverWinHttp();
261 #elif defined(OS_MACOSX)
262 return new ProxyResolverMac();
263 #else
264 NOTREACHED();
265 return NULL;
266 #endif
269 static bool IsSupported() {
270 #if defined(OS_WIN) || defined(OS_MACOSX)
271 return true;
272 #else
273 return false;
274 #endif
278 // Returns NetLog parameters describing a proxy configuration change.
279 base::Value* NetLogProxyConfigChangedCallback(
280 const ProxyConfig* old_config,
281 const ProxyConfig* new_config,
282 NetLog::LogLevel /* log_level */) {
283 base::DictionaryValue* dict = new base::DictionaryValue();
284 // The "old_config" is optional -- the first notification will not have
285 // any "previous" configuration.
286 if (old_config->is_valid())
287 dict->Set("old_config", old_config->ToValue());
288 dict->Set("new_config", new_config->ToValue());
289 return dict;
292 base::Value* NetLogBadProxyListCallback(const ProxyRetryInfoMap* retry_info,
293 NetLog::LogLevel /* log_level */) {
294 base::DictionaryValue* dict = new base::DictionaryValue();
295 base::ListValue* list = new base::ListValue();
297 for (ProxyRetryInfoMap::const_iterator iter = retry_info->begin();
298 iter != retry_info->end(); ++iter) {
299 list->Append(new base::StringValue(iter->first));
301 dict->Set("bad_proxy_list", list);
302 return dict;
305 // Returns NetLog parameters on a successfuly proxy resolution.
306 base::Value* NetLogFinishedResolvingProxyCallback(
307 ProxyInfo* result,
308 NetLog::LogLevel /* log_level */) {
309 base::DictionaryValue* dict = new base::DictionaryValue();
310 dict->SetString("pac_string", result->ToPacString());
311 return dict;
314 #if defined(OS_CHROMEOS)
315 class UnsetProxyConfigService : public ProxyConfigService {
316 public:
317 UnsetProxyConfigService() {}
318 virtual ~UnsetProxyConfigService() {}
320 virtual void AddObserver(Observer* observer) OVERRIDE {}
321 virtual void RemoveObserver(Observer* observer) OVERRIDE {}
322 virtual ConfigAvailability GetLatestProxyConfig(
323 ProxyConfig* config) OVERRIDE {
324 return CONFIG_UNSET;
327 #endif
329 } // namespace
331 // ProxyService::InitProxyResolver --------------------------------------------
333 // This glues together two asynchronous steps:
334 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
335 // to figure out what we should configure against.
336 // (2) Feed the fetched PAC script into the ProxyResolver.
338 // InitProxyResolver is a single-use class which encapsulates cancellation as
339 // part of its destructor. Start() or StartSkipDecider() should be called just
340 // once. The instance can be destroyed at any time, and the request will be
341 // cancelled.
343 class ProxyService::InitProxyResolver {
344 public:
345 InitProxyResolver()
346 : proxy_resolver_(NULL),
347 next_state_(STATE_NONE),
348 quick_check_enabled_(true) {
351 ~InitProxyResolver() {
352 // Note that the destruction of ProxyScriptDecider will automatically cancel
353 // any outstanding work.
354 if (next_state_ == STATE_SET_PAC_SCRIPT_COMPLETE) {
355 proxy_resolver_->CancelSetPacScript();
359 // Begins initializing the proxy resolver; calls |callback| when done.
360 int Start(ProxyResolver* proxy_resolver,
361 ProxyScriptFetcher* proxy_script_fetcher,
362 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
363 NetLog* net_log,
364 const ProxyConfig& config,
365 TimeDelta wait_delay,
366 const CompletionCallback& callback) {
367 DCHECK_EQ(STATE_NONE, next_state_);
368 proxy_resolver_ = proxy_resolver;
370 decider_.reset(new ProxyScriptDecider(
371 proxy_script_fetcher, dhcp_proxy_script_fetcher, net_log));
372 decider_->set_quick_check_enabled(quick_check_enabled_);
373 config_ = config;
374 wait_delay_ = wait_delay;
375 callback_ = callback;
377 next_state_ = STATE_DECIDE_PROXY_SCRIPT;
378 return DoLoop(OK);
381 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
382 // |effective_config|, |decider_result| and |script_data| will be used as the
383 // inputs for initializing the ProxyResolver.
384 int StartSkipDecider(ProxyResolver* proxy_resolver,
385 const ProxyConfig& effective_config,
386 int decider_result,
387 ProxyResolverScriptData* script_data,
388 const CompletionCallback& callback) {
389 DCHECK_EQ(STATE_NONE, next_state_);
390 proxy_resolver_ = proxy_resolver;
392 effective_config_ = effective_config;
393 script_data_ = script_data;
394 callback_ = callback;
396 if (decider_result != OK)
397 return decider_result;
399 next_state_ = STATE_SET_PAC_SCRIPT;
400 return DoLoop(OK);
403 // Returns the proxy configuration that was selected by ProxyScriptDecider.
404 // Should only be called upon completion of the initialization.
405 const ProxyConfig& effective_config() const {
406 DCHECK_EQ(STATE_NONE, next_state_);
407 return effective_config_;
410 // Returns the PAC script data that was selected by ProxyScriptDecider.
411 // Should only be called upon completion of the initialization.
412 ProxyResolverScriptData* script_data() {
413 DCHECK_EQ(STATE_NONE, next_state_);
414 return script_data_.get();
417 LoadState GetLoadState() const {
418 if (next_state_ == STATE_DECIDE_PROXY_SCRIPT_COMPLETE) {
419 // In addition to downloading, this state may also include the stall time
420 // after network change events (kDelayAfterNetworkChangesMs).
421 return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT;
423 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
426 void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
427 bool quick_check_enabled() const { return quick_check_enabled_; }
429 private:
430 enum State {
431 STATE_NONE,
432 STATE_DECIDE_PROXY_SCRIPT,
433 STATE_DECIDE_PROXY_SCRIPT_COMPLETE,
434 STATE_SET_PAC_SCRIPT,
435 STATE_SET_PAC_SCRIPT_COMPLETE,
438 int DoLoop(int result) {
439 DCHECK_NE(next_state_, STATE_NONE);
440 int rv = result;
441 do {
442 State state = next_state_;
443 next_state_ = STATE_NONE;
444 switch (state) {
445 case STATE_DECIDE_PROXY_SCRIPT:
446 DCHECK_EQ(OK, rv);
447 rv = DoDecideProxyScript();
448 break;
449 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE:
450 rv = DoDecideProxyScriptComplete(rv);
451 break;
452 case STATE_SET_PAC_SCRIPT:
453 DCHECK_EQ(OK, rv);
454 rv = DoSetPacScript();
455 break;
456 case STATE_SET_PAC_SCRIPT_COMPLETE:
457 rv = DoSetPacScriptComplete(rv);
458 break;
459 default:
460 NOTREACHED() << "bad state: " << state;
461 rv = ERR_UNEXPECTED;
462 break;
464 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
465 return rv;
468 int DoDecideProxyScript() {
469 next_state_ = STATE_DECIDE_PROXY_SCRIPT_COMPLETE;
471 return decider_->Start(
472 config_, wait_delay_, proxy_resolver_->expects_pac_bytes(),
473 base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
476 int DoDecideProxyScriptComplete(int result) {
477 if (result != OK)
478 return result;
480 effective_config_ = decider_->effective_config();
481 script_data_ = decider_->script_data();
483 next_state_ = STATE_SET_PAC_SCRIPT;
484 return OK;
487 int DoSetPacScript() {
488 DCHECK(script_data_.get());
489 // TODO(eroman): Should log this latency to the NetLog.
490 next_state_ = STATE_SET_PAC_SCRIPT_COMPLETE;
491 return proxy_resolver_->SetPacScript(
492 script_data_,
493 base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
496 int DoSetPacScriptComplete(int result) {
497 return result;
500 void OnIOCompletion(int result) {
501 DCHECK_NE(STATE_NONE, next_state_);
502 int rv = DoLoop(result);
503 if (rv != ERR_IO_PENDING)
504 DoCallback(rv);
507 void DoCallback(int result) {
508 DCHECK_NE(ERR_IO_PENDING, result);
509 callback_.Run(result);
512 ProxyConfig config_;
513 ProxyConfig effective_config_;
514 scoped_refptr<ProxyResolverScriptData> script_data_;
515 TimeDelta wait_delay_;
516 scoped_ptr<ProxyScriptDecider> decider_;
517 ProxyResolver* proxy_resolver_;
518 CompletionCallback callback_;
519 State next_state_;
520 bool quick_check_enabled_;
522 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver);
525 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
527 // This helper class encapsulates the logic to schedule and run periodic
528 // background checks to see if the PAC script (or effective proxy configuration)
529 // has changed. If a change is detected, then the caller will be notified via
530 // the ChangeCallback.
531 class ProxyService::ProxyScriptDeciderPoller {
532 public:
533 typedef base::Callback<void(int, ProxyResolverScriptData*,
534 const ProxyConfig&)> ChangeCallback;
536 // Builds a poller helper, and starts polling for updates. Whenever a change
537 // is observed, |callback| will be invoked with the details.
539 // |config| specifies the (unresolved) proxy configuration to poll.
540 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
541 // to use the resulting script data with
542 // (so it can choose the right format).
543 // |proxy_script_fetcher| this pointer must remain alive throughout our
544 // lifetime. It is the dependency that will be used
545 // for downloading proxy scripts.
546 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
547 // the DHCP dependency.
548 // |init_net_error| This is the initial network error (possibly success)
549 // encountered by the first PAC fetch attempt. We use it
550 // to schedule updates more aggressively if the initial
551 // fetch resulted in an error.
552 // |init_script_data| the initial script data from the PAC fetch attempt.
553 // This is the baseline used to determine when the
554 // script's contents have changed.
555 // |net_log| the NetLog to log progress into.
556 ProxyScriptDeciderPoller(ChangeCallback callback,
557 const ProxyConfig& config,
558 bool proxy_resolver_expects_pac_bytes,
559 ProxyScriptFetcher* proxy_script_fetcher,
560 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
561 int init_net_error,
562 ProxyResolverScriptData* init_script_data,
563 NetLog* net_log)
564 : weak_factory_(this),
565 change_callback_(callback),
566 config_(config),
567 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes),
568 proxy_script_fetcher_(proxy_script_fetcher),
569 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher),
570 last_error_(init_net_error),
571 last_script_data_(init_script_data),
572 last_poll_time_(TimeTicks::Now()) {
573 // Set the initial poll delay.
574 next_poll_mode_ = poll_policy()->GetNextDelay(
575 last_error_, TimeDelta::FromSeconds(-1), &next_poll_delay_);
576 TryToStartNextPoll(false);
579 void OnLazyPoll() {
580 // We have just been notified of network activity. Use this opportunity to
581 // see if we can start our next poll.
582 TryToStartNextPoll(true);
585 static const PacPollPolicy* set_policy(const PacPollPolicy* policy) {
586 const PacPollPolicy* prev = poll_policy_;
587 poll_policy_ = policy;
588 return prev;
591 void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
592 bool quick_check_enabled() const { return quick_check_enabled_; }
594 private:
595 // Returns the effective poll policy (the one injected by unit-tests, or the
596 // default).
597 const PacPollPolicy* poll_policy() {
598 if (poll_policy_)
599 return poll_policy_;
600 return &default_poll_policy_;
603 void StartPollTimer() {
604 DCHECK(!decider_.get());
606 base::MessageLoop::current()->PostDelayedTask(
607 FROM_HERE,
608 base::Bind(&ProxyScriptDeciderPoller::DoPoll,
609 weak_factory_.GetWeakPtr()),
610 next_poll_delay_);
613 void TryToStartNextPoll(bool triggered_by_activity) {
614 switch (next_poll_mode_) {
615 case PacPollPolicy::MODE_USE_TIMER:
616 if (!triggered_by_activity)
617 StartPollTimer();
618 break;
620 case PacPollPolicy::MODE_START_AFTER_ACTIVITY:
621 if (triggered_by_activity && !decider_.get()) {
622 TimeDelta elapsed_time = TimeTicks::Now() - last_poll_time_;
623 if (elapsed_time >= next_poll_delay_)
624 DoPoll();
626 break;
630 void DoPoll() {
631 last_poll_time_ = TimeTicks::Now();
633 // Start the proxy script decider to see if anything has changed.
634 // TODO(eroman): Pass a proper NetLog rather than NULL.
635 decider_.reset(new ProxyScriptDecider(
636 proxy_script_fetcher_, dhcp_proxy_script_fetcher_, NULL));
637 decider_->set_quick_check_enabled(quick_check_enabled_);
638 int result = decider_->Start(
639 config_, TimeDelta(), proxy_resolver_expects_pac_bytes_,
640 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted,
641 base::Unretained(this)));
643 if (result != ERR_IO_PENDING)
644 OnProxyScriptDeciderCompleted(result);
647 void OnProxyScriptDeciderCompleted(int result) {
648 if (HasScriptDataChanged(result, decider_->script_data())) {
649 // Something has changed, we must notify the ProxyService so it can
650 // re-initialize its ProxyResolver. Note that we post a notification task
651 // rather than calling it directly -- this is done to avoid an ugly
652 // destruction sequence, since |this| might be destroyed as a result of
653 // the notification.
654 base::MessageLoop::current()->PostTask(
655 FROM_HERE,
656 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange,
657 weak_factory_.GetWeakPtr(),
658 result,
659 make_scoped_refptr(decider_->script_data()),
660 decider_->effective_config()));
661 return;
664 decider_.reset();
666 // Decide when the next poll should take place, and possibly start the
667 // next timer.
668 next_poll_mode_ = poll_policy()->GetNextDelay(
669 last_error_, next_poll_delay_, &next_poll_delay_);
670 TryToStartNextPoll(false);
673 bool HasScriptDataChanged(int result, ProxyResolverScriptData* script_data) {
674 if (result != last_error_) {
675 // Something changed -- it was failing before and now it succeeded, or
676 // conversely it succeeded before and now it failed. Or it failed in
677 // both cases, however the specific failure error codes differ.
678 return true;
681 if (result != OK) {
682 // If it failed last time and failed again with the same error code this
683 // time, then nothing has actually changed.
684 return false;
687 // Otherwise if it succeeded both this time and last time, we need to look
688 // closer and see if we ended up downloading different content for the PAC
689 // script.
690 return !script_data->Equals(last_script_data_.get());
693 void NotifyProxyServiceOfChange(
694 int result,
695 const scoped_refptr<ProxyResolverScriptData>& script_data,
696 const ProxyConfig& effective_config) {
697 // Note that |this| may be deleted after calling into the ProxyService.
698 change_callback_.Run(result, script_data.get(), effective_config);
701 base::WeakPtrFactory<ProxyScriptDeciderPoller> weak_factory_;
703 ChangeCallback change_callback_;
704 ProxyConfig config_;
705 bool proxy_resolver_expects_pac_bytes_;
706 ProxyScriptFetcher* proxy_script_fetcher_;
707 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher_;
709 int last_error_;
710 scoped_refptr<ProxyResolverScriptData> last_script_data_;
712 scoped_ptr<ProxyScriptDecider> decider_;
713 TimeDelta next_poll_delay_;
714 PacPollPolicy::Mode next_poll_mode_;
716 TimeTicks last_poll_time_;
718 // Polling policy injected by unit-tests. Otherwise this is NULL and the
719 // default policy will be used.
720 static const PacPollPolicy* poll_policy_;
722 const DefaultPollPolicy default_poll_policy_;
724 bool quick_check_enabled_;
726 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller);
729 // static
730 const ProxyService::PacPollPolicy*
731 ProxyService::ProxyScriptDeciderPoller::poll_policy_ = NULL;
733 // ProxyService::PacRequest ---------------------------------------------------
735 class ProxyService::PacRequest
736 : public base::RefCounted<ProxyService::PacRequest> {
737 public:
738 PacRequest(ProxyService* service,
739 const GURL& url,
740 ProxyInfo* results,
741 const net::CompletionCallback& user_callback,
742 const BoundNetLog& net_log)
743 : service_(service),
744 user_callback_(user_callback),
745 results_(results),
746 url_(url),
747 resolve_job_(NULL),
748 config_id_(ProxyConfig::kInvalidConfigID),
749 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN),
750 net_log_(net_log) {
751 DCHECK(!user_callback.is_null());
754 // Starts the resolve proxy request.
755 int Start() {
756 DCHECK(!was_cancelled());
757 DCHECK(!is_started());
759 DCHECK(service_->config_.is_valid());
761 config_id_ = service_->config_.id();
762 config_source_ = service_->config_.source();
763 proxy_resolve_start_time_ = TimeTicks::Now();
765 return resolver()->GetProxyForURL(
766 url_, results_,
767 base::Bind(&PacRequest::QueryComplete, base::Unretained(this)),
768 &resolve_job_, net_log_);
771 bool is_started() const {
772 // Note that !! casts to bool. (VS gives a warning otherwise).
773 return !!resolve_job_;
776 void StartAndCompleteCheckingForSynchronous() {
777 int rv = service_->TryToCompleteSynchronously(url_, results_);
778 if (rv == ERR_IO_PENDING)
779 rv = Start();
780 if (rv != ERR_IO_PENDING)
781 QueryComplete(rv);
784 void CancelResolveJob() {
785 DCHECK(is_started());
786 // The request may already be running in the resolver.
787 resolver()->CancelRequest(resolve_job_);
788 resolve_job_ = NULL;
789 DCHECK(!is_started());
792 void Cancel() {
793 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
795 if (is_started())
796 CancelResolveJob();
798 // Mark as cancelled, to prevent accessing this again later.
799 service_ = NULL;
800 user_callback_.Reset();
801 results_ = NULL;
803 net_log_.EndEvent(NetLog::TYPE_PROXY_SERVICE);
806 // Returns true if Cancel() has been called.
807 bool was_cancelled() const {
808 return user_callback_.is_null();
811 // Helper to call after ProxyResolver completion (both synchronous and
812 // asynchronous). Fixes up the result that is to be returned to user.
813 int QueryDidComplete(int result_code) {
814 DCHECK(!was_cancelled());
816 // Note that DidFinishResolvingProxy might modify |results_|.
817 int rv = service_->DidFinishResolvingProxy(results_, result_code, net_log_);
819 // Make a note in the results which configuration was in use at the
820 // time of the resolve.
821 results_->config_id_ = config_id_;
822 results_->config_source_ = config_source_;
823 results_->did_use_pac_script_ = true;
824 results_->proxy_resolve_start_time_ = proxy_resolve_start_time_;
825 results_->proxy_resolve_end_time_ = TimeTicks::Now();
827 // Reset the state associated with in-progress-resolve.
828 resolve_job_ = NULL;
829 config_id_ = ProxyConfig::kInvalidConfigID;
830 config_source_ = PROXY_CONFIG_SOURCE_UNKNOWN;
832 return rv;
835 BoundNetLog* net_log() { return &net_log_; }
837 LoadState GetLoadState() const {
838 if (is_started())
839 return resolver()->GetLoadState(resolve_job_);
840 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
843 private:
844 friend class base::RefCounted<ProxyService::PacRequest>;
846 ~PacRequest() {}
848 // Callback for when the ProxyResolver request has completed.
849 void QueryComplete(int result_code) {
850 result_code = QueryDidComplete(result_code);
852 // Remove this completed PacRequest from the service's pending list.
853 /// (which will probably cause deletion of |this|).
854 if (!user_callback_.is_null()) {
855 net::CompletionCallback callback = user_callback_;
856 service_->RemovePendingRequest(this);
857 callback.Run(result_code);
861 ProxyResolver* resolver() const { return service_->resolver_.get(); }
863 // Note that we don't hold a reference to the ProxyService. Outstanding
864 // requests are cancelled during ~ProxyService, so this is guaranteed
865 // to be valid throughout our lifetime.
866 ProxyService* service_;
867 net::CompletionCallback user_callback_;
868 ProxyInfo* results_;
869 GURL url_;
870 ProxyResolver::RequestHandle resolve_job_;
871 ProxyConfig::ID config_id_; // The config id when the resolve was started.
872 ProxyConfigSource config_source_; // The source of proxy settings.
873 BoundNetLog net_log_;
874 // Time when the PAC is started. Cached here since resetting ProxyInfo also
875 // clears the proxy times.
876 TimeTicks proxy_resolve_start_time_;
879 // ProxyService ---------------------------------------------------------------
881 ProxyService::ProxyService(ProxyConfigService* config_service,
882 ProxyResolver* resolver,
883 NetLog* net_log)
884 : resolver_(resolver),
885 next_config_id_(1),
886 current_state_(STATE_NONE) ,
887 net_log_(net_log),
888 stall_proxy_auto_config_delay_(TimeDelta::FromMilliseconds(
889 kDelayAfterNetworkChangesMs)),
890 quick_check_enabled_(true) {
891 NetworkChangeNotifier::AddIPAddressObserver(this);
892 NetworkChangeNotifier::AddDNSObserver(this);
893 ResetConfigService(config_service);
896 // static
897 ProxyService* ProxyService::CreateUsingSystemProxyResolver(
898 ProxyConfigService* proxy_config_service,
899 size_t num_pac_threads,
900 NetLog* net_log) {
901 DCHECK(proxy_config_service);
903 if (!ProxyResolverFactoryForSystem::IsSupported()) {
904 LOG(WARNING) << "PAC support disabled because there is no "
905 "system implementation";
906 return CreateWithoutProxyResolver(proxy_config_service, net_log);
909 if (num_pac_threads == 0)
910 num_pac_threads = kDefaultNumPacThreads;
912 ProxyResolver* proxy_resolver = new MultiThreadedProxyResolver(
913 new ProxyResolverFactoryForSystem(), num_pac_threads);
915 return new ProxyService(proxy_config_service, proxy_resolver, net_log);
918 // static
919 ProxyService* ProxyService::CreateWithoutProxyResolver(
920 ProxyConfigService* proxy_config_service,
921 NetLog* net_log) {
922 return new ProxyService(proxy_config_service,
923 new ProxyResolverNull(),
924 net_log);
927 // static
928 ProxyService* ProxyService::CreateFixed(const ProxyConfig& pc) {
929 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
930 // a PAC script.
931 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc),
932 0, NULL);
935 // static
936 ProxyService* ProxyService::CreateFixed(const std::string& proxy) {
937 net::ProxyConfig proxy_config;
938 proxy_config.proxy_rules().ParseFromString(proxy);
939 return ProxyService::CreateFixed(proxy_config);
942 // static
943 ProxyService* ProxyService::CreateDirect() {
944 return CreateDirectWithNetLog(NULL);
947 ProxyService* ProxyService::CreateDirectWithNetLog(NetLog* net_log) {
948 // Use direct connections.
949 return new ProxyService(new ProxyConfigServiceDirect, new ProxyResolverNull,
950 net_log);
953 // static
954 ProxyService* ProxyService::CreateFixedFromPacResult(
955 const std::string& pac_string) {
957 // We need the settings to contain an "automatic" setting, otherwise the
958 // ProxyResolver dependency we give it will never be used.
959 scoped_ptr<ProxyConfigService> proxy_config_service(
960 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
962 scoped_ptr<ProxyResolver> proxy_resolver(
963 new ProxyResolverFromPacString(pac_string));
965 return new ProxyService(proxy_config_service.release(),
966 proxy_resolver.release(),
967 NULL);
970 int ProxyService::ResolveProxy(const GURL& raw_url,
971 ProxyInfo* result,
972 const net::CompletionCallback& callback,
973 PacRequest** pac_request,
974 const BoundNetLog& net_log) {
975 DCHECK(CalledOnValidThread());
976 DCHECK(!callback.is_null());
978 net_log.BeginEvent(NetLog::TYPE_PROXY_SERVICE);
980 // Notify our polling-based dependencies that a resolve is taking place.
981 // This way they can schedule their polls in response to network activity.
982 config_service_->OnLazyPoll();
983 if (script_poller_.get())
984 script_poller_->OnLazyPoll();
986 if (current_state_ == STATE_NONE)
987 ApplyProxyConfigIfAvailable();
989 // Strip away any reference fragments and the username/password, as they
990 // are not relevant to proxy resolution.
991 GURL url = SimplifyUrlForRequest(raw_url);
993 // Check if the request can be completed right away. (This is the case when
994 // using a direct connection for example).
995 int rv = TryToCompleteSynchronously(url, result);
996 if (rv != ERR_IO_PENDING)
997 return DidFinishResolvingProxy(result, rv, net_log);
999 scoped_refptr<PacRequest> req(
1000 new PacRequest(this, url, result, callback, net_log));
1002 if (current_state_ == STATE_READY) {
1003 // Start the resolve request.
1004 rv = req->Start();
1005 if (rv != ERR_IO_PENDING)
1006 return req->QueryDidComplete(rv);
1007 } else {
1008 req->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1011 DCHECK_EQ(ERR_IO_PENDING, rv);
1012 DCHECK(!ContainsPendingRequest(req.get()));
1013 pending_requests_.push_back(req);
1015 // Completion will be notified through |callback|, unless the caller cancels
1016 // the request using |pac_request|.
1017 if (pac_request)
1018 *pac_request = req.get();
1019 return rv; // ERR_IO_PENDING
1022 int ProxyService::TryToCompleteSynchronously(const GURL& url,
1023 ProxyInfo* result) {
1024 DCHECK_NE(STATE_NONE, current_state_);
1026 if (current_state_ != STATE_READY)
1027 return ERR_IO_PENDING; // Still initializing.
1029 DCHECK_NE(config_.id(), ProxyConfig::kInvalidConfigID);
1031 // If it was impossible to fetch or parse the PAC script, we cannot complete
1032 // the request here and bail out.
1033 if (permanent_error_ != OK)
1034 return permanent_error_;
1036 if (config_.HasAutomaticSettings())
1037 return ERR_IO_PENDING; // Must submit the request to the proxy resolver.
1039 // Use the manual proxy settings.
1040 config_.proxy_rules().Apply(url, result);
1041 result->config_source_ = config_.source();
1042 result->config_id_ = config_.id();
1043 return OK;
1046 ProxyService::~ProxyService() {
1047 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1048 NetworkChangeNotifier::RemoveDNSObserver(this);
1049 config_service_->RemoveObserver(this);
1051 // Cancel any inprogress requests.
1052 for (PendingRequests::iterator it = pending_requests_.begin();
1053 it != pending_requests_.end();
1054 ++it) {
1055 (*it)->Cancel();
1059 void ProxyService::SuspendAllPendingRequests() {
1060 for (PendingRequests::iterator it = pending_requests_.begin();
1061 it != pending_requests_.end();
1062 ++it) {
1063 PacRequest* req = it->get();
1064 if (req->is_started()) {
1065 req->CancelResolveJob();
1067 req->net_log()->BeginEvent(
1068 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1073 void ProxyService::SetReady() {
1074 DCHECK(!init_proxy_resolver_.get());
1075 current_state_ = STATE_READY;
1077 // Make a copy in case |this| is deleted during the synchronous completion
1078 // of one of the requests. If |this| is deleted then all of the PacRequest
1079 // instances will be Cancel()-ed.
1080 PendingRequests pending_copy = pending_requests_;
1082 for (PendingRequests::iterator it = pending_copy.begin();
1083 it != pending_copy.end();
1084 ++it) {
1085 PacRequest* req = it->get();
1086 if (!req->is_started() && !req->was_cancelled()) {
1087 req->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1089 // Note that we re-check for synchronous completion, in case we are
1090 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1091 req->StartAndCompleteCheckingForSynchronous();
1096 void ProxyService::ApplyProxyConfigIfAvailable() {
1097 DCHECK_EQ(STATE_NONE, current_state_);
1099 config_service_->OnLazyPoll();
1101 // If we have already fetched the configuration, start applying it.
1102 if (fetched_config_.is_valid()) {
1103 InitializeUsingLastFetchedConfig();
1104 return;
1107 // Otherwise we need to first fetch the configuration.
1108 current_state_ = STATE_WAITING_FOR_PROXY_CONFIG;
1110 // Retrieve the current proxy configuration from the ProxyConfigService.
1111 // If a configuration is not available yet, we will get called back later
1112 // by our ProxyConfigService::Observer once it changes.
1113 ProxyConfig config;
1114 ProxyConfigService::ConfigAvailability availability =
1115 config_service_->GetLatestProxyConfig(&config);
1116 if (availability != ProxyConfigService::CONFIG_PENDING)
1117 OnProxyConfigChanged(config, availability);
1120 void ProxyService::OnInitProxyResolverComplete(int result) {
1121 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER, current_state_);
1122 DCHECK(init_proxy_resolver_.get());
1123 DCHECK(fetched_config_.HasAutomaticSettings());
1124 config_ = init_proxy_resolver_->effective_config();
1126 // At this point we have decided which proxy settings to use (i.e. which PAC
1127 // script if any). We start up a background poller to periodically revisit
1128 // this decision. If the contents of the PAC script change, or if the
1129 // result of proxy auto-discovery changes, this poller will notice it and
1130 // will trigger a re-initialization using the newly discovered PAC.
1131 script_poller_.reset(new ProxyScriptDeciderPoller(
1132 base::Bind(&ProxyService::InitializeUsingDecidedConfig,
1133 base::Unretained(this)),
1134 fetched_config_,
1135 resolver_->expects_pac_bytes(),
1136 proxy_script_fetcher_.get(),
1137 dhcp_proxy_script_fetcher_.get(),
1138 result,
1139 init_proxy_resolver_->script_data(),
1140 NULL));
1141 script_poller_->set_quick_check_enabled(quick_check_enabled_);
1143 init_proxy_resolver_.reset();
1145 if (result != OK) {
1146 if (fetched_config_.pac_mandatory()) {
1147 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1148 "traffic.";
1149 config_ = fetched_config_;
1150 result = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
1151 } else {
1152 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1153 "proxy servers.";
1154 config_ = fetched_config_;
1155 config_.ClearAutomaticSettings();
1156 result = OK;
1159 permanent_error_ = result;
1161 // TODO(eroman): Make this ID unique in the case where configuration changed
1162 // due to ProxyScriptDeciderPoller.
1163 config_.set_id(fetched_config_.id());
1164 config_.set_source(fetched_config_.source());
1166 // Resume any requests which we had to defer until the PAC script was
1167 // downloaded.
1168 SetReady();
1171 int ProxyService::ReconsiderProxyAfterError(const GURL& url,
1172 int net_error,
1173 ProxyInfo* result,
1174 const CompletionCallback& callback,
1175 PacRequest** pac_request,
1176 const BoundNetLog& net_log) {
1177 DCHECK(CalledOnValidThread());
1179 // Check to see if we have a new config since ResolveProxy was called. We
1180 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1181 // direct connection failed and we never tried the current config.
1183 bool re_resolve = result->config_id_ != config_.id();
1185 if (re_resolve) {
1186 // If we have a new config or the config was never tried, we delete the
1187 // list of bad proxies and we try again.
1188 proxy_retry_info_.clear();
1189 return ResolveProxy(url, result, callback, pac_request, net_log);
1192 #if defined(SPDY_PROXY_AUTH_ORIGIN)
1193 if (result->proxy_server().isDataReductionProxy()) {
1194 RecordDataReductionProxyBypassInfo(
1195 true, result->proxy_server(), ERROR_BYPASS);
1196 RecordDataReductionProxyBypassOnNetworkError(
1197 true, result->proxy_server(), net_error);
1198 } else if (result->proxy_server().isDataReductionProxyFallback()) {
1199 RecordDataReductionProxyBypassInfo(
1200 false, result->proxy_server(), ERROR_BYPASS);
1201 RecordDataReductionProxyBypassOnNetworkError(
1202 false, result->proxy_server(), net_error);
1204 #endif
1206 // We don't have new proxy settings to try, try to fallback to the next proxy
1207 // in the list.
1208 bool did_fallback = result->Fallback(net_log);
1210 // Return synchronous failure if there is nothing left to fall-back to.
1211 // TODO(eroman): This is a yucky API, clean it up.
1212 return did_fallback ? OK : ERR_FAILED;
1215 bool ProxyService::MarkProxiesAsBadUntil(
1216 const ProxyInfo& result,
1217 base::TimeDelta retry_delay,
1218 const ProxyServer& another_bad_proxy,
1219 const BoundNetLog& net_log) {
1220 result.proxy_list_.UpdateRetryInfoOnFallback(&proxy_retry_info_, retry_delay,
1221 false,
1222 another_bad_proxy,
1223 net_log);
1224 if (another_bad_proxy.is_valid())
1225 return result.proxy_list_.size() > 2;
1226 else
1227 return result.proxy_list_.size() > 1;
1230 void ProxyService::ReportSuccess(const ProxyInfo& result) {
1231 DCHECK(CalledOnValidThread());
1233 const ProxyRetryInfoMap& new_retry_info = result.proxy_retry_info();
1234 if (new_retry_info.empty())
1235 return;
1237 for (ProxyRetryInfoMap::const_iterator iter = new_retry_info.begin();
1238 iter != new_retry_info.end(); ++iter) {
1239 ProxyRetryInfoMap::iterator existing = proxy_retry_info_.find(iter->first);
1240 if (existing == proxy_retry_info_.end())
1241 proxy_retry_info_[iter->first] = iter->second;
1242 else if (existing->second.bad_until < iter->second.bad_until)
1243 existing->second.bad_until = iter->second.bad_until;
1245 if (net_log_) {
1246 net_log_->AddGlobalEntry(
1247 NetLog::TYPE_BAD_PROXY_LIST_REPORTED,
1248 base::Bind(&NetLogBadProxyListCallback, &new_retry_info));
1252 void ProxyService::CancelPacRequest(PacRequest* req) {
1253 DCHECK(CalledOnValidThread());
1254 DCHECK(req);
1255 req->Cancel();
1256 RemovePendingRequest(req);
1259 LoadState ProxyService::GetLoadState(const PacRequest* req) const {
1260 CHECK(req);
1261 if (current_state_ == STATE_WAITING_FOR_INIT_PROXY_RESOLVER)
1262 return init_proxy_resolver_->GetLoadState();
1263 return req->GetLoadState();
1266 bool ProxyService::ContainsPendingRequest(PacRequest* req) {
1267 PendingRequests::iterator it = std::find(
1268 pending_requests_.begin(), pending_requests_.end(), req);
1269 return pending_requests_.end() != it;
1272 void ProxyService::RemovePendingRequest(PacRequest* req) {
1273 DCHECK(ContainsPendingRequest(req));
1274 PendingRequests::iterator it = std::find(
1275 pending_requests_.begin(), pending_requests_.end(), req);
1276 pending_requests_.erase(it);
1279 int ProxyService::DidFinishResolvingProxy(ProxyInfo* result,
1280 int result_code,
1281 const BoundNetLog& net_log) {
1282 // Log the result of the proxy resolution.
1283 if (result_code == OK) {
1284 // When logging all events is enabled, dump the proxy list.
1285 if (net_log.IsLogging()) {
1286 net_log.AddEvent(
1287 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST,
1288 base::Bind(&NetLogFinishedResolvingProxyCallback, result));
1290 result->DeprioritizeBadProxies(proxy_retry_info_);
1291 } else {
1292 net_log.AddEventWithNetErrorCode(
1293 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST, result_code);
1295 if (!config_.pac_mandatory()) {
1296 // Fall-back to direct when the proxy resolver fails. This corresponds
1297 // with a javascript runtime error in the PAC script.
1299 // This implicit fall-back to direct matches Firefox 3.5 and
1300 // Internet Explorer 8. For more information, see:
1302 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1303 result->UseDirect();
1304 result_code = OK;
1305 } else {
1306 result_code = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
1310 net_log.EndEvent(NetLog::TYPE_PROXY_SERVICE);
1311 return result_code;
1314 void ProxyService::SetProxyScriptFetchers(
1315 ProxyScriptFetcher* proxy_script_fetcher,
1316 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher) {
1317 DCHECK(CalledOnValidThread());
1318 State previous_state = ResetProxyConfig(false);
1319 proxy_script_fetcher_.reset(proxy_script_fetcher);
1320 dhcp_proxy_script_fetcher_.reset(dhcp_proxy_script_fetcher);
1321 if (previous_state != STATE_NONE)
1322 ApplyProxyConfigIfAvailable();
1325 ProxyScriptFetcher* ProxyService::GetProxyScriptFetcher() const {
1326 DCHECK(CalledOnValidThread());
1327 return proxy_script_fetcher_.get();
1330 ProxyService::State ProxyService::ResetProxyConfig(bool reset_fetched_config) {
1331 DCHECK(CalledOnValidThread());
1332 State previous_state = current_state_;
1334 permanent_error_ = OK;
1335 proxy_retry_info_.clear();
1336 script_poller_.reset();
1337 init_proxy_resolver_.reset();
1338 SuspendAllPendingRequests();
1339 config_ = ProxyConfig();
1340 if (reset_fetched_config)
1341 fetched_config_ = ProxyConfig();
1342 current_state_ = STATE_NONE;
1344 return previous_state;
1347 void ProxyService::ResetConfigService(
1348 ProxyConfigService* new_proxy_config_service) {
1349 DCHECK(CalledOnValidThread());
1350 State previous_state = ResetProxyConfig(true);
1352 // Release the old configuration service.
1353 if (config_service_.get())
1354 config_service_->RemoveObserver(this);
1356 // Set the new configuration service.
1357 config_service_.reset(new_proxy_config_service);
1358 config_service_->AddObserver(this);
1360 if (previous_state != STATE_NONE)
1361 ApplyProxyConfigIfAvailable();
1364 void ProxyService::ForceReloadProxyConfig() {
1365 DCHECK(CalledOnValidThread());
1366 ResetProxyConfig(false);
1367 ApplyProxyConfigIfAvailable();
1370 // static
1371 ProxyConfigService* ProxyService::CreateSystemProxyConfigService(
1372 base::SingleThreadTaskRunner* io_thread_task_runner,
1373 base::MessageLoop* file_loop) {
1374 #if defined(OS_WIN)
1375 return new ProxyConfigServiceWin();
1376 #elif defined(OS_IOS)
1377 return new ProxyConfigServiceIOS();
1378 #elif defined(OS_MACOSX)
1379 return new ProxyConfigServiceMac(io_thread_task_runner);
1380 #elif defined(OS_CHROMEOS)
1381 LOG(ERROR) << "ProxyConfigService for ChromeOS should be created in "
1382 << "profile_io_data.cc::CreateProxyConfigService and this should "
1383 << "be used only for examples.";
1384 return new UnsetProxyConfigService;
1385 #elif defined(OS_LINUX)
1386 ProxyConfigServiceLinux* linux_config_service =
1387 new ProxyConfigServiceLinux();
1389 // Assume we got called on the thread that runs the default glib
1390 // main loop, so the current thread is where we should be running
1391 // gconf calls from.
1392 scoped_refptr<base::SingleThreadTaskRunner> glib_thread_task_runner =
1393 base::ThreadTaskRunnerHandle::Get();
1395 // The file loop should be a MessageLoopForIO on Linux.
1396 DCHECK_EQ(base::MessageLoop::TYPE_IO, file_loop->type());
1398 // Synchronously fetch the current proxy config (since we are
1399 // running on glib_default_loop). Additionally register for
1400 // notifications (delivered in either |glib_default_loop| or
1401 // |file_loop|) to keep us updated when the proxy config changes.
1402 linux_config_service->SetupAndFetchInitialConfig(
1403 glib_thread_task_runner.get(),
1404 io_thread_task_runner,
1405 static_cast<base::MessageLoopForIO*>(file_loop));
1407 return linux_config_service;
1408 #elif defined(OS_ANDROID)
1409 return new ProxyConfigServiceAndroid(
1410 io_thread_task_runner,
1411 base::MessageLoop::current()->message_loop_proxy());
1412 #else
1413 LOG(WARNING) << "Failed to choose a system proxy settings fetcher "
1414 "for this platform.";
1415 return new ProxyConfigServiceDirect();
1416 #endif
1419 // static
1420 const ProxyService::PacPollPolicy* ProxyService::set_pac_script_poll_policy(
1421 const PacPollPolicy* policy) {
1422 return ProxyScriptDeciderPoller::set_policy(policy);
1425 // static
1426 scoped_ptr<ProxyService::PacPollPolicy>
1427 ProxyService::CreateDefaultPacPollPolicy() {
1428 return scoped_ptr<PacPollPolicy>(new DefaultPollPolicy());
1431 #if defined(SPDY_PROXY_AUTH_ORIGIN)
1432 void ProxyService::RecordDataReductionProxyBypassInfo(
1433 bool is_primary,
1434 const ProxyServer& proxy_server,
1435 DataReductionProxyBypassEventType bypass_type) const {
1436 // Only record UMA if the proxy isn't already on the retry list.
1437 if (proxy_retry_info_.find(proxy_server.ToURI()) != proxy_retry_info_.end())
1438 return;
1440 if (is_primary) {
1441 UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.BypassInfoPrimary",
1442 bypass_type, BYPASS_EVENT_TYPE_MAX);
1443 } else {
1444 UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.BypassInfoFallback",
1445 bypass_type, BYPASS_EVENT_TYPE_MAX);
1449 void ProxyService::RecordDataReductionProxyBypassOnNetworkError(
1450 bool is_primary,
1451 const ProxyServer& proxy_server,
1452 int net_error) {
1453 // Only record UMA if the proxy isn't already on the retry list.
1454 if (proxy_retry_info_.find(proxy_server.ToURI()) != proxy_retry_info_.end())
1455 return;
1457 if (is_primary) {
1458 UMA_HISTOGRAM_SPARSE_SLOWLY(
1459 "DataReductionProxy.BypassOnNetworkErrorPrimary",
1460 std::abs(net_error));
1461 return;
1463 UMA_HISTOGRAM_SPARSE_SLOWLY(
1464 "DataReductionProxy.BypassOnNetworkErrorFallback",
1465 std::abs(net_error));
1467 #endif // defined(SPDY_PROXY_AUTH_ORIGIN)
1469 void ProxyService::OnProxyConfigChanged(
1470 const ProxyConfig& config,
1471 ProxyConfigService::ConfigAvailability availability) {
1472 // Retrieve the current proxy configuration from the ProxyConfigService.
1473 // If a configuration is not available yet, we will get called back later
1474 // by our ProxyConfigService::Observer once it changes.
1475 ProxyConfig effective_config;
1476 switch (availability) {
1477 case ProxyConfigService::CONFIG_PENDING:
1478 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1479 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1480 return;
1481 case ProxyConfigService::CONFIG_VALID:
1482 effective_config = config;
1483 break;
1484 case ProxyConfigService::CONFIG_UNSET:
1485 effective_config = ProxyConfig::CreateDirect();
1486 break;
1489 // Emit the proxy settings change to the NetLog stream.
1490 if (net_log_) {
1491 net_log_->AddGlobalEntry(
1492 net::NetLog::TYPE_PROXY_CONFIG_CHANGED,
1493 base::Bind(&NetLogProxyConfigChangedCallback,
1494 &fetched_config_, &effective_config));
1497 // Set the new configuration as the most recently fetched one.
1498 fetched_config_ = effective_config;
1499 fetched_config_.set_id(1); // Needed for a later DCHECK of is_valid().
1501 InitializeUsingLastFetchedConfig();
1504 void ProxyService::InitializeUsingLastFetchedConfig() {
1505 ResetProxyConfig(false);
1507 DCHECK(fetched_config_.is_valid());
1509 // Increment the ID to reflect that the config has changed.
1510 fetched_config_.set_id(next_config_id_++);
1512 if (!fetched_config_.HasAutomaticSettings()) {
1513 config_ = fetched_config_;
1514 SetReady();
1515 return;
1518 // Start downloading + testing the PAC scripts for this new configuration.
1519 current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
1521 // If we changed networks recently, we should delay running proxy auto-config.
1522 TimeDelta wait_delay =
1523 stall_proxy_autoconfig_until_ - TimeTicks::Now();
1525 init_proxy_resolver_.reset(new InitProxyResolver());
1526 init_proxy_resolver_->set_quick_check_enabled(quick_check_enabled_);
1527 int rv = init_proxy_resolver_->Start(
1528 resolver_.get(),
1529 proxy_script_fetcher_.get(),
1530 dhcp_proxy_script_fetcher_.get(),
1531 net_log_,
1532 fetched_config_,
1533 wait_delay,
1534 base::Bind(&ProxyService::OnInitProxyResolverComplete,
1535 base::Unretained(this)));
1537 if (rv != ERR_IO_PENDING)
1538 OnInitProxyResolverComplete(rv);
1541 void ProxyService::InitializeUsingDecidedConfig(
1542 int decider_result,
1543 ProxyResolverScriptData* script_data,
1544 const ProxyConfig& effective_config) {
1545 DCHECK(fetched_config_.is_valid());
1546 DCHECK(fetched_config_.HasAutomaticSettings());
1548 ResetProxyConfig(false);
1550 current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
1552 init_proxy_resolver_.reset(new InitProxyResolver());
1553 int rv = init_proxy_resolver_->StartSkipDecider(
1554 resolver_.get(),
1555 effective_config,
1556 decider_result,
1557 script_data,
1558 base::Bind(&ProxyService::OnInitProxyResolverComplete,
1559 base::Unretained(this)));
1561 if (rv != ERR_IO_PENDING)
1562 OnInitProxyResolverComplete(rv);
1565 void ProxyService::OnIPAddressChanged() {
1566 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1567 stall_proxy_autoconfig_until_ =
1568 TimeTicks::Now() + stall_proxy_auto_config_delay_;
1570 State previous_state = ResetProxyConfig(false);
1571 if (previous_state != STATE_NONE)
1572 ApplyProxyConfigIfAvailable();
1575 void ProxyService::OnDNSChanged() {
1576 OnIPAddressChanged();
1579 SyncProxyServiceHelper::SyncProxyServiceHelper(
1580 base::MessageLoop* io_message_loop,
1581 ProxyService* proxy_service)
1582 : io_message_loop_(io_message_loop),
1583 proxy_service_(proxy_service),
1584 event_(false, false),
1585 callback_(base::Bind(&SyncProxyServiceHelper::OnCompletion,
1586 base::Unretained(this))) {
1587 DCHECK(io_message_loop_ != base::MessageLoop::current());
1590 int SyncProxyServiceHelper::ResolveProxy(const GURL& url,
1591 ProxyInfo* proxy_info,
1592 const BoundNetLog& net_log) {
1593 DCHECK(io_message_loop_ != base::MessageLoop::current());
1595 io_message_loop_->PostTask(
1596 FROM_HERE,
1597 base::Bind(&SyncProxyServiceHelper::StartAsyncResolve, this, url,
1598 net_log));
1600 event_.Wait();
1602 if (result_ == net::OK) {
1603 *proxy_info = proxy_info_;
1605 return result_;
1608 int SyncProxyServiceHelper::ReconsiderProxyAfterError(
1609 const GURL& url, int net_error, ProxyInfo* proxy_info,
1610 const BoundNetLog& net_log) {
1611 DCHECK(io_message_loop_ != base::MessageLoop::current());
1613 io_message_loop_->PostTask(
1614 FROM_HERE,
1615 base::Bind(&SyncProxyServiceHelper::StartAsyncReconsider, this, url,
1616 net_error, net_log));
1618 event_.Wait();
1620 if (result_ == net::OK) {
1621 *proxy_info = proxy_info_;
1623 return result_;
1626 SyncProxyServiceHelper::~SyncProxyServiceHelper() {}
1628 void SyncProxyServiceHelper::StartAsyncResolve(const GURL& url,
1629 const BoundNetLog& net_log) {
1630 result_ = proxy_service_->ResolveProxy(
1631 url, &proxy_info_, callback_, NULL, net_log);
1632 if (result_ != net::ERR_IO_PENDING) {
1633 OnCompletion(result_);
1637 void SyncProxyServiceHelper::StartAsyncReconsider(const GURL& url,
1638 int net_error,
1639 const BoundNetLog& net_log) {
1640 result_ = proxy_service_->ReconsiderProxyAfterError(
1641 url, net_error, &proxy_info_, callback_, NULL, net_log);
1642 if (result_ != net::ERR_IO_PENDING) {
1643 OnCompletion(result_);
1647 void SyncProxyServiceHelper::OnCompletion(int rv) {
1648 result_ = rv;
1649 event_.Signal();
1652 } // namespace net