This source file includes following definitions.
- GetNextDelay
- AddObserver
- RemoveObserver
- GetLatestProxyConfig
- GetProxyForURL
- CancelRequest
- GetLoadState
- CancelSetPacScript
- SetPacScript
- pac_string_
- GetProxyForURL
- CancelRequest
- GetLoadState
- CancelSetPacScript
- SetPacScript
- CreateProxyResolver
- IsSupported
- NetLogProxyConfigChangedCallback
- NetLogBadProxyListCallback
- NetLogFinishedResolvingProxyCallback
- AddObserver
- RemoveObserver
- GetLatestProxyConfig
- quick_check_enabled_
- InitProxyResolver
- Start
- StartSkipDecider
- effective_config
- script_data
- GetLoadState
- set_quick_check_enabled
- quick_check_enabled
- DoLoop
- DoDecideProxyScript
- DoDecideProxyScriptComplete
- DoSetPacScript
- DoSetPacScriptComplete
- OnIOCompletion
- DoCallback
- last_poll_time_
- OnLazyPoll
- set_policy
- set_quick_check_enabled
- quick_check_enabled
- poll_policy
- StartPollTimer
- TryToStartNextPoll
- DoPoll
- OnProxyScriptDeciderCompleted
- HasScriptDataChanged
- NotifyProxyServiceOfChange
- net_log_
- Start
- is_started
- StartAndCompleteCheckingForSynchronous
- CancelResolveJob
- Cancel
- was_cancelled
- QueryDidComplete
- net_log
- GetLoadState
- QueryComplete
- resolver
- quick_check_enabled_
- CreateUsingSystemProxyResolver
- CreateWithoutProxyResolver
- CreateFixed
- CreateFixed
- CreateDirect
- CreateDirectWithNetLog
- CreateFixedFromPacResult
- ResolveProxy
- TryToCompleteSynchronously
- SuspendAllPendingRequests
- SetReady
- ApplyProxyConfigIfAvailable
- OnInitProxyResolverComplete
- ReconsiderProxyAfterError
- MarkProxiesAsBadUntil
- ReportSuccess
- CancelPacRequest
- GetLoadState
- ContainsPendingRequest
- RemovePendingRequest
- DidFinishResolvingProxy
- SetProxyScriptFetchers
- GetProxyScriptFetcher
- ResetProxyConfig
- ResetConfigService
- ForceReloadProxyConfig
- CreateSystemProxyConfigService
- set_pac_script_poll_policy
- CreateDefaultPacPollPolicy
- RecordDataReductionProxyBypassInfo
- OnProxyConfigChanged
- InitializeUsingLastFetchedConfig
- InitializeUsingDecidedConfig
- OnIPAddressChanged
- OnDNSChanged
- callback_
- ResolveProxy
- ReconsiderProxyAfterError
- StartAsyncResolve
- StartAsyncReconsider
- OnCompletion
#include "net/proxy/proxy_service.h"
#include <algorithm>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"
#include "net/base/completion_callback.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/net_util.h"
#include "net/proxy/dhcp_proxy_script_fetcher.h"
#include "net/proxy/multi_threaded_proxy_resolver.h"
#include "net/proxy/network_delegate_error_observer.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_resolver.h"
#include "net/proxy/proxy_script_decider.h"
#include "net/proxy/proxy_script_fetcher.h"
#include "net/url_request/url_request_context.h"
#include "url/gurl.h"
#if defined(OS_WIN)
#include "net/proxy/proxy_config_service_win.h"
#include "net/proxy/proxy_resolver_winhttp.h"
#elif defined(OS_IOS)
#include "net/proxy/proxy_config_service_ios.h"
#include "net/proxy/proxy_resolver_mac.h"
#elif defined(OS_MACOSX)
#include "net/proxy/proxy_config_service_mac.h"
#include "net/proxy/proxy_resolver_mac.h"
#elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
#include "net/proxy/proxy_config_service_linux.h"
#elif defined(OS_ANDROID)
#include "net/proxy/proxy_config_service_android.h"
#endif
#if defined(SPDY_PROXY_AUTH_ORIGIN)
#include "base/metrics/histogram.h"
#endif
using base::TimeDelta;
using base::TimeTicks;
namespace net {
namespace {
const int64 kDelayAfterNetworkChangesMs = 2000;
class DefaultPollPolicy : public ProxyService::PacPollPolicy {
public:
DefaultPollPolicy() {}
virtual Mode GetNextDelay(int initial_error,
TimeDelta current_delay,
TimeDelta* next_delay) const OVERRIDE {
if (initial_error != OK) {
const int kDelay1Seconds = 8;
const int kDelay2Seconds = 32;
const int kDelay3Seconds = 2 * 60;
const int kDelay4Seconds = 4 * 60 * 60;
if (current_delay < TimeDelta()) {
*next_delay = TimeDelta::FromSeconds(kDelay1Seconds);
return MODE_USE_TIMER;
}
switch (current_delay.InSeconds()) {
case kDelay1Seconds:
*next_delay = TimeDelta::FromSeconds(kDelay2Seconds);
return MODE_START_AFTER_ACTIVITY;
case kDelay2Seconds:
*next_delay = TimeDelta::FromSeconds(kDelay3Seconds);
return MODE_START_AFTER_ACTIVITY;
default:
*next_delay = TimeDelta::FromSeconds(kDelay4Seconds);
return MODE_START_AFTER_ACTIVITY;
}
} else {
*next_delay = TimeDelta::FromHours(12);
return MODE_START_AFTER_ACTIVITY;
}
}
private:
DISALLOW_COPY_AND_ASSIGN(DefaultPollPolicy);
};
class ProxyConfigServiceDirect : public ProxyConfigService {
public:
virtual void AddObserver(Observer* observer) OVERRIDE {}
virtual void RemoveObserver(Observer* observer) OVERRIDE {}
virtual ConfigAvailability GetLatestProxyConfig(ProxyConfig* config)
OVERRIDE {
*config = ProxyConfig::CreateDirect();
config->set_source(PROXY_CONFIG_SOURCE_UNKNOWN);
return CONFIG_VALID;
}
};
class ProxyResolverNull : public ProxyResolver {
public:
ProxyResolverNull() : ProxyResolver(false ) {}
virtual int GetProxyForURL(const GURL& url,
ProxyInfo* results,
const CompletionCallback& callback,
RequestHandle* request,
const BoundNetLog& net_log) OVERRIDE {
return ERR_NOT_IMPLEMENTED;
}
virtual void CancelRequest(RequestHandle request) OVERRIDE {
NOTREACHED();
}
virtual LoadState GetLoadState(RequestHandle request) const OVERRIDE {
NOTREACHED();
return LOAD_STATE_IDLE;
}
virtual void CancelSetPacScript() OVERRIDE {
NOTREACHED();
}
virtual int SetPacScript(
const scoped_refptr<ProxyResolverScriptData>& ,
const CompletionCallback& ) OVERRIDE {
return ERR_NOT_IMPLEMENTED;
}
};
class ProxyResolverFromPacString : public ProxyResolver {
public:
explicit ProxyResolverFromPacString(const std::string& pac_string)
: ProxyResolver(false ),
pac_string_(pac_string) {}
virtual int GetProxyForURL(const GURL& url,
ProxyInfo* results,
const CompletionCallback& callback,
RequestHandle* request,
const BoundNetLog& net_log) OVERRIDE {
results->UsePacString(pac_string_);
return OK;
}
virtual void CancelRequest(RequestHandle request) OVERRIDE {
NOTREACHED();
}
virtual LoadState GetLoadState(RequestHandle request) const OVERRIDE {
NOTREACHED();
return LOAD_STATE_IDLE;
}
virtual void CancelSetPacScript() OVERRIDE {
NOTREACHED();
}
virtual int SetPacScript(
const scoped_refptr<ProxyResolverScriptData>& pac_script,
const CompletionCallback& callback) OVERRIDE {
return OK;
}
private:
const std::string pac_string_;
};
class ProxyResolverFactoryForSystem : public ProxyResolverFactory {
public:
ProxyResolverFactoryForSystem()
: ProxyResolverFactory(false ) {}
virtual ProxyResolver* CreateProxyResolver() OVERRIDE {
DCHECK(IsSupported());
#if defined(OS_WIN)
return new ProxyResolverWinHttp();
#elif defined(OS_MACOSX)
return new ProxyResolverMac();
#else
NOTREACHED();
return NULL;
#endif
}
static bool IsSupported() {
#if defined(OS_WIN) || defined(OS_MACOSX)
return true;
#else
return false;
#endif
}
};
base::Value* NetLogProxyConfigChangedCallback(
const ProxyConfig* old_config,
const ProxyConfig* new_config,
NetLog::LogLevel ) {
base::DictionaryValue* dict = new base::DictionaryValue();
if (old_config->is_valid())
dict->Set("old_config", old_config->ToValue());
dict->Set("new_config", new_config->ToValue());
return dict;
}
base::Value* NetLogBadProxyListCallback(const ProxyRetryInfoMap* retry_info,
NetLog::LogLevel ) {
base::DictionaryValue* dict = new base::DictionaryValue();
base::ListValue* list = new base::ListValue();
for (ProxyRetryInfoMap::const_iterator iter = retry_info->begin();
iter != retry_info->end(); ++iter) {
list->Append(new base::StringValue(iter->first));
}
dict->Set("bad_proxy_list", list);
return dict;
}
base::Value* NetLogFinishedResolvingProxyCallback(
ProxyInfo* result,
NetLog::LogLevel ) {
base::DictionaryValue* dict = new base::DictionaryValue();
dict->SetString("pac_string", result->ToPacString());
return dict;
}
#if defined(OS_CHROMEOS)
class UnsetProxyConfigService : public ProxyConfigService {
public:
UnsetProxyConfigService() {}
virtual ~UnsetProxyConfigService() {}
virtual void AddObserver(Observer* observer) OVERRIDE {}
virtual void RemoveObserver(Observer* observer) OVERRIDE {}
virtual ConfigAvailability GetLatestProxyConfig(
ProxyConfig* config) OVERRIDE {
return CONFIG_UNSET;
}
};
#endif
}
class ProxyService::InitProxyResolver {
public:
InitProxyResolver()
: proxy_resolver_(NULL),
next_state_(STATE_NONE),
quick_check_enabled_(true) {
}
~InitProxyResolver() {
if (next_state_ == STATE_SET_PAC_SCRIPT_COMPLETE) {
proxy_resolver_->CancelSetPacScript();
}
}
int Start(ProxyResolver* proxy_resolver,
ProxyScriptFetcher* proxy_script_fetcher,
DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
NetLog* net_log,
const ProxyConfig& config,
TimeDelta wait_delay,
const CompletionCallback& callback) {
DCHECK_EQ(STATE_NONE, next_state_);
proxy_resolver_ = proxy_resolver;
decider_.reset(new ProxyScriptDecider(
proxy_script_fetcher, dhcp_proxy_script_fetcher, net_log));
decider_->set_quick_check_enabled(quick_check_enabled_);
config_ = config;
wait_delay_ = wait_delay;
callback_ = callback;
next_state_ = STATE_DECIDE_PROXY_SCRIPT;
return DoLoop(OK);
}
int StartSkipDecider(ProxyResolver* proxy_resolver,
const ProxyConfig& effective_config,
int decider_result,
ProxyResolverScriptData* script_data,
const CompletionCallback& callback) {
DCHECK_EQ(STATE_NONE, next_state_);
proxy_resolver_ = proxy_resolver;
effective_config_ = effective_config;
script_data_ = script_data;
callback_ = callback;
if (decider_result != OK)
return decider_result;
next_state_ = STATE_SET_PAC_SCRIPT;
return DoLoop(OK);
}
const ProxyConfig& effective_config() const {
DCHECK_EQ(STATE_NONE, next_state_);
return effective_config_;
}
ProxyResolverScriptData* script_data() {
DCHECK_EQ(STATE_NONE, next_state_);
return script_data_.get();
}
LoadState GetLoadState() const {
if (next_state_ == STATE_DECIDE_PROXY_SCRIPT_COMPLETE) {
return LOAD_STATE_DOWNLOADING_PROXY_SCRIPT;
}
return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
}
void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
bool quick_check_enabled() const { return quick_check_enabled_; }
private:
enum State {
STATE_NONE,
STATE_DECIDE_PROXY_SCRIPT,
STATE_DECIDE_PROXY_SCRIPT_COMPLETE,
STATE_SET_PAC_SCRIPT,
STATE_SET_PAC_SCRIPT_COMPLETE,
};
int DoLoop(int result) {
DCHECK_NE(next_state_, STATE_NONE);
int rv = result;
do {
State state = next_state_;
next_state_ = STATE_NONE;
switch (state) {
case STATE_DECIDE_PROXY_SCRIPT:
DCHECK_EQ(OK, rv);
rv = DoDecideProxyScript();
break;
case STATE_DECIDE_PROXY_SCRIPT_COMPLETE:
rv = DoDecideProxyScriptComplete(rv);
break;
case STATE_SET_PAC_SCRIPT:
DCHECK_EQ(OK, rv);
rv = DoSetPacScript();
break;
case STATE_SET_PAC_SCRIPT_COMPLETE:
rv = DoSetPacScriptComplete(rv);
break;
default:
NOTREACHED() << "bad state: " << state;
rv = ERR_UNEXPECTED;
break;
}
} while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
return rv;
}
int DoDecideProxyScript() {
next_state_ = STATE_DECIDE_PROXY_SCRIPT_COMPLETE;
return decider_->Start(
config_, wait_delay_, proxy_resolver_->expects_pac_bytes(),
base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
}
int DoDecideProxyScriptComplete(int result) {
if (result != OK)
return result;
effective_config_ = decider_->effective_config();
script_data_ = decider_->script_data();
next_state_ = STATE_SET_PAC_SCRIPT;
return OK;
}
int DoSetPacScript() {
DCHECK(script_data_.get());
next_state_ = STATE_SET_PAC_SCRIPT_COMPLETE;
return proxy_resolver_->SetPacScript(
script_data_,
base::Bind(&InitProxyResolver::OnIOCompletion, base::Unretained(this)));
}
int DoSetPacScriptComplete(int result) {
return result;
}
void OnIOCompletion(int result) {
DCHECK_NE(STATE_NONE, next_state_);
int rv = DoLoop(result);
if (rv != ERR_IO_PENDING)
DoCallback(rv);
}
void DoCallback(int result) {
DCHECK_NE(ERR_IO_PENDING, result);
callback_.Run(result);
}
ProxyConfig config_;
ProxyConfig effective_config_;
scoped_refptr<ProxyResolverScriptData> script_data_;
TimeDelta wait_delay_;
scoped_ptr<ProxyScriptDecider> decider_;
ProxyResolver* proxy_resolver_;
CompletionCallback callback_;
State next_state_;
bool quick_check_enabled_;
DISALLOW_COPY_AND_ASSIGN(InitProxyResolver);
};
class ProxyService::ProxyScriptDeciderPoller {
public:
typedef base::Callback<void(int, ProxyResolverScriptData*,
const ProxyConfig&)> ChangeCallback;
ProxyScriptDeciderPoller(ChangeCallback callback,
const ProxyConfig& config,
bool proxy_resolver_expects_pac_bytes,
ProxyScriptFetcher* proxy_script_fetcher,
DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher,
int init_net_error,
ProxyResolverScriptData* init_script_data,
NetLog* net_log)
: weak_factory_(this),
change_callback_(callback),
config_(config),
proxy_resolver_expects_pac_bytes_(proxy_resolver_expects_pac_bytes),
proxy_script_fetcher_(proxy_script_fetcher),
dhcp_proxy_script_fetcher_(dhcp_proxy_script_fetcher),
last_error_(init_net_error),
last_script_data_(init_script_data),
last_poll_time_(TimeTicks::Now()) {
next_poll_mode_ = poll_policy()->GetNextDelay(
last_error_, TimeDelta::FromSeconds(-1), &next_poll_delay_);
TryToStartNextPoll(false);
}
void OnLazyPoll() {
TryToStartNextPoll(true);
}
static const PacPollPolicy* set_policy(const PacPollPolicy* policy) {
const PacPollPolicy* prev = poll_policy_;
poll_policy_ = policy;
return prev;
}
void set_quick_check_enabled(bool enabled) { quick_check_enabled_ = enabled; }
bool quick_check_enabled() const { return quick_check_enabled_; }
private:
const PacPollPolicy* poll_policy() {
if (poll_policy_)
return poll_policy_;
return &default_poll_policy_;
}
void StartPollTimer() {
DCHECK(!decider_.get());
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ProxyScriptDeciderPoller::DoPoll,
weak_factory_.GetWeakPtr()),
next_poll_delay_);
}
void TryToStartNextPoll(bool triggered_by_activity) {
switch (next_poll_mode_) {
case PacPollPolicy::MODE_USE_TIMER:
if (!triggered_by_activity)
StartPollTimer();
break;
case PacPollPolicy::MODE_START_AFTER_ACTIVITY:
if (triggered_by_activity && !decider_.get()) {
TimeDelta elapsed_time = TimeTicks::Now() - last_poll_time_;
if (elapsed_time >= next_poll_delay_)
DoPoll();
}
break;
}
}
void DoPoll() {
last_poll_time_ = TimeTicks::Now();
decider_.reset(new ProxyScriptDecider(
proxy_script_fetcher_, dhcp_proxy_script_fetcher_, NULL));
decider_->set_quick_check_enabled(quick_check_enabled_);
int result = decider_->Start(
config_, TimeDelta(), proxy_resolver_expects_pac_bytes_,
base::Bind(&ProxyScriptDeciderPoller::OnProxyScriptDeciderCompleted,
base::Unretained(this)));
if (result != ERR_IO_PENDING)
OnProxyScriptDeciderCompleted(result);
}
void OnProxyScriptDeciderCompleted(int result) {
if (HasScriptDataChanged(result, decider_->script_data())) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&ProxyScriptDeciderPoller::NotifyProxyServiceOfChange,
weak_factory_.GetWeakPtr(),
result,
make_scoped_refptr(decider_->script_data()),
decider_->effective_config()));
return;
}
decider_.reset();
next_poll_mode_ = poll_policy()->GetNextDelay(
last_error_, next_poll_delay_, &next_poll_delay_);
TryToStartNextPoll(false);
}
bool HasScriptDataChanged(int result, ProxyResolverScriptData* script_data) {
if (result != last_error_) {
return true;
}
if (result != OK) {
return false;
}
return !script_data->Equals(last_script_data_.get());
}
void NotifyProxyServiceOfChange(
int result,
const scoped_refptr<ProxyResolverScriptData>& script_data,
const ProxyConfig& effective_config) {
change_callback_.Run(result, script_data.get(), effective_config);
}
base::WeakPtrFactory<ProxyScriptDeciderPoller> weak_factory_;
ChangeCallback change_callback_;
ProxyConfig config_;
bool proxy_resolver_expects_pac_bytes_;
ProxyScriptFetcher* proxy_script_fetcher_;
DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher_;
int last_error_;
scoped_refptr<ProxyResolverScriptData> last_script_data_;
scoped_ptr<ProxyScriptDecider> decider_;
TimeDelta next_poll_delay_;
PacPollPolicy::Mode next_poll_mode_;
TimeTicks last_poll_time_;
static const PacPollPolicy* poll_policy_;
const DefaultPollPolicy default_poll_policy_;
bool quick_check_enabled_;
DISALLOW_COPY_AND_ASSIGN(ProxyScriptDeciderPoller);
};
const ProxyService::PacPollPolicy*
ProxyService::ProxyScriptDeciderPoller::poll_policy_ = NULL;
class ProxyService::PacRequest
: public base::RefCounted<ProxyService::PacRequest> {
public:
PacRequest(ProxyService* service,
const GURL& url,
ProxyInfo* results,
const net::CompletionCallback& user_callback,
const BoundNetLog& net_log)
: service_(service),
user_callback_(user_callback),
results_(results),
url_(url),
resolve_job_(NULL),
config_id_(ProxyConfig::kInvalidConfigID),
config_source_(PROXY_CONFIG_SOURCE_UNKNOWN),
net_log_(net_log) {
DCHECK(!user_callback.is_null());
}
int Start() {
DCHECK(!was_cancelled());
DCHECK(!is_started());
DCHECK(service_->config_.is_valid());
config_id_ = service_->config_.id();
config_source_ = service_->config_.source();
proxy_resolve_start_time_ = TimeTicks::Now();
return resolver()->GetProxyForURL(
url_, results_,
base::Bind(&PacRequest::QueryComplete, base::Unretained(this)),
&resolve_job_, net_log_);
}
bool is_started() const {
return !!resolve_job_;
}
void StartAndCompleteCheckingForSynchronous() {
int rv = service_->TryToCompleteSynchronously(url_, results_);
if (rv == ERR_IO_PENDING)
rv = Start();
if (rv != ERR_IO_PENDING)
QueryComplete(rv);
}
void CancelResolveJob() {
DCHECK(is_started());
resolver()->CancelRequest(resolve_job_);
resolve_job_ = NULL;
DCHECK(!is_started());
}
void Cancel() {
net_log_.AddEvent(NetLog::TYPE_CANCELLED);
if (is_started())
CancelResolveJob();
service_ = NULL;
user_callback_.Reset();
results_ = NULL;
net_log_.EndEvent(NetLog::TYPE_PROXY_SERVICE);
}
bool was_cancelled() const {
return user_callback_.is_null();
}
int QueryDidComplete(int result_code) {
DCHECK(!was_cancelled());
int rv = service_->DidFinishResolvingProxy(results_, result_code, net_log_);
results_->config_id_ = config_id_;
results_->config_source_ = config_source_;
results_->did_use_pac_script_ = true;
results_->proxy_resolve_start_time_ = proxy_resolve_start_time_;
results_->proxy_resolve_end_time_ = TimeTicks::Now();
resolve_job_ = NULL;
config_id_ = ProxyConfig::kInvalidConfigID;
config_source_ = PROXY_CONFIG_SOURCE_UNKNOWN;
return rv;
}
BoundNetLog* net_log() { return &net_log_; }
LoadState GetLoadState() const {
if (is_started())
return resolver()->GetLoadState(resolve_job_);
return LOAD_STATE_RESOLVING_PROXY_FOR_URL;
}
private:
friend class base::RefCounted<ProxyService::PacRequest>;
~PacRequest() {}
void QueryComplete(int result_code) {
result_code = QueryDidComplete(result_code);
if (!user_callback_.is_null()) {
net::CompletionCallback callback = user_callback_;
service_->RemovePendingRequest(this);
callback.Run(result_code);
}
}
ProxyResolver* resolver() const { return service_->resolver_.get(); }
ProxyService* service_;
net::CompletionCallback user_callback_;
ProxyInfo* results_;
GURL url_;
ProxyResolver::RequestHandle resolve_job_;
ProxyConfig::ID config_id_;
ProxyConfigSource config_source_;
BoundNetLog net_log_;
TimeTicks proxy_resolve_start_time_;
};
ProxyService::ProxyService(ProxyConfigService* config_service,
ProxyResolver* resolver,
NetLog* net_log)
: resolver_(resolver),
next_config_id_(1),
current_state_(STATE_NONE) ,
net_log_(net_log),
stall_proxy_auto_config_delay_(TimeDelta::FromMilliseconds(
kDelayAfterNetworkChangesMs)),
quick_check_enabled_(true) {
NetworkChangeNotifier::AddIPAddressObserver(this);
NetworkChangeNotifier::AddDNSObserver(this);
ResetConfigService(config_service);
}
ProxyService* ProxyService::CreateUsingSystemProxyResolver(
ProxyConfigService* proxy_config_service,
size_t num_pac_threads,
NetLog* net_log) {
DCHECK(proxy_config_service);
if (!ProxyResolverFactoryForSystem::IsSupported()) {
LOG(WARNING) << "PAC support disabled because there is no "
"system implementation";
return CreateWithoutProxyResolver(proxy_config_service, net_log);
}
if (num_pac_threads == 0)
num_pac_threads = kDefaultNumPacThreads;
ProxyResolver* proxy_resolver = new MultiThreadedProxyResolver(
new ProxyResolverFactoryForSystem(), num_pac_threads);
return new ProxyService(proxy_config_service, proxy_resolver, net_log);
}
ProxyService* ProxyService::CreateWithoutProxyResolver(
ProxyConfigService* proxy_config_service,
NetLog* net_log) {
return new ProxyService(proxy_config_service,
new ProxyResolverNull(),
net_log);
}
ProxyService* ProxyService::CreateFixed(const ProxyConfig& pc) {
return CreateUsingSystemProxyResolver(new ProxyConfigServiceFixed(pc),
0, NULL);
}
ProxyService* ProxyService::CreateFixed(const std::string& proxy) {
net::ProxyConfig proxy_config;
proxy_config.proxy_rules().ParseFromString(proxy);
return ProxyService::CreateFixed(proxy_config);
}
ProxyService* ProxyService::CreateDirect() {
return CreateDirectWithNetLog(NULL);
}
ProxyService* ProxyService::CreateDirectWithNetLog(NetLog* net_log) {
return new ProxyService(new ProxyConfigServiceDirect, new ProxyResolverNull,
net_log);
}
ProxyService* ProxyService::CreateFixedFromPacResult(
const std::string& pac_string) {
scoped_ptr<ProxyConfigService> proxy_config_service(
new ProxyConfigServiceFixed(ProxyConfig::CreateAutoDetect()));
scoped_ptr<ProxyResolver> proxy_resolver(
new ProxyResolverFromPacString(pac_string));
return new ProxyService(proxy_config_service.release(),
proxy_resolver.release(),
NULL);
}
int ProxyService::ResolveProxy(const GURL& raw_url,
ProxyInfo* result,
const net::CompletionCallback& callback,
PacRequest** pac_request,
const BoundNetLog& net_log) {
DCHECK(CalledOnValidThread());
DCHECK(!callback.is_null());
net_log.BeginEvent(NetLog::TYPE_PROXY_SERVICE);
config_service_->OnLazyPoll();
if (script_poller_.get())
script_poller_->OnLazyPoll();
if (current_state_ == STATE_NONE)
ApplyProxyConfigIfAvailable();
GURL url = SimplifyUrlForRequest(raw_url);
int rv = TryToCompleteSynchronously(url, result);
if (rv != ERR_IO_PENDING)
return DidFinishResolvingProxy(result, rv, net_log);
scoped_refptr<PacRequest> req(
new PacRequest(this, url, result, callback, net_log));
if (current_state_ == STATE_READY) {
rv = req->Start();
if (rv != ERR_IO_PENDING)
return req->QueryDidComplete(rv);
} else {
req->net_log()->BeginEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
}
DCHECK_EQ(ERR_IO_PENDING, rv);
DCHECK(!ContainsPendingRequest(req.get()));
pending_requests_.push_back(req);
if (pac_request)
*pac_request = req.get();
return rv;
}
int ProxyService::TryToCompleteSynchronously(const GURL& url,
ProxyInfo* result) {
DCHECK_NE(STATE_NONE, current_state_);
if (current_state_ != STATE_READY)
return ERR_IO_PENDING;
DCHECK_NE(config_.id(), ProxyConfig::kInvalidConfigID);
if (permanent_error_ != OK)
return permanent_error_;
if (config_.HasAutomaticSettings())
return ERR_IO_PENDING;
config_.proxy_rules().Apply(url, result);
result->config_source_ = config_.source();
result->config_id_ = config_.id();
return OK;
}
ProxyService::~ProxyService() {
NetworkChangeNotifier::RemoveIPAddressObserver(this);
NetworkChangeNotifier::RemoveDNSObserver(this);
config_service_->RemoveObserver(this);
for (PendingRequests::iterator it = pending_requests_.begin();
it != pending_requests_.end();
++it) {
(*it)->Cancel();
}
}
void ProxyService::SuspendAllPendingRequests() {
for (PendingRequests::iterator it = pending_requests_.begin();
it != pending_requests_.end();
++it) {
PacRequest* req = it->get();
if (req->is_started()) {
req->CancelResolveJob();
req->net_log()->BeginEvent(
NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
}
}
}
void ProxyService::SetReady() {
DCHECK(!init_proxy_resolver_.get());
current_state_ = STATE_READY;
PendingRequests pending_copy = pending_requests_;
for (PendingRequests::iterator it = pending_copy.begin();
it != pending_copy.end();
++it) {
PacRequest* req = it->get();
if (!req->is_started() && !req->was_cancelled()) {
req->net_log()->EndEvent(NetLog::TYPE_PROXY_SERVICE_WAITING_FOR_INIT_PAC);
req->StartAndCompleteCheckingForSynchronous();
}
}
}
void ProxyService::ApplyProxyConfigIfAvailable() {
DCHECK_EQ(STATE_NONE, current_state_);
config_service_->OnLazyPoll();
if (fetched_config_.is_valid()) {
InitializeUsingLastFetchedConfig();
return;
}
current_state_ = STATE_WAITING_FOR_PROXY_CONFIG;
ProxyConfig config;
ProxyConfigService::ConfigAvailability availability =
config_service_->GetLatestProxyConfig(&config);
if (availability != ProxyConfigService::CONFIG_PENDING)
OnProxyConfigChanged(config, availability);
}
void ProxyService::OnInitProxyResolverComplete(int result) {
DCHECK_EQ(STATE_WAITING_FOR_INIT_PROXY_RESOLVER, current_state_);
DCHECK(init_proxy_resolver_.get());
DCHECK(fetched_config_.HasAutomaticSettings());
config_ = init_proxy_resolver_->effective_config();
script_poller_.reset(new ProxyScriptDeciderPoller(
base::Bind(&ProxyService::InitializeUsingDecidedConfig,
base::Unretained(this)),
fetched_config_,
resolver_->expects_pac_bytes(),
proxy_script_fetcher_.get(),
dhcp_proxy_script_fetcher_.get(),
result,
init_proxy_resolver_->script_data(),
NULL));
script_poller_->set_quick_check_enabled(quick_check_enabled_);
init_proxy_resolver_.reset();
if (result != OK) {
if (fetched_config_.pac_mandatory()) {
VLOG(1) << "Failed configuring with mandatory PAC script, blocking all "
"traffic.";
config_ = fetched_config_;
result = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
} else {
VLOG(1) << "Failed configuring with PAC script, falling-back to manual "
"proxy servers.";
config_ = fetched_config_;
config_.ClearAutomaticSettings();
result = OK;
}
}
permanent_error_ = result;
config_.set_id(fetched_config_.id());
config_.set_source(fetched_config_.source());
SetReady();
}
int ProxyService::ReconsiderProxyAfterError(const GURL& url,
ProxyInfo* result,
const CompletionCallback& callback,
PacRequest** pac_request,
const BoundNetLog& net_log) {
DCHECK(CalledOnValidThread());
bool re_resolve = result->config_id_ != config_.id();
if (re_resolve) {
proxy_retry_info_.clear();
return ResolveProxy(url, result, callback, pac_request, net_log);
}
#if defined(SPDY_PROXY_AUTH_ORIGIN)
if (result->proxy_server().isDataReductionProxy()) {
RecordDataReductionProxyBypassInfo(
true, result->proxy_server(), ERROR_BYPASS);
} else if (result->proxy_server().isDataReductionProxyFallback()) {
RecordDataReductionProxyBypassInfo(
false, result->proxy_server(), ERROR_BYPASS);
}
#endif
bool did_fallback = result->Fallback(net_log);
return did_fallback ? OK : ERR_FAILED;
}
bool ProxyService::MarkProxiesAsBadUntil(
const ProxyInfo& result,
base::TimeDelta retry_delay,
const ProxyServer& another_bad_proxy,
const BoundNetLog& net_log) {
result.proxy_list_.UpdateRetryInfoOnFallback(&proxy_retry_info_, retry_delay,
false,
another_bad_proxy,
net_log);
if (another_bad_proxy.is_valid())
return result.proxy_list_.size() > 2;
else
return result.proxy_list_.size() > 1;
}
void ProxyService::ReportSuccess(const ProxyInfo& result) {
DCHECK(CalledOnValidThread());
const ProxyRetryInfoMap& new_retry_info = result.proxy_retry_info();
if (new_retry_info.empty())
return;
for (ProxyRetryInfoMap::const_iterator iter = new_retry_info.begin();
iter != new_retry_info.end(); ++iter) {
ProxyRetryInfoMap::iterator existing = proxy_retry_info_.find(iter->first);
if (existing == proxy_retry_info_.end())
proxy_retry_info_[iter->first] = iter->second;
else if (existing->second.bad_until < iter->second.bad_until)
existing->second.bad_until = iter->second.bad_until;
}
if (net_log_) {
net_log_->AddGlobalEntry(
NetLog::TYPE_BAD_PROXY_LIST_REPORTED,
base::Bind(&NetLogBadProxyListCallback, &new_retry_info));
}
}
void ProxyService::CancelPacRequest(PacRequest* req) {
DCHECK(CalledOnValidThread());
DCHECK(req);
req->Cancel();
RemovePendingRequest(req);
}
LoadState ProxyService::GetLoadState(const PacRequest* req) const {
CHECK(req);
if (current_state_ == STATE_WAITING_FOR_INIT_PROXY_RESOLVER)
return init_proxy_resolver_->GetLoadState();
return req->GetLoadState();
}
bool ProxyService::ContainsPendingRequest(PacRequest* req) {
PendingRequests::iterator it = std::find(
pending_requests_.begin(), pending_requests_.end(), req);
return pending_requests_.end() != it;
}
void ProxyService::RemovePendingRequest(PacRequest* req) {
DCHECK(ContainsPendingRequest(req));
PendingRequests::iterator it = std::find(
pending_requests_.begin(), pending_requests_.end(), req);
pending_requests_.erase(it);
}
int ProxyService::DidFinishResolvingProxy(ProxyInfo* result,
int result_code,
const BoundNetLog& net_log) {
if (result_code == OK) {
if (net_log.IsLogging()) {
net_log.AddEvent(
NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST,
base::Bind(&NetLogFinishedResolvingProxyCallback, result));
}
result->DeprioritizeBadProxies(proxy_retry_info_);
} else {
net_log.AddEventWithNetErrorCode(
NetLog::TYPE_PROXY_SERVICE_RESOLVED_PROXY_LIST, result_code);
if (!config_.pac_mandatory()) {
result->UseDirect();
result_code = OK;
} else {
result_code = ERR_MANDATORY_PROXY_CONFIGURATION_FAILED;
}
}
net_log.EndEvent(NetLog::TYPE_PROXY_SERVICE);
return result_code;
}
void ProxyService::SetProxyScriptFetchers(
ProxyScriptFetcher* proxy_script_fetcher,
DhcpProxyScriptFetcher* dhcp_proxy_script_fetcher) {
DCHECK(CalledOnValidThread());
State previous_state = ResetProxyConfig(false);
proxy_script_fetcher_.reset(proxy_script_fetcher);
dhcp_proxy_script_fetcher_.reset(dhcp_proxy_script_fetcher);
if (previous_state != STATE_NONE)
ApplyProxyConfigIfAvailable();
}
ProxyScriptFetcher* ProxyService::GetProxyScriptFetcher() const {
DCHECK(CalledOnValidThread());
return proxy_script_fetcher_.get();
}
ProxyService::State ProxyService::ResetProxyConfig(bool reset_fetched_config) {
DCHECK(CalledOnValidThread());
State previous_state = current_state_;
permanent_error_ = OK;
proxy_retry_info_.clear();
script_poller_.reset();
init_proxy_resolver_.reset();
SuspendAllPendingRequests();
config_ = ProxyConfig();
if (reset_fetched_config)
fetched_config_ = ProxyConfig();
current_state_ = STATE_NONE;
return previous_state;
}
void ProxyService::ResetConfigService(
ProxyConfigService* new_proxy_config_service) {
DCHECK(CalledOnValidThread());
State previous_state = ResetProxyConfig(true);
if (config_service_.get())
config_service_->RemoveObserver(this);
config_service_.reset(new_proxy_config_service);
config_service_->AddObserver(this);
if (previous_state != STATE_NONE)
ApplyProxyConfigIfAvailable();
}
void ProxyService::ForceReloadProxyConfig() {
DCHECK(CalledOnValidThread());
ResetProxyConfig(false);
ApplyProxyConfigIfAvailable();
}
ProxyConfigService* ProxyService::CreateSystemProxyConfigService(
base::SingleThreadTaskRunner* io_thread_task_runner,
base::MessageLoop* file_loop) {
#if defined(OS_WIN)
return new ProxyConfigServiceWin();
#elif defined(OS_IOS)
return new ProxyConfigServiceIOS();
#elif defined(OS_MACOSX)
return new ProxyConfigServiceMac(io_thread_task_runner);
#elif defined(OS_CHROMEOS)
LOG(ERROR) << "ProxyConfigService for ChromeOS should be created in "
<< "profile_io_data.cc::CreateProxyConfigService and this should "
<< "be used only for examples.";
return new UnsetProxyConfigService;
#elif defined(OS_LINUX)
ProxyConfigServiceLinux* linux_config_service =
new ProxyConfigServiceLinux();
scoped_refptr<base::SingleThreadTaskRunner> glib_thread_task_runner =
base::ThreadTaskRunnerHandle::Get();
DCHECK_EQ(base::MessageLoop::TYPE_IO, file_loop->type());
linux_config_service->SetupAndFetchInitialConfig(
glib_thread_task_runner.get(),
io_thread_task_runner,
static_cast<base::MessageLoopForIO*>(file_loop));
return linux_config_service;
#elif defined(OS_ANDROID)
return new ProxyConfigServiceAndroid(
io_thread_task_runner,
base::MessageLoop::current()->message_loop_proxy());
#else
LOG(WARNING) << "Failed to choose a system proxy settings fetcher "
"for this platform.";
return new ProxyConfigServiceDirect();
#endif
}
const ProxyService::PacPollPolicy* ProxyService::set_pac_script_poll_policy(
const PacPollPolicy* policy) {
return ProxyScriptDeciderPoller::set_policy(policy);
}
scoped_ptr<ProxyService::PacPollPolicy>
ProxyService::CreateDefaultPacPollPolicy() {
return scoped_ptr<PacPollPolicy>(new DefaultPollPolicy());
}
#if defined(SPDY_PROXY_AUTH_ORIGIN)
void ProxyService::RecordDataReductionProxyBypassInfo(
bool is_primary,
const ProxyServer& proxy_server,
DataReductionProxyBypassEventType bypass_type) const {
if (proxy_retry_info_.find(proxy_server.ToURI()) != proxy_retry_info_.end())
return;
if (is_primary) {
UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.BypassInfoPrimary",
bypass_type, BYPASS_EVENT_TYPE_MAX);
} else {
UMA_HISTOGRAM_ENUMERATION("DataReductionProxy.BypassInfoFallback",
bypass_type, BYPASS_EVENT_TYPE_MAX);
}
}
#endif
void ProxyService::OnProxyConfigChanged(
const ProxyConfig& config,
ProxyConfigService::ConfigAvailability availability) {
ProxyConfig effective_config;
switch (availability) {
case ProxyConfigService::CONFIG_PENDING:
NOTREACHED() << "Proxy config change with CONFIG_PENDING availability!";
return;
case ProxyConfigService::CONFIG_VALID:
effective_config = config;
break;
case ProxyConfigService::CONFIG_UNSET:
effective_config = ProxyConfig::CreateDirect();
break;
}
if (net_log_) {
net_log_->AddGlobalEntry(
net::NetLog::TYPE_PROXY_CONFIG_CHANGED,
base::Bind(&NetLogProxyConfigChangedCallback,
&fetched_config_, &effective_config));
}
fetched_config_ = effective_config;
fetched_config_.set_id(1);
InitializeUsingLastFetchedConfig();
}
void ProxyService::InitializeUsingLastFetchedConfig() {
ResetProxyConfig(false);
DCHECK(fetched_config_.is_valid());
fetched_config_.set_id(next_config_id_++);
if (!fetched_config_.HasAutomaticSettings()) {
config_ = fetched_config_;
SetReady();
return;
}
current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
TimeDelta wait_delay =
stall_proxy_autoconfig_until_ - TimeTicks::Now();
init_proxy_resolver_.reset(new InitProxyResolver());
init_proxy_resolver_->set_quick_check_enabled(quick_check_enabled_);
int rv = init_proxy_resolver_->Start(
resolver_.get(),
proxy_script_fetcher_.get(),
dhcp_proxy_script_fetcher_.get(),
net_log_,
fetched_config_,
wait_delay,
base::Bind(&ProxyService::OnInitProxyResolverComplete,
base::Unretained(this)));
if (rv != ERR_IO_PENDING)
OnInitProxyResolverComplete(rv);
}
void ProxyService::InitializeUsingDecidedConfig(
int decider_result,
ProxyResolverScriptData* script_data,
const ProxyConfig& effective_config) {
DCHECK(fetched_config_.is_valid());
DCHECK(fetched_config_.HasAutomaticSettings());
ResetProxyConfig(false);
current_state_ = STATE_WAITING_FOR_INIT_PROXY_RESOLVER;
init_proxy_resolver_.reset(new InitProxyResolver());
int rv = init_proxy_resolver_->StartSkipDecider(
resolver_.get(),
effective_config,
decider_result,
script_data,
base::Bind(&ProxyService::OnInitProxyResolverComplete,
base::Unretained(this)));
if (rv != ERR_IO_PENDING)
OnInitProxyResolverComplete(rv);
}
void ProxyService::OnIPAddressChanged() {
stall_proxy_autoconfig_until_ =
TimeTicks::Now() + stall_proxy_auto_config_delay_;
State previous_state = ResetProxyConfig(false);
if (previous_state != STATE_NONE)
ApplyProxyConfigIfAvailable();
}
void ProxyService::OnDNSChanged() {
OnIPAddressChanged();
}
SyncProxyServiceHelper::SyncProxyServiceHelper(
base::MessageLoop* io_message_loop,
ProxyService* proxy_service)
: io_message_loop_(io_message_loop),
proxy_service_(proxy_service),
event_(false, false),
callback_(base::Bind(&SyncProxyServiceHelper::OnCompletion,
base::Unretained(this))) {
DCHECK(io_message_loop_ != base::MessageLoop::current());
}
int SyncProxyServiceHelper::ResolveProxy(const GURL& url,
ProxyInfo* proxy_info,
const BoundNetLog& net_log) {
DCHECK(io_message_loop_ != base::MessageLoop::current());
io_message_loop_->PostTask(
FROM_HERE,
base::Bind(&SyncProxyServiceHelper::StartAsyncResolve, this, url,
net_log));
event_.Wait();
if (result_ == net::OK) {
*proxy_info = proxy_info_;
}
return result_;
}
int SyncProxyServiceHelper::ReconsiderProxyAfterError(
const GURL& url, ProxyInfo* proxy_info, const BoundNetLog& net_log) {
DCHECK(io_message_loop_ != base::MessageLoop::current());
io_message_loop_->PostTask(
FROM_HERE,
base::Bind(&SyncProxyServiceHelper::StartAsyncReconsider, this, url,
net_log));
event_.Wait();
if (result_ == net::OK) {
*proxy_info = proxy_info_;
}
return result_;
}
SyncProxyServiceHelper::~SyncProxyServiceHelper() {}
void SyncProxyServiceHelper::StartAsyncResolve(const GURL& url,
const BoundNetLog& net_log) {
result_ = proxy_service_->ResolveProxy(
url, &proxy_info_, callback_, NULL, net_log);
if (result_ != net::ERR_IO_PENDING) {
OnCompletion(result_);
}
}
void SyncProxyServiceHelper::StartAsyncReconsider(const GURL& url,
const BoundNetLog& net_log) {
result_ = proxy_service_->ReconsiderProxyAfterError(
url, &proxy_info_, callback_, NULL, net_log);
if (result_ != net::ERR_IO_PENDING) {
OnCompletion(result_);
}
}
void SyncProxyServiceHelper::OnCompletion(int rv) {
result_ = rv;
event_.Signal();
}
}