pref_proxy_config_tracker_impl.cc revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
1// Copyright (c) 2011 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.
4
5#include "chrome/browser/net/pref_proxy_config_tracker_impl.h"
6
7#include "base/bind.h"
8#include "base/prefs/pref_registry_simple.h"
9#include "base/prefs/pref_service.h"
10#include "base/values.h"
11#include "chrome/browser/prefs/proxy_config_dictionary.h"
12#include "chrome/common/chrome_notification_types.h"
13#include "chrome/common/pref_names.h"
14#include "components/user_prefs/pref_registry_syncable.h"
15#include "content/public/browser/browser_thread.h"
16#include "content/public/browser/notification_details.h"
17#include "content/public/browser/notification_source.h"
18
19using content::BrowserThread;
20
21//============================= ChromeProxyConfigService =======================
22
23ChromeProxyConfigService::ChromeProxyConfigService(
24    net::ProxyConfigService* base_service)
25    : base_service_(base_service),
26      pref_config_state_(ProxyPrefs::CONFIG_UNSET),
27      pref_config_read_pending_(true),
28      registered_observer_(false) {
29}
30
31ChromeProxyConfigService::~ChromeProxyConfigService() {
32  if (registered_observer_ && base_service_.get())
33    base_service_->RemoveObserver(this);
34}
35
36void ChromeProxyConfigService::AddObserver(
37    net::ProxyConfigService::Observer* observer) {
38  RegisterObserver();
39  observers_.AddObserver(observer);
40}
41
42void ChromeProxyConfigService::RemoveObserver(
43    net::ProxyConfigService::Observer* observer) {
44  observers_.RemoveObserver(observer);
45}
46
47net::ProxyConfigService::ConfigAvailability
48    ChromeProxyConfigService::GetLatestProxyConfig(net::ProxyConfig* config) {
49  RegisterObserver();
50
51  if (pref_config_read_pending_)
52    return net::ProxyConfigService::CONFIG_PENDING;
53
54  // Ask the base service if available.
55  net::ProxyConfig system_config;
56  ConfigAvailability system_availability =
57      net::ProxyConfigService::CONFIG_UNSET;
58  if (base_service_.get())
59    system_availability = base_service_->GetLatestProxyConfig(&system_config);
60
61  ProxyPrefs::ConfigState config_state;
62  return PrefProxyConfigTrackerImpl::GetEffectiveProxyConfig(
63      pref_config_state_, pref_config_,
64      system_availability, system_config, false,
65      &config_state, config);
66}
67
68void ChromeProxyConfigService::OnLazyPoll() {
69  if (base_service_.get())
70    base_service_->OnLazyPoll();
71}
72
73void ChromeProxyConfigService::UpdateProxyConfig(
74    ProxyPrefs::ConfigState config_state,
75    const net::ProxyConfig& config) {
76  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
77
78  pref_config_read_pending_ = false;
79  pref_config_state_ = config_state;
80  pref_config_ = config;
81
82  if (!observers_.size())
83    return;
84
85  // Evaluate the proxy configuration. If GetLatestProxyConfig returns
86  // CONFIG_PENDING, we are using the system proxy service, but it doesn't have
87  // a valid configuration yet. Once it is ready, OnProxyConfigChanged() will be
88  // called and broadcast the proxy configuration.
89  // Note: If a switch between a preference proxy configuration and the system
90  // proxy configuration occurs an unnecessary notification might get send if
91  // the two configurations agree. This case should be rare however, so we don't
92  // handle that case specially.
93  net::ProxyConfig new_config;
94  ConfigAvailability availability = GetLatestProxyConfig(&new_config);
95  if (availability != CONFIG_PENDING) {
96    FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_,
97                      OnProxyConfigChanged(new_config, availability));
98  }
99}
100
101void ChromeProxyConfigService::OnProxyConfigChanged(
102    const net::ProxyConfig& config,
103    ConfigAvailability availability) {
104  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
105
106  // Check whether there is a proxy configuration defined by preferences. In
107  // this case that proxy configuration takes precedence and the change event
108  // from the delegate proxy service can be disregarded.
109  if (!PrefProxyConfigTrackerImpl::PrefPrecedes(pref_config_state_)) {
110    net::ProxyConfig actual_config;
111    availability = GetLatestProxyConfig(&actual_config);
112    FOR_EACH_OBSERVER(net::ProxyConfigService::Observer, observers_,
113                      OnProxyConfigChanged(actual_config, availability));
114  }
115}
116
117void ChromeProxyConfigService::RegisterObserver() {
118  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
119  if (!registered_observer_ && base_service_.get()) {
120    base_service_->AddObserver(this);
121    registered_observer_ = true;
122  }
123}
124
125//========================= PrefProxyConfigTrackerImpl =========================
126
127PrefProxyConfigTrackerImpl::PrefProxyConfigTrackerImpl(
128    PrefService* pref_service)
129    : pref_service_(pref_service),
130      chrome_proxy_config_service_(NULL),
131      update_pending_(true) {
132  config_state_ = ReadPrefConfig(&pref_config_);
133  proxy_prefs_.Init(pref_service);
134  proxy_prefs_.Add(prefs::kProxy,
135                   base::Bind(&PrefProxyConfigTrackerImpl::OnProxyPrefChanged,
136                              base::Unretained(this)));
137}
138
139PrefProxyConfigTrackerImpl::~PrefProxyConfigTrackerImpl() {
140  DCHECK(pref_service_ == NULL);
141}
142
143void PrefProxyConfigTrackerImpl::SetChromeProxyConfigService(
144    ChromeProxyConfigService* chrome_proxy_config_service) {
145  VLOG(1) << this << ": set chrome proxy config service to "
146          << chrome_proxy_config_service;
147  chrome_proxy_config_service_ = chrome_proxy_config_service;
148  if (chrome_proxy_config_service_ && update_pending_)
149    OnProxyConfigChanged(config_state_, pref_config_);
150}
151
152void PrefProxyConfigTrackerImpl::DetachFromPrefService() {
153  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
154  // Stop notifications.
155  proxy_prefs_.RemoveAll();
156  pref_service_ = NULL;
157  SetChromeProxyConfigService(NULL);
158}
159
160// static
161bool PrefProxyConfigTrackerImpl::PrefPrecedes(
162    ProxyPrefs::ConfigState config_state) {
163  return config_state == ProxyPrefs::CONFIG_POLICY ||
164         config_state == ProxyPrefs::CONFIG_EXTENSION ||
165         config_state == ProxyPrefs::CONFIG_OTHER_PRECEDE;
166}
167
168// static
169net::ProxyConfigService::ConfigAvailability
170    PrefProxyConfigTrackerImpl::GetEffectiveProxyConfig(
171        ProxyPrefs::ConfigState pref_state,
172        const net::ProxyConfig& pref_config,
173        net::ProxyConfigService::ConfigAvailability system_availability,
174        const net::ProxyConfig& system_config,
175        bool ignore_fallback_config,
176        ProxyPrefs::ConfigState* effective_config_state,
177        net::ProxyConfig* effective_config) {
178  *effective_config_state = pref_state;
179
180  if (PrefPrecedes(pref_state)) {
181    *effective_config = pref_config;
182    return net::ProxyConfigService::CONFIG_VALID;
183  }
184
185  // If there's no system proxy config, fall back to prefs or default.
186  if (system_availability == net::ProxyConfigService::CONFIG_UNSET) {
187    if (pref_state == ProxyPrefs::CONFIG_FALLBACK && !ignore_fallback_config)
188      *effective_config = pref_config;
189    else
190      *effective_config = net::ProxyConfig::CreateDirect();
191    return net::ProxyConfigService::CONFIG_VALID;
192  }
193
194  *effective_config_state = ProxyPrefs::CONFIG_SYSTEM;
195  *effective_config = system_config;
196  return system_availability;
197}
198
199// static
200void PrefProxyConfigTrackerImpl::RegisterPrefs(PrefRegistrySimple* registry) {
201  DictionaryValue* default_settings = ProxyConfigDictionary::CreateSystem();
202  registry->RegisterDictionaryPref(prefs::kProxy, default_settings);
203}
204
205// static
206void PrefProxyConfigTrackerImpl::RegisterUserPrefs(
207    PrefRegistrySyncable* pref_service) {
208  DictionaryValue* default_settings = ProxyConfigDictionary::CreateSystem();
209  pref_service->RegisterDictionaryPref(prefs::kProxy,
210                                       default_settings,
211                                       PrefRegistrySyncable::UNSYNCABLE_PREF);
212}
213
214ProxyPrefs::ConfigState PrefProxyConfigTrackerImpl::GetProxyConfig(
215    net::ProxyConfig* config) {
216  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
217  if (config_state_ != ProxyPrefs::CONFIG_UNSET)
218    *config = pref_config_;
219  return config_state_;
220}
221
222void PrefProxyConfigTrackerImpl::OnProxyConfigChanged(
223    ProxyPrefs::ConfigState config_state,
224    const net::ProxyConfig& config) {
225  if (!chrome_proxy_config_service_) {
226    VLOG(1) << "No chrome proxy config service to push to UpdateProxyConfig";
227    update_pending_ = true;
228    return;
229  }
230  update_pending_ = !BrowserThread::PostTask(
231      BrowserThread::IO, FROM_HERE,
232      base::Bind(&ChromeProxyConfigService::UpdateProxyConfig,
233                 base::Unretained(chrome_proxy_config_service_),
234                 config_state, config));
235  VLOG(1) << this << (update_pending_ ? ": Error" : ": Done")
236          << " pushing proxy to UpdateProxyConfig";
237}
238
239bool PrefProxyConfigTrackerImpl::PrefConfigToNetConfig(
240    const ProxyConfigDictionary& proxy_dict,
241    net::ProxyConfig* config) {
242  ProxyPrefs::ProxyMode mode;
243  if (!proxy_dict.GetMode(&mode)) {
244    // Fall back to system settings if the mode preference is invalid.
245    return false;
246  }
247
248  switch (mode) {
249    case ProxyPrefs::MODE_SYSTEM:
250      // Use system settings.
251      return false;
252    case ProxyPrefs::MODE_DIRECT:
253      // Ignore all the other proxy config preferences if the use of a proxy
254      // has been explicitly disabled.
255      return true;
256    case ProxyPrefs::MODE_AUTO_DETECT:
257      config->set_auto_detect(true);
258      return true;
259    case ProxyPrefs::MODE_PAC_SCRIPT: {
260      std::string proxy_pac;
261      if (!proxy_dict.GetPacUrl(&proxy_pac)) {
262        LOG(ERROR) << "Proxy settings request PAC script but do not specify "
263                   << "its URL. Falling back to direct connection.";
264        return true;
265      }
266      GURL proxy_pac_url(proxy_pac);
267      if (!proxy_pac_url.is_valid()) {
268        LOG(ERROR) << "Invalid proxy PAC url: " << proxy_pac;
269        return true;
270      }
271      config->set_pac_url(proxy_pac_url);
272      bool pac_mandatory = false;
273      proxy_dict.GetPacMandatory(&pac_mandatory);
274      config->set_pac_mandatory(pac_mandatory);
275      return true;
276    }
277    case ProxyPrefs::MODE_FIXED_SERVERS: {
278      std::string proxy_server;
279      if (!proxy_dict.GetProxyServer(&proxy_server)) {
280        LOG(ERROR) << "Proxy settings request fixed proxy servers but do not "
281                   << "specify their URLs. Falling back to direct connection.";
282        return true;
283      }
284      config->proxy_rules().ParseFromString(proxy_server);
285
286      std::string proxy_bypass;
287      if (proxy_dict.GetBypassList(&proxy_bypass)) {
288        config->proxy_rules().bypass_rules.ParseFromString(proxy_bypass);
289      }
290      return true;
291    }
292    case ProxyPrefs::kModeCount: {
293      // Fall through to NOTREACHED().
294    }
295  }
296  NOTREACHED() << "Unknown proxy mode, falling back to system settings.";
297  return false;
298}
299
300void PrefProxyConfigTrackerImpl::OnProxyPrefChanged() {
301  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
302  net::ProxyConfig new_config;
303  ProxyPrefs::ConfigState config_state = ReadPrefConfig(&new_config);
304  if (config_state_ != config_state ||
305      (config_state_ != ProxyPrefs::CONFIG_UNSET &&
306       !pref_config_.Equals(new_config))) {
307    config_state_ = config_state;
308    if (config_state_ != ProxyPrefs::CONFIG_UNSET)
309      pref_config_ = new_config;
310    update_pending_ = true;
311  }
312  if (update_pending_)
313    OnProxyConfigChanged(config_state, new_config);
314}
315
316ProxyPrefs::ConfigState PrefProxyConfigTrackerImpl::ReadPrefConfig(
317    net::ProxyConfig* config) {
318  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
319
320  // Clear the configuration and source.
321  *config = net::ProxyConfig();
322  ProxyPrefs::ConfigState config_state = ProxyPrefs::CONFIG_UNSET;
323
324  const PrefService::Preference* pref =
325      pref_service_->FindPreference(prefs::kProxy);
326  DCHECK(pref);
327
328  const DictionaryValue* dict = pref_service_->GetDictionary(prefs::kProxy);
329  DCHECK(dict);
330  ProxyConfigDictionary proxy_dict(dict);
331
332  if (PrefConfigToNetConfig(proxy_dict, config)) {
333    if (!pref->IsUserModifiable() || pref->HasUserSetting()) {
334      if (pref->IsManaged())
335        config_state = ProxyPrefs::CONFIG_POLICY;
336      else if (pref->IsExtensionControlled())
337        config_state = ProxyPrefs::CONFIG_EXTENSION;
338      else
339        config_state = ProxyPrefs::CONFIG_OTHER_PRECEDE;
340    } else  {
341      config_state = ProxyPrefs::CONFIG_FALLBACK;
342    }
343  }
344
345  return config_state;
346}
347