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_config_service_linux.h"
7 // glib >=2.40 deprecate g_settings_list_schemas in favor of
8 // g_settings_schema_source_list_schemas. This function is not available on
9 // earlier versions that we still need to support (specifically, 2.32), so
10 // disable the warning.
11 // TODO(mgiuca): Remove this suppression when we drop support for Ubuntu 13.10
12 // (saucy) and earlier. Update the code to use
13 // g_settings_schema_source_list_schemas instead.
14 #define GLIB_DISABLE_DEPRECATION_WARNINGS
18 #if defined(USE_GCONF)
19 #include <gconf/gconf-client.h>
20 #endif // defined(USE_GCONF)
24 #include <sys/inotify.h>
29 #include "base/bind.h"
30 #include "base/compiler_specific.h"
31 #include "base/debug/leak_annotations.h"
32 #include "base/environment.h"
33 #include "base/file_util.h"
34 #include "base/files/file_path.h"
35 #include "base/files/scoped_file.h"
36 #include "base/logging.h"
37 #include "base/message_loop/message_loop.h"
38 #include "base/nix/xdg_util.h"
39 #include "base/single_thread_task_runner.h"
40 #include "base/strings/string_number_conversions.h"
41 #include "base/strings/string_tokenizer.h"
42 #include "base/strings/string_util.h"
43 #include "base/threading/thread_restrictions.h"
44 #include "base/timer/timer.h"
45 #include "net/base/net_errors.h"
46 #include "net/http/http_util.h"
47 #include "net/proxy/proxy_config.h"
48 #include "net/proxy/proxy_server.h"
49 #include "url/url_canon.h"
52 #include "library_loaders/libgio.h"
53 #endif // defined(USE_GIO)
59 // Given a proxy hostname from a setting, returns that hostname with
60 // an appropriate proxy server scheme prefix.
61 // scheme indicates the desired proxy scheme: usually http, with
62 // socks 4 or 5 as special cases.
63 // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
64 std::string
FixupProxyHostScheme(ProxyServer::Scheme scheme
,
66 if (scheme
== ProxyServer::SCHEME_SOCKS5
&&
67 StartsWithASCII(host
, "socks4://", false)) {
68 // We default to socks 5, but if the user specifically set it to
69 // socks4://, then use that.
70 scheme
= ProxyServer::SCHEME_SOCKS4
;
72 // Strip the scheme if any.
73 std::string::size_type colon
= host
.find("://");
74 if (colon
!= std::string::npos
)
75 host
= host
.substr(colon
+ 3);
76 // If a username and perhaps password are specified, give a warning.
77 std::string::size_type at_sign
= host
.find("@");
78 // Should this be supported?
79 if (at_sign
!= std::string::npos
) {
80 // ProxyConfig does not support authentication parameters, but Chrome
81 // will prompt for the password later. Disregard the
82 // authentication parameters and continue with this hostname.
83 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
84 host
= host
.substr(at_sign
+ 1);
86 // If this is a socks proxy, prepend a scheme so as to tell
87 // ProxyServer. This also allows ProxyServer to choose the right
89 if (scheme
== ProxyServer::SCHEME_SOCKS4
)
90 host
= "socks4://" + host
;
91 else if (scheme
== ProxyServer::SCHEME_SOCKS5
)
92 host
= "socks5://" + host
;
93 // If there is a trailing slash, remove it so |host| will parse correctly
94 // even if it includes a port number (since the slash is not numeric).
95 if (host
.length() && host
[host
.length() - 1] == '/')
96 host
.resize(host
.length() - 1);
102 ProxyConfigServiceLinux::Delegate::~Delegate() {
105 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
106 const char* variable
, ProxyServer::Scheme scheme
,
107 ProxyServer
* result_server
) {
108 std::string env_value
;
109 if (env_var_getter_
->GetVar(variable
, &env_value
)) {
110 if (!env_value
.empty()) {
111 env_value
= FixupProxyHostScheme(scheme
, env_value
);
112 ProxyServer proxy_server
=
113 ProxyServer::FromURI(env_value
, ProxyServer::SCHEME_HTTP
);
114 if (proxy_server
.is_valid() && !proxy_server
.is_direct()) {
115 *result_server
= proxy_server
;
118 LOG(ERROR
) << "Failed to parse environment variable " << variable
;
125 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
126 const char* variable
, ProxyServer
* result_server
) {
127 return GetProxyFromEnvVarForScheme(variable
, ProxyServer::SCHEME_HTTP
,
131 bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig
* config
) {
132 // Check for automatic configuration first, in
133 // "auto_proxy". Possibly only the "environment_proxy" firefox
134 // extension has ever used this, but it still sounds like a good
136 std::string auto_proxy
;
137 if (env_var_getter_
->GetVar("auto_proxy", &auto_proxy
)) {
138 if (auto_proxy
.empty()) {
139 // Defined and empty => autodetect
140 config
->set_auto_detect(true);
142 // specified autoconfig URL
143 config
->set_pac_url(GURL(auto_proxy
));
147 // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
148 ProxyServer proxy_server
;
149 if (GetProxyFromEnvVar("all_proxy", &proxy_server
)) {
150 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
151 config
->proxy_rules().single_proxies
.SetSingleProxyServer(proxy_server
);
153 bool have_http
= GetProxyFromEnvVar("http_proxy", &proxy_server
);
155 config
->proxy_rules().proxies_for_http
.SetSingleProxyServer(proxy_server
);
156 // It would be tempting to let http_proxy apply for all protocols
157 // if https_proxy and ftp_proxy are not defined. Googling turns up
158 // several documents that mention only http_proxy. But then the
159 // user really might not want to proxy https. And it doesn't seem
160 // like other apps do this. So we will refrain.
161 bool have_https
= GetProxyFromEnvVar("https_proxy", &proxy_server
);
163 config
->proxy_rules().proxies_for_https
.
164 SetSingleProxyServer(proxy_server
);
165 bool have_ftp
= GetProxyFromEnvVar("ftp_proxy", &proxy_server
);
167 config
->proxy_rules().proxies_for_ftp
.SetSingleProxyServer(proxy_server
);
168 if (have_http
|| have_https
|| have_ftp
) {
169 // mustn't change type unless some rules are actually set.
170 config
->proxy_rules().type
=
171 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
174 if (config
->proxy_rules().empty()) {
175 // If the above were not defined, try for socks.
176 // For environment variables, we default to version 5, per the gnome
177 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
178 ProxyServer::Scheme scheme
= ProxyServer::SCHEME_SOCKS5
;
179 std::string env_version
;
180 if (env_var_getter_
->GetVar("SOCKS_VERSION", &env_version
)
181 && env_version
== "4")
182 scheme
= ProxyServer::SCHEME_SOCKS4
;
183 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme
, &proxy_server
)) {
184 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
185 config
->proxy_rules().single_proxies
.SetSingleProxyServer(proxy_server
);
188 // Look for the proxy bypass list.
189 std::string no_proxy
;
190 env_var_getter_
->GetVar("no_proxy", &no_proxy
);
191 if (config
->proxy_rules().empty()) {
192 // Having only "no_proxy" set, presumably to "*", makes it
193 // explicit that env vars do specify a configuration: having no
194 // rules specified only means the user explicitly asks for direct
196 return !no_proxy
.empty();
198 // Note that this uses "suffix" matching. So a bypass of "google.com"
199 // is understood to mean a bypass of "*google.com".
200 config
->proxy_rules().bypass_rules
.ParseFromStringUsingSuffixMatching(
207 const int kDebounceTimeoutMilliseconds
= 250;
208 const char kProxyGConfSchema
[] = "org.gnome.system.proxy";
210 #if defined(USE_GCONF)
211 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
212 class SettingGetterImplGConf
: public ProxyConfigServiceLinux::SettingGetter
{
214 SettingGetterImplGConf()
215 : client_(NULL
), system_proxy_id_(0), system_http_proxy_id_(0),
216 notify_delegate_(NULL
) {
219 virtual ~SettingGetterImplGConf() {
220 // client_ should have been released before now, from
221 // Delegate::OnDestroy(), while running on the UI thread. However
222 // on exiting the process, it may happen that Delegate::OnDestroy()
223 // task is left pending on the glib loop after the loop was quit,
224 // and pending tasks may then be deleted without being run.
226 // gconf client was not cleaned up.
227 if (task_runner_
->BelongsToCurrentThread()) {
228 // We are on the UI thread so we can clean it safely. This is
229 // the case at least for ui_tests running under Valgrind in
231 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
234 // This is very bad! We are deleting the setting getter but we're not on
235 // the UI thread. This is not supposed to happen: the setting getter is
236 // owned by the proxy config service's delegate, which is supposed to be
237 // destroyed on the UI thread only. We will get change notifications to
238 // a deleted object if we continue here, so fail now.
239 LOG(FATAL
) << "~SettingGetterImplGConf: deleting on wrong thread!";
245 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
246 base::MessageLoopForIO
* file_loop
) OVERRIDE
{
247 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
249 DCHECK(!task_runner_
.get());
250 task_runner_
= glib_thread_task_runner
;
251 client_
= gconf_client_get_default();
253 // It's not clear whether/when this can return NULL.
254 LOG(ERROR
) << "Unable to create a gconf client";
258 GError
* error
= NULL
;
259 bool added_system_proxy
= false;
260 // We need to add the directories for which we'll be asking
261 // for notifications, and we might as well ask to preload them.
262 // These need to be removed again in ShutDown(); we are careful
263 // here to only leave client_ non-NULL if both have been added.
264 gconf_client_add_dir(client_
, "/system/proxy",
265 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
267 added_system_proxy
= true;
268 gconf_client_add_dir(client_
, "/system/http_proxy",
269 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
272 LOG(ERROR
) << "Error requesting gconf directory: " << error
->message
;
274 if (added_system_proxy
)
275 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
276 g_object_unref(client_
);
284 virtual void ShutDown() OVERRIDE
{
286 DCHECK(task_runner_
->BelongsToCurrentThread());
287 // We must explicitly disable gconf notifications here, because the gconf
288 // client will be shared between all setting getters, and they do not all
289 // have the same lifetimes. (For instance, incognito sessions get their
290 // own, which is destroyed when the session ends.)
291 gconf_client_notify_remove(client_
, system_http_proxy_id_
);
292 gconf_client_notify_remove(client_
, system_proxy_id_
);
293 gconf_client_remove_dir(client_
, "/system/http_proxy", NULL
);
294 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
295 g_object_unref(client_
);
301 virtual bool SetUpNotifications(
302 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
304 DCHECK(task_runner_
->BelongsToCurrentThread());
305 GError
* error
= NULL
;
306 notify_delegate_
= delegate
;
307 // We have to keep track of the IDs returned by gconf_client_notify_add() so
308 // that we can remove them in ShutDown(). (Otherwise, notifications will be
309 // delivered to this object after it is deleted, which is bad, m'kay?)
310 system_proxy_id_
= gconf_client_notify_add(
311 client_
, "/system/proxy",
312 OnGConfChangeNotification
, this,
315 system_http_proxy_id_
= gconf_client_notify_add(
316 client_
, "/system/http_proxy",
317 OnGConfChangeNotification
, this,
321 LOG(ERROR
) << "Error requesting gconf notifications: " << error
->message
;
326 // Simulate a change to avoid possibly losing updates before this point.
327 OnChangeNotification();
331 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
332 return task_runner_
.get();
335 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
336 return PROXY_CONFIG_SOURCE_GCONF
;
339 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
342 return GetStringByPath("/system/proxy/mode", result
);
343 case PROXY_AUTOCONF_URL
:
344 return GetStringByPath("/system/proxy/autoconfig_url", result
);
345 case PROXY_HTTP_HOST
:
346 return GetStringByPath("/system/http_proxy/host", result
);
347 case PROXY_HTTPS_HOST
:
348 return GetStringByPath("/system/proxy/secure_host", result
);
350 return GetStringByPath("/system/proxy/ftp_host", result
);
351 case PROXY_SOCKS_HOST
:
352 return GetStringByPath("/system/proxy/socks_host", result
);
354 return false; // Placate compiler.
356 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
358 case PROXY_USE_HTTP_PROXY
:
359 return GetBoolByPath("/system/http_proxy/use_http_proxy", result
);
360 case PROXY_USE_SAME_PROXY
:
361 return GetBoolByPath("/system/http_proxy/use_same_proxy", result
);
362 case PROXY_USE_AUTHENTICATION
:
363 return GetBoolByPath("/system/http_proxy/use_authentication", result
);
365 return false; // Placate compiler.
367 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
369 case PROXY_HTTP_PORT
:
370 return GetIntByPath("/system/http_proxy/port", result
);
371 case PROXY_HTTPS_PORT
:
372 return GetIntByPath("/system/proxy/secure_port", result
);
374 return GetIntByPath("/system/proxy/ftp_port", result
);
375 case PROXY_SOCKS_PORT
:
376 return GetIntByPath("/system/proxy/socks_port", result
);
378 return false; // Placate compiler.
380 virtual bool GetStringList(StringListSetting key
,
381 std::vector
<std::string
>* result
) OVERRIDE
{
383 case PROXY_IGNORE_HOSTS
:
384 return GetStringListByPath("/system/http_proxy/ignore_hosts", result
);
386 return false; // Placate compiler.
389 virtual bool BypassListIsReversed() OVERRIDE
{
390 // This is a KDE-specific setting.
394 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
399 bool GetStringByPath(const char* key
, std::string
* result
) {
401 DCHECK(task_runner_
->BelongsToCurrentThread());
402 GError
* error
= NULL
;
403 gchar
* value
= gconf_client_get_string(client_
, key
, &error
);
404 if (HandleGError(error
, key
))
412 bool GetBoolByPath(const char* key
, bool* result
) {
414 DCHECK(task_runner_
->BelongsToCurrentThread());
415 GError
* error
= NULL
;
416 // We want to distinguish unset values from values defaulting to
417 // false. For that we need to use the type-generic
418 // gconf_client_get() rather than gconf_client_get_bool().
419 GConfValue
* gconf_value
= gconf_client_get(client_
, key
, &error
);
420 if (HandleGError(error
, key
))
426 if (gconf_value
->type
!= GCONF_VALUE_BOOL
) {
427 gconf_value_free(gconf_value
);
430 gboolean bool_value
= gconf_value_get_bool(gconf_value
);
431 *result
= static_cast<bool>(bool_value
);
432 gconf_value_free(gconf_value
);
435 bool GetIntByPath(const char* key
, int* result
) {
437 DCHECK(task_runner_
->BelongsToCurrentThread());
438 GError
* error
= NULL
;
439 int value
= gconf_client_get_int(client_
, key
, &error
);
440 if (HandleGError(error
, key
))
442 // We don't bother to distinguish an unset value because callers
443 // don't care. 0 is returned if unset.
447 bool GetStringListByPath(const char* key
, std::vector
<std::string
>* result
) {
449 DCHECK(task_runner_
->BelongsToCurrentThread());
450 GError
* error
= NULL
;
451 GSList
* list
= gconf_client_get_list(client_
, key
,
452 GCONF_VALUE_STRING
, &error
);
453 if (HandleGError(error
, key
))
457 for (GSList
*it
= list
; it
; it
= it
->next
) {
458 result
->push_back(static_cast<char*>(it
->data
));
465 // Logs and frees a glib error. Returns false if there was no error
467 bool HandleGError(GError
* error
, const char* key
) {
469 LOG(ERROR
) << "Error getting gconf value for " << key
470 << ": " << error
->message
;
477 // This is the callback from the debounce timer.
478 void OnDebouncedNotification() {
479 DCHECK(task_runner_
->BelongsToCurrentThread());
480 CHECK(notify_delegate_
);
481 // Forward to a method on the proxy config service delegate object.
482 notify_delegate_
->OnCheckProxyConfigSettings();
485 void OnChangeNotification() {
486 // We don't use Reset() because the timer may not yet be running.
487 // (In that case Stop() is a no-op.)
488 debounce_timer_
.Stop();
489 debounce_timer_
.Start(FROM_HERE
,
490 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
491 this, &SettingGetterImplGConf::OnDebouncedNotification
);
494 // gconf notification callback, dispatched on the default glib main loop.
495 static void OnGConfChangeNotification(GConfClient
* client
, guint cnxn_id
,
496 GConfEntry
* entry
, gpointer user_data
) {
497 VLOG(1) << "gconf change notification for key "
498 << gconf_entry_get_key(entry
);
499 // We don't track which key has changed, just that something did change.
500 SettingGetterImplGConf
* setting_getter
=
501 reinterpret_cast<SettingGetterImplGConf
*>(user_data
);
502 setting_getter
->OnChangeNotification();
505 GConfClient
* client_
;
506 // These ids are the values returned from gconf_client_notify_add(), which we
507 // will need in order to later call gconf_client_notify_remove().
508 guint system_proxy_id_
;
509 guint system_http_proxy_id_
;
511 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
512 base::OneShotTimer
<SettingGetterImplGConf
> debounce_timer_
;
514 // Task runner for the thread that we make gconf calls on. It should
515 // be the UI thread and all our methods should be called on this
516 // thread. Only for assertions.
517 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
519 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf
);
521 #endif // defined(USE_GCONF)
524 // This setting getter uses gsettings, as used in most GNOME 3 desktops.
525 class SettingGetterImplGSettings
526 : public ProxyConfigServiceLinux::SettingGetter
{
528 SettingGetterImplGSettings() :
534 notify_delegate_(NULL
) {
537 virtual ~SettingGetterImplGSettings() {
538 // client_ should have been released before now, from
539 // Delegate::OnDestroy(), while running on the UI thread. However
540 // on exiting the process, it may happen that
541 // Delegate::OnDestroy() task is left pending on the glib loop
542 // after the loop was quit, and pending tasks may then be deleted
543 // without being run.
545 // gconf client was not cleaned up.
546 if (task_runner_
->BelongsToCurrentThread()) {
547 // We are on the UI thread so we can clean it safely. This is
548 // the case at least for ui_tests running under Valgrind in
550 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
553 LOG(WARNING
) << "~SettingGetterImplGSettings: leaking gsettings client";
560 bool SchemaExists(const char* schema_name
) {
561 const gchar
* const* schemas
= libgio_loader_
.g_settings_list_schemas();
563 if (strcmp(schema_name
, static_cast<const char*>(*schemas
)) == 0)
570 // LoadAndCheckVersion() must be called *before* Init()!
571 bool LoadAndCheckVersion(base::Environment
* env
);
573 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
574 base::MessageLoopForIO
* file_loop
) OVERRIDE
{
575 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
577 DCHECK(!task_runner_
.get());
579 if (!SchemaExists(kProxyGConfSchema
) ||
580 !(client_
= libgio_loader_
.g_settings_new(kProxyGConfSchema
))) {
581 // It's not clear whether/when this can return NULL.
582 LOG(ERROR
) << "Unable to create a gsettings client";
585 task_runner_
= glib_thread_task_runner
;
586 // We assume these all work if the above call worked.
587 http_client_
= libgio_loader_
.g_settings_get_child(client_
, "http");
588 https_client_
= libgio_loader_
.g_settings_get_child(client_
, "https");
589 ftp_client_
= libgio_loader_
.g_settings_get_child(client_
, "ftp");
590 socks_client_
= libgio_loader_
.g_settings_get_child(client_
, "socks");
591 DCHECK(http_client_
&& https_client_
&& ftp_client_
&& socks_client_
);
595 virtual void ShutDown() OVERRIDE
{
597 DCHECK(task_runner_
->BelongsToCurrentThread());
598 // This also disables gsettings notifications.
599 g_object_unref(socks_client_
);
600 g_object_unref(ftp_client_
);
601 g_object_unref(https_client_
);
602 g_object_unref(http_client_
);
603 g_object_unref(client_
);
604 // We only need to null client_ because it's the only one that we check.
610 virtual bool SetUpNotifications(
611 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
613 DCHECK(task_runner_
->BelongsToCurrentThread());
614 notify_delegate_
= delegate
;
615 // We could watch for the change-event signal instead of changed, but
616 // since we have to watch more than one object, we'd still have to
617 // debounce change notifications. This is conceptually simpler.
618 g_signal_connect(G_OBJECT(client_
), "changed",
619 G_CALLBACK(OnGSettingsChangeNotification
), this);
620 g_signal_connect(G_OBJECT(http_client_
), "changed",
621 G_CALLBACK(OnGSettingsChangeNotification
), this);
622 g_signal_connect(G_OBJECT(https_client_
), "changed",
623 G_CALLBACK(OnGSettingsChangeNotification
), this);
624 g_signal_connect(G_OBJECT(ftp_client_
), "changed",
625 G_CALLBACK(OnGSettingsChangeNotification
), this);
626 g_signal_connect(G_OBJECT(socks_client_
), "changed",
627 G_CALLBACK(OnGSettingsChangeNotification
), this);
628 // Simulate a change to avoid possibly losing updates before this point.
629 OnChangeNotification();
633 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
634 return task_runner_
.get();
637 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
638 return PROXY_CONFIG_SOURCE_GSETTINGS
;
641 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
645 return GetStringByPath(client_
, "mode", result
);
646 case PROXY_AUTOCONF_URL
:
647 return GetStringByPath(client_
, "autoconfig-url", result
);
648 case PROXY_HTTP_HOST
:
649 return GetStringByPath(http_client_
, "host", result
);
650 case PROXY_HTTPS_HOST
:
651 return GetStringByPath(https_client_
, "host", result
);
653 return GetStringByPath(ftp_client_
, "host", result
);
654 case PROXY_SOCKS_HOST
:
655 return GetStringByPath(socks_client_
, "host", result
);
657 return false; // Placate compiler.
659 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
662 case PROXY_USE_HTTP_PROXY
:
663 // Although there is an "enabled" boolean in http_client_, it is not set
664 // to true by the proxy config utility. We ignore it and return false.
666 case PROXY_USE_SAME_PROXY
:
667 // Similarly, although there is a "use-same-proxy" boolean in client_,
668 // it is never set to false by the proxy config utility. We ignore it.
670 case PROXY_USE_AUTHENTICATION
:
671 // There is also no way to set this in the proxy config utility, but it
672 // doesn't hurt us to get the actual setting (unlike the two above).
673 return GetBoolByPath(http_client_
, "use-authentication", result
);
675 return false; // Placate compiler.
677 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
680 case PROXY_HTTP_PORT
:
681 return GetIntByPath(http_client_
, "port", result
);
682 case PROXY_HTTPS_PORT
:
683 return GetIntByPath(https_client_
, "port", result
);
685 return GetIntByPath(ftp_client_
, "port", result
);
686 case PROXY_SOCKS_PORT
:
687 return GetIntByPath(socks_client_
, "port", result
);
689 return false; // Placate compiler.
691 virtual bool GetStringList(StringListSetting key
,
692 std::vector
<std::string
>* result
) OVERRIDE
{
695 case PROXY_IGNORE_HOSTS
:
696 return GetStringListByPath(client_
, "ignore-hosts", result
);
698 return false; // Placate compiler.
701 virtual bool BypassListIsReversed() OVERRIDE
{
702 // This is a KDE-specific setting.
706 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
711 bool GetStringByPath(GSettings
* client
, const char* key
,
712 std::string
* result
) {
713 DCHECK(task_runner_
->BelongsToCurrentThread());
714 gchar
* value
= libgio_loader_
.g_settings_get_string(client
, key
);
721 bool GetBoolByPath(GSettings
* client
, const char* key
, bool* result
) {
722 DCHECK(task_runner_
->BelongsToCurrentThread());
723 *result
= static_cast<bool>(
724 libgio_loader_
.g_settings_get_boolean(client
, key
));
727 bool GetIntByPath(GSettings
* client
, const char* key
, int* result
) {
728 DCHECK(task_runner_
->BelongsToCurrentThread());
729 *result
= libgio_loader_
.g_settings_get_int(client
, key
);
732 bool GetStringListByPath(GSettings
* client
, const char* key
,
733 std::vector
<std::string
>* result
) {
734 DCHECK(task_runner_
->BelongsToCurrentThread());
735 gchar
** list
= libgio_loader_
.g_settings_get_strv(client
, key
);
738 for (size_t i
= 0; list
[i
]; ++i
) {
739 result
->push_back(static_cast<char*>(list
[i
]));
746 // This is the callback from the debounce timer.
747 void OnDebouncedNotification() {
748 DCHECK(task_runner_
->BelongsToCurrentThread());
749 CHECK(notify_delegate_
);
750 // Forward to a method on the proxy config service delegate object.
751 notify_delegate_
->OnCheckProxyConfigSettings();
754 void OnChangeNotification() {
755 // We don't use Reset() because the timer may not yet be running.
756 // (In that case Stop() is a no-op.)
757 debounce_timer_
.Stop();
758 debounce_timer_
.Start(FROM_HERE
,
759 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
760 this, &SettingGetterImplGSettings::OnDebouncedNotification
);
763 // gsettings notification callback, dispatched on the default glib main loop.
764 static void OnGSettingsChangeNotification(GSettings
* client
, gchar
* key
,
765 gpointer user_data
) {
766 VLOG(1) << "gsettings change notification for key " << key
;
767 // We don't track which key has changed, just that something did change.
768 SettingGetterImplGSettings
* setting_getter
=
769 reinterpret_cast<SettingGetterImplGSettings
*>(user_data
);
770 setting_getter
->OnChangeNotification();
774 GSettings
* http_client_
;
775 GSettings
* https_client_
;
776 GSettings
* ftp_client_
;
777 GSettings
* socks_client_
;
778 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
779 base::OneShotTimer
<SettingGetterImplGSettings
> debounce_timer_
;
781 // Task runner for the thread that we make gsettings calls on. It should
782 // be the UI thread and all our methods should be called on this
783 // thread. Only for assertions.
784 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
786 LibGioLoader libgio_loader_
;
788 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings
);
791 bool SettingGetterImplGSettings::LoadAndCheckVersion(
792 base::Environment
* env
) {
793 // LoadAndCheckVersion() must be called *before* Init()!
796 // The APIs to query gsettings were introduced after the minimum glib
797 // version we target, so we can't link directly against them. We load them
798 // dynamically at runtime, and if they don't exist, return false here. (We
799 // support linking directly via gyp flags though.) Additionally, even when
800 // they are present, we do two additional checks to make sure we should use
801 // them and not gconf. First, we attempt to load the schema for proxy
802 // settings. Second, we check for the program that was used in older
803 // versions of GNOME to configure proxy settings, and return false if it
804 // exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
805 // but don't use gsettings for proxy settings, but they do have the old
806 // binary, so we detect these systems that way.
809 // TODO(phajdan.jr): Redesign the code to load library on different thread.
810 base::ThreadRestrictions::ScopedAllowIO allow_io
;
812 // Try also without .0 at the end; on some systems this may be required.
813 if (!libgio_loader_
.Load("libgio-2.0.so.0") &&
814 !libgio_loader_
.Load("libgio-2.0.so")) {
815 VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
820 GSettings
* client
= NULL
;
821 if (SchemaExists(kProxyGConfSchema
)) {
822 ANNOTATE_SCOPED_MEMORY_LEAK
; // http://crbug.com/380782
823 client
= libgio_loader_
.g_settings_new(kProxyGConfSchema
);
826 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
829 g_object_unref(client
);
832 if (!env
->GetVar("PATH", &path
)) {
833 LOG(ERROR
) << "No $PATH variable. Assuming no gnome-network-properties.";
835 // Yes, we're on the UI thread. Yes, we're accessing the file system.
836 // Sadly, we don't have much choice. We need the proxy settings and we
837 // need them now, and to figure out where to get them, we have to check
838 // for this binary. See http://crbug.com/69057 for additional details.
839 base::ThreadRestrictions::ScopedAllowIO allow_io
;
840 std::vector
<std::string
> paths
;
841 Tokenize(path
, ":", &paths
);
842 for (size_t i
= 0; i
< paths
.size(); ++i
) {
843 base::FilePath
file(paths
[i
]);
844 if (base::PathExists(file
.Append("gnome-network-properties"))) {
845 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
851 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
854 #endif // defined(USE_GIO)
856 // This is the KDE version that reads kioslaverc and simulates gconf.
857 // Doing this allows the main Delegate code, as well as the unit tests
858 // for it, to stay the same - and the settings map fairly well besides.
859 class SettingGetterImplKDE
: public ProxyConfigServiceLinux::SettingGetter
,
860 public base::MessagePumpLibevent::Watcher
{
862 explicit SettingGetterImplKDE(base::Environment
* env_var_getter
)
863 : inotify_fd_(-1), notify_delegate_(NULL
), indirect_manual_(false),
864 auto_no_pac_(false), reversed_bypass_list_(false),
865 env_var_getter_(env_var_getter
), file_loop_(NULL
) {
866 // This has to be called on the UI thread (http://crbug.com/69057).
867 base::ThreadRestrictions::ScopedAllowIO allow_io
;
869 // Derive the location of the kde config dir from the environment.
871 if (env_var_getter
->GetVar("KDEHOME", &home
) && !home
.empty()) {
872 // $KDEHOME is set. Use it unconditionally.
873 kde_config_dir_
= KDEHomeToConfigPath(base::FilePath(home
));
875 // $KDEHOME is unset. Try to figure out what to use. This seems to be
876 // the common case on most distributions.
877 if (!env_var_getter
->GetVar(base::env_vars::kHome
, &home
))
878 // User has no $HOME? Give up. Later we'll report the failure.
880 if (base::nix::GetDesktopEnvironment(env_var_getter
) ==
881 base::nix::DESKTOP_ENVIRONMENT_KDE3
) {
882 // KDE3 always uses .kde for its configuration.
883 base::FilePath kde_path
= base::FilePath(home
).Append(".kde");
884 kde_config_dir_
= KDEHomeToConfigPath(kde_path
);
886 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
887 // both can be installed side-by-side. Sadly they don't all do this, and
888 // they don't always do this: some distributions have started switching
889 // back as well. So if there is a .kde4 directory, check the timestamps
890 // of the config directories within and use the newest one.
891 // Note that we should currently be running in the UI thread, because in
892 // the gconf version, that is the only thread that can access the proxy
893 // settings (a gconf restriction). As noted below, the initial read of
894 // the proxy settings will be done in this thread anyway, so we check
895 // for .kde4 here in this thread as well.
896 base::FilePath kde3_path
= base::FilePath(home
).Append(".kde");
897 base::FilePath kde3_config
= KDEHomeToConfigPath(kde3_path
);
898 base::FilePath kde4_path
= base::FilePath(home
).Append(".kde4");
899 base::FilePath kde4_config
= KDEHomeToConfigPath(kde4_path
);
900 bool use_kde4
= false;
901 if (base::DirectoryExists(kde4_path
)) {
902 base::File::Info kde3_info
;
903 base::File::Info kde4_info
;
904 if (base::GetFileInfo(kde4_config
, &kde4_info
)) {
905 if (base::GetFileInfo(kde3_config
, &kde3_info
)) {
906 use_kde4
= kde4_info
.last_modified
>= kde3_info
.last_modified
;
913 kde_config_dir_
= KDEHomeToConfigPath(kde4_path
);
915 kde_config_dir_
= KDEHomeToConfigPath(kde3_path
);
921 virtual ~SettingGetterImplKDE() {
922 // inotify_fd_ should have been closed before now, from
923 // Delegate::OnDestroy(), while running on the file thread. However
924 // on exiting the process, it may happen that Delegate::OnDestroy()
925 // task is left pending on the file loop after the loop was quit,
926 // and pending tasks may then be deleted without being run.
927 // Here in the KDE version, we can safely close the file descriptor
928 // anyway. (Not that it really matters; the process is exiting.)
929 if (inotify_fd_
>= 0)
931 DCHECK(inotify_fd_
< 0);
934 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
935 base::MessageLoopForIO
* file_loop
) OVERRIDE
{
936 // This has to be called on the UI thread (http://crbug.com/69057).
937 base::ThreadRestrictions::ScopedAllowIO allow_io
;
938 DCHECK(inotify_fd_
< 0);
939 inotify_fd_
= inotify_init();
940 if (inotify_fd_
< 0) {
941 PLOG(ERROR
) << "inotify_init failed";
944 int flags
= fcntl(inotify_fd_
, F_GETFL
);
945 if (fcntl(inotify_fd_
, F_SETFL
, flags
| O_NONBLOCK
) < 0) {
946 PLOG(ERROR
) << "fcntl failed";
951 file_loop_
= file_loop
;
952 // The initial read is done on the current thread, not |file_loop_|,
953 // since we will need to have it for SetUpAndFetchInitialConfig().
954 UpdateCachedSettings();
958 virtual void ShutDown() OVERRIDE
{
959 if (inotify_fd_
>= 0) {
960 ResetCachedSettings();
961 inotify_watcher_
.StopWatchingFileDescriptor();
967 virtual bool SetUpNotifications(
968 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
969 DCHECK(inotify_fd_
>= 0);
970 DCHECK(base::MessageLoop::current() == file_loop_
);
971 // We can't just watch the kioslaverc file directly, since KDE will write
972 // a new copy of it and then rename it whenever settings are changed and
973 // inotify watches inodes (so we'll be watching the old deleted file after
974 // the first change, and it will never change again). So, we watch the
975 // directory instead. We then act only on changes to the kioslaverc entry.
976 if (inotify_add_watch(inotify_fd_
, kde_config_dir_
.value().c_str(),
977 IN_MODIFY
| IN_MOVED_TO
) < 0)
979 notify_delegate_
= delegate
;
980 if (!file_loop_
->WatchFileDescriptor(inotify_fd_
,
982 base::MessageLoopForIO::WATCH_READ
,
986 // Simulate a change to avoid possibly losing updates before this point.
987 OnChangeNotification();
991 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
992 return file_loop_
? file_loop_
->message_loop_proxy().get() : NULL
;
995 // Implement base::MessagePumpLibevent::Watcher.
996 virtual void OnFileCanReadWithoutBlocking(int fd
) OVERRIDE
{
997 DCHECK_EQ(fd
, inotify_fd_
);
998 DCHECK(base::MessageLoop::current() == file_loop_
);
999 OnChangeNotification();
1001 virtual void OnFileCanWriteWithoutBlocking(int fd
) OVERRIDE
{
1005 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
1006 return PROXY_CONFIG_SOURCE_KDE
;
1009 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
1010 string_map_type::iterator it
= string_table_
.find(key
);
1011 if (it
== string_table_
.end())
1013 *result
= it
->second
;
1016 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
1017 // We don't ever have any booleans.
1020 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
1021 // We don't ever have any integers. (See AddProxy() below about ports.)
1024 virtual bool GetStringList(StringListSetting key
,
1025 std::vector
<std::string
>* result
) OVERRIDE
{
1026 strings_map_type::iterator it
= strings_table_
.find(key
);
1027 if (it
== strings_table_
.end())
1029 *result
= it
->second
;
1033 virtual bool BypassListIsReversed() OVERRIDE
{
1034 return reversed_bypass_list_
;
1037 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
1042 void ResetCachedSettings() {
1043 string_table_
.clear();
1044 strings_table_
.clear();
1045 indirect_manual_
= false;
1046 auto_no_pac_
= false;
1047 reversed_bypass_list_
= false;
1050 base::FilePath
KDEHomeToConfigPath(const base::FilePath
& kde_home
) {
1051 return kde_home
.Append("share").Append("config");
1054 void AddProxy(StringSetting host_key
, const std::string
& value
) {
1055 if (value
.empty() || value
.substr(0, 3) == "//:")
1058 size_t space
= value
.find(' ');
1059 if (space
!= std::string::npos
) {
1060 // Newer versions of KDE use a space rather than a colon to separate the
1061 // port number from the hostname. If we find this, we need to convert it.
1062 std::string fixed
= value
;
1064 string_table_
[host_key
] = fixed
;
1066 // We don't need to parse the port number out; GetProxyFromSettings()
1067 // would only append it right back again. So we just leave the port
1068 // number right in the host string.
1069 string_table_
[host_key
] = value
;
1073 void AddHostList(StringListSetting key
, const std::string
& value
) {
1074 std::vector
<std::string
> tokens
;
1075 base::StringTokenizer
tk(value
, ", ");
1076 while (tk
.GetNext()) {
1077 std::string token
= tk
.token();
1079 tokens
.push_back(token
);
1081 strings_table_
[key
] = tokens
;
1084 void AddKDESetting(const std::string
& key
, const std::string
& value
) {
1085 if (key
== "ProxyType") {
1086 const char* mode
= "none";
1087 indirect_manual_
= false;
1088 auto_no_pac_
= false;
1090 base::StringToInt(value
, &int_value
);
1091 switch (int_value
) {
1092 case 0: // No proxy, or maybe kioslaverc syntax error.
1094 case 1: // Manual configuration.
1102 auto_no_pac_
= true;
1104 case 4: // Indirect manual via environment variables.
1106 indirect_manual_
= true;
1109 string_table_
[PROXY_MODE
] = mode
;
1110 } else if (key
== "Proxy Config Script") {
1111 string_table_
[PROXY_AUTOCONF_URL
] = value
;
1112 } else if (key
== "httpProxy") {
1113 AddProxy(PROXY_HTTP_HOST
, value
);
1114 } else if (key
== "httpsProxy") {
1115 AddProxy(PROXY_HTTPS_HOST
, value
);
1116 } else if (key
== "ftpProxy") {
1117 AddProxy(PROXY_FTP_HOST
, value
);
1118 } else if (key
== "socksProxy") {
1119 // Older versions of KDE configure SOCKS in a weird way involving
1120 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1121 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1122 AddProxy(PROXY_SOCKS_HOST
, value
);
1123 } else if (key
== "ReversedException") {
1124 // We count "true" or any nonzero number as true, otherwise false.
1125 // Note that if the value is not actually numeric StringToInt()
1126 // will return 0, which we count as false.
1128 base::StringToInt(value
, &int_value
);
1129 reversed_bypass_list_
= (value
== "true" || int_value
);
1130 } else if (key
== "NoProxyFor") {
1131 AddHostList(PROXY_IGNORE_HOSTS
, value
);
1132 } else if (key
== "AuthMode") {
1133 // Check for authentication, just so we can warn.
1135 base::StringToInt(value
, &mode
);
1137 // ProxyConfig does not support authentication parameters, but
1138 // Chrome will prompt for the password later. So we ignore this.
1140 "Proxy authentication parameters ignored, see bug 16709";
1145 void ResolveIndirect(StringSetting key
) {
1146 string_map_type::iterator it
= string_table_
.find(key
);
1147 if (it
!= string_table_
.end()) {
1149 if (env_var_getter_
->GetVar(it
->second
.c_str(), &value
))
1152 string_table_
.erase(it
);
1156 void ResolveIndirectList(StringListSetting key
) {
1157 strings_map_type::iterator it
= strings_table_
.find(key
);
1158 if (it
!= strings_table_
.end()) {
1160 if (!it
->second
.empty() &&
1161 env_var_getter_
->GetVar(it
->second
[0].c_str(), &value
))
1162 AddHostList(key
, value
);
1164 strings_table_
.erase(it
);
1168 // The settings in kioslaverc could occur in any order, but some affect
1169 // others. Rather than read the whole file in and then query them in an
1170 // order that allows us to handle that, we read the settings in whatever
1171 // order they occur and do any necessary tweaking after we finish.
1172 void ResolveModeEffects() {
1173 if (indirect_manual_
) {
1174 ResolveIndirect(PROXY_HTTP_HOST
);
1175 ResolveIndirect(PROXY_HTTPS_HOST
);
1176 ResolveIndirect(PROXY_FTP_HOST
);
1177 ResolveIndirectList(PROXY_IGNORE_HOSTS
);
1180 // Remove the PAC URL; we're not supposed to use it.
1181 string_table_
.erase(PROXY_AUTOCONF_URL
);
1185 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1186 // each relevant name-value pair to the appropriate value table.
1187 void UpdateCachedSettings() {
1188 base::FilePath kioslaverc
= kde_config_dir_
.Append("kioslaverc");
1189 base::ScopedFILE
input(base::OpenFile(kioslaverc
, "r"));
1192 ResetCachedSettings();
1193 bool in_proxy_settings
= false;
1194 bool line_too_long
= false;
1195 char line
[BUFFER_SIZE
];
1196 // fgets() will return NULL on EOF or error.
1197 while (fgets(line
, sizeof(line
), input
.get())) {
1198 // fgets() guarantees the line will be properly terminated.
1199 size_t length
= strlen(line
);
1202 // This should be true even with CRLF endings.
1203 if (line
[length
- 1] != '\n') {
1204 line_too_long
= true;
1207 if (line_too_long
) {
1208 // The previous line had no line ending, but this done does. This is
1209 // the end of the line that was too long, so warn here and skip it.
1210 LOG(WARNING
) << "skipped very long line in " << kioslaverc
.value();
1211 line_too_long
= false;
1214 // Remove the LF at the end, and the CR if there is one.
1215 line
[--length
] = '\0';
1216 if (length
&& line
[length
- 1] == '\r')
1217 line
[--length
] = '\0';
1218 // Now parse the line.
1219 if (line
[0] == '[') {
1220 // Switching sections. All we care about is whether this is
1221 // the (a?) proxy settings section, for both KDE3 and KDE4.
1222 in_proxy_settings
= !strncmp(line
, "[Proxy Settings]", 16);
1223 } else if (in_proxy_settings
) {
1224 // A regular line, in the (a?) proxy settings section.
1225 char* split
= strchr(line
, '=');
1226 // Skip this line if it does not contain an = sign.
1229 // Split the line on the = and advance |split|.
1231 std::string key
= line
;
1232 std::string value
= split
;
1233 base::TrimWhitespaceASCII(key
, base::TRIM_ALL
, &key
);
1234 base::TrimWhitespaceASCII(value
, base::TRIM_ALL
, &value
);
1235 // Skip this line if the key name is empty.
1238 // Is the value name localized?
1239 if (key
[key
.length() - 1] == ']') {
1240 // Find the matching bracket.
1241 length
= key
.rfind('[');
1242 // Skip this line if the localization indicator is malformed.
1243 if (length
== std::string::npos
)
1245 // Trim the localization indicator off.
1247 // Remove any resulting trailing whitespace.
1248 base::TrimWhitespaceASCII(key
, base::TRIM_TRAILING
, &key
);
1249 // Skip this line if the key name is now empty.
1253 // Now fill in the tables.
1254 AddKDESetting(key
, value
);
1257 if (ferror(input
.get()))
1258 LOG(ERROR
) << "error reading " << kioslaverc
.value();
1259 ResolveModeEffects();
1262 // This is the callback from the debounce timer.
1263 void OnDebouncedNotification() {
1264 DCHECK(base::MessageLoop::current() == file_loop_
);
1265 VLOG(1) << "inotify change notification for kioslaverc";
1266 UpdateCachedSettings();
1267 CHECK(notify_delegate_
);
1268 // Forward to a method on the proxy config service delegate object.
1269 notify_delegate_
->OnCheckProxyConfigSettings();
1272 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1273 // from the inotify file descriptor and starts up a debounce timer if
1274 // an event for kioslaverc is seen.
1275 void OnChangeNotification() {
1276 DCHECK_GE(inotify_fd_
, 0);
1277 DCHECK(base::MessageLoop::current() == file_loop_
);
1278 char event_buf
[(sizeof(inotify_event
) + NAME_MAX
+ 1) * 4];
1279 bool kioslaverc_touched
= false;
1281 while ((r
= read(inotify_fd_
, event_buf
, sizeof(event_buf
))) > 0) {
1282 // inotify returns variable-length structures, which is why we have
1283 // this strange-looking loop instead of iterating through an array.
1284 char* event_ptr
= event_buf
;
1285 while (event_ptr
< event_buf
+ r
) {
1286 inotify_event
* event
= reinterpret_cast<inotify_event
*>(event_ptr
);
1287 // The kernel always feeds us whole events.
1288 CHECK_LE(event_ptr
+ sizeof(inotify_event
), event_buf
+ r
);
1289 CHECK_LE(event
->name
+ event
->len
, event_buf
+ r
);
1290 if (!strcmp(event
->name
, "kioslaverc"))
1291 kioslaverc_touched
= true;
1292 // Advance the pointer just past the end of the filename.
1293 event_ptr
= event
->name
+ event
->len
;
1295 // We keep reading even if |kioslaverc_touched| is true to drain the
1296 // inotify event queue.
1299 // Instead of returning -1 and setting errno to EINVAL if there is not
1300 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1301 // new behavior (EINVAL) so we can reuse the code below.
1303 if (errno
!= EAGAIN
) {
1304 PLOG(WARNING
) << "error reading inotify file descriptor";
1305 if (errno
== EINVAL
) {
1306 // Our buffer is not large enough to read the next event. This should
1307 // not happen (because its size is calculated to always be sufficiently
1308 // large), but if it does we'd warn continuously since |inotify_fd_|
1309 // would be forever ready to read. Close it and stop watching instead.
1310 LOG(ERROR
) << "inotify failure; no longer watching kioslaverc!";
1311 inotify_watcher_
.StopWatchingFileDescriptor();
1316 if (kioslaverc_touched
) {
1317 // We don't use Reset() because the timer may not yet be running.
1318 // (In that case Stop() is a no-op.)
1319 debounce_timer_
.Stop();
1320 debounce_timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(
1321 kDebounceTimeoutMilliseconds
), this,
1322 &SettingGetterImplKDE::OnDebouncedNotification
);
1326 typedef std::map
<StringSetting
, std::string
> string_map_type
;
1327 typedef std::map
<StringListSetting
,
1328 std::vector
<std::string
> > strings_map_type
;
1331 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_
;
1332 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
1333 base::OneShotTimer
<SettingGetterImplKDE
> debounce_timer_
;
1334 base::FilePath kde_config_dir_
;
1335 bool indirect_manual_
;
1337 bool reversed_bypass_list_
;
1338 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1339 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1341 base::Environment
* env_var_getter_
;
1343 // We cache these settings whenever we re-read the kioslaverc file.
1344 string_map_type string_table_
;
1345 strings_map_type strings_table_
;
1347 // Message loop of the file thread, for reading kioslaverc. If NULL,
1348 // just read it directly (for testing). We also handle inotify events
1350 base::MessageLoopForIO
* file_loop_
;
1352 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE
);
1357 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1358 SettingGetter::StringSetting host_key
,
1359 ProxyServer
* result_server
) {
1361 if (!setting_getter_
->GetString(host_key
, &host
) || host
.empty()) {
1365 // Check for an optional port.
1367 SettingGetter::IntSetting port_key
=
1368 SettingGetter::HostSettingToPortSetting(host_key
);
1369 setting_getter_
->GetInt(port_key
, &port
);
1371 // If a port is set and non-zero:
1372 host
+= ":" + base::IntToString(port
);
1375 // gconf settings do not appear to distinguish between SOCKS version. We
1376 // default to version 5. For more information on this policy decision, see:
1377 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1378 ProxyServer::Scheme scheme
= (host_key
== SettingGetter::PROXY_SOCKS_HOST
) ?
1379 ProxyServer::SCHEME_SOCKS5
: ProxyServer::SCHEME_HTTP
;
1380 host
= FixupProxyHostScheme(scheme
, host
);
1381 ProxyServer proxy_server
= ProxyServer::FromURI(host
,
1382 ProxyServer::SCHEME_HTTP
);
1383 if (proxy_server
.is_valid()) {
1384 *result_server
= proxy_server
;
1390 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1391 ProxyConfig
* config
) {
1393 if (!setting_getter_
->GetString(SettingGetter::PROXY_MODE
, &mode
)) {
1394 // We expect this to always be set, so if we don't see it then we
1395 // probably have a gconf/gsettings problem, and so we don't have a valid
1399 if (mode
== "none") {
1400 // Specifically specifies no proxy.
1404 if (mode
== "auto") {
1405 // Automatic proxy config.
1406 std::string pac_url_str
;
1407 if (setting_getter_
->GetString(SettingGetter::PROXY_AUTOCONF_URL
,
1409 if (!pac_url_str
.empty()) {
1410 // If the PAC URL is actually a file path, then put file:// in front.
1411 if (pac_url_str
[0] == '/')
1412 pac_url_str
= "file://" + pac_url_str
;
1413 GURL
pac_url(pac_url_str
);
1414 if (!pac_url
.is_valid())
1416 config
->set_pac_url(pac_url
);
1420 config
->set_auto_detect(true);
1424 if (mode
!= "manual") {
1425 // Mode is unrecognized.
1428 bool use_http_proxy
;
1429 if (setting_getter_
->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY
,
1431 && !use_http_proxy
) {
1432 // Another master switch for some reason. If set to false, then no
1433 // proxy. But we don't panic if the key doesn't exist.
1437 bool same_proxy
= false;
1438 // Indicates to use the http proxy for all protocols. This one may
1439 // not exist (presumably on older versions); we assume false in that
1441 setting_getter_
->GetBool(SettingGetter::PROXY_USE_SAME_PROXY
,
1444 ProxyServer proxy_for_http
;
1445 ProxyServer proxy_for_https
;
1446 ProxyServer proxy_for_ftp
;
1447 ProxyServer socks_proxy
; // (socks)
1449 // This counts how many of the above ProxyServers were defined and valid.
1450 size_t num_proxies_specified
= 0;
1452 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1453 // specified for the scheme, then the resulting ProxyServer will be invalid.
1454 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST
, &proxy_for_http
))
1455 num_proxies_specified
++;
1456 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST
, &proxy_for_https
))
1457 num_proxies_specified
++;
1458 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST
, &proxy_for_ftp
))
1459 num_proxies_specified
++;
1460 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST
, &socks_proxy
))
1461 num_proxies_specified
++;
1464 if (proxy_for_http
.is_valid()) {
1465 // Use the http proxy for all schemes.
1466 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1467 config
->proxy_rules().single_proxies
.SetSingleProxyServer(proxy_for_http
);
1469 } else if (num_proxies_specified
> 0) {
1470 if (socks_proxy
.is_valid() && num_proxies_specified
== 1) {
1471 // If the only proxy specified was for SOCKS, use it for all schemes.
1472 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1473 config
->proxy_rules().single_proxies
.SetSingleProxyServer(socks_proxy
);
1475 // Otherwise use the indicated proxies per-scheme.
1476 config
->proxy_rules().type
=
1477 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
1478 config
->proxy_rules().proxies_for_http
.
1479 SetSingleProxyServer(proxy_for_http
);
1480 config
->proxy_rules().proxies_for_https
.
1481 SetSingleProxyServer(proxy_for_https
);
1482 config
->proxy_rules().proxies_for_ftp
.SetSingleProxyServer(proxy_for_ftp
);
1483 config
->proxy_rules().fallback_proxies
.SetSingleProxyServer(socks_proxy
);
1487 if (config
->proxy_rules().empty()) {
1488 // Manual mode but we couldn't parse any rules.
1492 // Check for authentication, just so we can warn.
1493 bool use_auth
= false;
1494 setting_getter_
->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION
,
1497 // ProxyConfig does not support authentication parameters, but
1498 // Chrome will prompt for the password later. So we ignore
1499 // /system/http_proxy/*auth* settings.
1500 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
1503 // Now the bypass list.
1504 std::vector
<std::string
> ignore_hosts_list
;
1505 config
->proxy_rules().bypass_rules
.Clear();
1506 if (setting_getter_
->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS
,
1507 &ignore_hosts_list
)) {
1508 std::vector
<std::string
>::const_iterator
it(ignore_hosts_list
.begin());
1509 for (; it
!= ignore_hosts_list
.end(); ++it
) {
1510 if (setting_getter_
->MatchHostsUsingSuffixMatching()) {
1511 config
->proxy_rules().bypass_rules
.
1512 AddRuleFromStringUsingSuffixMatching(*it
);
1514 config
->proxy_rules().bypass_rules
.AddRuleFromString(*it
);
1518 // Note that there are no settings with semantics corresponding to
1519 // bypass of local names in GNOME. In KDE, "<local>" is supported
1520 // as a hostname rule.
1522 // KDE allows one to reverse the bypass rules.
1523 config
->proxy_rules().reverse_bypass
=
1524 setting_getter_
->BypassListIsReversed();
1529 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment
* env_var_getter
)
1530 : env_var_getter_(env_var_getter
) {
1531 // Figure out which SettingGetterImpl to use, if any.
1532 switch (base::nix::GetDesktopEnvironment(env_var_getter
)) {
1533 case base::nix::DESKTOP_ENVIRONMENT_GNOME
:
1534 case base::nix::DESKTOP_ENVIRONMENT_UNITY
:
1535 #if defined(USE_GIO)
1537 scoped_ptr
<SettingGetterImplGSettings
> gs_getter(
1538 new SettingGetterImplGSettings());
1539 // We have to load symbols and check the GNOME version in use to decide
1540 // if we should use the gsettings getter. See LoadAndCheckVersion().
1541 if (gs_getter
->LoadAndCheckVersion(env_var_getter
))
1542 setting_getter_
.reset(gs_getter
.release());
1545 #if defined(USE_GCONF)
1546 // Fall back on gconf if gsettings is unavailable or incorrect.
1547 if (!setting_getter_
.get())
1548 setting_getter_
.reset(new SettingGetterImplGConf());
1551 case base::nix::DESKTOP_ENVIRONMENT_KDE3
:
1552 case base::nix::DESKTOP_ENVIRONMENT_KDE4
:
1553 setting_getter_
.reset(new SettingGetterImplKDE(env_var_getter
));
1555 case base::nix::DESKTOP_ENVIRONMENT_XFCE
:
1556 case base::nix::DESKTOP_ENVIRONMENT_OTHER
:
1561 ProxyConfigServiceLinux::Delegate::Delegate(
1562 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1563 : env_var_getter_(env_var_getter
), setting_getter_(setting_getter
) {
1566 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1567 base::SingleThreadTaskRunner
* glib_thread_task_runner
,
1568 base::SingleThreadTaskRunner
* io_thread_task_runner
,
1569 base::MessageLoopForIO
* file_loop
) {
1570 // We should be running on the default glib main loop thread right
1571 // now. gconf can only be accessed from this thread.
1572 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
1573 glib_thread_task_runner_
= glib_thread_task_runner
;
1574 io_thread_task_runner_
= io_thread_task_runner
;
1576 // If we are passed a NULL |io_thread_task_runner| or |file_loop|,
1577 // then we don't set up proxy setting change notifications. This
1578 // should not be the usual case but is intended to simplify test
1580 if (!io_thread_task_runner_
.get() || !file_loop
)
1581 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1583 // Fetch and cache the current proxy config. The config is left in
1584 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1585 // will expect to find it. This is safe to do because we return
1586 // before this ProxyConfigServiceLinux is passed on to
1587 // the ProxyService.
1589 // Note: It would be nice to prioritize environment variables
1590 // and only fall back to gconf if env vars were unset. But
1591 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1592 // does so even if the proxy mode is set to auto, which would
1595 bool got_config
= false;
1596 if (setting_getter_
.get() &&
1597 setting_getter_
->Init(glib_thread_task_runner
, file_loop
) &&
1598 GetConfigFromSettings(&cached_config_
)) {
1599 cached_config_
.set_id(1); // Mark it as valid.
1600 cached_config_
.set_source(setting_getter_
->GetConfigSource());
1601 VLOG(1) << "Obtained proxy settings from "
1602 << ProxyConfigSourceToString(cached_config_
.source());
1604 // If gconf proxy mode is "none", meaning direct, then we take
1605 // that to be a valid config and will not check environment
1606 // variables. The alternative would have been to look for a proxy
1607 // whereever we can find one.
1610 // Keep a copy of the config for use from this thread for
1611 // comparison with updated settings when we get notifications.
1612 reference_config_
= cached_config_
;
1613 reference_config_
.set_id(1); // Mark it as valid.
1615 // We only set up notifications if we have IO and file loops available.
1616 // We do this after getting the initial configuration so that we don't have
1617 // to worry about cancelling it if the initial fetch above fails. Note that
1618 // setting up notifications has the side effect of simulating a change, so
1619 // that we won't lose any updates that may have happened after the initial
1620 // fetch and before setting up notifications. We'll detect the common case
1621 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1622 if (io_thread_task_runner
&& file_loop
) {
1623 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1624 setting_getter_
->GetNotificationTaskRunner();
1625 if (!required_loop
.get() || required_loop
->BelongsToCurrentThread()) {
1626 // In this case we are already on an acceptable thread.
1627 SetUpNotifications();
1629 // Post a task to set up notifications. We don't wait for success.
1630 required_loop
->PostTask(FROM_HERE
, base::Bind(
1631 &ProxyConfigServiceLinux::Delegate::SetUpNotifications
, this));
1637 // We fall back on environment variables.
1639 // Consulting environment variables doesn't need to be done from the
1640 // default glib main loop, but it's a tiny enough amount of work.
1641 if (GetConfigFromEnv(&cached_config_
)) {
1642 cached_config_
.set_source(PROXY_CONFIG_SOURCE_ENV
);
1643 cached_config_
.set_id(1); // Mark it as valid.
1644 VLOG(1) << "Obtained proxy settings from environment variables";
1649 // Depending on the SettingGetter in use, this method will be called
1650 // on either the UI thread (GConf) or the file thread (KDE).
1651 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1652 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1653 setting_getter_
->GetNotificationTaskRunner();
1654 DCHECK(!required_loop
.get() || required_loop
->BelongsToCurrentThread());
1655 if (!setting_getter_
->SetUpNotifications(this))
1656 LOG(ERROR
) << "Unable to set up proxy configuration change notifications";
1659 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer
* observer
) {
1660 observers_
.AddObserver(observer
);
1663 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer
* observer
) {
1664 observers_
.RemoveObserver(observer
);
1667 ProxyConfigService::ConfigAvailability
1668 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1669 ProxyConfig
* config
) {
1670 // This is called from the IO thread.
1671 DCHECK(!io_thread_task_runner_
.get() ||
1672 io_thread_task_runner_
->BelongsToCurrentThread());
1674 // Simply return the last proxy configuration that glib_default_loop
1676 if (cached_config_
.is_valid()) {
1677 *config
= cached_config_
;
1679 *config
= ProxyConfig::CreateDirect();
1680 config
->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED
);
1683 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1684 // going to be available since we initialized eagerly on the UI thread.
1685 // TODO(eroman): do lazy initialization instead, so we no longer need
1686 // to construct ProxyConfigServiceLinux on the UI thread.
1687 // In which case, we may return false here.
1688 return CONFIG_VALID
;
1691 // Depending on the SettingGetter in use, this method will be called
1692 // on either the UI thread (GConf) or the file thread (KDE).
1693 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1694 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1695 setting_getter_
->GetNotificationTaskRunner();
1696 DCHECK(!required_loop
.get() || required_loop
->BelongsToCurrentThread());
1697 ProxyConfig new_config
;
1698 bool valid
= GetConfigFromSettings(&new_config
);
1700 new_config
.set_id(1); // mark it as valid
1702 // See if it is different from what we had before.
1703 if (new_config
.is_valid() != reference_config_
.is_valid() ||
1704 !new_config
.Equals(reference_config_
)) {
1705 // Post a task to the IO thread with the new configuration, so it can
1706 // update |cached_config_|.
1707 io_thread_task_runner_
->PostTask(FROM_HERE
, base::Bind(
1708 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig
,
1710 // Update the thread-private copy in |reference_config_| as well.
1711 reference_config_
= new_config
;
1713 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1717 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1718 const ProxyConfig
& new_config
) {
1719 DCHECK(io_thread_task_runner_
->BelongsToCurrentThread());
1720 VLOG(1) << "Proxy configuration changed";
1721 cached_config_
= new_config
;
1723 Observer
, observers_
,
1724 OnProxyConfigChanged(new_config
, ProxyConfigService::CONFIG_VALID
));
1727 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1728 if (!setting_getter_
.get())
1730 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1731 setting_getter_
->GetNotificationTaskRunner();
1732 if (!shutdown_loop
.get() || shutdown_loop
->BelongsToCurrentThread()) {
1733 // Already on the right thread, call directly.
1734 // This is the case for the unittests.
1737 // Post to shutdown thread. Note that on browser shutdown, we may quit
1738 // this MessageLoop and exit the program before ever running this.
1739 shutdown_loop
->PostTask(FROM_HERE
, base::Bind(
1740 &ProxyConfigServiceLinux::Delegate::OnDestroy
, this));
1743 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1744 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1745 setting_getter_
->GetNotificationTaskRunner();
1746 DCHECK(!shutdown_loop
.get() || shutdown_loop
->BelongsToCurrentThread());
1747 setting_getter_
->ShutDown();
1750 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1751 : delegate_(new Delegate(base::Environment::Create())) {
1754 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1755 delegate_
->PostDestroyTask();
1758 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1759 base::Environment
* env_var_getter
)
1760 : delegate_(new Delegate(env_var_getter
)) {
1763 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1764 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1765 : delegate_(new Delegate(env_var_getter
, setting_getter
)) {
1768 void ProxyConfigServiceLinux::AddObserver(Observer
* observer
) {
1769 delegate_
->AddObserver(observer
);
1772 void ProxyConfigServiceLinux::RemoveObserver(Observer
* observer
) {
1773 delegate_
->RemoveObserver(observer
);
1776 ProxyConfigService::ConfigAvailability
1777 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig
* config
) {
1778 return delegate_
->GetLatestProxyConfig(config
);