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"
10 #include <gconf/gconf-client.h>
11 #endif // defined(USE_GCONF)
15 #include <sys/inotify.h>
20 #include "base/bind.h"
21 #include "base/compiler_specific.h"
22 #include "base/environment.h"
23 #include "base/file_path.h"
24 #include "base/file_util.h"
25 #include "base/logging.h"
26 #include "base/message_loop.h"
27 #include "base/nix/xdg_util.h"
28 #include "base/single_thread_task_runner.h"
29 #include "base/string_number_conversions.h"
30 #include "base/string_tokenizer.h"
31 #include "base/string_util.h"
32 #include "base/threading/thread_restrictions.h"
33 #include "base/timer.h"
34 #include "googleurl/src/url_canon.h"
35 #include "net/base/net_errors.h"
36 #include "net/http/http_util.h"
37 #include "net/proxy/proxy_config.h"
38 #include "net/proxy/proxy_server.h"
41 #include "library_loaders/libgio.h"
42 #endif // defined(USE_GIO)
48 // Given a proxy hostname from a setting, returns that hostname with
49 // an appropriate proxy server scheme prefix.
50 // scheme indicates the desired proxy scheme: usually http, with
51 // socks 4 or 5 as special cases.
52 // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
53 std::string
FixupProxyHostScheme(ProxyServer::Scheme scheme
,
55 if (scheme
== ProxyServer::SCHEME_SOCKS5
&&
56 StartsWithASCII(host
, "socks4://", false)) {
57 // We default to socks 5, but if the user specifically set it to
58 // socks4://, then use that.
59 scheme
= ProxyServer::SCHEME_SOCKS4
;
61 // Strip the scheme if any.
62 std::string::size_type colon
= host
.find("://");
63 if (colon
!= std::string::npos
)
64 host
= host
.substr(colon
+ 3);
65 // If a username and perhaps password are specified, give a warning.
66 std::string::size_type at_sign
= host
.find("@");
67 // Should this be supported?
68 if (at_sign
!= std::string::npos
) {
69 // ProxyConfig does not support authentication parameters, but Chrome
70 // will prompt for the password later. Disregard the
71 // authentication parameters and continue with this hostname.
72 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
73 host
= host
.substr(at_sign
+ 1);
75 // If this is a socks proxy, prepend a scheme so as to tell
76 // ProxyServer. This also allows ProxyServer to choose the right
78 if (scheme
== ProxyServer::SCHEME_SOCKS4
)
79 host
= "socks4://" + host
;
80 else if (scheme
== ProxyServer::SCHEME_SOCKS5
)
81 host
= "socks5://" + host
;
82 // If there is a trailing slash, remove it so |host| will parse correctly
83 // even if it includes a port number (since the slash is not numeric).
84 if (host
.length() && host
[host
.length() - 1] == '/')
85 host
.resize(host
.length() - 1);
91 ProxyConfigServiceLinux::Delegate::~Delegate() {
94 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
95 const char* variable
, ProxyServer::Scheme scheme
,
96 ProxyServer
* result_server
) {
97 std::string env_value
;
98 if (env_var_getter_
->GetVar(variable
, &env_value
)) {
99 if (!env_value
.empty()) {
100 env_value
= FixupProxyHostScheme(scheme
, env_value
);
101 ProxyServer proxy_server
=
102 ProxyServer::FromURI(env_value
, ProxyServer::SCHEME_HTTP
);
103 if (proxy_server
.is_valid() && !proxy_server
.is_direct()) {
104 *result_server
= proxy_server
;
107 LOG(ERROR
) << "Failed to parse environment variable " << variable
;
114 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
115 const char* variable
, ProxyServer
* result_server
) {
116 return GetProxyFromEnvVarForScheme(variable
, ProxyServer::SCHEME_HTTP
,
120 bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig
* config
) {
121 // Check for automatic configuration first, in
122 // "auto_proxy". Possibly only the "environment_proxy" firefox
123 // extension has ever used this, but it still sounds like a good
125 std::string auto_proxy
;
126 if (env_var_getter_
->GetVar("auto_proxy", &auto_proxy
)) {
127 if (auto_proxy
.empty()) {
128 // Defined and empty => autodetect
129 config
->set_auto_detect(true);
131 // specified autoconfig URL
132 config
->set_pac_url(GURL(auto_proxy
));
136 // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
137 ProxyServer proxy_server
;
138 if (GetProxyFromEnvVar("all_proxy", &proxy_server
)) {
139 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
140 config
->proxy_rules().single_proxy
= proxy_server
;
142 bool have_http
= GetProxyFromEnvVar("http_proxy", &proxy_server
);
144 config
->proxy_rules().proxy_for_http
= proxy_server
;
145 // It would be tempting to let http_proxy apply for all protocols
146 // if https_proxy and ftp_proxy are not defined. Googling turns up
147 // several documents that mention only http_proxy. But then the
148 // user really might not want to proxy https. And it doesn't seem
149 // like other apps do this. So we will refrain.
150 bool have_https
= GetProxyFromEnvVar("https_proxy", &proxy_server
);
152 config
->proxy_rules().proxy_for_https
= proxy_server
;
153 bool have_ftp
= GetProxyFromEnvVar("ftp_proxy", &proxy_server
);
155 config
->proxy_rules().proxy_for_ftp
= proxy_server
;
156 if (have_http
|| have_https
|| have_ftp
) {
157 // mustn't change type unless some rules are actually set.
158 config
->proxy_rules().type
=
159 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
162 if (config
->proxy_rules().empty()) {
163 // If the above were not defined, try for socks.
164 // For environment variables, we default to version 5, per the gnome
165 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
166 ProxyServer::Scheme scheme
= ProxyServer::SCHEME_SOCKS5
;
167 std::string env_version
;
168 if (env_var_getter_
->GetVar("SOCKS_VERSION", &env_version
)
169 && env_version
== "4")
170 scheme
= ProxyServer::SCHEME_SOCKS4
;
171 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme
, &proxy_server
)) {
172 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
173 config
->proxy_rules().single_proxy
= proxy_server
;
176 // Look for the proxy bypass list.
177 std::string no_proxy
;
178 env_var_getter_
->GetVar("no_proxy", &no_proxy
);
179 if (config
->proxy_rules().empty()) {
180 // Having only "no_proxy" set, presumably to "*", makes it
181 // explicit that env vars do specify a configuration: having no
182 // rules specified only means the user explicitly asks for direct
184 return !no_proxy
.empty();
186 // Note that this uses "suffix" matching. So a bypass of "google.com"
187 // is understood to mean a bypass of "*google.com".
188 config
->proxy_rules().bypass_rules
.ParseFromStringUsingSuffixMatching(
195 const int kDebounceTimeoutMilliseconds
= 250;
197 #if defined(USE_GCONF)
198 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
199 class SettingGetterImplGConf
: public ProxyConfigServiceLinux::SettingGetter
{
201 SettingGetterImplGConf()
202 : client_(NULL
), system_proxy_id_(0), system_http_proxy_id_(0),
203 notify_delegate_(NULL
) {
206 virtual ~SettingGetterImplGConf() {
207 // client_ should have been released before now, from
208 // Delegate::OnDestroy(), while running on the UI thread. However
209 // on exiting the process, it may happen that Delegate::OnDestroy()
210 // task is left pending on the glib loop after the loop was quit,
211 // and pending tasks may then be deleted without being run.
213 // gconf client was not cleaned up.
214 if (task_runner_
->BelongsToCurrentThread()) {
215 // We are on the UI thread so we can clean it safely. This is
216 // the case at least for ui_tests running under Valgrind in
218 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
221 // This is very bad! We are deleting the setting getter but we're not on
222 // the UI thread. This is not supposed to happen: the setting getter is
223 // owned by the proxy config service's delegate, which is supposed to be
224 // destroyed on the UI thread only. We will get change notifications to
225 // a deleted object if we continue here, so fail now.
226 LOG(FATAL
) << "~SettingGetterImplGConf: deleting on wrong thread!";
232 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
233 MessageLoopForIO
* file_loop
) OVERRIDE
{
234 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
236 DCHECK(!task_runner_
);
237 task_runner_
= glib_thread_task_runner
;
238 client_
= gconf_client_get_default();
240 // It's not clear whether/when this can return NULL.
241 LOG(ERROR
) << "Unable to create a gconf client";
245 GError
* error
= NULL
;
246 bool added_system_proxy
= false;
247 // We need to add the directories for which we'll be asking
248 // for notifications, and we might as well ask to preload them.
249 // These need to be removed again in ShutDown(); we are careful
250 // here to only leave client_ non-NULL if both have been added.
251 gconf_client_add_dir(client_
, "/system/proxy",
252 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
254 added_system_proxy
= true;
255 gconf_client_add_dir(client_
, "/system/http_proxy",
256 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
259 LOG(ERROR
) << "Error requesting gconf directory: " << error
->message
;
261 if (added_system_proxy
)
262 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
263 g_object_unref(client_
);
271 virtual void ShutDown() OVERRIDE
{
273 DCHECK(task_runner_
->BelongsToCurrentThread());
274 // We must explicitly disable gconf notifications here, because the gconf
275 // client will be shared between all setting getters, and they do not all
276 // have the same lifetimes. (For instance, incognito sessions get their
277 // own, which is destroyed when the session ends.)
278 gconf_client_notify_remove(client_
, system_http_proxy_id_
);
279 gconf_client_notify_remove(client_
, system_proxy_id_
);
280 gconf_client_remove_dir(client_
, "/system/http_proxy", NULL
);
281 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
282 g_object_unref(client_
);
288 virtual bool SetUpNotifications(
289 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
291 DCHECK(task_runner_
->BelongsToCurrentThread());
292 GError
* error
= NULL
;
293 notify_delegate_
= delegate
;
294 // We have to keep track of the IDs returned by gconf_client_notify_add() so
295 // that we can remove them in ShutDown(). (Otherwise, notifications will be
296 // delivered to this object after it is deleted, which is bad, m'kay?)
297 system_proxy_id_
= gconf_client_notify_add(
298 client_
, "/system/proxy",
299 OnGConfChangeNotification
, this,
302 system_http_proxy_id_
= gconf_client_notify_add(
303 client_
, "/system/http_proxy",
304 OnGConfChangeNotification
, this,
308 LOG(ERROR
) << "Error requesting gconf notifications: " << error
->message
;
313 // Simulate a change to avoid possibly losing updates before this point.
314 OnChangeNotification();
318 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
322 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
323 return PROXY_CONFIG_SOURCE_GCONF
;
326 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
329 return GetStringByPath("/system/proxy/mode", result
);
330 case PROXY_AUTOCONF_URL
:
331 return GetStringByPath("/system/proxy/autoconfig_url", result
);
332 case PROXY_HTTP_HOST
:
333 return GetStringByPath("/system/http_proxy/host", result
);
334 case PROXY_HTTPS_HOST
:
335 return GetStringByPath("/system/proxy/secure_host", result
);
337 return GetStringByPath("/system/proxy/ftp_host", result
);
338 case PROXY_SOCKS_HOST
:
339 return GetStringByPath("/system/proxy/socks_host", result
);
341 return false; // Placate compiler.
343 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
345 case PROXY_USE_HTTP_PROXY
:
346 return GetBoolByPath("/system/http_proxy/use_http_proxy", result
);
347 case PROXY_USE_SAME_PROXY
:
348 return GetBoolByPath("/system/http_proxy/use_same_proxy", result
);
349 case PROXY_USE_AUTHENTICATION
:
350 return GetBoolByPath("/system/http_proxy/use_authentication", result
);
352 return false; // Placate compiler.
354 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
356 case PROXY_HTTP_PORT
:
357 return GetIntByPath("/system/http_proxy/port", result
);
358 case PROXY_HTTPS_PORT
:
359 return GetIntByPath("/system/proxy/secure_port", result
);
361 return GetIntByPath("/system/proxy/ftp_port", result
);
362 case PROXY_SOCKS_PORT
:
363 return GetIntByPath("/system/proxy/socks_port", result
);
365 return false; // Placate compiler.
367 virtual bool GetStringList(StringListSetting key
,
368 std::vector
<std::string
>* result
) OVERRIDE
{
370 case PROXY_IGNORE_HOSTS
:
371 return GetStringListByPath("/system/http_proxy/ignore_hosts", result
);
373 return false; // Placate compiler.
376 virtual bool BypassListIsReversed() OVERRIDE
{
377 // This is a KDE-specific setting.
381 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
386 bool GetStringByPath(const char* key
, std::string
* result
) {
388 DCHECK(task_runner_
->BelongsToCurrentThread());
389 GError
* error
= NULL
;
390 gchar
* value
= gconf_client_get_string(client_
, key
, &error
);
391 if (HandleGError(error
, key
))
399 bool GetBoolByPath(const char* key
, bool* result
) {
401 DCHECK(task_runner_
->BelongsToCurrentThread());
402 GError
* error
= NULL
;
403 // We want to distinguish unset values from values defaulting to
404 // false. For that we need to use the type-generic
405 // gconf_client_get() rather than gconf_client_get_bool().
406 GConfValue
* gconf_value
= gconf_client_get(client_
, key
, &error
);
407 if (HandleGError(error
, key
))
413 if (gconf_value
->type
!= GCONF_VALUE_BOOL
) {
414 gconf_value_free(gconf_value
);
417 gboolean bool_value
= gconf_value_get_bool(gconf_value
);
418 *result
= static_cast<bool>(bool_value
);
419 gconf_value_free(gconf_value
);
422 bool GetIntByPath(const char* key
, int* result
) {
424 DCHECK(task_runner_
->BelongsToCurrentThread());
425 GError
* error
= NULL
;
426 int value
= gconf_client_get_int(client_
, key
, &error
);
427 if (HandleGError(error
, key
))
429 // We don't bother to distinguish an unset value because callers
430 // don't care. 0 is returned if unset.
434 bool GetStringListByPath(const char* key
, std::vector
<std::string
>* result
) {
436 DCHECK(task_runner_
->BelongsToCurrentThread());
437 GError
* error
= NULL
;
438 GSList
* list
= gconf_client_get_list(client_
, key
,
439 GCONF_VALUE_STRING
, &error
);
440 if (HandleGError(error
, key
))
444 for (GSList
*it
= list
; it
; it
= it
->next
) {
445 result
->push_back(static_cast<char*>(it
->data
));
452 // Logs and frees a glib error. Returns false if there was no error
454 bool HandleGError(GError
* error
, const char* key
) {
456 LOG(ERROR
) << "Error getting gconf value for " << key
457 << ": " << error
->message
;
464 // This is the callback from the debounce timer.
465 void OnDebouncedNotification() {
466 DCHECK(task_runner_
->BelongsToCurrentThread());
467 CHECK(notify_delegate_
);
468 // Forward to a method on the proxy config service delegate object.
469 notify_delegate_
->OnCheckProxyConfigSettings();
472 void OnChangeNotification() {
473 // We don't use Reset() because the timer may not yet be running.
474 // (In that case Stop() is a no-op.)
475 debounce_timer_
.Stop();
476 debounce_timer_
.Start(FROM_HERE
,
477 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
478 this, &SettingGetterImplGConf::OnDebouncedNotification
);
481 // gconf notification callback, dispatched on the default glib main loop.
482 static void OnGConfChangeNotification(GConfClient
* client
, guint cnxn_id
,
483 GConfEntry
* entry
, gpointer user_data
) {
484 VLOG(1) << "gconf change notification for key "
485 << gconf_entry_get_key(entry
);
486 // We don't track which key has changed, just that something did change.
487 SettingGetterImplGConf
* setting_getter
=
488 reinterpret_cast<SettingGetterImplGConf
*>(user_data
);
489 setting_getter
->OnChangeNotification();
492 GConfClient
* client_
;
493 // These ids are the values returned from gconf_client_notify_add(), which we
494 // will need in order to later call gconf_client_notify_remove().
495 guint system_proxy_id_
;
496 guint system_http_proxy_id_
;
498 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
499 base::OneShotTimer
<SettingGetterImplGConf
> debounce_timer_
;
501 // Task runner for the thread that we make gconf calls on. It should
502 // be the UI thread and all our methods should be called on this
503 // thread. Only for assertions.
504 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
506 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf
);
508 #endif // defined(USE_GCONF)
511 // This setting getter uses gsettings, as used in most GNOME 3 desktops.
512 class SettingGetterImplGSettings
513 : public ProxyConfigServiceLinux::SettingGetter
{
515 SettingGetterImplGSettings() :
521 notify_delegate_(NULL
) {
524 virtual ~SettingGetterImplGSettings() {
525 // client_ should have been released before now, from
526 // Delegate::OnDestroy(), while running on the UI thread. However
527 // on exiting the process, it may happen that
528 // Delegate::OnDestroy() task is left pending on the glib loop
529 // after the loop was quit, and pending tasks may then be deleted
530 // without being run.
532 // gconf client was not cleaned up.
533 if (task_runner_
->BelongsToCurrentThread()) {
534 // We are on the UI thread so we can clean it safely. This is
535 // the case at least for ui_tests running under Valgrind in
537 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
540 LOG(WARNING
) << "~SettingGetterImplGSettings: leaking gsettings client";
547 bool SchemaExists(const char* schema_name
) {
548 const gchar
* const* schemas
= libgio_loader_
.g_settings_list_schemas();
550 if (strcmp(schema_name
, static_cast<const char*>(*schemas
)) == 0)
557 // LoadAndCheckVersion() must be called *before* Init()!
558 bool LoadAndCheckVersion(base::Environment
* env
);
560 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
561 MessageLoopForIO
* file_loop
) OVERRIDE
{
562 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
564 DCHECK(!task_runner_
);
566 if (!SchemaExists("org.gnome.system.proxy") ||
567 !(client_
= libgio_loader_
.g_settings_new("org.gnome.system.proxy"))) {
568 // It's not clear whether/when this can return NULL.
569 LOG(ERROR
) << "Unable to create a gsettings client";
572 task_runner_
= glib_thread_task_runner
;
573 // We assume these all work if the above call worked.
574 http_client_
= libgio_loader_
.g_settings_get_child(client_
, "http");
575 https_client_
= libgio_loader_
.g_settings_get_child(client_
, "https");
576 ftp_client_
= libgio_loader_
.g_settings_get_child(client_
, "ftp");
577 socks_client_
= libgio_loader_
.g_settings_get_child(client_
, "socks");
578 DCHECK(http_client_
&& https_client_
&& ftp_client_
&& socks_client_
);
582 virtual void ShutDown() OVERRIDE
{
584 DCHECK(task_runner_
->BelongsToCurrentThread());
585 // This also disables gsettings notifications.
586 g_object_unref(socks_client_
);
587 g_object_unref(ftp_client_
);
588 g_object_unref(https_client_
);
589 g_object_unref(http_client_
);
590 g_object_unref(client_
);
591 // We only need to null client_ because it's the only one that we check.
597 virtual bool SetUpNotifications(
598 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
600 DCHECK(task_runner_
->BelongsToCurrentThread());
601 notify_delegate_
= delegate
;
602 // We could watch for the change-event signal instead of changed, but
603 // since we have to watch more than one object, we'd still have to
604 // debounce change notifications. This is conceptually simpler.
605 g_signal_connect(G_OBJECT(client_
), "changed",
606 G_CALLBACK(OnGSettingsChangeNotification
), this);
607 g_signal_connect(G_OBJECT(http_client_
), "changed",
608 G_CALLBACK(OnGSettingsChangeNotification
), this);
609 g_signal_connect(G_OBJECT(https_client_
), "changed",
610 G_CALLBACK(OnGSettingsChangeNotification
), this);
611 g_signal_connect(G_OBJECT(ftp_client_
), "changed",
612 G_CALLBACK(OnGSettingsChangeNotification
), this);
613 g_signal_connect(G_OBJECT(socks_client_
), "changed",
614 G_CALLBACK(OnGSettingsChangeNotification
), this);
615 // Simulate a change to avoid possibly losing updates before this point.
616 OnChangeNotification();
620 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
624 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
625 return PROXY_CONFIG_SOURCE_GSETTINGS
;
628 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
632 return GetStringByPath(client_
, "mode", result
);
633 case PROXY_AUTOCONF_URL
:
634 return GetStringByPath(client_
, "autoconfig-url", result
);
635 case PROXY_HTTP_HOST
:
636 return GetStringByPath(http_client_
, "host", result
);
637 case PROXY_HTTPS_HOST
:
638 return GetStringByPath(https_client_
, "host", result
);
640 return GetStringByPath(ftp_client_
, "host", result
);
641 case PROXY_SOCKS_HOST
:
642 return GetStringByPath(socks_client_
, "host", result
);
644 return false; // Placate compiler.
646 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
649 case PROXY_USE_HTTP_PROXY
:
650 // Although there is an "enabled" boolean in http_client_, it is not set
651 // to true by the proxy config utility. We ignore it and return false.
653 case PROXY_USE_SAME_PROXY
:
654 // Similarly, although there is a "use-same-proxy" boolean in client_,
655 // it is never set to false by the proxy config utility. We ignore it.
657 case PROXY_USE_AUTHENTICATION
:
658 // There is also no way to set this in the proxy config utility, but it
659 // doesn't hurt us to get the actual setting (unlike the two above).
660 return GetBoolByPath(http_client_
, "use-authentication", result
);
662 return false; // Placate compiler.
664 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
667 case PROXY_HTTP_PORT
:
668 return GetIntByPath(http_client_
, "port", result
);
669 case PROXY_HTTPS_PORT
:
670 return GetIntByPath(https_client_
, "port", result
);
672 return GetIntByPath(ftp_client_
, "port", result
);
673 case PROXY_SOCKS_PORT
:
674 return GetIntByPath(socks_client_
, "port", result
);
676 return false; // Placate compiler.
678 virtual bool GetStringList(StringListSetting key
,
679 std::vector
<std::string
>* result
) OVERRIDE
{
682 case PROXY_IGNORE_HOSTS
:
683 return GetStringListByPath(client_
, "ignore-hosts", result
);
685 return false; // Placate compiler.
688 virtual bool BypassListIsReversed() OVERRIDE
{
689 // This is a KDE-specific setting.
693 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
698 bool GetStringByPath(GSettings
* client
, const char* key
,
699 std::string
* result
) {
700 DCHECK(task_runner_
->BelongsToCurrentThread());
701 gchar
* value
= libgio_loader_
.g_settings_get_string(client
, key
);
708 bool GetBoolByPath(GSettings
* client
, const char* key
, bool* result
) {
709 DCHECK(task_runner_
->BelongsToCurrentThread());
710 *result
= static_cast<bool>(
711 libgio_loader_
.g_settings_get_boolean(client
, key
));
714 bool GetIntByPath(GSettings
* client
, const char* key
, int* result
) {
715 DCHECK(task_runner_
->BelongsToCurrentThread());
716 *result
= libgio_loader_
.g_settings_get_int(client
, key
);
719 bool GetStringListByPath(GSettings
* client
, const char* key
,
720 std::vector
<std::string
>* result
) {
721 DCHECK(task_runner_
->BelongsToCurrentThread());
722 gchar
** list
= libgio_loader_
.g_settings_get_strv(client
, key
);
725 for (size_t i
= 0; list
[i
]; ++i
) {
726 result
->push_back(static_cast<char*>(list
[i
]));
733 // This is the callback from the debounce timer.
734 void OnDebouncedNotification() {
735 DCHECK(task_runner_
->BelongsToCurrentThread());
736 CHECK(notify_delegate_
);
737 // Forward to a method on the proxy config service delegate object.
738 notify_delegate_
->OnCheckProxyConfigSettings();
741 void OnChangeNotification() {
742 // We don't use Reset() because the timer may not yet be running.
743 // (In that case Stop() is a no-op.)
744 debounce_timer_
.Stop();
745 debounce_timer_
.Start(FROM_HERE
,
746 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
747 this, &SettingGetterImplGSettings::OnDebouncedNotification
);
750 // gsettings notification callback, dispatched on the default glib main loop.
751 static void OnGSettingsChangeNotification(GSettings
* client
, gchar
* key
,
752 gpointer user_data
) {
753 VLOG(1) << "gsettings change notification for key " << key
;
754 // We don't track which key has changed, just that something did change.
755 SettingGetterImplGSettings
* setting_getter
=
756 reinterpret_cast<SettingGetterImplGSettings
*>(user_data
);
757 setting_getter
->OnChangeNotification();
761 GSettings
* http_client_
;
762 GSettings
* https_client_
;
763 GSettings
* ftp_client_
;
764 GSettings
* socks_client_
;
765 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
766 base::OneShotTimer
<SettingGetterImplGSettings
> debounce_timer_
;
768 // Task runner for the thread that we make gsettings calls on. It should
769 // be the UI thread and all our methods should be called on this
770 // thread. Only for assertions.
771 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
773 LibGioLoader libgio_loader_
;
775 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings
);
778 bool SettingGetterImplGSettings::LoadAndCheckVersion(
779 base::Environment
* env
) {
780 // LoadAndCheckVersion() must be called *before* Init()!
783 // The APIs to query gsettings were introduced after the minimum glib
784 // version we target, so we can't link directly against them. We load them
785 // dynamically at runtime, and if they don't exist, return false here. (We
786 // support linking directly via gyp flags though.) Additionally, even when
787 // they are present, we do two additional checks to make sure we should use
788 // them and not gconf. First, we attempt to load the schema for proxy
789 // settings. Second, we check for the program that was used in older
790 // versions of GNOME to configure proxy settings, and return false if it
791 // exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
792 // but don't use gsettings for proxy settings, but they do have the old
793 // binary, so we detect these systems that way.
796 // TODO(phajdan.jr): Redesign the code to load library on different thread.
797 base::ThreadRestrictions::ScopedAllowIO allow_io
;
799 // Try also without .0 at the end; on some systems this may be required.
800 if (!libgio_loader_
.Load("libgio-2.0.so.0") &&
801 !libgio_loader_
.Load("libgio-2.0.so")) {
802 VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
808 if (!SchemaExists("org.gnome.system.proxy") ||
809 !(client
= libgio_loader_
.g_settings_new("org.gnome.system.proxy"))) {
810 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
813 g_object_unref(client
);
816 if (!env
->GetVar("PATH", &path
)) {
817 LOG(ERROR
) << "No $PATH variable. Assuming no gnome-network-properties.";
819 // Yes, we're on the UI thread. Yes, we're accessing the file system.
820 // Sadly, we don't have much choice. We need the proxy settings and we
821 // need them now, and to figure out where to get them, we have to check
822 // for this binary. See http://crbug.com/69057 for additional details.
823 base::ThreadRestrictions::ScopedAllowIO allow_io
;
824 std::vector
<std::string
> paths
;
825 Tokenize(path
, ":", &paths
);
826 for (size_t i
= 0; i
< paths
.size(); ++i
) {
827 FilePath
file(paths
[i
]);
828 if (file_util::PathExists(file
.Append("gnome-network-properties"))) {
829 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
835 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
838 #endif // defined(USE_GIO)
840 // This is the KDE version that reads kioslaverc and simulates gconf.
841 // Doing this allows the main Delegate code, as well as the unit tests
842 // for it, to stay the same - and the settings map fairly well besides.
843 class SettingGetterImplKDE
: public ProxyConfigServiceLinux::SettingGetter
,
844 public base::MessagePumpLibevent::Watcher
{
846 explicit SettingGetterImplKDE(base::Environment
* env_var_getter
)
847 : inotify_fd_(-1), notify_delegate_(NULL
), indirect_manual_(false),
848 auto_no_pac_(false), reversed_bypass_list_(false),
849 env_var_getter_(env_var_getter
), file_loop_(NULL
) {
850 // This has to be called on the UI thread (http://crbug.com/69057).
851 base::ThreadRestrictions::ScopedAllowIO allow_io
;
853 // Derive the location of the kde config dir from the environment.
855 if (env_var_getter
->GetVar("KDEHOME", &home
) && !home
.empty()) {
856 // $KDEHOME is set. Use it unconditionally.
857 kde_config_dir_
= KDEHomeToConfigPath(FilePath(home
));
859 // $KDEHOME is unset. Try to figure out what to use. This seems to be
860 // the common case on most distributions.
861 if (!env_var_getter
->GetVar(base::env_vars::kHome
, &home
))
862 // User has no $HOME? Give up. Later we'll report the failure.
864 if (base::nix::GetDesktopEnvironment(env_var_getter
) ==
865 base::nix::DESKTOP_ENVIRONMENT_KDE3
) {
866 // KDE3 always uses .kde for its configuration.
867 FilePath kde_path
= FilePath(home
).Append(".kde");
868 kde_config_dir_
= KDEHomeToConfigPath(kde_path
);
870 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
871 // both can be installed side-by-side. Sadly they don't all do this, and
872 // they don't always do this: some distributions have started switching
873 // back as well. So if there is a .kde4 directory, check the timestamps
874 // of the config directories within and use the newest one.
875 // Note that we should currently be running in the UI thread, because in
876 // the gconf version, that is the only thread that can access the proxy
877 // settings (a gconf restriction). As noted below, the initial read of
878 // the proxy settings will be done in this thread anyway, so we check
879 // for .kde4 here in this thread as well.
880 FilePath kde3_path
= FilePath(home
).Append(".kde");
881 FilePath kde3_config
= KDEHomeToConfigPath(kde3_path
);
882 FilePath kde4_path
= FilePath(home
).Append(".kde4");
883 FilePath kde4_config
= KDEHomeToConfigPath(kde4_path
);
884 bool use_kde4
= false;
885 if (file_util::DirectoryExists(kde4_path
)) {
886 base::PlatformFileInfo kde3_info
;
887 base::PlatformFileInfo kde4_info
;
888 if (file_util::GetFileInfo(kde4_config
, &kde4_info
)) {
889 if (file_util::GetFileInfo(kde3_config
, &kde3_info
)) {
890 use_kde4
= kde4_info
.last_modified
>= kde3_info
.last_modified
;
897 kde_config_dir_
= KDEHomeToConfigPath(kde4_path
);
899 kde_config_dir_
= KDEHomeToConfigPath(kde3_path
);
905 virtual ~SettingGetterImplKDE() {
906 // inotify_fd_ should have been closed before now, from
907 // Delegate::OnDestroy(), while running on the file thread. However
908 // on exiting the process, it may happen that Delegate::OnDestroy()
909 // task is left pending on the file loop after the loop was quit,
910 // and pending tasks may then be deleted without being run.
911 // Here in the KDE version, we can safely close the file descriptor
912 // anyway. (Not that it really matters; the process is exiting.)
913 if (inotify_fd_
>= 0)
915 DCHECK(inotify_fd_
< 0);
918 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
919 MessageLoopForIO
* file_loop
) OVERRIDE
{
920 // This has to be called on the UI thread (http://crbug.com/69057).
921 base::ThreadRestrictions::ScopedAllowIO allow_io
;
922 DCHECK(inotify_fd_
< 0);
923 inotify_fd_
= inotify_init();
924 if (inotify_fd_
< 0) {
925 PLOG(ERROR
) << "inotify_init failed";
928 int flags
= fcntl(inotify_fd_
, F_GETFL
);
929 if (fcntl(inotify_fd_
, F_SETFL
, flags
| O_NONBLOCK
) < 0) {
930 PLOG(ERROR
) << "fcntl failed";
935 file_loop_
= file_loop
;
936 // The initial read is done on the current thread, not |file_loop_|,
937 // since we will need to have it for SetUpAndFetchInitialConfig().
938 UpdateCachedSettings();
942 virtual void ShutDown() OVERRIDE
{
943 if (inotify_fd_
>= 0) {
944 ResetCachedSettings();
945 inotify_watcher_
.StopWatchingFileDescriptor();
951 virtual bool SetUpNotifications(
952 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
953 DCHECK(inotify_fd_
>= 0);
954 DCHECK(MessageLoop::current() == file_loop_
);
955 // We can't just watch the kioslaverc file directly, since KDE will write
956 // a new copy of it and then rename it whenever settings are changed and
957 // inotify watches inodes (so we'll be watching the old deleted file after
958 // the first change, and it will never change again). So, we watch the
959 // directory instead. We then act only on changes to the kioslaverc entry.
960 if (inotify_add_watch(inotify_fd_
, kde_config_dir_
.value().c_str(),
961 IN_MODIFY
| IN_MOVED_TO
) < 0)
963 notify_delegate_
= delegate
;
964 if (!file_loop_
->WatchFileDescriptor(inotify_fd_
, true,
965 MessageLoopForIO::WATCH_READ
, &inotify_watcher_
, this))
967 // Simulate a change to avoid possibly losing updates before this point.
968 OnChangeNotification();
972 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
973 return file_loop_
? file_loop_
->message_loop_proxy() : NULL
;
976 // Implement base::MessagePumpLibevent::Watcher.
977 virtual void OnFileCanReadWithoutBlocking(int fd
) OVERRIDE
{
978 DCHECK_EQ(fd
, inotify_fd_
);
979 DCHECK(MessageLoop::current() == file_loop_
);
980 OnChangeNotification();
982 virtual void OnFileCanWriteWithoutBlocking(int fd
) OVERRIDE
{
986 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
987 return PROXY_CONFIG_SOURCE_KDE
;
990 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
991 string_map_type::iterator it
= string_table_
.find(key
);
992 if (it
== string_table_
.end())
994 *result
= it
->second
;
997 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
998 // We don't ever have any booleans.
1001 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
1002 // We don't ever have any integers. (See AddProxy() below about ports.)
1005 virtual bool GetStringList(StringListSetting key
,
1006 std::vector
<std::string
>* result
) OVERRIDE
{
1007 strings_map_type::iterator it
= strings_table_
.find(key
);
1008 if (it
== strings_table_
.end())
1010 *result
= it
->second
;
1014 virtual bool BypassListIsReversed() OVERRIDE
{
1015 return reversed_bypass_list_
;
1018 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
1023 void ResetCachedSettings() {
1024 string_table_
.clear();
1025 strings_table_
.clear();
1026 indirect_manual_
= false;
1027 auto_no_pac_
= false;
1028 reversed_bypass_list_
= false;
1031 FilePath
KDEHomeToConfigPath(const FilePath
& kde_home
) {
1032 return kde_home
.Append("share").Append("config");
1035 void AddProxy(StringSetting host_key
, const std::string
& value
) {
1036 if (value
.empty() || value
.substr(0, 3) == "//:")
1039 size_t space
= value
.find(' ');
1040 if (space
!= std::string::npos
) {
1041 // Newer versions of KDE use a space rather than a colon to separate the
1042 // port number from the hostname. If we find this, we need to convert it.
1043 std::string fixed
= value
;
1045 string_table_
[host_key
] = fixed
;
1047 // We don't need to parse the port number out; GetProxyFromSettings()
1048 // would only append it right back again. So we just leave the port
1049 // number right in the host string.
1050 string_table_
[host_key
] = value
;
1054 void AddHostList(StringListSetting key
, const std::string
& value
) {
1055 std::vector
<std::string
> tokens
;
1056 StringTokenizer
tk(value
, ", ");
1057 while (tk
.GetNext()) {
1058 std::string token
= tk
.token();
1060 tokens
.push_back(token
);
1062 strings_table_
[key
] = tokens
;
1065 void AddKDESetting(const std::string
& key
, const std::string
& value
) {
1066 if (key
== "ProxyType") {
1067 const char* mode
= "none";
1068 indirect_manual_
= false;
1069 auto_no_pac_
= false;
1071 base::StringToInt(value
, &int_value
);
1072 switch (int_value
) {
1073 case 0: // No proxy, or maybe kioslaverc syntax error.
1075 case 1: // Manual configuration.
1083 auto_no_pac_
= true;
1085 case 4: // Indirect manual via environment variables.
1087 indirect_manual_
= true;
1090 string_table_
[PROXY_MODE
] = mode
;
1091 } else if (key
== "Proxy Config Script") {
1092 string_table_
[PROXY_AUTOCONF_URL
] = value
;
1093 } else if (key
== "httpProxy") {
1094 AddProxy(PROXY_HTTP_HOST
, value
);
1095 } else if (key
== "httpsProxy") {
1096 AddProxy(PROXY_HTTPS_HOST
, value
);
1097 } else if (key
== "ftpProxy") {
1098 AddProxy(PROXY_FTP_HOST
, value
);
1099 } else if (key
== "socksProxy") {
1100 // Older versions of KDE configure SOCKS in a weird way involving
1101 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1102 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1103 AddProxy(PROXY_SOCKS_HOST
, value
);
1104 } else if (key
== "ReversedException") {
1105 // We count "true" or any nonzero number as true, otherwise false.
1106 // Note that if the value is not actually numeric StringToInt()
1107 // will return 0, which we count as false.
1109 base::StringToInt(value
, &int_value
);
1110 reversed_bypass_list_
= (value
== "true" || int_value
);
1111 } else if (key
== "NoProxyFor") {
1112 AddHostList(PROXY_IGNORE_HOSTS
, value
);
1113 } else if (key
== "AuthMode") {
1114 // Check for authentication, just so we can warn.
1116 base::StringToInt(value
, &mode
);
1118 // ProxyConfig does not support authentication parameters, but
1119 // Chrome will prompt for the password later. So we ignore this.
1121 "Proxy authentication parameters ignored, see bug 16709";
1126 void ResolveIndirect(StringSetting key
) {
1127 string_map_type::iterator it
= string_table_
.find(key
);
1128 if (it
!= string_table_
.end()) {
1130 if (env_var_getter_
->GetVar(it
->second
.c_str(), &value
))
1133 string_table_
.erase(it
);
1137 void ResolveIndirectList(StringListSetting key
) {
1138 strings_map_type::iterator it
= strings_table_
.find(key
);
1139 if (it
!= strings_table_
.end()) {
1141 if (!it
->second
.empty() &&
1142 env_var_getter_
->GetVar(it
->second
[0].c_str(), &value
))
1143 AddHostList(key
, value
);
1145 strings_table_
.erase(it
);
1149 // The settings in kioslaverc could occur in any order, but some affect
1150 // others. Rather than read the whole file in and then query them in an
1151 // order that allows us to handle that, we read the settings in whatever
1152 // order they occur and do any necessary tweaking after we finish.
1153 void ResolveModeEffects() {
1154 if (indirect_manual_
) {
1155 ResolveIndirect(PROXY_HTTP_HOST
);
1156 ResolveIndirect(PROXY_HTTPS_HOST
);
1157 ResolveIndirect(PROXY_FTP_HOST
);
1158 ResolveIndirectList(PROXY_IGNORE_HOSTS
);
1161 // Remove the PAC URL; we're not supposed to use it.
1162 string_table_
.erase(PROXY_AUTOCONF_URL
);
1166 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1167 // each relevant name-value pair to the appropriate value table.
1168 void UpdateCachedSettings() {
1169 FilePath kioslaverc
= kde_config_dir_
.Append("kioslaverc");
1170 file_util::ScopedFILE
input(file_util::OpenFile(kioslaverc
, "r"));
1173 ResetCachedSettings();
1174 bool in_proxy_settings
= false;
1175 bool line_too_long
= false;
1176 char line
[BUFFER_SIZE
];
1177 // fgets() will return NULL on EOF or error.
1178 while (fgets(line
, sizeof(line
), input
.get())) {
1179 // fgets() guarantees the line will be properly terminated.
1180 size_t length
= strlen(line
);
1183 // This should be true even with CRLF endings.
1184 if (line
[length
- 1] != '\n') {
1185 line_too_long
= true;
1188 if (line_too_long
) {
1189 // The previous line had no line ending, but this done does. This is
1190 // the end of the line that was too long, so warn here and skip it.
1191 LOG(WARNING
) << "skipped very long line in " << kioslaverc
.value();
1192 line_too_long
= false;
1195 // Remove the LF at the end, and the CR if there is one.
1196 line
[--length
] = '\0';
1197 if (length
&& line
[length
- 1] == '\r')
1198 line
[--length
] = '\0';
1199 // Now parse the line.
1200 if (line
[0] == '[') {
1201 // Switching sections. All we care about is whether this is
1202 // the (a?) proxy settings section, for both KDE3 and KDE4.
1203 in_proxy_settings
= !strncmp(line
, "[Proxy Settings]", 16);
1204 } else if (in_proxy_settings
) {
1205 // A regular line, in the (a?) proxy settings section.
1206 char* split
= strchr(line
, '=');
1207 // Skip this line if it does not contain an = sign.
1210 // Split the line on the = and advance |split|.
1212 std::string key
= line
;
1213 std::string value
= split
;
1214 TrimWhitespaceASCII(key
, TRIM_ALL
, &key
);
1215 TrimWhitespaceASCII(value
, TRIM_ALL
, &value
);
1216 // Skip this line if the key name is empty.
1219 // Is the value name localized?
1220 if (key
[key
.length() - 1] == ']') {
1221 // Find the matching bracket.
1222 length
= key
.rfind('[');
1223 // Skip this line if the localization indicator is malformed.
1224 if (length
== std::string::npos
)
1226 // Trim the localization indicator off.
1228 // Remove any resulting trailing whitespace.
1229 TrimWhitespaceASCII(key
, TRIM_TRAILING
, &key
);
1230 // Skip this line if the key name is now empty.
1234 // Now fill in the tables.
1235 AddKDESetting(key
, value
);
1238 if (ferror(input
.get()))
1239 LOG(ERROR
) << "error reading " << kioslaverc
.value();
1240 ResolveModeEffects();
1243 // This is the callback from the debounce timer.
1244 void OnDebouncedNotification() {
1245 DCHECK(MessageLoop::current() == file_loop_
);
1246 VLOG(1) << "inotify change notification for kioslaverc";
1247 UpdateCachedSettings();
1248 CHECK(notify_delegate_
);
1249 // Forward to a method on the proxy config service delegate object.
1250 notify_delegate_
->OnCheckProxyConfigSettings();
1253 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1254 // from the inotify file descriptor and starts up a debounce timer if
1255 // an event for kioslaverc is seen.
1256 void OnChangeNotification() {
1257 DCHECK_GE(inotify_fd_
, 0);
1258 DCHECK(MessageLoop::current() == file_loop_
);
1259 char event_buf
[(sizeof(inotify_event
) + NAME_MAX
+ 1) * 4];
1260 bool kioslaverc_touched
= false;
1262 while ((r
= read(inotify_fd_
, event_buf
, sizeof(event_buf
))) > 0) {
1263 // inotify returns variable-length structures, which is why we have
1264 // this strange-looking loop instead of iterating through an array.
1265 char* event_ptr
= event_buf
;
1266 while (event_ptr
< event_buf
+ r
) {
1267 inotify_event
* event
= reinterpret_cast<inotify_event
*>(event_ptr
);
1268 // The kernel always feeds us whole events.
1269 CHECK_LE(event_ptr
+ sizeof(inotify_event
), event_buf
+ r
);
1270 CHECK_LE(event
->name
+ event
->len
, event_buf
+ r
);
1271 if (!strcmp(event
->name
, "kioslaverc"))
1272 kioslaverc_touched
= true;
1273 // Advance the pointer just past the end of the filename.
1274 event_ptr
= event
->name
+ event
->len
;
1276 // We keep reading even if |kioslaverc_touched| is true to drain the
1277 // inotify event queue.
1280 // Instead of returning -1 and setting errno to EINVAL if there is not
1281 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1282 // new behavior (EINVAL) so we can reuse the code below.
1284 if (errno
!= EAGAIN
) {
1285 PLOG(WARNING
) << "error reading inotify file descriptor";
1286 if (errno
== EINVAL
) {
1287 // Our buffer is not large enough to read the next event. This should
1288 // not happen (because its size is calculated to always be sufficiently
1289 // large), but if it does we'd warn continuously since |inotify_fd_|
1290 // would be forever ready to read. Close it and stop watching instead.
1291 LOG(ERROR
) << "inotify failure; no longer watching kioslaverc!";
1292 inotify_watcher_
.StopWatchingFileDescriptor();
1297 if (kioslaverc_touched
) {
1298 // We don't use Reset() because the timer may not yet be running.
1299 // (In that case Stop() is a no-op.)
1300 debounce_timer_
.Stop();
1301 debounce_timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(
1302 kDebounceTimeoutMilliseconds
), this,
1303 &SettingGetterImplKDE::OnDebouncedNotification
);
1307 typedef std::map
<StringSetting
, std::string
> string_map_type
;
1308 typedef std::map
<StringListSetting
,
1309 std::vector
<std::string
> > strings_map_type
;
1312 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_
;
1313 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
1314 base::OneShotTimer
<SettingGetterImplKDE
> debounce_timer_
;
1315 FilePath kde_config_dir_
;
1316 bool indirect_manual_
;
1318 bool reversed_bypass_list_
;
1319 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1320 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1322 base::Environment
* env_var_getter_
;
1324 // We cache these settings whenever we re-read the kioslaverc file.
1325 string_map_type string_table_
;
1326 strings_map_type strings_table_
;
1328 // Message loop of the file thread, for reading kioslaverc. If NULL,
1329 // just read it directly (for testing). We also handle inotify events
1331 MessageLoopForIO
* file_loop_
;
1333 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE
);
1338 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1339 SettingGetter::StringSetting host_key
,
1340 ProxyServer
* result_server
) {
1342 if (!setting_getter_
->GetString(host_key
, &host
) || host
.empty()) {
1346 // Check for an optional port.
1348 SettingGetter::IntSetting port_key
=
1349 SettingGetter::HostSettingToPortSetting(host_key
);
1350 setting_getter_
->GetInt(port_key
, &port
);
1352 // If a port is set and non-zero:
1353 host
+= ":" + base::IntToString(port
);
1356 // gconf settings do not appear to distinguish between SOCKS version. We
1357 // default to version 5. For more information on this policy decision, see:
1358 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1359 ProxyServer::Scheme scheme
= (host_key
== SettingGetter::PROXY_SOCKS_HOST
) ?
1360 ProxyServer::SCHEME_SOCKS5
: ProxyServer::SCHEME_HTTP
;
1361 host
= FixupProxyHostScheme(scheme
, host
);
1362 ProxyServer proxy_server
= ProxyServer::FromURI(host
,
1363 ProxyServer::SCHEME_HTTP
);
1364 if (proxy_server
.is_valid()) {
1365 *result_server
= proxy_server
;
1371 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1372 ProxyConfig
* config
) {
1374 if (!setting_getter_
->GetString(SettingGetter::PROXY_MODE
, &mode
)) {
1375 // We expect this to always be set, so if we don't see it then we
1376 // probably have a gconf/gsettings problem, and so we don't have a valid
1380 if (mode
== "none") {
1381 // Specifically specifies no proxy.
1385 if (mode
== "auto") {
1386 // Automatic proxy config.
1387 std::string pac_url_str
;
1388 if (setting_getter_
->GetString(SettingGetter::PROXY_AUTOCONF_URL
,
1390 if (!pac_url_str
.empty()) {
1391 // If the PAC URL is actually a file path, then put file:// in front.
1392 if (pac_url_str
[0] == '/')
1393 pac_url_str
= "file://" + pac_url_str
;
1394 GURL
pac_url(pac_url_str
);
1395 if (!pac_url
.is_valid())
1397 config
->set_pac_url(pac_url
);
1401 config
->set_auto_detect(true);
1405 if (mode
!= "manual") {
1406 // Mode is unrecognized.
1409 bool use_http_proxy
;
1410 if (setting_getter_
->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY
,
1412 && !use_http_proxy
) {
1413 // Another master switch for some reason. If set to false, then no
1414 // proxy. But we don't panic if the key doesn't exist.
1418 bool same_proxy
= false;
1419 // Indicates to use the http proxy for all protocols. This one may
1420 // not exist (presumably on older versions); we assume false in that
1422 setting_getter_
->GetBool(SettingGetter::PROXY_USE_SAME_PROXY
,
1425 ProxyServer proxy_for_http
;
1426 ProxyServer proxy_for_https
;
1427 ProxyServer proxy_for_ftp
;
1428 ProxyServer socks_proxy
; // (socks)
1430 // This counts how many of the above ProxyServers were defined and valid.
1431 size_t num_proxies_specified
= 0;
1433 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1434 // specified for the scheme, then the resulting ProxyServer will be invalid.
1435 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST
, &proxy_for_http
))
1436 num_proxies_specified
++;
1437 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST
, &proxy_for_https
))
1438 num_proxies_specified
++;
1439 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST
, &proxy_for_ftp
))
1440 num_proxies_specified
++;
1441 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST
, &socks_proxy
))
1442 num_proxies_specified
++;
1445 if (proxy_for_http
.is_valid()) {
1446 // Use the http proxy for all schemes.
1447 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1448 config
->proxy_rules().single_proxy
= proxy_for_http
;
1450 } else if (num_proxies_specified
> 0) {
1451 if (socks_proxy
.is_valid() && num_proxies_specified
== 1) {
1452 // If the only proxy specified was for SOCKS, use it for all schemes.
1453 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1454 config
->proxy_rules().single_proxy
= socks_proxy
;
1456 // Otherwise use the indicate proxies per-scheme.
1457 config
->proxy_rules().type
=
1458 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
1459 config
->proxy_rules().proxy_for_http
= proxy_for_http
;
1460 config
->proxy_rules().proxy_for_https
= proxy_for_https
;
1461 config
->proxy_rules().proxy_for_ftp
= proxy_for_ftp
;
1462 config
->proxy_rules().fallback_proxy
= socks_proxy
;
1466 if (config
->proxy_rules().empty()) {
1467 // Manual mode but we couldn't parse any rules.
1471 // Check for authentication, just so we can warn.
1472 bool use_auth
= false;
1473 setting_getter_
->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION
,
1476 // ProxyConfig does not support authentication parameters, but
1477 // Chrome will prompt for the password later. So we ignore
1478 // /system/http_proxy/*auth* settings.
1479 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
1482 // Now the bypass list.
1483 std::vector
<std::string
> ignore_hosts_list
;
1484 config
->proxy_rules().bypass_rules
.Clear();
1485 if (setting_getter_
->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS
,
1486 &ignore_hosts_list
)) {
1487 std::vector
<std::string
>::const_iterator
it(ignore_hosts_list
.begin());
1488 for (; it
!= ignore_hosts_list
.end(); ++it
) {
1489 if (setting_getter_
->MatchHostsUsingSuffixMatching()) {
1490 config
->proxy_rules().bypass_rules
.
1491 AddRuleFromStringUsingSuffixMatching(*it
);
1493 config
->proxy_rules().bypass_rules
.AddRuleFromString(*it
);
1497 // Note that there are no settings with semantics corresponding to
1498 // bypass of local names in GNOME. In KDE, "<local>" is supported
1499 // as a hostname rule.
1501 // KDE allows one to reverse the bypass rules.
1502 config
->proxy_rules().reverse_bypass
=
1503 setting_getter_
->BypassListIsReversed();
1508 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment
* env_var_getter
)
1509 : env_var_getter_(env_var_getter
) {
1510 // Figure out which SettingGetterImpl to use, if any.
1511 switch (base::nix::GetDesktopEnvironment(env_var_getter
)) {
1512 case base::nix::DESKTOP_ENVIRONMENT_GNOME
:
1513 case base::nix::DESKTOP_ENVIRONMENT_UNITY
:
1514 #if defined(USE_GIO)
1516 scoped_ptr
<SettingGetterImplGSettings
> gs_getter(
1517 new SettingGetterImplGSettings());
1518 // We have to load symbols and check the GNOME version in use to decide
1519 // if we should use the gsettings getter. See LoadAndCheckVersion().
1520 if (gs_getter
->LoadAndCheckVersion(env_var_getter
))
1521 setting_getter_
.reset(gs_getter
.release());
1524 #if defined(USE_GCONF)
1525 // Fall back on gconf if gsettings is unavailable or incorrect.
1526 if (!setting_getter_
.get())
1527 setting_getter_
.reset(new SettingGetterImplGConf());
1530 case base::nix::DESKTOP_ENVIRONMENT_KDE3
:
1531 case base::nix::DESKTOP_ENVIRONMENT_KDE4
:
1532 setting_getter_
.reset(new SettingGetterImplKDE(env_var_getter
));
1534 case base::nix::DESKTOP_ENVIRONMENT_XFCE
:
1535 case base::nix::DESKTOP_ENVIRONMENT_OTHER
:
1540 ProxyConfigServiceLinux::Delegate::Delegate(
1541 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1542 : env_var_getter_(env_var_getter
), setting_getter_(setting_getter
) {
1545 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1546 base::SingleThreadTaskRunner
* glib_thread_task_runner
,
1547 base::SingleThreadTaskRunner
* io_thread_task_runner
,
1548 MessageLoopForIO
* file_loop
) {
1549 // We should be running on the default glib main loop thread right
1550 // now. gconf can only be accessed from this thread.
1551 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
1552 glib_thread_task_runner_
= glib_thread_task_runner
;
1553 io_thread_task_runner_
= io_thread_task_runner
;
1555 // If we are passed a NULL |io_thread_task_runner| or |file_loop|,
1556 // then we don't set up proxy setting change notifications. This
1557 // should not be the usual case but is intended to simplify test
1559 if (!io_thread_task_runner_
|| !file_loop
)
1560 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1562 // Fetch and cache the current proxy config. The config is left in
1563 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1564 // will expect to find it. This is safe to do because we return
1565 // before this ProxyConfigServiceLinux is passed on to
1566 // the ProxyService.
1568 // Note: It would be nice to prioritize environment variables
1569 // and only fall back to gconf if env vars were unset. But
1570 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1571 // does so even if the proxy mode is set to auto, which would
1574 bool got_config
= false;
1575 if (setting_getter_
.get() &&
1576 setting_getter_
->Init(glib_thread_task_runner
, file_loop
) &&
1577 GetConfigFromSettings(&cached_config_
)) {
1578 cached_config_
.set_id(1); // Mark it as valid.
1579 cached_config_
.set_source(setting_getter_
->GetConfigSource());
1580 VLOG(1) << "Obtained proxy settings from "
1581 << ProxyConfigSourceToString(cached_config_
.source());
1583 // If gconf proxy mode is "none", meaning direct, then we take
1584 // that to be a valid config and will not check environment
1585 // variables. The alternative would have been to look for a proxy
1586 // whereever we can find one.
1589 // Keep a copy of the config for use from this thread for
1590 // comparison with updated settings when we get notifications.
1591 reference_config_
= cached_config_
;
1592 reference_config_
.set_id(1); // Mark it as valid.
1594 // We only set up notifications if we have IO and file loops available.
1595 // We do this after getting the initial configuration so that we don't have
1596 // to worry about cancelling it if the initial fetch above fails. Note that
1597 // setting up notifications has the side effect of simulating a change, so
1598 // that we won't lose any updates that may have happened after the initial
1599 // fetch and before setting up notifications. We'll detect the common case
1600 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1601 if (io_thread_task_runner
&& file_loop
) {
1602 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1603 setting_getter_
->GetNotificationTaskRunner();
1604 if (!required_loop
|| required_loop
->BelongsToCurrentThread()) {
1605 // In this case we are already on an acceptable thread.
1606 SetUpNotifications();
1608 // Post a task to set up notifications. We don't wait for success.
1609 required_loop
->PostTask(FROM_HERE
, base::Bind(
1610 &ProxyConfigServiceLinux::Delegate::SetUpNotifications
, this));
1616 // We fall back on environment variables.
1618 // Consulting environment variables doesn't need to be done from the
1619 // default glib main loop, but it's a tiny enough amount of work.
1620 if (GetConfigFromEnv(&cached_config_
)) {
1621 cached_config_
.set_source(PROXY_CONFIG_SOURCE_ENV
);
1622 cached_config_
.set_id(1); // Mark it as valid.
1623 VLOG(1) << "Obtained proxy settings from environment variables";
1628 // Depending on the SettingGetter in use, this method will be called
1629 // on either the UI thread (GConf) or the file thread (KDE).
1630 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1631 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1632 setting_getter_
->GetNotificationTaskRunner();
1633 DCHECK(!required_loop
|| required_loop
->BelongsToCurrentThread());
1634 if (!setting_getter_
->SetUpNotifications(this))
1635 LOG(ERROR
) << "Unable to set up proxy configuration change notifications";
1638 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer
* observer
) {
1639 observers_
.AddObserver(observer
);
1642 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer
* observer
) {
1643 observers_
.RemoveObserver(observer
);
1646 ProxyConfigService::ConfigAvailability
1647 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1648 ProxyConfig
* config
) {
1649 // This is called from the IO thread.
1650 DCHECK(!io_thread_task_runner_
||
1651 io_thread_task_runner_
->BelongsToCurrentThread());
1653 // Simply return the last proxy configuration that glib_default_loop
1655 if (cached_config_
.is_valid()) {
1656 *config
= cached_config_
;
1658 *config
= ProxyConfig::CreateDirect();
1659 config
->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED
);
1662 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1663 // going to be available since we initialized eagerly on the UI thread.
1664 // TODO(eroman): do lazy initialization instead, so we no longer need
1665 // to construct ProxyConfigServiceLinux on the UI thread.
1666 // In which case, we may return false here.
1667 return CONFIG_VALID
;
1670 // Depending on the SettingGetter in use, this method will be called
1671 // on either the UI thread (GConf) or the file thread (KDE).
1672 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1673 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1674 setting_getter_
->GetNotificationTaskRunner();
1675 DCHECK(!required_loop
|| required_loop
->BelongsToCurrentThread());
1676 ProxyConfig new_config
;
1677 bool valid
= GetConfigFromSettings(&new_config
);
1679 new_config
.set_id(1); // mark it as valid
1681 // See if it is different from what we had before.
1682 if (new_config
.is_valid() != reference_config_
.is_valid() ||
1683 !new_config
.Equals(reference_config_
)) {
1684 // Post a task to the IO thread with the new configuration, so it can
1685 // update |cached_config_|.
1686 io_thread_task_runner_
->PostTask(FROM_HERE
, base::Bind(
1687 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig
,
1689 // Update the thread-private copy in |reference_config_| as well.
1690 reference_config_
= new_config
;
1692 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1696 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1697 const ProxyConfig
& new_config
) {
1698 DCHECK(io_thread_task_runner_
->BelongsToCurrentThread());
1699 VLOG(1) << "Proxy configuration changed";
1700 cached_config_
= new_config
;
1702 Observer
, observers_
,
1703 OnProxyConfigChanged(new_config
, ProxyConfigService::CONFIG_VALID
));
1706 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1707 if (!setting_getter_
.get())
1709 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1710 setting_getter_
->GetNotificationTaskRunner();
1711 if (!shutdown_loop
|| shutdown_loop
->BelongsToCurrentThread()) {
1712 // Already on the right thread, call directly.
1713 // This is the case for the unittests.
1716 // Post to shutdown thread. Note that on browser shutdown, we may quit
1717 // this MessageLoop and exit the program before ever running this.
1718 shutdown_loop
->PostTask(FROM_HERE
, base::Bind(
1719 &ProxyConfigServiceLinux::Delegate::OnDestroy
, this));
1722 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1723 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1724 setting_getter_
->GetNotificationTaskRunner();
1725 DCHECK(!shutdown_loop
|| shutdown_loop
->BelongsToCurrentThread());
1726 setting_getter_
->ShutDown();
1729 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1730 : delegate_(new Delegate(base::Environment::Create())) {
1733 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1734 delegate_
->PostDestroyTask();
1737 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1738 base::Environment
* env_var_getter
)
1739 : delegate_(new Delegate(env_var_getter
)) {
1742 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1743 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1744 : delegate_(new Delegate(env_var_getter
, setting_getter
)) {
1747 void ProxyConfigServiceLinux::AddObserver(Observer
* observer
) {
1748 delegate_
->AddObserver(observer
);
1751 void ProxyConfigServiceLinux::RemoveObserver(Observer
* observer
) {
1752 delegate_
->RemoveObserver(observer
);
1755 ProxyConfigService::ConfigAvailability
1756 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig
* config
) {
1757 return delegate_
->GetLatestProxyConfig(config
);