Show Pages in chrome://md-settings
[chromium-blink-merge.git] / net / proxy / proxy_service.cc
blobcd6e376be5299c05af52adcad7631eb14a38a358
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/profiler/scoped_tracker.h"
17 #include "base/strings/string_util.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/values.h"
20 #include "net/base/completion_callback.h"
21 #include "net/base/load_flags.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/net_log.h"
24 #include "net/base/net_util.h"
25 #include "net/proxy/dhcp_proxy_script_fetcher.h"
26 #include "net/proxy/multi_threaded_proxy_resolver.h"
27 #include "net/proxy/network_delegate_error_observer.h"
28 #include "net/proxy/proxy_config_service_fixed.h"
29 #include "net/proxy/proxy_resolver.h"
30 #include "net/proxy/proxy_script_decider.h"
31 #include "net/proxy/proxy_script_fetcher.h"
32 #include "net/url_request/url_request_context.h"
33 #include "url/gurl.h"
35 #if defined(OS_WIN)
36 #include "net/proxy/proxy_config_service_win.h"
37 #include "net/proxy/proxy_resolver_winhttp.h"
38 #elif defined(OS_IOS)
39 #include "net/proxy/proxy_config_service_ios.h"
40 #include "net/proxy/proxy_resolver_mac.h"
41 #elif defined(OS_MACOSX)
42 #include "net/proxy/proxy_config_service_mac.h"
43 #include "net/proxy/proxy_resolver_mac.h"
44 #elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
45 #include "net/proxy/proxy_config_service_linux.h"
46 #elif defined(OS_ANDROID)
47 #include "net/proxy/proxy_config_service_android.h"
48 #endif
50 using base::TimeDelta;
51 using base::TimeTicks;
53 namespace net {
55 namespace {
57 // When the IP address changes we don't immediately re-run proxy auto-config.
58 // Instead, we wait for |kDelayAfterNetworkChangesMs| before
59 // attempting to re-valuate proxy auto-config.
61 // During this time window, any resolve requests sent to the ProxyService will
62 // be queued. Once we have waited the required amount of them, the proxy
63 // auto-config step will be run, and the queued requests resumed.
65 // The reason we play this game is that our signal for detecting network
66 // changes (NetworkChangeNotifier) may fire *before* the system's networking
67 // dependencies are fully configured. This is a problem since it means if
68 // we were to run proxy auto-config right away, it could fail due to spurious
69 // DNS failures. (see http://crbug.com/50779 for more details.)
71 // By adding the wait window, we give things a better chance to get properly
72 // set up. Network failures can happen at any time though, so we additionally
73 // poll the PAC script for changes, which will allow us to recover from these
74 // sorts of problems.
75 const int64 kDelayAfterNetworkChangesMs = 2000;
77 // This is the default policy for polling the PAC script.
79 // In response to a failure, the poll intervals are:
80 // 0: 8 seconds (scheduled on timer)
81 // 1: 32 seconds
82 // 2: 2 minutes
83 // 3+: 4 hours
85 // In response to a success, the poll intervals are:
86 // 0+: 12 hours
88 // Only the 8 second poll is scheduled on a timer, the rest happen in response
89 // to network activity (and hence will take longer than the written time).
91 // Explanation for these values:
93 // TODO(eroman): These values are somewhat arbitrary, and need to be tuned
94 // using some histograms data. Trying to be conservative so as not to break
95 // existing setups when deployed. A simple exponential retry scheme would be
96 // more elegant, but places more load on server.
98 // The motivation for trying quickly after failures (8 seconds) is to recover
99 // from spurious network failures, which are common after the IP address has
100 // just changed (like DNS failing to resolve). The next 32 second boundary is
101 // to try and catch other VPN weirdness which anecdotally I have seen take
102 // 10+ seconds for some users.
104 // The motivation for re-trying after a success is to check for possible
105 // content changes to the script, or to the WPAD auto-discovery results. We are
106 // not very aggressive with these checks so as to minimize the risk of
107 // overloading existing PAC setups. Moreover it is unlikely that PAC scripts
108 // change very frequently in existing setups. More research is needed to
109 // motivate what safe values are here, and what other user agents do.
111 // Comparison to other browsers:
113 // In Firefox the PAC URL is re-tried on failures according to
114 // network.proxy.autoconfig_retry_interval_min and
115 // network.proxy.autoconfig_retry_interval_max. The defaults are 5 seconds and
116 // 5 minutes respectively. It doubles the interval at each attempt.
118 // TODO(eroman): Figure out what Internet Explorer does.
119 class DefaultPollPolicy : public ProxyService::PacPollPolicy {
120 public:
121 DefaultPollPolicy() {}
123 Mode GetNextDelay(int initial_error,
124 TimeDelta current_delay,
125 TimeDelta* next_delay) const override {
126 if (initial_error != OK) {
127 // Re-try policy for failures.
128 const int kDelay1Seconds = 8;
129 const int kDelay2Seconds = 32;
130 const int kDelay3Seconds = 2 * 60; // 2 minutes
131 const int kDelay4Seconds = 4 * 60 * 60; // 4 Hours
133 // Initial poll.
134 if (current_delay < TimeDelta()) {
135 *next_delay = TimeDelta::FromSeconds(kDelay1Seconds);
136 return MODE_USE_TIMER;
138 switch (current_delay.InSeconds()) {
139 case kDelay1Seconds:
140 *next_delay = TimeDelta::FromSeconds(kDelay2Seconds);
141 return MODE_START_AFTER_ACTIVITY;
142 case kDelay2Seconds:
143 *next_delay = TimeDelta::FromSeconds(kDelay3Seconds);
144 return MODE_START_AFTER_ACTIVITY;
145 default:
146 *next_delay = TimeDelta::FromSeconds(kDelay4Seconds);
147 return MODE_START_AFTER_ACTIVITY;
149 } else {
150 // Re-try policy for succeses.
151 *next_delay = TimeDelta::FromHours(12);
152 return MODE_START_AFTER_ACTIVITY;
156 private:
157 DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy);
160 // Config getter that always returns direct settings.
161 class ProxyConfigServiceDirect : public ProxyConfigService {
162 public:
163 // ProxyConfigService implementation:
164 void AddObserver(Observer* observer) override {}
165 void RemoveObserver(Observer* observer) override {}
166 ConfigAvailability GetLatestProxyConfig(ProxyConfig* config) override {
167 *config = ProxyConfig::CreateDirect();
168 config->set_source(PROXY_CONFIG_SOURCE_UNKNOWN);
169 return CONFIG_VALID;
173 // Proxy resolver that fails every time.
174 class ProxyResolverNull : public ProxyResolver {
175 public:
176 ProxyResolverNull() : ProxyResolver(false /*expects_pac_bytes*/) {}
178 // ProxyResolver implementation.
179 int GetProxyForURL(const GURL& url,
180 ProxyInfo* results,
181 const CompletionCallback& callback,
182 RequestHandle* request,
183 const BoundNetLog& net_log) override {
184 return ERR_NOT_IMPLEMENTED;
187 void CancelRequest(RequestHandle request) override { NOTREACHED(); }
189 LoadState GetLoadState(RequestHandle request) const override {
190 NOTREACHED();
191 return LOAD_STATE_IDLE;
194 void CancelSetPacScript() override { NOTREACHED(); }
196 int SetPacScript(
197 const scoped_refptr<ProxyResolverScriptData>& /*script_data*/,
198 const CompletionCallback& /*callback*/) override {
199 return ERR_NOT_IMPLEMENTED;
203 // ProxyResolver that simulates a PAC script which returns
204 // |pac_string| for every single URL.
205 class ProxyResolverFromPacString : public ProxyResolver {
206 public:
207 explicit ProxyResolverFromPacString(const std::string& pac_string)
208 : ProxyResolver(false /*expects_pac_bytes*/),
209 pac_string_(pac_string) {}
211 int GetProxyForURL(const GURL& url,
212 ProxyInfo* results,
213 const CompletionCallback& callback,
214 RequestHandle* request,
215 const BoundNetLog& net_log) override {
216 results->UsePacString(pac_string_);
217 return OK;
220 void CancelRequest(RequestHandle request) override { NOTREACHED(); }
222 LoadState GetLoadState(RequestHandle request) const override {
223 NOTREACHED();
224 return LOAD_STATE_IDLE;
227 void CancelSetPacScript() override { NOTREACHED(); }
229 int SetPacScript(const scoped_refptr<ProxyResolverScriptData>& pac_script,
230 const CompletionCallback& callback) override {
231 return OK;
234 private:
235 const std::string pac_string_;
238 // Creates ProxyResolvers using a platform-specific implementation.
239 class ProxyResolverFactoryForSystem : public ProxyResolverFactory {
240 public:
241 ProxyResolverFactoryForSystem()
242 : ProxyResolverFactory(false /*expects_pac_bytes*/) {}
244 ProxyResolver* CreateProxyResolver() override {
245 DCHECK(IsSupported());
246 #if defined(OS_WIN)
247 return new ProxyResolverWinHttp();
248 #elif defined(OS_MACOSX)
249 return new ProxyResolverMac();
250 #else
251 NOTREACHED();
252 return NULL;
253 #endif
256 static bool IsSupported() {
257 #if defined(OS_WIN) || defined(OS_MACOSX)
258 return true;
259 #else
260 return false;
261 #endif
265 // Returns NetLog parameters describing a proxy configuration change.
266 base::Value* NetLogProxyConfigChangedCallback(
267 const ProxyConfig* old_config,
268 const ProxyConfig* new_config,
269 NetLog::LogLevel /* log_level */) {
270 base::DictionaryValue* dict = new base::DictionaryValue();
271 // The "old_config" is optional -- the first notification will not have
272 // any "previous" configuration.
273 if (old_config->is_valid())
274 dict->Set("old_config", old_config->ToValue());
275 dict->Set("new_config", new_config->ToValue());
276 return dict;
279 base::Value* NetLogBadProxyListCallback(const ProxyRetryInfoMap* retry_info,
280 NetLog::LogLevel /* log_level */) {
281 base::DictionaryValue* dict = new base::DictionaryValue();
282 base::ListValue* list = new base::ListValue();
284 for (ProxyRetryInfoMap::const_iterator iter = retry_info->begin();
285 iter != retry_info->end(); ++iter) {
286 list->Append(new base::StringValue(iter->first));
288 dict->Set("bad_proxy_list", list);
289 return dict;
292 // Returns NetLog parameters on a successfuly proxy resolution.
293 base::Value* NetLogFinishedResolvingProxyCallback(
294 const ProxyInfo* result,
295 NetLog::LogLevel /* log_level */) {
296 base::DictionaryValue* dict = new base::DictionaryValue();
297 dict->SetString("pac_string", result->ToPacString());
298 return dict;
301 #if defined(OS_CHROMEOS)
302 class UnsetProxyConfigService : public ProxyConfigService {
303 public:
304 UnsetProxyConfigService() {}
305 ~UnsetProxyConfigService() override {}
307 void AddObserver(Observer* observer) override {}
308 void RemoveObserver(Observer* observer) override {}
309 ConfigAvailability GetLatestProxyConfig(ProxyConfig* config) override {
310 return CONFIG_UNSET;
313 #endif
315 } // namespace
317 // ProxyService::InitProxyResolver --------------------------------------------
319 // This glues together two asynchronous steps:
320 // (1) ProxyScriptDecider -- try to fetch/validate a sequence of PAC scripts
321 // to figure out what we should configure against.
322 // (2) Feed the fetched PAC script into the ProxyResolver.
324 // InitProxyResolver is a single-use class which encapsulates cancellation as
325 // part of its destructor. Start() or StartSkipDecider() should be called just
326 // once. The instance can be destroyed at any time, and the request will be
327 // cancelled.
329 class ProxyService::InitProxyResolver {
330 public:
331 InitProxyResolver()
332 : proxy_resolver_(NULL),
333 next_state_(STATE_NONE),
334 quick_check_enabled_(true) {
337 ~InitProxyResolver() {
338 // Note that the destruction of ProxyScriptDecider will automatically cancel
339 // any outstanding work.
340 if (next_state_ == STATE_SET_PAC_SCRIPT_COMPLETE) {
341 proxy_resolver_->CancelSetPacScript();
345 // Begins initializing the proxy resolver; calls |callback| when done.
346 int Start(ProxyResolver* proxy_resolver,
347 ProxyScriptFetcher* proxy_script_fetcher,
348 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
349 NetLog* net_log,
350 const ProxyConfig& config,
351 TimeDelta wait_delay,
352 const CompletionCallback& callback) {
353 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455942 is
354 // fixed.
355 tracked_objects::ScopedTracker tracking_profile(
356 FROM_HERE_WITH_EXPLICIT_FUNCTION(
357 "455942 ProxyService::InitProxyResolver::Start"));
358 DCHECK_EQ(STATE_NONE, next_state_);
359 proxy_resolver_ = proxy_resolver;
361 decider_.reset(new ProxyScriptDecider(
362 proxy_script_fetcher, dhcp_proxy_script_fetcher, net_log));
363 decider_->set_quick_check_enabled(quick_check_enabled_);
364 config_ = config;
365 wait_delay_ = wait_delay;
366 callback_ = callback;
368 next_state_ = STATE_DECIDE_PROXY_SCRIPT;
369 return DoLoop(OK);
372 // Similar to Start(), however it skips the ProxyScriptDecider stage. Instead
373 // |effective_config|, |decider_result| and |script_data| will be used as the
374 // inputs for initializing the ProxyResolver.
375 int StartSkipDecider(ProxyResolver* proxy_resolver,
376 const ProxyConfig& effective_config,
377 int decider_result,
378 ProxyResolverScriptData* script_data,
379 const CompletionCallback& callback) {
380 DCHECK_EQ(STATE_NONE, next_state_);
381 proxy_resolver_ = proxy_resolver;
383 effective_config_ = effective_config;
384 script_data_ = script_data;
385 callback_ = callback;
387 if (decider_result != OK)
388 return decider_result;
390 next_state_ = STATE_SET_PAC_SCRIPT;
391 return DoLoop(OK);
394 // Returns the proxy configuration that was selected by ProxyScriptDecider.
395 // Should only be called upon completion of the initialization.
396 const ProxyConfig& effective_config() const {
397 DCHECK_EQ(STATE_NONE, next_state_);
398 return effective_config_;
401 // Returns the PAC script data that was selected by ProxyScriptDecider.
402 // Should only be called upon completion of the initialization.
403 ProxyResolverScriptData* script_data() {
404 DCHECK_EQ(STATE_NONE, next_state_);
405 return script_data_.get();
408 LoadState GetLoadState() const {
409 if (next_state_ == STATE_DECIDE_PROXY_SCRIPT_COMPLETE) {
410 // In addition to downloading, this state may also include the stall time
411 // after network change events (kDelayAfterNetworkChangesMs).
412 return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT;
414 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
417 void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
418 bool quick_check_enabled() const { return quick_check_enabled_; }
420 private:
421 enum State {
422 STATE_NONE,
423 STATE_DECIDE_PROXY_SCRIPT,
424 STATE_DECIDE_PROXY_SCRIPT_COMPLETE,
425 STATE_SET_PAC_SCRIPT,
426 STATE_SET_PAC_SCRIPT_COMPLETE,
429 int DoLoop(int result) {
430 DCHECK_NE(next_state_, STATE_NONE);
431 int rv = result;
432 do {
433 State state = next_state_;
434 next_state_ = STATE_NONE;
435 switch (state) {
436 case STATE_DECIDE_PROXY_SCRIPT:
437 DCHECK_EQ(OK, rv);
438 rv = DoDecideProxyScript();
439 break;
440 case STATE_DECIDE_PROXY_SCRIPT_COMPLETE:
441 rv = DoDecideProxyScriptComplete(rv);
442 break;
443 case STATE_SET_PAC_SCRIPT:
444 DCHECK_EQ(OK, rv);
445 rv = DoSetPacScript();
446 break;
447 case STATE_SET_PAC_SCRIPT_COMPLETE:
448 rv = DoSetPacScriptComplete(rv);
449 break;
450 default:
451 NOTREACHED() << "bad state: " << state;
452 rv = ERR_UNEXPECTED;
453 break;
455 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
456 return rv;
459 int DoDecideProxyScript() {
460 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455942 is
461 // fixed.
462 tracked_objects::ScopedTracker tracking_profile(
463 FROM_HERE_WITH_EXPLICIT_FUNCTION(
464 "455942 ProxyService::InitProxyResolver::DoDecideProxyScript"));
465 next_state_ = STATE_DECIDE_PROXY_SCRIPT_COMPLETE;
467 return decider_->Start(
468 config_, wait_delay_, proxy_resolver_->expects_pac_bytes(),
469 base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
472 int DoDecideProxyScriptComplete(int result) {
473 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455942 is
474 // fixed.
475 tracked_objects::ScopedTracker tracking_profile(
476 FROM_HERE_WITH_EXPLICIT_FUNCTION(
477 "455942 "
478 "ProxyService::InitProxyResolver::DoDecideProxyScriptComplete"));
479 if (result != OK)
480 return result;
482 effective_config_ = decider_->effective_config();
483 script_data_ = decider_->script_data();
485 next_state_ = STATE_SET_PAC_SCRIPT;
486 return OK;
489 int DoSetPacScript() {
490 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455942 is
491 // fixed.
492 tracked_objects::ScopedTracker tracking_profile(
493 FROM_HERE_WITH_EXPLICIT_FUNCTION(
494 "455942 ProxyService::InitProxyResolver::DoSetPacScript"));
495 DCHECK(script_data_.get());
496 // TODO(eroman): Should log this latency to the NetLog.
497 next_state_ = STATE_SET_PAC_SCRIPT_COMPLETE;
498 return proxy_resolver_->SetPacScript(
499 script_data_,
500 base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
503 int DoSetPacScriptComplete(int result) {
504 return result;
507 void OnIOCompletion(int result) {
508 DCHECK_NE(STATE_NONE, next_state_);
509 int rv = DoLoop(result);
510 if (rv != ERR_IO_PENDING)
511 DoCallback(rv);
514 void DoCallback(int result) {
515 DCHECK_NE(ERR_IO_PENDING, result);
516 callback_.Run(result);
519 ProxyConfig config_;
520 ProxyConfig effective_config_;
521 scoped_refptr<ProxyResolverScriptData> script_data_;
522 TimeDelta wait_delay_;
523 scoped_ptr<ProxyScriptDecider> decider_;
524 ProxyResolver* proxy_resolver_;
525 CompletionCallback callback_;
526 State next_state_;
527 bool quick_check_enabled_;
529 DISALLOW_COPY_AND_ASSIGN(InitProxyResolver);
532 // ProxyService::ProxyScriptDeciderPoller -------------------------------------
534 // This helper class encapsulates the logic to schedule and run periodic
535 // background checks to see if the PAC script (or effective proxy configuration)
536 // has changed. If a change is detected, then the caller will be notified via
537 // the ChangeCallback.
538 class ProxyService::ProxyScriptDeciderPoller {
539 public:
540 typedef base::Callback<void(int, ProxyResolverScriptData*,
541 const ProxyConfig&)> ChangeCallback;
543 // Builds a poller helper, and starts polling for updates. Whenever a change
544 // is observed, |callback| will be invoked with the details.
546 // |config| specifies the (unresolved) proxy configuration to poll.
547 // |proxy_resolver_expects_pac_bytes| the type of proxy resolver we expect
548 // to use the resulting script data with
549 // (so it can choose the right format).
550 // |proxy_script_fetcher| this pointer must remain alive throughout our
551 // lifetime. It is the dependency that will be used
552 // for downloading proxy scripts.
553 // |dhcp_proxy_script_fetcher| similar to |proxy_script_fetcher|, but for
554 // the DHCP dependency.
555 // |init_net_error| This is the initial network error (possibly success)
556 // encountered by the first PAC fetch attempt. We use it
557 // to schedule updates more aggressively if the initial
558 // fetch resulted in an error.
559 // |init_script_data| the initial script data from the PAC fetch attempt.
560 // This is the baseline used to determine when the
561 // script's contents have changed.
562 // |net_log| the NetLog to log progress into.
563 ProxyScriptDeciderPoller(ChangeCallback callback,
564 const ProxyConfig& config,
565 bool proxy_resolver_expects_pac_bytes,
566 ProxyScriptFetcher* proxy_script_fetcher,
567 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
568 int init_net_error,
569 ProxyResolverScriptData* init_script_data,
570 NetLog* net_log)
571 : change_callback_(callback),
572 config_(config),
573 proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes),
574 proxy_script_fetcher_(proxy_script_fetcher),
575 dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher),
576 last_error_(init_net_error),
577 last_script_data_(init_script_data),
578 last_poll_time_(TimeTicks::Now()),
579 weak_factory_(this) {
580 // Set the initial poll delay.
581 next_poll_mode_ = poll_policy()->GetNextDelay(
582 last_error_, TimeDelta::FromSeconds(-1), &next_poll_delay_);
583 TryToStartNextPoll(false);
586 void OnLazyPoll() {
587 // We have just been notified of network activity. Use this opportunity to
588 // see if we can start our next poll.
589 TryToStartNextPoll(true);
592 static const PacPollPolicy* set_policy(const PacPollPolicy* policy) {
593 const PacPollPolicy* prev = poll_policy_;
594 poll_policy_ = policy;
595 return prev;
598 void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
599 bool quick_check_enabled() const { return quick_check_enabled_; }
601 private:
602 // Returns the effective poll policy (the one injected by unit-tests, or the
603 // default).
604 const PacPollPolicy* poll_policy() {
605 if (poll_policy_)
606 return poll_policy_;
607 return &default_poll_policy_;
610 void StartPollTimer() {
611 DCHECK(!decider_.get());
613 base::MessageLoop::current()->PostDelayedTask(
614 FROM_HERE,
615 base::Bind(&ProxyScriptDeciderPoller::DoPoll,
616 weak_factory_.GetWeakPtr()),
617 next_poll_delay_);
620 void TryToStartNextPoll(bool triggered_by_activity) {
621 switch (next_poll_mode_) {
622 case PacPollPolicy::MODE_USE_TIMER:
623 if (!triggered_by_activity)
624 StartPollTimer();
625 break;
627 case PacPollPolicy::MODE_START_AFTER_ACTIVITY:
628 if (triggered_by_activity && !decider_.get()) {
629 TimeDelta elapsed_time = TimeTicks::Now() - last_poll_time_;
630 if (elapsed_time >= next_poll_delay_)
631 DoPoll();
633 break;
637 void DoPoll() {
638 last_poll_time_ = TimeTicks::Now();
640 // Start the proxy script decider to see if anything has changed.
641 // TODO(eroman): Pass a proper NetLog rather than NULL.
642 decider_.reset(new ProxyScriptDecider(
643 proxy_script_fetcher_, dhcp_proxy_script_fetcher_, NULL));
644 decider_->set_quick_check_enabled(quick_check_enabled_);
645 int result = decider_->Start(
646 config_, TimeDelta(), proxy_resolver_expects_pac_bytes_,
647 base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted,
648 base::Unretained(this)));
650 if (result != ERR_IO_PENDING)
651 OnProxyScriptDeciderCompleted(result);
654 void OnProxyScriptDeciderCompleted(int result) {
655 if (HasScriptDataChanged(result, decider_->script_data())) {
656 // Something has changed, we must notify the ProxyService so it can
657 // re-initialize its ProxyResolver. Note that we post a notification task
658 // rather than calling it directly -- this is done to avoid an ugly
659 // destruction sequence, since |this| might be destroyed as a result of
660 // the notification.
661 base::MessageLoop::current()->PostTask(
662 FROM_HERE,
663 base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange,
664 weak_factory_.GetWeakPtr(),
665 result,
666 make_scoped_refptr(decider_->script_data()),
667 decider_->effective_config()));
668 return;
671 decider_.reset();
673 // Decide when the next poll should take place, and possibly start the
674 // next timer.
675 next_poll_mode_ = poll_policy()->GetNextDelay(
676 last_error_, next_poll_delay_, &next_poll_delay_);
677 TryToStartNextPoll(false);
680 bool HasScriptDataChanged(int result, ProxyResolverScriptData* script_data) {
681 if (result != last_error_) {
682 // Something changed -- it was failing before and now it succeeded, or
683 // conversely it succeeded before and now it failed. Or it failed in
684 // both cases, however the specific failure error codes differ.
685 return true;
688 if (result != OK) {
689 // If it failed last time and failed again with the same error code this
690 // time, then nothing has actually changed.
691 return false;
694 // Otherwise if it succeeded both this time and last time, we need to look
695 // closer and see if we ended up downloading different content for the PAC
696 // script.
697 return !script_data->Equals(last_script_data_.get());
700 void NotifyProxyServiceOfChange(
701 int result,
702 const scoped_refptr<ProxyResolverScriptData>& script_data,
703 const ProxyConfig& effective_config) {
704 // Note that |this| may be deleted after calling into the ProxyService.
705 change_callback_.Run(result, script_data.get(), effective_config);
708 ChangeCallback change_callback_;
709 ProxyConfig config_;
710 bool proxy_resolver_expects_pac_bytes_;
711 ProxyScriptFetcher* proxy_script_fetcher_;
712 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher_;
714 int last_error_;
715 scoped_refptr<ProxyResolverScriptData> last_script_data_;
717 scoped_ptr<ProxyScriptDecider> decider_;
718 TimeDelta next_poll_delay_;
719 PacPollPolicy::Mode next_poll_mode_;
721 TimeTicks last_poll_time_;
723 // Polling policy injected by unit-tests. Otherwise this is NULL and the
724 // default policy will be used.
725 static const PacPollPolicy* poll_policy_;
727 const DefaultPollPolicy default_poll_policy_;
729 bool quick_check_enabled_;
731 base::WeakPtrFactory<ProxyScriptDeciderPoller> weak_factory_;
733 DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller);
736 // static
737 const ProxyService::PacPollPolicy*
738 ProxyService::ProxyScriptDeciderPoller::poll_policy_ = NULL;
740 // ProxyService::PacRequest ---------------------------------------------------
742 class ProxyService::PacRequest
743 : public base::RefCounted<ProxyService::PacRequest> {
744 public:
745 PacRequest(ProxyService* service,
746 const GURL& url,
747 int load_flags,
748 NetworkDelegate* network_delegate,
749 ProxyInfo* results,
750 const net::CompletionCallback& user_callback,
751 const BoundNetLog& net_log)
752 : service_(service),
753 user_callback_(user_callback),
754 results_(results),
755 url_(url),
756 load_flags_(load_flags),
757 network_delegate_(network_delegate),
758 resolve_job_(NULL),
759 config_id_(ProxyConfig::kInvalidConfigID),
760 config_source_(PROXY_CONFIG_SOURCE_UNKNOWN),
761 net_log_(net_log) {
762 DCHECK(!user_callback.is_null());
765 // Starts the resolve proxy request.
766 int Start() {
767 DCHECK(!was_cancelled());
768 DCHECK(!is_started());
770 DCHECK(service_->config_.is_valid());
772 config_id_ = service_->config_.id();
773 config_source_ = service_->config_.source();
774 proxy_resolve_start_time_ = TimeTicks::Now();
776 return resolver()->GetProxyForURL(
777 url_, results_,
778 base::Bind(&PacRequest::QueryComplete, base::Unretained(this)),
779 &resolve_job_, net_log_);
782 bool is_started() const {
783 // Note that !! casts to bool. (VS gives a warning otherwise).
784 return !!resolve_job_;
787 void StartAndCompleteCheckingForSynchronous() {
788 int rv = service_->TryToCompleteSynchronously(url_, load_flags_,
789 network_delegate_, results_);
790 if (rv == ERR_IO_PENDING)
791 rv = Start();
792 if (rv != ERR_IO_PENDING)
793 QueryComplete(rv);
796 void CancelResolveJob() {
797 DCHECK(is_started());
798 // The request may already be running in the resolver.
799 resolver()->CancelRequest(resolve_job_);
800 resolve_job_ = NULL;
801 DCHECK(!is_started());
804 void Cancel() {
805 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
807 if (is_started())
808 CancelResolveJob();
810 // Mark as cancelled, to prevent accessing this again later.
811 service_ = NULL;
812 user_callback_.Reset();
813 results_ = NULL;
815 net_log_.EndEvent(NetLog::TYPE_PROXY_SERVICE);
818 // Returns true if Cancel() has been called.
819 bool was_cancelled() const {
820 return user_callback_.is_null();
823 // Helper to call after ProxyResolver completion (both synchronous and
824 // asynchronous). Fixes up the result that is to be returned to user.
825 int QueryDidComplete(int result_code) {
826 DCHECK(!was_cancelled());
828 // Note that DidFinishResolvingProxy might modify |results_|.
829 int rv = service_->DidFinishResolvingProxy(url_, load_flags_,
830 network_delegate_, results_,
831 result_code, net_log_);
833 // Make a note in the results which configuration was in use at the
834 // time of the resolve.
835 results_->config_id_ = config_id_;
836 results_->config_source_ = config_source_;
837 results_->did_use_pac_script_ = true;
838 results_->proxy_resolve_start_time_ = proxy_resolve_start_time_;
839 results_->proxy_resolve_end_time_ = TimeTicks::Now();
841 // Reset the state associated with in-progress-resolve.
842 resolve_job_ = NULL;
843 config_id_ = ProxyConfig::kInvalidConfigID;
844 config_source_ = PROXY_CONFIG_SOURCE_UNKNOWN;
846 return rv;
849 BoundNetLog* net_log() { return &net_log_; }
851 LoadState GetLoadState() const {
852 if (is_started())
853 return resolver()->GetLoadState(resolve_job_);
854 return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
857 private:
858 friend class base::RefCounted<ProxyService::PacRequest>;
860 ~PacRequest() {}
862 // Callback for when the ProxyResolver request has completed.
863 void QueryComplete(int result_code) {
864 result_code = QueryDidComplete(result_code);
866 // Remove this completed PacRequest from the service's pending list.
867 /// (which will probably cause deletion of |this|).
868 if (!user_callback_.is_null()) {
869 net::CompletionCallback callback = user_callback_;
870 service_->RemovePendingRequest(this);
871 callback.Run(result_code);
875 ProxyResolver* resolver() const { return service_->resolver_.get(); }
877 // Note that we don't hold a reference to the ProxyService. Outstanding
878 // requests are cancelled during ~ProxyService, so this is guaranteed
879 // to be valid throughout our lifetime.
880 ProxyService* service_;
881 net::CompletionCallback user_callback_;
882 ProxyInfo* results_;
883 GURL url_;
884 int load_flags_;
885 NetworkDelegate* network_delegate_;
886 ProxyResolver::RequestHandle resolve_job_;
887 ProxyConfig::ID config_id_; // The config id when the resolve was started.
888 ProxyConfigSource config_source_; // The source of proxy settings.
889 BoundNetLog net_log_;
890 // Time when the PAC is started. Cached here since resetting ProxyInfo also
891 // clears the proxy times.
892 TimeTicks proxy_resolve_start_time_;
895 // ProxyService ---------------------------------------------------------------
897 ProxyService::ProxyService(ProxyConfigService* config_service,
898 ProxyResolver* resolver,
899 NetLog* net_log)
900 : resolver_(resolver),
901 next_config_id_(1),
902 current_state_(STATE_NONE),
903 net_log_(net_log),
904 stall_proxy_auto_config_delay_(TimeDelta::FromMilliseconds(
905 kDelayAfterNetworkChangesMs)),
906 quick_check_enabled_(true) {
907 NetworkChangeNotifier::AddIPAddressObserver(this);
908 NetworkChangeNotifier::AddDNSObserver(this);
909 ResetConfigService(config_service);
912 // static
913 ProxyService* ProxyService::CreateUsingSystemProxyResolver(
914 ProxyConfigService* proxy_config_service,
915 size_t num_pac_threads,
916 NetLog* net_log) {
917 DCHECK(proxy_config_service);
919 if (!ProxyResolverFactoryForSystem::IsSupported()) {
920 VLOG(1) << "PAC support disabled because there is no system implementation";
921 return CreateWithoutProxyResolver(proxy_config_service, net_log);
924 if (num_pac_threads == 0)
925 num_pac_threads = kDefaultNumPacThreads;
927 ProxyResolver* proxy_resolver = new MultiThreadedProxyResolver(
928 new ProxyResolverFactoryForSystem(), num_pac_threads);
930 return new ProxyService(proxy_config_service, proxy_resolver, net_log);
933 // static
934 ProxyService* ProxyService::CreateWithoutProxyResolver(
935 ProxyConfigService* proxy_config_service,
936 NetLog* net_log) {
937 return new ProxyService(proxy_config_service,
938 new ProxyResolverNull(),
939 net_log);
942 // static
943 ProxyService* ProxyService::CreateFixed(const ProxyConfig& pc) {
944 // TODO(eroman): This isn't quite right, won't work if |pc| specifies
945 // a PAC script.
946 return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc),
947 0, NULL);
950 // static
951 ProxyService* ProxyService::CreateFixed(const std::string& proxy) {
952 net::ProxyConfig proxy_config;
953 proxy_config.proxy_rules().ParseFromString(proxy);
954 return ProxyService::CreateFixed(proxy_config);
957 // static
958 ProxyService* ProxyService::CreateDirect() {
959 return CreateDirectWithNetLog(NULL);
962 ProxyService* ProxyService::CreateDirectWithNetLog(NetLog* net_log) {
963 // Use direct connections.
964 return new ProxyService(new ProxyConfigServiceDirect, new ProxyResolverNull,
965 net_log);
968 // static
969 ProxyService* ProxyService::CreateFixedFromPacResult(
970 const std::string& pac_string) {
972 // We need the settings to contain an "automatic" setting, otherwise the
973 // ProxyResolver dependency we give it will never be used.
974 scoped_ptr<ProxyConfigService> proxy_config_service(
975 new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
977 scoped_ptr<ProxyResolver> proxy_resolver(
978 new ProxyResolverFromPacString(pac_string));
980 return new ProxyService(proxy_config_service.release(),
981 proxy_resolver.release(),
982 NULL);
985 int ProxyService::ResolveProxy(const GURL& raw_url,
986 int load_flags,
987 ProxyInfo* result,
988 const net::CompletionCallback& callback,
989 PacRequest** pac_request,
990 NetworkDelegate* network_delegate,
991 const BoundNetLog& net_log) {
992 DCHECK(!callback.is_null());
993 return ResolveProxyHelper(raw_url,
994 load_flags,
995 result,
996 callback,
997 pac_request,
998 network_delegate,
999 net_log);
1002 int ProxyService::ResolveProxyHelper(const GURL& raw_url,
1003 int load_flags,
1004 ProxyInfo* result,
1005 const net::CompletionCallback& callback,
1006 PacRequest** pac_request,
1007 NetworkDelegate* network_delegate,
1008 const BoundNetLog& net_log) {
1009 DCHECK(CalledOnValidThread());
1011 net_log.BeginEvent(NetLog::TYPE_PROXY_SERVICE);
1013 // Notify our polling-based dependencies that a resolve is taking place.
1014 // This way they can schedule their polls in response to network activity.
1015 config_service_->OnLazyPoll();
1016 if (script_poller_.get())
1017 script_poller_->OnLazyPoll();
1019 if (current_state_ == STATE_NONE)
1020 ApplyProxyConfigIfAvailable();
1022 // Strip away any reference fragments and the username/password, as they
1023 // are not relevant to proxy resolution.
1024 GURL url = SimplifyUrlForRequest(raw_url);
1026 // Check if the request can be completed right away. (This is the case when
1027 // using a direct connection for example).
1028 int rv = TryToCompleteSynchronously(url, load_flags,
1029 network_delegate, result);
1030 if (rv != ERR_IO_PENDING)
1031 return DidFinishResolvingProxy(url, load_flags, network_delegate,
1032 result, rv, net_log);
1034 if (callback.is_null())
1035 return ERR_IO_PENDING;
1037 scoped_refptr<PacRequest> req(
1038 new PacRequest(this, url, load_flags, network_delegate,
1039 result, callback, net_log));
1041 if (current_state_ == STATE_READY) {
1042 // Start the resolve request.
1043 rv = req->Start();
1044 if (rv != ERR_IO_PENDING)
1045 return req->QueryDidComplete(rv);
1046 } else {
1047 req->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1050 DCHECK_EQ(ERR_IO_PENDING, rv);
1051 DCHECK(!ContainsPendingRequest(req.get()));
1052 pending_requests_.push_back(req);
1054 // Completion will be notified through |callback|, unless the caller cancels
1055 // the request using |pac_request|.
1056 if (pac_request)
1057 *pac_request = req.get();
1058 return rv; // ERR_IO_PENDING
1061 bool ProxyService:: TryResolveProxySynchronously(
1062 const GURL& raw_url,
1063 int load_flags,
1064 ProxyInfo* result,
1065 NetworkDelegate* network_delegate,
1066 const BoundNetLog& net_log) {
1067 net::CompletionCallback null_callback;
1068 return ResolveProxyHelper(raw_url,
1069 load_flags,
1070 result,
1071 null_callback,
1072 NULL /* pac_request*/,
1073 network_delegate,
1074 net_log) == OK;
1077 int ProxyService::TryToCompleteSynchronously(const GURL& url,
1078 int load_flags,
1079 NetworkDelegate* network_delegate,
1080 ProxyInfo* result) {
1081 DCHECK_NE(STATE_NONE, current_state_);
1083 if (current_state_ != STATE_READY)
1084 return ERR_IO_PENDING; // Still initializing.
1086 DCHECK_NE(config_.id(), ProxyConfig::kInvalidConfigID);
1088 // If it was impossible to fetch or parse the PAC script, we cannot complete
1089 // the request here and bail out.
1090 if (permanent_error_ != OK)
1091 return permanent_error_;
1093 if (config_.HasAutomaticSettings())
1094 return ERR_IO_PENDING; // Must submit the request to the proxy resolver.
1096 // Use the manual proxy settings.
1097 config_.proxy_rules().Apply(url, result);
1098 result->config_source_ = config_.source();
1099 result->config_id_ = config_.id();
1101 return OK;
1104 ProxyService::~ProxyService() {
1105 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1106 NetworkChangeNotifier::RemoveDNSObserver(this);
1107 config_service_->RemoveObserver(this);
1109 // Cancel any inprogress requests.
1110 for (PendingRequests::iterator it = pending_requests_.begin();
1111 it != pending_requests_.end();
1112 ++it) {
1113 (*it)->Cancel();
1117 void ProxyService::SuspendAllPendingRequests() {
1118 for (PendingRequests::iterator it = pending_requests_.begin();
1119 it != pending_requests_.end();
1120 ++it) {
1121 PacRequest* req = it->get();
1122 if (req->is_started()) {
1123 req->CancelResolveJob();
1125 req->net_log()->BeginEvent(
1126 NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1131 void ProxyService::SetReady() {
1132 DCHECK(!init_proxy_resolver_.get());
1133 current_state_ = STATE_READY;
1135 // Make a copy in case |this| is deleted during the synchronous completion
1136 // of one of the requests. If |this| is deleted then all of the PacRequest
1137 // instances will be Cancel()-ed.
1138 PendingRequests pending_copy = pending_requests_;
1140 for (PendingRequests::iterator it = pending_copy.begin();
1141 it != pending_copy.end();
1142 ++it) {
1143 PacRequest* req = it->get();
1144 if (!req->is_started() && !req->was_cancelled()) {
1145 req->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
1147 // Note that we re-check for synchronous completion, in case we are
1148 // no longer using a ProxyResolver (can happen if we fell-back to manual).
1149 req->StartAndCompleteCheckingForSynchronous();
1154 void ProxyService::ApplyProxyConfigIfAvailable() {
1155 DCHECK_EQ(STATE_NONE, current_state_);
1157 config_service_->OnLazyPoll();
1159 // If we have already fetched the configuration, start applying it.
1160 if (fetched_config_.is_valid()) {
1161 InitializeUsingLastFetchedConfig();
1162 return;
1165 // Otherwise we need to first fetch the configuration.
1166 current_state_ = STATE_WAITING_FOR_PROXY_CONFIG;
1168 // Retrieve the current proxy configuration from the ProxyConfigService.
1169 // If a configuration is not available yet, we will get called back later
1170 // by our ProxyConfigService::Observer once it changes.
1171 ProxyConfig config;
1172 ProxyConfigService::ConfigAvailability availability =
1173 config_service_->GetLatestProxyConfig(&config);
1174 if (availability != ProxyConfigService::CONFIG_PENDING)
1175 OnProxyConfigChanged(config, availability);
1178 void ProxyService::OnInitProxyResolverComplete(int result) {
1179 DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER, current_state_);
1180 DCHECK(init_proxy_resolver_.get());
1181 DCHECK(fetched_config_.HasAutomaticSettings());
1182 config_ = init_proxy_resolver_->effective_config();
1184 // At this point we have decided which proxy settings to use (i.e. which PAC
1185 // script if any). We start up a background poller to periodically revisit
1186 // this decision. If the contents of the PAC script change, or if the
1187 // result of proxy auto-discovery changes, this poller will notice it and
1188 // will trigger a re-initialization using the newly discovered PAC.
1189 script_poller_.reset(new ProxyScriptDeciderPoller(
1190 base::Bind(&ProxyService::InitializeUsingDecidedConfig,
1191 base::Unretained(this)),
1192 fetched_config_,
1193 resolver_->expects_pac_bytes(),
1194 proxy_script_fetcher_.get(),
1195 dhcp_proxy_script_fetcher_.get(),
1196 result,
1197 init_proxy_resolver_->script_data(),
1198 NULL));
1199 script_poller_->set_quick_check_enabled(quick_check_enabled_);
1201 init_proxy_resolver_.reset();
1203 if (result != OK) {
1204 if (fetched_config_.pac_mandatory()) {
1205 VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
1206 "traffic.";
1207 config_ = fetched_config_;
1208 result = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
1209 } else {
1210 VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
1211 "proxy servers.";
1212 config_ = fetched_config_;
1213 config_.ClearAutomaticSettings();
1214 result = OK;
1217 permanent_error_ = result;
1219 // TODO(eroman): Make this ID unique in the case where configuration changed
1220 // due to ProxyScriptDeciderPoller.
1221 config_.set_id(fetched_config_.id());
1222 config_.set_source(fetched_config_.source());
1224 // Resume any requests which we had to defer until the PAC script was
1225 // downloaded.
1226 SetReady();
1229 int ProxyService::ReconsiderProxyAfterError(const GURL& url,
1230 int load_flags,
1231 int net_error,
1232 ProxyInfo* result,
1233 const CompletionCallback& callback,
1234 PacRequest** pac_request,
1235 NetworkDelegate* network_delegate,
1236 const BoundNetLog& net_log) {
1237 DCHECK(CalledOnValidThread());
1239 // Check to see if we have a new config since ResolveProxy was called. We
1240 // want to re-run ResolveProxy in two cases: 1) we have a new config, or 2) a
1241 // direct connection failed and we never tried the current config.
1243 DCHECK(result);
1244 bool re_resolve = result->config_id_ != config_.id();
1246 if (re_resolve) {
1247 // If we have a new config or the config was never tried, we delete the
1248 // list of bad proxies and we try again.
1249 proxy_retry_info_.clear();
1250 return ResolveProxy(url, load_flags, result, callback, pac_request,
1251 network_delegate, net_log);
1254 DCHECK(!result->is_empty());
1255 ProxyServer bad_proxy = result->proxy_server();
1257 // We don't have new proxy settings to try, try to fallback to the next proxy
1258 // in the list.
1259 bool did_fallback = result->Fallback(net_error, net_log);
1261 // Return synchronous failure if there is nothing left to fall-back to.
1262 // TODO(eroman): This is a yucky API, clean it up.
1263 return did_fallback ? OK : ERR_FAILED;
1266 bool ProxyService::MarkProxiesAsBadUntil(
1267 const ProxyInfo& result,
1268 base::TimeDelta retry_delay,
1269 const ProxyServer& another_bad_proxy,
1270 const BoundNetLog& net_log) {
1271 result.proxy_list_.UpdateRetryInfoOnFallback(&proxy_retry_info_,
1272 retry_delay,
1273 false,
1274 another_bad_proxy,
1276 net_log);
1277 if (another_bad_proxy.is_valid())
1278 return result.proxy_list_.size() > 2;
1279 else
1280 return result.proxy_list_.size() > 1;
1283 void ProxyService::ReportSuccess(const ProxyInfo& result,
1284 NetworkDelegate* network_delegate) {
1285 DCHECK(CalledOnValidThread());
1287 const ProxyRetryInfoMap& new_retry_info = result.proxy_retry_info();
1288 if (new_retry_info.empty())
1289 return;
1291 for (ProxyRetryInfoMap::const_iterator iter = new_retry_info.begin();
1292 iter != new_retry_info.end(); ++iter) {
1293 ProxyRetryInfoMap::iterator existing = proxy_retry_info_.find(iter->first);
1294 if (existing == proxy_retry_info_.end()) {
1295 proxy_retry_info_[iter->first] = iter->second;
1296 if (network_delegate) {
1297 const ProxyServer& bad_proxy =
1298 ProxyServer::FromURI(iter->first, ProxyServer::SCHEME_HTTP);
1299 const ProxyRetryInfo& proxy_retry_info = iter->second;
1300 network_delegate->NotifyProxyFallback(bad_proxy,
1301 proxy_retry_info.net_error);
1304 else if (existing->second.bad_until < iter->second.bad_until)
1305 existing->second.bad_until = iter->second.bad_until;
1307 if (net_log_) {
1308 net_log_->AddGlobalEntry(
1309 NetLog::TYPE_BAD_PROXY_LIST_REPORTED,
1310 base::Bind(&NetLogBadProxyListCallback, &new_retry_info));
1314 void ProxyService::CancelPacRequest(PacRequest* req) {
1315 DCHECK(CalledOnValidThread());
1316 DCHECK(req);
1317 req->Cancel();
1318 RemovePendingRequest(req);
1321 LoadState ProxyService::GetLoadState(const PacRequest* req) const {
1322 CHECK(req);
1323 if (current_state_ == STATE_WAITING_FOR_INIT_PROXY_RESOLVER)
1324 return init_proxy_resolver_->GetLoadState();
1325 return req->GetLoadState();
1328 bool ProxyService::ContainsPendingRequest(PacRequest* req) {
1329 PendingRequests::iterator it = std::find(
1330 pending_requests_.begin(), pending_requests_.end(), req);
1331 return pending_requests_.end() != it;
1334 void ProxyService::RemovePendingRequest(PacRequest* req) {
1335 DCHECK(ContainsPendingRequest(req));
1336 PendingRequests::iterator it = std::find(
1337 pending_requests_.begin(), pending_requests_.end(), req);
1338 pending_requests_.erase(it);
1341 int ProxyService::DidFinishResolvingProxy(const GURL& url,
1342 int load_flags,
1343 NetworkDelegate* network_delegate,
1344 ProxyInfo* result,
1345 int result_code,
1346 const BoundNetLog& net_log) {
1347 // Log the result of the proxy resolution.
1348 if (result_code == OK) {
1349 // Allow the network delegate to interpose on the resolution decision,
1350 // possibly modifying the ProxyInfo.
1351 if (network_delegate)
1352 network_delegate->NotifyResolveProxy(url, load_flags, *this, result);
1354 // When logging all events is enabled, dump the proxy list.
1355 if (net_log.IsLogging()) {
1356 net_log.AddEvent(
1357 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST,
1358 base::Bind(&NetLogFinishedResolvingProxyCallback, result));
1360 result->DeprioritizeBadProxies(proxy_retry_info_);
1361 } else {
1362 net_log.AddEventWithNetErrorCode(
1363 NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST, result_code);
1365 if (!config_.pac_mandatory()) {
1366 // Fall-back to direct when the proxy resolver fails. This corresponds
1367 // with a javascript runtime error in the PAC script.
1369 // This implicit fall-back to direct matches Firefox 3.5 and
1370 // Internet Explorer 8. For more information, see:
1372 // http://www.chromium.org/developers/design-documents/proxy-settings-fallback
1373 result->UseDirect();
1374 result_code = OK;
1376 // Allow the network delegate to interpose on the resolution decision,
1377 // possibly modifying the ProxyInfo.
1378 if (network_delegate)
1379 network_delegate->NotifyResolveProxy(url, load_flags, *this, result);
1380 } else {
1381 result_code = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
1385 net_log.EndEvent(NetLog::TYPE_PROXY_SERVICE);
1386 return result_code;
1389 void ProxyService::SetProxyScriptFetchers(
1390 ProxyScriptFetcher* proxy_script_fetcher,
1391 DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher) {
1392 DCHECK(CalledOnValidThread());
1393 State previous_state = ResetProxyConfig(false);
1394 proxy_script_fetcher_.reset(proxy_script_fetcher);
1395 dhcp_proxy_script_fetcher_.reset(dhcp_proxy_script_fetcher);
1396 if (previous_state != STATE_NONE)
1397 ApplyProxyConfigIfAvailable();
1400 ProxyScriptFetcher* ProxyService::GetProxyScriptFetcher() const {
1401 DCHECK(CalledOnValidThread());
1402 return proxy_script_fetcher_.get();
1405 ProxyService::State ProxyService::ResetProxyConfig(bool reset_fetched_config) {
1406 DCHECK(CalledOnValidThread());
1407 State previous_state = current_state_;
1409 permanent_error_ = OK;
1410 proxy_retry_info_.clear();
1411 script_poller_.reset();
1412 init_proxy_resolver_.reset();
1413 SuspendAllPendingRequests();
1414 config_ = ProxyConfig();
1415 if (reset_fetched_config)
1416 fetched_config_ = ProxyConfig();
1417 current_state_ = STATE_NONE;
1419 return previous_state;
1422 void ProxyService::ResetConfigService(
1423 ProxyConfigService* new_proxy_config_service) {
1424 DCHECK(CalledOnValidThread());
1425 State previous_state = ResetProxyConfig(true);
1427 // Release the old configuration service.
1428 if (config_service_.get())
1429 config_service_->RemoveObserver(this);
1431 // Set the new configuration service.
1432 config_service_.reset(new_proxy_config_service);
1433 config_service_->AddObserver(this);
1435 if (previous_state != STATE_NONE)
1436 ApplyProxyConfigIfAvailable();
1439 void ProxyService::ForceReloadProxyConfig() {
1440 DCHECK(CalledOnValidThread());
1441 ResetProxyConfig(false);
1442 ApplyProxyConfigIfAvailable();
1445 // static
1446 ProxyConfigService* ProxyService::CreateSystemProxyConfigService(
1447 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
1448 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner) {
1449 #if defined(OS_WIN)
1450 return new ProxyConfigServiceWin();
1451 #elif defined(OS_IOS)
1452 return new ProxyConfigServiceIOS();
1453 #elif defined(OS_MACOSX)
1454 return new ProxyConfigServiceMac(io_task_runner);
1455 #elif defined(OS_CHROMEOS)
1456 LOG(ERROR) << "ProxyConfigService for ChromeOS should be created in "
1457 << "profile_io_data.cc::CreateProxyConfigService and this should "
1458 << "be used only for examples.";
1459 return new UnsetProxyConfigService;
1460 #elif defined(OS_LINUX)
1461 ProxyConfigServiceLinux* linux_config_service =
1462 new ProxyConfigServiceLinux();
1464 // Assume we got called on the thread that runs the default glib
1465 // main loop, so the current thread is where we should be running
1466 // gconf calls from.
1467 scoped_refptr<base::SingleThreadTaskRunner> glib_thread_task_runner =
1468 base::ThreadTaskRunnerHandle::Get();
1470 // Synchronously fetch the current proxy config (since we are running on
1471 // glib_default_loop). Additionally register for notifications (delivered in
1472 // either |glib_default_loop| or |file_task_runner|) to keep us updated when
1473 // the proxy config changes.
1474 linux_config_service->SetupAndFetchInitialConfig(
1475 glib_thread_task_runner, io_task_runner, file_task_runner);
1477 return linux_config_service;
1478 #elif defined(OS_ANDROID)
1479 return new ProxyConfigServiceAndroid(
1480 io_task_runner, base::MessageLoop::current()->message_loop_proxy());
1481 #else
1482 LOG(WARNING) << "Failed to choose a system proxy settings fetcher "
1483 "for this platform.";
1484 return new ProxyConfigServiceDirect();
1485 #endif
1488 // static
1489 const ProxyService::PacPollPolicy* ProxyService::set_pac_script_poll_policy(
1490 const PacPollPolicy* policy) {
1491 return ProxyScriptDeciderPoller::set_policy(policy);
1494 // static
1495 scoped_ptr<ProxyService::PacPollPolicy>
1496 ProxyService::CreateDefaultPacPollPolicy() {
1497 return scoped_ptr<PacPollPolicy>(new DefaultPollPolicy());
1500 void ProxyService::OnProxyConfigChanged(
1501 const ProxyConfig& config,
1502 ProxyConfigService::ConfigAvailability availability) {
1503 // Retrieve the current proxy configuration from the ProxyConfigService.
1504 // If a configuration is not available yet, we will get called back later
1505 // by our ProxyConfigService::Observer once it changes.
1506 ProxyConfig effective_config;
1507 switch (availability) {
1508 case ProxyConfigService::CONFIG_PENDING:
1509 // ProxyConfigService implementors should never pass CONFIG_PENDING.
1510 NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
1511 return;
1512 case ProxyConfigService::CONFIG_VALID:
1513 effective_config = config;
1514 break;
1515 case ProxyConfigService::CONFIG_UNSET:
1516 effective_config = ProxyConfig::CreateDirect();
1517 break;
1520 // Emit the proxy settings change to the NetLog stream.
1521 if (net_log_) {
1522 net_log_->AddGlobalEntry(
1523 net::NetLog::TYPE_PROXY_CONFIG_CHANGED,
1524 base::Bind(&NetLogProxyConfigChangedCallback,
1525 &fetched_config_, &effective_config));
1528 // Set the new configuration as the most recently fetched one.
1529 fetched_config_ = effective_config;
1530 fetched_config_.set_id(1); // Needed for a later DCHECK of is_valid().
1532 InitializeUsingLastFetchedConfig();
1535 void ProxyService::InitializeUsingLastFetchedConfig() {
1536 ResetProxyConfig(false);
1538 DCHECK(fetched_config_.is_valid());
1540 // Increment the ID to reflect that the config has changed.
1541 fetched_config_.set_id(next_config_id_++);
1543 if (!fetched_config_.HasAutomaticSettings()) {
1544 config_ = fetched_config_;
1545 SetReady();
1546 return;
1549 // Start downloading + testing the PAC scripts for this new configuration.
1550 current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
1552 // If we changed networks recently, we should delay running proxy auto-config.
1553 TimeDelta wait_delay =
1554 stall_proxy_autoconfig_until_ - TimeTicks::Now();
1556 init_proxy_resolver_.reset(new InitProxyResolver());
1557 init_proxy_resolver_->set_quick_check_enabled(quick_check_enabled_);
1558 int rv = init_proxy_resolver_->Start(
1559 resolver_.get(),
1560 proxy_script_fetcher_.get(),
1561 dhcp_proxy_script_fetcher_.get(),
1562 net_log_,
1563 fetched_config_,
1564 wait_delay,
1565 base::Bind(&ProxyService::OnInitProxyResolverComplete,
1566 base::Unretained(this)));
1568 if (rv != ERR_IO_PENDING)
1569 OnInitProxyResolverComplete(rv);
1572 void ProxyService::InitializeUsingDecidedConfig(
1573 int decider_result,
1574 ProxyResolverScriptData* script_data,
1575 const ProxyConfig& effective_config) {
1576 DCHECK(fetched_config_.is_valid());
1577 DCHECK(fetched_config_.HasAutomaticSettings());
1579 ResetProxyConfig(false);
1581 current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
1583 init_proxy_resolver_.reset(new InitProxyResolver());
1584 int rv = init_proxy_resolver_->StartSkipDecider(
1585 resolver_.get(),
1586 effective_config,
1587 decider_result,
1588 script_data,
1589 base::Bind(&ProxyService::OnInitProxyResolverComplete,
1590 base::Unretained(this)));
1592 if (rv != ERR_IO_PENDING)
1593 OnInitProxyResolverComplete(rv);
1596 void ProxyService::OnIPAddressChanged() {
1597 // See the comment block by |kDelayAfterNetworkChangesMs| for info.
1598 stall_proxy_autoconfig_until_ =
1599 TimeTicks::Now() + stall_proxy_auto_config_delay_;
1601 State previous_state = ResetProxyConfig(false);
1602 if (previous_state != STATE_NONE)
1603 ApplyProxyConfigIfAvailable();
1606 void ProxyService::OnDNSChanged() {
1607 OnIPAddressChanged();
1610 } // namespace net