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)
14 #if defined(DLOPEN_GSETTINGS)
16 #endif // defined(DLOPEN_GSETTINGS)
17 #endif // defined(USE_GIO)
21 #include <sys/inotify.h>
26 #include "base/bind.h"
27 #include "base/compiler_specific.h"
28 #include "base/environment.h"
29 #include "base/file_path.h"
30 #include "base/file_util.h"
31 #include "base/logging.h"
32 #include "base/message_loop.h"
33 #include "base/nix/xdg_util.h"
34 #include "base/single_thread_task_runner.h"
35 #include "base/string_number_conversions.h"
36 #include "base/string_tokenizer.h"
37 #include "base/string_util.h"
38 #include "base/threading/thread_restrictions.h"
39 #include "base/timer.h"
40 #include "googleurl/src/url_canon.h"
41 #include "net/base/net_errors.h"
42 #include "net/http/http_util.h"
43 #include "net/proxy/proxy_config.h"
44 #include "net/proxy/proxy_server.h"
50 // Given a proxy hostname from a setting, returns that hostname with
51 // an appropriate proxy server scheme prefix.
52 // scheme indicates the desired proxy scheme: usually http, with
53 // socks 4 or 5 as special cases.
54 // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
55 std::string
FixupProxyHostScheme(ProxyServer::Scheme scheme
,
57 if (scheme
== ProxyServer::SCHEME_SOCKS5
&&
58 StartsWithASCII(host
, "socks4://", false)) {
59 // We default to socks 5, but if the user specifically set it to
60 // socks4://, then use that.
61 scheme
= ProxyServer::SCHEME_SOCKS4
;
63 // Strip the scheme if any.
64 std::string::size_type colon
= host
.find("://");
65 if (colon
!= std::string::npos
)
66 host
= host
.substr(colon
+ 3);
67 // If a username and perhaps password are specified, give a warning.
68 std::string::size_type at_sign
= host
.find("@");
69 // Should this be supported?
70 if (at_sign
!= std::string::npos
) {
71 // ProxyConfig does not support authentication parameters, but Chrome
72 // will prompt for the password later. Disregard the
73 // authentication parameters and continue with this hostname.
74 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
75 host
= host
.substr(at_sign
+ 1);
77 // If this is a socks proxy, prepend a scheme so as to tell
78 // ProxyServer. This also allows ProxyServer to choose the right
80 if (scheme
== ProxyServer::SCHEME_SOCKS4
)
81 host
= "socks4://" + host
;
82 else if (scheme
== ProxyServer::SCHEME_SOCKS5
)
83 host
= "socks5://" + host
;
84 // If there is a trailing slash, remove it so |host| will parse correctly
85 // even if it includes a port number (since the slash is not numeric).
86 if (host
.length() && host
[host
.length() - 1] == '/')
87 host
.resize(host
.length() - 1);
93 ProxyConfigServiceLinux::Delegate::~Delegate() {
96 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
97 const char* variable
, ProxyServer::Scheme scheme
,
98 ProxyServer
* result_server
) {
99 std::string env_value
;
100 if (env_var_getter_
->GetVar(variable
, &env_value
)) {
101 if (!env_value
.empty()) {
102 env_value
= FixupProxyHostScheme(scheme
, env_value
);
103 ProxyServer proxy_server
=
104 ProxyServer::FromURI(env_value
, ProxyServer::SCHEME_HTTP
);
105 if (proxy_server
.is_valid() && !proxy_server
.is_direct()) {
106 *result_server
= proxy_server
;
109 LOG(ERROR
) << "Failed to parse environment variable " << variable
;
116 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
117 const char* variable
, ProxyServer
* result_server
) {
118 return GetProxyFromEnvVarForScheme(variable
, ProxyServer::SCHEME_HTTP
,
122 bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig
* config
) {
123 // Check for automatic configuration first, in
124 // "auto_proxy". Possibly only the "environment_proxy" firefox
125 // extension has ever used this, but it still sounds like a good
127 std::string auto_proxy
;
128 if (env_var_getter_
->GetVar("auto_proxy", &auto_proxy
)) {
129 if (auto_proxy
.empty()) {
130 // Defined and empty => autodetect
131 config
->set_auto_detect(true);
133 // specified autoconfig URL
134 config
->set_pac_url(GURL(auto_proxy
));
138 // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
139 ProxyServer proxy_server
;
140 if (GetProxyFromEnvVar("all_proxy", &proxy_server
)) {
141 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
142 config
->proxy_rules().single_proxy
= proxy_server
;
144 bool have_http
= GetProxyFromEnvVar("http_proxy", &proxy_server
);
146 config
->proxy_rules().proxy_for_http
= proxy_server
;
147 // It would be tempting to let http_proxy apply for all protocols
148 // if https_proxy and ftp_proxy are not defined. Googling turns up
149 // several documents that mention only http_proxy. But then the
150 // user really might not want to proxy https. And it doesn't seem
151 // like other apps do this. So we will refrain.
152 bool have_https
= GetProxyFromEnvVar("https_proxy", &proxy_server
);
154 config
->proxy_rules().proxy_for_https
= proxy_server
;
155 bool have_ftp
= GetProxyFromEnvVar("ftp_proxy", &proxy_server
);
157 config
->proxy_rules().proxy_for_ftp
= proxy_server
;
158 if (have_http
|| have_https
|| have_ftp
) {
159 // mustn't change type unless some rules are actually set.
160 config
->proxy_rules().type
=
161 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
164 if (config
->proxy_rules().empty()) {
165 // If the above were not defined, try for socks.
166 // For environment variables, we default to version 5, per the gnome
167 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
168 ProxyServer::Scheme scheme
= ProxyServer::SCHEME_SOCKS5
;
169 std::string env_version
;
170 if (env_var_getter_
->GetVar("SOCKS_VERSION", &env_version
)
171 && env_version
== "4")
172 scheme
= ProxyServer::SCHEME_SOCKS4
;
173 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme
, &proxy_server
)) {
174 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
175 config
->proxy_rules().single_proxy
= proxy_server
;
178 // Look for the proxy bypass list.
179 std::string no_proxy
;
180 env_var_getter_
->GetVar("no_proxy", &no_proxy
);
181 if (config
->proxy_rules().empty()) {
182 // Having only "no_proxy" set, presumably to "*", makes it
183 // explicit that env vars do specify a configuration: having no
184 // rules specified only means the user explicitly asks for direct
186 return !no_proxy
.empty();
188 // Note that this uses "suffix" matching. So a bypass of "google.com"
189 // is understood to mean a bypass of "*google.com".
190 config
->proxy_rules().bypass_rules
.ParseFromStringUsingSuffixMatching(
197 const int kDebounceTimeoutMilliseconds
= 250;
199 #if defined(USE_GCONF)
200 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
201 class SettingGetterImplGConf
: public ProxyConfigServiceLinux::SettingGetter
{
203 SettingGetterImplGConf()
204 : client_(NULL
), system_proxy_id_(0), system_http_proxy_id_(0),
205 notify_delegate_(NULL
) {
208 virtual ~SettingGetterImplGConf() {
209 // client_ should have been released before now, from
210 // Delegate::OnDestroy(), while running on the UI thread. However
211 // on exiting the process, it may happen that Delegate::OnDestroy()
212 // task is left pending on the glib loop after the loop was quit,
213 // and pending tasks may then be deleted without being run.
215 // gconf client was not cleaned up.
216 if (task_runner_
->BelongsToCurrentThread()) {
217 // We are on the UI thread so we can clean it safely. This is
218 // the case at least for ui_tests running under Valgrind in
220 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
223 // This is very bad! We are deleting the setting getter but we're not on
224 // the UI thread. This is not supposed to happen: the setting getter is
225 // owned by the proxy config service's delegate, which is supposed to be
226 // destroyed on the UI thread only. We will get change notifications to
227 // a deleted object if we continue here, so fail now.
228 LOG(FATAL
) << "~SettingGetterImplGConf: deleting on wrong thread!";
234 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
235 MessageLoopForIO
* file_loop
) OVERRIDE
{
236 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
238 DCHECK(!task_runner_
);
239 task_runner_
= glib_thread_task_runner
;
240 client_
= gconf_client_get_default();
242 // It's not clear whether/when this can return NULL.
243 LOG(ERROR
) << "Unable to create a gconf client";
247 GError
* error
= NULL
;
248 bool added_system_proxy
= false;
249 // We need to add the directories for which we'll be asking
250 // for notifications, and we might as well ask to preload them.
251 // These need to be removed again in ShutDown(); we are careful
252 // here to only leave client_ non-NULL if both have been added.
253 gconf_client_add_dir(client_
, "/system/proxy",
254 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
256 added_system_proxy
= true;
257 gconf_client_add_dir(client_
, "/system/http_proxy",
258 GCONF_CLIENT_PRELOAD_ONELEVEL
, &error
);
261 LOG(ERROR
) << "Error requesting gconf directory: " << error
->message
;
263 if (added_system_proxy
)
264 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
265 g_object_unref(client_
);
273 virtual void ShutDown() OVERRIDE
{
275 DCHECK(task_runner_
->BelongsToCurrentThread());
276 // We must explicitly disable gconf notifications here, because the gconf
277 // client will be shared between all setting getters, and they do not all
278 // have the same lifetimes. (For instance, incognito sessions get their
279 // own, which is destroyed when the session ends.)
280 gconf_client_notify_remove(client_
, system_http_proxy_id_
);
281 gconf_client_notify_remove(client_
, system_proxy_id_
);
282 gconf_client_remove_dir(client_
, "/system/http_proxy", NULL
);
283 gconf_client_remove_dir(client_
, "/system/proxy", NULL
);
284 g_object_unref(client_
);
290 virtual bool SetUpNotifications(
291 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
293 DCHECK(task_runner_
->BelongsToCurrentThread());
294 GError
* error
= NULL
;
295 notify_delegate_
= delegate
;
296 // We have to keep track of the IDs returned by gconf_client_notify_add() so
297 // that we can remove them in ShutDown(). (Otherwise, notifications will be
298 // delivered to this object after it is deleted, which is bad, m'kay?)
299 system_proxy_id_
= gconf_client_notify_add(
300 client_
, "/system/proxy",
301 OnGConfChangeNotification
, this,
304 system_http_proxy_id_
= gconf_client_notify_add(
305 client_
, "/system/http_proxy",
306 OnGConfChangeNotification
, this,
310 LOG(ERROR
) << "Error requesting gconf notifications: " << error
->message
;
315 // Simulate a change to avoid possibly losing updates before this point.
316 OnChangeNotification();
320 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
324 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
325 return PROXY_CONFIG_SOURCE_GCONF
;
328 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
331 return GetStringByPath("/system/proxy/mode", result
);
332 case PROXY_AUTOCONF_URL
:
333 return GetStringByPath("/system/proxy/autoconfig_url", result
);
334 case PROXY_HTTP_HOST
:
335 return GetStringByPath("/system/http_proxy/host", result
);
336 case PROXY_HTTPS_HOST
:
337 return GetStringByPath("/system/proxy/secure_host", result
);
339 return GetStringByPath("/system/proxy/ftp_host", result
);
340 case PROXY_SOCKS_HOST
:
341 return GetStringByPath("/system/proxy/socks_host", result
);
343 return false; // Placate compiler.
345 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
347 case PROXY_USE_HTTP_PROXY
:
348 return GetBoolByPath("/system/http_proxy/use_http_proxy", result
);
349 case PROXY_USE_SAME_PROXY
:
350 return GetBoolByPath("/system/http_proxy/use_same_proxy", result
);
351 case PROXY_USE_AUTHENTICATION
:
352 return GetBoolByPath("/system/http_proxy/use_authentication", result
);
354 return false; // Placate compiler.
356 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
358 case PROXY_HTTP_PORT
:
359 return GetIntByPath("/system/http_proxy/port", result
);
360 case PROXY_HTTPS_PORT
:
361 return GetIntByPath("/system/proxy/secure_port", result
);
363 return GetIntByPath("/system/proxy/ftp_port", result
);
364 case PROXY_SOCKS_PORT
:
365 return GetIntByPath("/system/proxy/socks_port", result
);
367 return false; // Placate compiler.
369 virtual bool GetStringList(StringListSetting key
,
370 std::vector
<std::string
>* result
) OVERRIDE
{
372 case PROXY_IGNORE_HOSTS
:
373 return GetStringListByPath("/system/http_proxy/ignore_hosts", result
);
375 return false; // Placate compiler.
378 virtual bool BypassListIsReversed() OVERRIDE
{
379 // This is a KDE-specific setting.
383 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
388 bool GetStringByPath(const char* key
, std::string
* result
) {
390 DCHECK(task_runner_
->BelongsToCurrentThread());
391 GError
* error
= NULL
;
392 gchar
* value
= gconf_client_get_string(client_
, key
, &error
);
393 if (HandleGError(error
, key
))
401 bool GetBoolByPath(const char* key
, bool* result
) {
403 DCHECK(task_runner_
->BelongsToCurrentThread());
404 GError
* error
= NULL
;
405 // We want to distinguish unset values from values defaulting to
406 // false. For that we need to use the type-generic
407 // gconf_client_get() rather than gconf_client_get_bool().
408 GConfValue
* gconf_value
= gconf_client_get(client_
, key
, &error
);
409 if (HandleGError(error
, key
))
415 if (gconf_value
->type
!= GCONF_VALUE_BOOL
) {
416 gconf_value_free(gconf_value
);
419 gboolean bool_value
= gconf_value_get_bool(gconf_value
);
420 *result
= static_cast<bool>(bool_value
);
421 gconf_value_free(gconf_value
);
424 bool GetIntByPath(const char* key
, int* result
) {
426 DCHECK(task_runner_
->BelongsToCurrentThread());
427 GError
* error
= NULL
;
428 int value
= gconf_client_get_int(client_
, key
, &error
);
429 if (HandleGError(error
, key
))
431 // We don't bother to distinguish an unset value because callers
432 // don't care. 0 is returned if unset.
436 bool GetStringListByPath(const char* key
, std::vector
<std::string
>* result
) {
438 DCHECK(task_runner_
->BelongsToCurrentThread());
439 GError
* error
= NULL
;
440 GSList
* list
= gconf_client_get_list(client_
, key
,
441 GCONF_VALUE_STRING
, &error
);
442 if (HandleGError(error
, key
))
446 for (GSList
*it
= list
; it
; it
= it
->next
) {
447 result
->push_back(static_cast<char*>(it
->data
));
454 // Logs and frees a glib error. Returns false if there was no error
456 bool HandleGError(GError
* error
, const char* key
) {
458 LOG(ERROR
) << "Error getting gconf value for " << key
459 << ": " << error
->message
;
466 // This is the callback from the debounce timer.
467 void OnDebouncedNotification() {
468 DCHECK(task_runner_
->BelongsToCurrentThread());
469 CHECK(notify_delegate_
);
470 // Forward to a method on the proxy config service delegate object.
471 notify_delegate_
->OnCheckProxyConfigSettings();
474 void OnChangeNotification() {
475 // We don't use Reset() because the timer may not yet be running.
476 // (In that case Stop() is a no-op.)
477 debounce_timer_
.Stop();
478 debounce_timer_
.Start(FROM_HERE
,
479 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
480 this, &SettingGetterImplGConf::OnDebouncedNotification
);
483 // gconf notification callback, dispatched on the default glib main loop.
484 static void OnGConfChangeNotification(GConfClient
* client
, guint cnxn_id
,
485 GConfEntry
* entry
, gpointer user_data
) {
486 VLOG(1) << "gconf change notification for key "
487 << gconf_entry_get_key(entry
);
488 // We don't track which key has changed, just that something did change.
489 SettingGetterImplGConf
* setting_getter
=
490 reinterpret_cast<SettingGetterImplGConf
*>(user_data
);
491 setting_getter
->OnChangeNotification();
494 GConfClient
* client_
;
495 // These ids are the values returned from gconf_client_notify_add(), which we
496 // will need in order to later call gconf_client_notify_remove().
497 guint system_proxy_id_
;
498 guint system_http_proxy_id_
;
500 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
501 base::OneShotTimer
<SettingGetterImplGConf
> debounce_timer_
;
503 // Task runner for the thread that we make gconf calls on. It should
504 // be the UI thread and all our methods should be called on this
505 // thread. Only for assertions.
506 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
508 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf
);
510 #endif // defined(USE_GCONF)
513 // This setting getter uses gsettings, as used in most GNOME 3 desktops.
514 class SettingGetterImplGSettings
515 : public ProxyConfigServiceLinux::SettingGetter
{
517 SettingGetterImplGSettings() :
518 #if defined(DLOPEN_GSETTINGS)
519 g_settings_new(NULL
),
520 g_settings_get_child(NULL
),
521 g_settings_get_boolean(NULL
),
522 g_settings_get_string(NULL
),
523 g_settings_get_int(NULL
),
524 g_settings_get_strv(NULL
),
525 g_settings_list_schemas(NULL
),
533 notify_delegate_(NULL
) {
536 virtual ~SettingGetterImplGSettings() {
537 // client_ should have been released before now, from
538 // Delegate::OnDestroy(), while running on the UI thread. However
539 // on exiting the process, it may happen that
540 // Delegate::OnDestroy() task is left pending on the glib loop
541 // after the loop was quit, and pending tasks may then be deleted
542 // without being run.
544 // gconf client was not cleaned up.
545 if (task_runner_
->BelongsToCurrentThread()) {
546 // We are on the UI thread so we can clean it safely. This is
547 // the case at least for ui_tests running under Valgrind in
549 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
552 LOG(WARNING
) << "~SettingGetterImplGSettings: leaking gsettings client";
557 #if defined(DLOPEN_GSETTINGS)
559 dlclose(gio_handle_
);
565 bool SchemaExists(const char* schema_name
) {
566 const gchar
* const* schemas
= g_settings_list_schemas();
568 if (strcmp(schema_name
, static_cast<const char*>(*schemas
)) == 0)
575 // LoadAndCheckVersion() must be called *before* Init()!
576 bool LoadAndCheckVersion(base::Environment
* env
);
578 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
579 MessageLoopForIO
* file_loop
) OVERRIDE
{
580 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
582 DCHECK(!task_runner_
);
584 if (!SchemaExists("org.gnome.system.proxy") ||
585 !(client_
= g_settings_new("org.gnome.system.proxy"))) {
586 // It's not clear whether/when this can return NULL.
587 LOG(ERROR
) << "Unable to create a gsettings client";
590 task_runner_
= glib_thread_task_runner
;
591 // We assume these all work if the above call worked.
592 http_client_
= g_settings_get_child(client_
, "http");
593 https_client_
= g_settings_get_child(client_
, "https");
594 ftp_client_
= g_settings_get_child(client_
, "ftp");
595 socks_client_
= g_settings_get_child(client_
, "socks");
596 DCHECK(http_client_
&& https_client_
&& ftp_client_
&& socks_client_
);
600 virtual void ShutDown() OVERRIDE
{
602 DCHECK(task_runner_
->BelongsToCurrentThread());
603 // This also disables gsettings notifications.
604 g_object_unref(socks_client_
);
605 g_object_unref(ftp_client_
);
606 g_object_unref(https_client_
);
607 g_object_unref(http_client_
);
608 g_object_unref(client_
);
609 // We only need to null client_ because it's the only one that we check.
615 virtual bool SetUpNotifications(
616 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
618 DCHECK(task_runner_
->BelongsToCurrentThread());
619 notify_delegate_
= delegate
;
620 // We could watch for the change-event signal instead of changed, but
621 // since we have to watch more than one object, we'd still have to
622 // debounce change notifications. This is conceptually simpler.
623 g_signal_connect(G_OBJECT(client_
), "changed",
624 G_CALLBACK(OnGSettingsChangeNotification
), this);
625 g_signal_connect(G_OBJECT(http_client_
), "changed",
626 G_CALLBACK(OnGSettingsChangeNotification
), this);
627 g_signal_connect(G_OBJECT(https_client_
), "changed",
628 G_CALLBACK(OnGSettingsChangeNotification
), this);
629 g_signal_connect(G_OBJECT(ftp_client_
), "changed",
630 G_CALLBACK(OnGSettingsChangeNotification
), this);
631 g_signal_connect(G_OBJECT(socks_client_
), "changed",
632 G_CALLBACK(OnGSettingsChangeNotification
), this);
633 // Simulate a change to avoid possibly losing updates before this point.
634 OnChangeNotification();
638 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
642 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
643 return PROXY_CONFIG_SOURCE_GSETTINGS
;
646 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
650 return GetStringByPath(client_
, "mode", result
);
651 case PROXY_AUTOCONF_URL
:
652 return GetStringByPath(client_
, "autoconfig-url", result
);
653 case PROXY_HTTP_HOST
:
654 return GetStringByPath(http_client_
, "host", result
);
655 case PROXY_HTTPS_HOST
:
656 return GetStringByPath(https_client_
, "host", result
);
658 return GetStringByPath(ftp_client_
, "host", result
);
659 case PROXY_SOCKS_HOST
:
660 return GetStringByPath(socks_client_
, "host", result
);
662 return false; // Placate compiler.
664 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
667 case PROXY_USE_HTTP_PROXY
:
668 // Although there is an "enabled" boolean in http_client_, it is not set
669 // to true by the proxy config utility. We ignore it and return false.
671 case PROXY_USE_SAME_PROXY
:
672 // Similarly, although there is a "use-same-proxy" boolean in client_,
673 // it is never set to false by the proxy config utility. We ignore it.
675 case PROXY_USE_AUTHENTICATION
:
676 // There is also no way to set this in the proxy config utility, but it
677 // doesn't hurt us to get the actual setting (unlike the two above).
678 return GetBoolByPath(http_client_
, "use-authentication", result
);
680 return false; // Placate compiler.
682 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
685 case PROXY_HTTP_PORT
:
686 return GetIntByPath(http_client_
, "port", result
);
687 case PROXY_HTTPS_PORT
:
688 return GetIntByPath(https_client_
, "port", result
);
690 return GetIntByPath(ftp_client_
, "port", result
);
691 case PROXY_SOCKS_PORT
:
692 return GetIntByPath(socks_client_
, "port", result
);
694 return false; // Placate compiler.
696 virtual bool GetStringList(StringListSetting key
,
697 std::vector
<std::string
>* result
) OVERRIDE
{
700 case PROXY_IGNORE_HOSTS
:
701 return GetStringListByPath(client_
, "ignore-hosts", result
);
703 return false; // Placate compiler.
706 virtual bool BypassListIsReversed() OVERRIDE
{
707 // This is a KDE-specific setting.
711 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
716 #if defined(DLOPEN_GSETTINGS)
717 // We replicate the prototypes for the g_settings APIs we need. We may not
718 // even be compiling on a system that has them. If we are, these won't
719 // conflict both because they are identical and also due to scoping. The
720 // scoping will also ensure that these get used instead of the global ones.
722 typedef struct _GSettings GSettings
;
723 GSettings
* (*g_settings_new
)(const gchar
* schema
);
724 GSettings
* (*g_settings_get_child
)(GSettings
* settings
, const gchar
* name
);
725 gboolean (*g_settings_get_boolean
)(GSettings
* settings
, const gchar
* key
);
726 gchar
* (*g_settings_get_string
)(GSettings
* settings
, const gchar
* key
);
727 gint (*g_settings_get_int
)(GSettings
* settings
, const gchar
* key
);
728 gchar
** (*g_settings_get_strv
)(GSettings
* settings
, const gchar
* key
);
729 const gchar
* const* (*g_settings_list_schemas
)();
731 // The library handle.
734 // Load a symbol from |gio_handle_| and store it into |*func_ptr|.
735 bool LoadSymbol(const char* name
, void** func_ptr
) {
737 *func_ptr
= dlsym(gio_handle_
, name
);
738 const char* error
= dlerror();
740 VLOG(1) << "Unable to load symbol " << name
<< ": " << error
;
745 #endif // defined(DLOPEN_GSETTINGS)
747 bool GetStringByPath(GSettings
* client
, const char* key
,
748 std::string
* result
) {
749 DCHECK(task_runner_
->BelongsToCurrentThread());
750 gchar
* value
= g_settings_get_string(client
, key
);
757 bool GetBoolByPath(GSettings
* client
, const char* key
, bool* result
) {
758 DCHECK(task_runner_
->BelongsToCurrentThread());
759 *result
= static_cast<bool>(g_settings_get_boolean(client
, key
));
762 bool GetIntByPath(GSettings
* client
, const char* key
, int* result
) {
763 DCHECK(task_runner_
->BelongsToCurrentThread());
764 *result
= g_settings_get_int(client
, key
);
767 bool GetStringListByPath(GSettings
* client
, const char* key
,
768 std::vector
<std::string
>* result
) {
769 DCHECK(task_runner_
->BelongsToCurrentThread());
770 gchar
** list
= g_settings_get_strv(client
, key
);
773 for (size_t i
= 0; list
[i
]; ++i
) {
774 result
->push_back(static_cast<char*>(list
[i
]));
781 // This is the callback from the debounce timer.
782 void OnDebouncedNotification() {
783 DCHECK(task_runner_
->BelongsToCurrentThread());
784 CHECK(notify_delegate_
);
785 // Forward to a method on the proxy config service delegate object.
786 notify_delegate_
->OnCheckProxyConfigSettings();
789 void OnChangeNotification() {
790 // We don't use Reset() because the timer may not yet be running.
791 // (In that case Stop() is a no-op.)
792 debounce_timer_
.Stop();
793 debounce_timer_
.Start(FROM_HERE
,
794 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds
),
795 this, &SettingGetterImplGSettings::OnDebouncedNotification
);
798 // gsettings notification callback, dispatched on the default glib main loop.
799 static void OnGSettingsChangeNotification(GSettings
* client
, gchar
* key
,
800 gpointer user_data
) {
801 VLOG(1) << "gsettings change notification for key " << key
;
802 // We don't track which key has changed, just that something did change.
803 SettingGetterImplGSettings
* setting_getter
=
804 reinterpret_cast<SettingGetterImplGSettings
*>(user_data
);
805 setting_getter
->OnChangeNotification();
809 GSettings
* http_client_
;
810 GSettings
* https_client_
;
811 GSettings
* ftp_client_
;
812 GSettings
* socks_client_
;
813 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
814 base::OneShotTimer
<SettingGetterImplGSettings
> debounce_timer_
;
816 // Task runner for the thread that we make gsettings calls on. It should
817 // be the UI thread and all our methods should be called on this
818 // thread. Only for assertions.
819 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
821 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings
);
824 bool SettingGetterImplGSettings::LoadAndCheckVersion(
825 base::Environment
* env
) {
826 // LoadAndCheckVersion() must be called *before* Init()!
829 // The APIs to query gsettings were introduced after the minimum glib
830 // version we target, so we can't link directly against them. We load them
831 // dynamically at runtime, and if they don't exist, return false here. (We
832 // support linking directly via gyp flags though.) Additionally, even when
833 // they are present, we do two additional checks to make sure we should use
834 // them and not gconf. First, we attempt to load the schema for proxy
835 // settings. Second, we check for the program that was used in older
836 // versions of GNOME to configure proxy settings, and return false if it
837 // exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
838 // but don't use gsettings for proxy settings, but they do have the old
839 // binary, so we detect these systems that way.
841 #ifdef DLOPEN_GSETTINGS
842 gio_handle_
= dlopen("libgio-2.0.so.0", RTLD_NOW
| RTLD_GLOBAL
);
844 // Try again without .0 at the end; on some systems this may be required.
845 gio_handle_
= dlopen("libgio-2.0.so", RTLD_NOW
| RTLD_GLOBAL
);
847 VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
851 if (!LoadSymbol("g_settings_new",
852 reinterpret_cast<void**>(&g_settings_new
)) ||
853 !LoadSymbol("g_settings_get_child",
854 reinterpret_cast<void**>(&g_settings_get_child
)) ||
855 !LoadSymbol("g_settings_get_string",
856 reinterpret_cast<void**>(&g_settings_get_string
)) ||
857 !LoadSymbol("g_settings_get_boolean",
858 reinterpret_cast<void**>(&g_settings_get_boolean
)) ||
859 !LoadSymbol("g_settings_get_int",
860 reinterpret_cast<void**>(&g_settings_get_int
)) ||
861 !LoadSymbol("g_settings_get_strv",
862 reinterpret_cast<void**>(&g_settings_get_strv
)) ||
863 !LoadSymbol("g_settings_list_schemas",
864 reinterpret_cast<void**>(&g_settings_list_schemas
))) {
865 VLOG(1) << "Cannot load gsettings API. Will fall back to gconf.";
866 dlclose(gio_handle_
);
873 if (!SchemaExists("org.gnome.system.proxy") ||
874 !(client
= g_settings_new("org.gnome.system.proxy"))) {
875 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
878 g_object_unref(client
);
881 if (!env
->GetVar("PATH", &path
)) {
882 LOG(ERROR
) << "No $PATH variable. Assuming no gnome-network-properties.";
884 // Yes, we're on the UI thread. Yes, we're accessing the file system.
885 // Sadly, we don't have much choice. We need the proxy settings and we
886 // need them now, and to figure out where to get them, we have to check
887 // for this binary. See http://crbug.com/69057 for additional details.
888 base::ThreadRestrictions::ScopedAllowIO allow_io
;
889 std::vector
<std::string
> paths
;
890 Tokenize(path
, ":", &paths
);
891 for (size_t i
= 0; i
< paths
.size(); ++i
) {
892 FilePath
file(paths
[i
]);
893 if (file_util::PathExists(file
.Append("gnome-network-properties"))) {
894 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
900 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
903 #endif // defined(USE_GIO)
905 // This is the KDE version that reads kioslaverc and simulates gconf.
906 // Doing this allows the main Delegate code, as well as the unit tests
907 // for it, to stay the same - and the settings map fairly well besides.
908 class SettingGetterImplKDE
: public ProxyConfigServiceLinux::SettingGetter
,
909 public base::MessagePumpLibevent::Watcher
{
911 explicit SettingGetterImplKDE(base::Environment
* env_var_getter
)
912 : inotify_fd_(-1), notify_delegate_(NULL
), indirect_manual_(false),
913 auto_no_pac_(false), reversed_bypass_list_(false),
914 env_var_getter_(env_var_getter
), file_loop_(NULL
) {
915 // This has to be called on the UI thread (http://crbug.com/69057).
916 base::ThreadRestrictions::ScopedAllowIO allow_io
;
918 // Derive the location of the kde config dir from the environment.
920 if (env_var_getter
->GetVar("KDEHOME", &home
) && !home
.empty()) {
921 // $KDEHOME is set. Use it unconditionally.
922 kde_config_dir_
= KDEHomeToConfigPath(FilePath(home
));
924 // $KDEHOME is unset. Try to figure out what to use. This seems to be
925 // the common case on most distributions.
926 if (!env_var_getter
->GetVar(base::env_vars::kHome
, &home
))
927 // User has no $HOME? Give up. Later we'll report the failure.
929 if (base::nix::GetDesktopEnvironment(env_var_getter
) ==
930 base::nix::DESKTOP_ENVIRONMENT_KDE3
) {
931 // KDE3 always uses .kde for its configuration.
932 FilePath kde_path
= FilePath(home
).Append(".kde");
933 kde_config_dir_
= KDEHomeToConfigPath(kde_path
);
935 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
936 // both can be installed side-by-side. Sadly they don't all do this, and
937 // they don't always do this: some distributions have started switching
938 // back as well. So if there is a .kde4 directory, check the timestamps
939 // of the config directories within and use the newest one.
940 // Note that we should currently be running in the UI thread, because in
941 // the gconf version, that is the only thread that can access the proxy
942 // settings (a gconf restriction). As noted below, the initial read of
943 // the proxy settings will be done in this thread anyway, so we check
944 // for .kde4 here in this thread as well.
945 FilePath kde3_path
= FilePath(home
).Append(".kde");
946 FilePath kde3_config
= KDEHomeToConfigPath(kde3_path
);
947 FilePath kde4_path
= FilePath(home
).Append(".kde4");
948 FilePath kde4_config
= KDEHomeToConfigPath(kde4_path
);
949 bool use_kde4
= false;
950 if (file_util::DirectoryExists(kde4_path
)) {
951 base::PlatformFileInfo kde3_info
;
952 base::PlatformFileInfo kde4_info
;
953 if (file_util::GetFileInfo(kde4_config
, &kde4_info
)) {
954 if (file_util::GetFileInfo(kde3_config
, &kde3_info
)) {
955 use_kde4
= kde4_info
.last_modified
>= kde3_info
.last_modified
;
962 kde_config_dir_
= KDEHomeToConfigPath(kde4_path
);
964 kde_config_dir_
= KDEHomeToConfigPath(kde3_path
);
970 virtual ~SettingGetterImplKDE() {
971 // inotify_fd_ should have been closed before now, from
972 // Delegate::OnDestroy(), while running on the file thread. However
973 // on exiting the process, it may happen that Delegate::OnDestroy()
974 // task is left pending on the file loop after the loop was quit,
975 // and pending tasks may then be deleted without being run.
976 // Here in the KDE version, we can safely close the file descriptor
977 // anyway. (Not that it really matters; the process is exiting.)
978 if (inotify_fd_
>= 0)
980 DCHECK(inotify_fd_
< 0);
983 virtual bool Init(base::SingleThreadTaskRunner
* glib_thread_task_runner
,
984 MessageLoopForIO
* file_loop
) OVERRIDE
{
985 // This has to be called on the UI thread (http://crbug.com/69057).
986 base::ThreadRestrictions::ScopedAllowIO allow_io
;
987 DCHECK(inotify_fd_
< 0);
988 inotify_fd_
= inotify_init();
989 if (inotify_fd_
< 0) {
990 PLOG(ERROR
) << "inotify_init failed";
993 int flags
= fcntl(inotify_fd_
, F_GETFL
);
994 if (fcntl(inotify_fd_
, F_SETFL
, flags
| O_NONBLOCK
) < 0) {
995 PLOG(ERROR
) << "fcntl failed";
1000 file_loop_
= file_loop
;
1001 // The initial read is done on the current thread, not |file_loop_|,
1002 // since we will need to have it for SetUpAndFetchInitialConfig().
1003 UpdateCachedSettings();
1007 virtual void ShutDown() OVERRIDE
{
1008 if (inotify_fd_
>= 0) {
1009 ResetCachedSettings();
1010 inotify_watcher_
.StopWatchingFileDescriptor();
1016 virtual bool SetUpNotifications(
1017 ProxyConfigServiceLinux::Delegate
* delegate
) OVERRIDE
{
1018 DCHECK(inotify_fd_
>= 0);
1019 DCHECK(MessageLoop::current() == file_loop_
);
1020 // We can't just watch the kioslaverc file directly, since KDE will write
1021 // a new copy of it and then rename it whenever settings are changed and
1022 // inotify watches inodes (so we'll be watching the old deleted file after
1023 // the first change, and it will never change again). So, we watch the
1024 // directory instead. We then act only on changes to the kioslaverc entry.
1025 if (inotify_add_watch(inotify_fd_
, kde_config_dir_
.value().c_str(),
1026 IN_MODIFY
| IN_MOVED_TO
) < 0)
1028 notify_delegate_
= delegate
;
1029 if (!file_loop_
->WatchFileDescriptor(inotify_fd_
, true,
1030 MessageLoopForIO::WATCH_READ
, &inotify_watcher_
, this))
1032 // Simulate a change to avoid possibly losing updates before this point.
1033 OnChangeNotification();
1037 virtual base::SingleThreadTaskRunner
* GetNotificationTaskRunner() OVERRIDE
{
1038 return file_loop_
? file_loop_
->message_loop_proxy() : NULL
;
1041 // Implement base::MessagePumpLibevent::Watcher.
1042 virtual void OnFileCanReadWithoutBlocking(int fd
) OVERRIDE
{
1043 DCHECK_EQ(fd
, inotify_fd_
);
1044 DCHECK(MessageLoop::current() == file_loop_
);
1045 OnChangeNotification();
1047 virtual void OnFileCanWriteWithoutBlocking(int fd
) OVERRIDE
{
1051 virtual ProxyConfigSource
GetConfigSource() OVERRIDE
{
1052 return PROXY_CONFIG_SOURCE_KDE
;
1055 virtual bool GetString(StringSetting key
, std::string
* result
) OVERRIDE
{
1056 string_map_type::iterator it
= string_table_
.find(key
);
1057 if (it
== string_table_
.end())
1059 *result
= it
->second
;
1062 virtual bool GetBool(BoolSetting key
, bool* result
) OVERRIDE
{
1063 // We don't ever have any booleans.
1066 virtual bool GetInt(IntSetting key
, int* result
) OVERRIDE
{
1067 // We don't ever have any integers. (See AddProxy() below about ports.)
1070 virtual bool GetStringList(StringListSetting key
,
1071 std::vector
<std::string
>* result
) OVERRIDE
{
1072 strings_map_type::iterator it
= strings_table_
.find(key
);
1073 if (it
== strings_table_
.end())
1075 *result
= it
->second
;
1079 virtual bool BypassListIsReversed() OVERRIDE
{
1080 return reversed_bypass_list_
;
1083 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE
{
1088 void ResetCachedSettings() {
1089 string_table_
.clear();
1090 strings_table_
.clear();
1091 indirect_manual_
= false;
1092 auto_no_pac_
= false;
1093 reversed_bypass_list_
= false;
1096 FilePath
KDEHomeToConfigPath(const FilePath
& kde_home
) {
1097 return kde_home
.Append("share").Append("config");
1100 void AddProxy(StringSetting host_key
, const std::string
& value
) {
1101 if (value
.empty() || value
.substr(0, 3) == "//:")
1104 size_t space
= value
.find(' ');
1105 if (space
!= std::string::npos
) {
1106 // Newer versions of KDE use a space rather than a colon to separate the
1107 // port number from the hostname. If we find this, we need to convert it.
1108 std::string fixed
= value
;
1110 string_table_
[host_key
] = fixed
;
1112 // We don't need to parse the port number out; GetProxyFromSettings()
1113 // would only append it right back again. So we just leave the port
1114 // number right in the host string.
1115 string_table_
[host_key
] = value
;
1119 void AddHostList(StringListSetting key
, const std::string
& value
) {
1120 std::vector
<std::string
> tokens
;
1121 StringTokenizer
tk(value
, ", ");
1122 while (tk
.GetNext()) {
1123 std::string token
= tk
.token();
1125 tokens
.push_back(token
);
1127 strings_table_
[key
] = tokens
;
1130 void AddKDESetting(const std::string
& key
, const std::string
& value
) {
1131 if (key
== "ProxyType") {
1132 const char* mode
= "none";
1133 indirect_manual_
= false;
1134 auto_no_pac_
= false;
1136 base::StringToInt(value
, &int_value
);
1137 switch (int_value
) {
1138 case 0: // No proxy, or maybe kioslaverc syntax error.
1140 case 1: // Manual configuration.
1148 auto_no_pac_
= true;
1150 case 4: // Indirect manual via environment variables.
1152 indirect_manual_
= true;
1155 string_table_
[PROXY_MODE
] = mode
;
1156 } else if (key
== "Proxy Config Script") {
1157 string_table_
[PROXY_AUTOCONF_URL
] = value
;
1158 } else if (key
== "httpProxy") {
1159 AddProxy(PROXY_HTTP_HOST
, value
);
1160 } else if (key
== "httpsProxy") {
1161 AddProxy(PROXY_HTTPS_HOST
, value
);
1162 } else if (key
== "ftpProxy") {
1163 AddProxy(PROXY_FTP_HOST
, value
);
1164 } else if (key
== "socksProxy") {
1165 // Older versions of KDE configure SOCKS in a weird way involving
1166 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1167 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1168 AddProxy(PROXY_SOCKS_HOST
, value
);
1169 } else if (key
== "ReversedException") {
1170 // We count "true" or any nonzero number as true, otherwise false.
1171 // Note that if the value is not actually numeric StringToInt()
1172 // will return 0, which we count as false.
1174 base::StringToInt(value
, &int_value
);
1175 reversed_bypass_list_
= (value
== "true" || int_value
);
1176 } else if (key
== "NoProxyFor") {
1177 AddHostList(PROXY_IGNORE_HOSTS
, value
);
1178 } else if (key
== "AuthMode") {
1179 // Check for authentication, just so we can warn.
1181 base::StringToInt(value
, &mode
);
1183 // ProxyConfig does not support authentication parameters, but
1184 // Chrome will prompt for the password later. So we ignore this.
1186 "Proxy authentication parameters ignored, see bug 16709";
1191 void ResolveIndirect(StringSetting key
) {
1192 string_map_type::iterator it
= string_table_
.find(key
);
1193 if (it
!= string_table_
.end()) {
1195 if (env_var_getter_
->GetVar(it
->second
.c_str(), &value
))
1198 string_table_
.erase(it
);
1202 void ResolveIndirectList(StringListSetting key
) {
1203 strings_map_type::iterator it
= strings_table_
.find(key
);
1204 if (it
!= strings_table_
.end()) {
1206 if (!it
->second
.empty() &&
1207 env_var_getter_
->GetVar(it
->second
[0].c_str(), &value
))
1208 AddHostList(key
, value
);
1210 strings_table_
.erase(it
);
1214 // The settings in kioslaverc could occur in any order, but some affect
1215 // others. Rather than read the whole file in and then query them in an
1216 // order that allows us to handle that, we read the settings in whatever
1217 // order they occur and do any necessary tweaking after we finish.
1218 void ResolveModeEffects() {
1219 if (indirect_manual_
) {
1220 ResolveIndirect(PROXY_HTTP_HOST
);
1221 ResolveIndirect(PROXY_HTTPS_HOST
);
1222 ResolveIndirect(PROXY_FTP_HOST
);
1223 ResolveIndirectList(PROXY_IGNORE_HOSTS
);
1226 // Remove the PAC URL; we're not supposed to use it.
1227 string_table_
.erase(PROXY_AUTOCONF_URL
);
1231 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1232 // each relevant name-value pair to the appropriate value table.
1233 void UpdateCachedSettings() {
1234 FilePath kioslaverc
= kde_config_dir_
.Append("kioslaverc");
1235 file_util::ScopedFILE
input(file_util::OpenFile(kioslaverc
, "r"));
1238 ResetCachedSettings();
1239 bool in_proxy_settings
= false;
1240 bool line_too_long
= false;
1241 char line
[BUFFER_SIZE
];
1242 // fgets() will return NULL on EOF or error.
1243 while (fgets(line
, sizeof(line
), input
.get())) {
1244 // fgets() guarantees the line will be properly terminated.
1245 size_t length
= strlen(line
);
1248 // This should be true even with CRLF endings.
1249 if (line
[length
- 1] != '\n') {
1250 line_too_long
= true;
1253 if (line_too_long
) {
1254 // The previous line had no line ending, but this done does. This is
1255 // the end of the line that was too long, so warn here and skip it.
1256 LOG(WARNING
) << "skipped very long line in " << kioslaverc
.value();
1257 line_too_long
= false;
1260 // Remove the LF at the end, and the CR if there is one.
1261 line
[--length
] = '\0';
1262 if (length
&& line
[length
- 1] == '\r')
1263 line
[--length
] = '\0';
1264 // Now parse the line.
1265 if (line
[0] == '[') {
1266 // Switching sections. All we care about is whether this is
1267 // the (a?) proxy settings section, for both KDE3 and KDE4.
1268 in_proxy_settings
= !strncmp(line
, "[Proxy Settings]", 16);
1269 } else if (in_proxy_settings
) {
1270 // A regular line, in the (a?) proxy settings section.
1271 char* split
= strchr(line
, '=');
1272 // Skip this line if it does not contain an = sign.
1275 // Split the line on the = and advance |split|.
1277 std::string key
= line
;
1278 std::string value
= split
;
1279 TrimWhitespaceASCII(key
, TRIM_ALL
, &key
);
1280 TrimWhitespaceASCII(value
, TRIM_ALL
, &value
);
1281 // Skip this line if the key name is empty.
1284 // Is the value name localized?
1285 if (key
[key
.length() - 1] == ']') {
1286 // Find the matching bracket.
1287 length
= key
.rfind('[');
1288 // Skip this line if the localization indicator is malformed.
1289 if (length
== std::string::npos
)
1291 // Trim the localization indicator off.
1293 // Remove any resulting trailing whitespace.
1294 TrimWhitespaceASCII(key
, TRIM_TRAILING
, &key
);
1295 // Skip this line if the key name is now empty.
1299 // Now fill in the tables.
1300 AddKDESetting(key
, value
);
1303 if (ferror(input
.get()))
1304 LOG(ERROR
) << "error reading " << kioslaverc
.value();
1305 ResolveModeEffects();
1308 // This is the callback from the debounce timer.
1309 void OnDebouncedNotification() {
1310 DCHECK(MessageLoop::current() == file_loop_
);
1311 VLOG(1) << "inotify change notification for kioslaverc";
1312 UpdateCachedSettings();
1313 CHECK(notify_delegate_
);
1314 // Forward to a method on the proxy config service delegate object.
1315 notify_delegate_
->OnCheckProxyConfigSettings();
1318 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1319 // from the inotify file descriptor and starts up a debounce timer if
1320 // an event for kioslaverc is seen.
1321 void OnChangeNotification() {
1322 DCHECK_GE(inotify_fd_
, 0);
1323 DCHECK(MessageLoop::current() == file_loop_
);
1324 char event_buf
[(sizeof(inotify_event
) + NAME_MAX
+ 1) * 4];
1325 bool kioslaverc_touched
= false;
1327 while ((r
= read(inotify_fd_
, event_buf
, sizeof(event_buf
))) > 0) {
1328 // inotify returns variable-length structures, which is why we have
1329 // this strange-looking loop instead of iterating through an array.
1330 char* event_ptr
= event_buf
;
1331 while (event_ptr
< event_buf
+ r
) {
1332 inotify_event
* event
= reinterpret_cast<inotify_event
*>(event_ptr
);
1333 // The kernel always feeds us whole events.
1334 CHECK_LE(event_ptr
+ sizeof(inotify_event
), event_buf
+ r
);
1335 CHECK_LE(event
->name
+ event
->len
, event_buf
+ r
);
1336 if (!strcmp(event
->name
, "kioslaverc"))
1337 kioslaverc_touched
= true;
1338 // Advance the pointer just past the end of the filename.
1339 event_ptr
= event
->name
+ event
->len
;
1341 // We keep reading even if |kioslaverc_touched| is true to drain the
1342 // inotify event queue.
1345 // Instead of returning -1 and setting errno to EINVAL if there is not
1346 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1347 // new behavior (EINVAL) so we can reuse the code below.
1349 if (errno
!= EAGAIN
) {
1350 PLOG(WARNING
) << "error reading inotify file descriptor";
1351 if (errno
== EINVAL
) {
1352 // Our buffer is not large enough to read the next event. This should
1353 // not happen (because its size is calculated to always be sufficiently
1354 // large), but if it does we'd warn continuously since |inotify_fd_|
1355 // would be forever ready to read. Close it and stop watching instead.
1356 LOG(ERROR
) << "inotify failure; no longer watching kioslaverc!";
1357 inotify_watcher_
.StopWatchingFileDescriptor();
1362 if (kioslaverc_touched
) {
1363 // We don't use Reset() because the timer may not yet be running.
1364 // (In that case Stop() is a no-op.)
1365 debounce_timer_
.Stop();
1366 debounce_timer_
.Start(FROM_HERE
, base::TimeDelta::FromMilliseconds(
1367 kDebounceTimeoutMilliseconds
), this,
1368 &SettingGetterImplKDE::OnDebouncedNotification
);
1372 typedef std::map
<StringSetting
, std::string
> string_map_type
;
1373 typedef std::map
<StringListSetting
,
1374 std::vector
<std::string
> > strings_map_type
;
1377 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_
;
1378 ProxyConfigServiceLinux::Delegate
* notify_delegate_
;
1379 base::OneShotTimer
<SettingGetterImplKDE
> debounce_timer_
;
1380 FilePath kde_config_dir_
;
1381 bool indirect_manual_
;
1383 bool reversed_bypass_list_
;
1384 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1385 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1387 base::Environment
* env_var_getter_
;
1389 // We cache these settings whenever we re-read the kioslaverc file.
1390 string_map_type string_table_
;
1391 strings_map_type strings_table_
;
1393 // Message loop of the file thread, for reading kioslaverc. If NULL,
1394 // just read it directly (for testing). We also handle inotify events
1396 MessageLoopForIO
* file_loop_
;
1398 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE
);
1403 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1404 SettingGetter::StringSetting host_key
,
1405 ProxyServer
* result_server
) {
1407 if (!setting_getter_
->GetString(host_key
, &host
) || host
.empty()) {
1411 // Check for an optional port.
1413 SettingGetter::IntSetting port_key
=
1414 SettingGetter::HostSettingToPortSetting(host_key
);
1415 setting_getter_
->GetInt(port_key
, &port
);
1417 // If a port is set and non-zero:
1418 host
+= ":" + base::IntToString(port
);
1421 // gconf settings do not appear to distinguish between SOCKS version. We
1422 // default to version 5. For more information on this policy decision, see:
1423 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1424 ProxyServer::Scheme scheme
= (host_key
== SettingGetter::PROXY_SOCKS_HOST
) ?
1425 ProxyServer::SCHEME_SOCKS5
: ProxyServer::SCHEME_HTTP
;
1426 host
= FixupProxyHostScheme(scheme
, host
);
1427 ProxyServer proxy_server
= ProxyServer::FromURI(host
,
1428 ProxyServer::SCHEME_HTTP
);
1429 if (proxy_server
.is_valid()) {
1430 *result_server
= proxy_server
;
1436 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1437 ProxyConfig
* config
) {
1439 if (!setting_getter_
->GetString(SettingGetter::PROXY_MODE
, &mode
)) {
1440 // We expect this to always be set, so if we don't see it then we
1441 // probably have a gconf/gsettings problem, and so we don't have a valid
1445 if (mode
== "none") {
1446 // Specifically specifies no proxy.
1450 if (mode
== "auto") {
1451 // Automatic proxy config.
1452 std::string pac_url_str
;
1453 if (setting_getter_
->GetString(SettingGetter::PROXY_AUTOCONF_URL
,
1455 if (!pac_url_str
.empty()) {
1456 // If the PAC URL is actually a file path, then put file:// in front.
1457 if (pac_url_str
[0] == '/')
1458 pac_url_str
= "file://" + pac_url_str
;
1459 GURL
pac_url(pac_url_str
);
1460 if (!pac_url
.is_valid())
1462 config
->set_pac_url(pac_url
);
1466 config
->set_auto_detect(true);
1470 if (mode
!= "manual") {
1471 // Mode is unrecognized.
1474 bool use_http_proxy
;
1475 if (setting_getter_
->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY
,
1477 && !use_http_proxy
) {
1478 // Another master switch for some reason. If set to false, then no
1479 // proxy. But we don't panic if the key doesn't exist.
1483 bool same_proxy
= false;
1484 // Indicates to use the http proxy for all protocols. This one may
1485 // not exist (presumably on older versions); we assume false in that
1487 setting_getter_
->GetBool(SettingGetter::PROXY_USE_SAME_PROXY
,
1490 ProxyServer proxy_for_http
;
1491 ProxyServer proxy_for_https
;
1492 ProxyServer proxy_for_ftp
;
1493 ProxyServer socks_proxy
; // (socks)
1495 // This counts how many of the above ProxyServers were defined and valid.
1496 size_t num_proxies_specified
= 0;
1498 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1499 // specified for the scheme, then the resulting ProxyServer will be invalid.
1500 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST
, &proxy_for_http
))
1501 num_proxies_specified
++;
1502 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST
, &proxy_for_https
))
1503 num_proxies_specified
++;
1504 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST
, &proxy_for_ftp
))
1505 num_proxies_specified
++;
1506 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST
, &socks_proxy
))
1507 num_proxies_specified
++;
1510 if (proxy_for_http
.is_valid()) {
1511 // Use the http proxy for all schemes.
1512 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1513 config
->proxy_rules().single_proxy
= proxy_for_http
;
1515 } else if (num_proxies_specified
> 0) {
1516 if (socks_proxy
.is_valid() && num_proxies_specified
== 1) {
1517 // If the only proxy specified was for SOCKS, use it for all schemes.
1518 config
->proxy_rules().type
= ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY
;
1519 config
->proxy_rules().single_proxy
= socks_proxy
;
1521 // Otherwise use the indicate proxies per-scheme.
1522 config
->proxy_rules().type
=
1523 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME
;
1524 config
->proxy_rules().proxy_for_http
= proxy_for_http
;
1525 config
->proxy_rules().proxy_for_https
= proxy_for_https
;
1526 config
->proxy_rules().proxy_for_ftp
= proxy_for_ftp
;
1527 config
->proxy_rules().fallback_proxy
= socks_proxy
;
1531 if (config
->proxy_rules().empty()) {
1532 // Manual mode but we couldn't parse any rules.
1536 // Check for authentication, just so we can warn.
1537 bool use_auth
= false;
1538 setting_getter_
->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION
,
1541 // ProxyConfig does not support authentication parameters, but
1542 // Chrome will prompt for the password later. So we ignore
1543 // /system/http_proxy/*auth* settings.
1544 LOG(WARNING
) << "Proxy authentication parameters ignored, see bug 16709";
1547 // Now the bypass list.
1548 std::vector
<std::string
> ignore_hosts_list
;
1549 config
->proxy_rules().bypass_rules
.Clear();
1550 if (setting_getter_
->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS
,
1551 &ignore_hosts_list
)) {
1552 std::vector
<std::string
>::const_iterator
it(ignore_hosts_list
.begin());
1553 for (; it
!= ignore_hosts_list
.end(); ++it
) {
1554 if (setting_getter_
->MatchHostsUsingSuffixMatching()) {
1555 config
->proxy_rules().bypass_rules
.
1556 AddRuleFromStringUsingSuffixMatching(*it
);
1558 config
->proxy_rules().bypass_rules
.AddRuleFromString(*it
);
1562 // Note that there are no settings with semantics corresponding to
1563 // bypass of local names in GNOME. In KDE, "<local>" is supported
1564 // as a hostname rule.
1566 // KDE allows one to reverse the bypass rules.
1567 config
->proxy_rules().reverse_bypass
=
1568 setting_getter_
->BypassListIsReversed();
1573 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment
* env_var_getter
)
1574 : env_var_getter_(env_var_getter
) {
1575 // Figure out which SettingGetterImpl to use, if any.
1576 switch (base::nix::GetDesktopEnvironment(env_var_getter
)) {
1577 case base::nix::DESKTOP_ENVIRONMENT_GNOME
:
1578 case base::nix::DESKTOP_ENVIRONMENT_UNITY
:
1579 #if defined(USE_GIO)
1581 scoped_ptr
<SettingGetterImplGSettings
> gs_getter(
1582 new SettingGetterImplGSettings());
1583 // We have to load symbols and check the GNOME version in use to decide
1584 // if we should use the gsettings getter. See LoadAndCheckVersion().
1585 if (gs_getter
->LoadAndCheckVersion(env_var_getter
))
1586 setting_getter_
.reset(gs_getter
.release());
1589 #if defined(USE_GCONF)
1590 // Fall back on gconf if gsettings is unavailable or incorrect.
1591 if (!setting_getter_
.get())
1592 setting_getter_
.reset(new SettingGetterImplGConf());
1595 case base::nix::DESKTOP_ENVIRONMENT_KDE3
:
1596 case base::nix::DESKTOP_ENVIRONMENT_KDE4
:
1597 setting_getter_
.reset(new SettingGetterImplKDE(env_var_getter
));
1599 case base::nix::DESKTOP_ENVIRONMENT_XFCE
:
1600 case base::nix::DESKTOP_ENVIRONMENT_OTHER
:
1605 ProxyConfigServiceLinux::Delegate::Delegate(
1606 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1607 : env_var_getter_(env_var_getter
), setting_getter_(setting_getter
) {
1610 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1611 base::SingleThreadTaskRunner
* glib_thread_task_runner
,
1612 base::SingleThreadTaskRunner
* io_thread_task_runner
,
1613 MessageLoopForIO
* file_loop
) {
1614 // We should be running on the default glib main loop thread right
1615 // now. gconf can only be accessed from this thread.
1616 DCHECK(glib_thread_task_runner
->BelongsToCurrentThread());
1617 glib_thread_task_runner_
= glib_thread_task_runner
;
1618 io_thread_task_runner_
= io_thread_task_runner
;
1620 // If we are passed a NULL |io_thread_task_runner| or |file_loop|,
1621 // then we don't set up proxy setting change notifications. This
1622 // should not be the usual case but is intended to simplify test
1624 if (!io_thread_task_runner_
|| !file_loop
)
1625 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1627 // Fetch and cache the current proxy config. The config is left in
1628 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1629 // will expect to find it. This is safe to do because we return
1630 // before this ProxyConfigServiceLinux is passed on to
1631 // the ProxyService.
1633 // Note: It would be nice to prioritize environment variables
1634 // and only fall back to gconf if env vars were unset. But
1635 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1636 // does so even if the proxy mode is set to auto, which would
1639 bool got_config
= false;
1640 if (setting_getter_
.get() &&
1641 setting_getter_
->Init(glib_thread_task_runner
, file_loop
) &&
1642 GetConfigFromSettings(&cached_config_
)) {
1643 cached_config_
.set_id(1); // Mark it as valid.
1644 cached_config_
.set_source(setting_getter_
->GetConfigSource());
1645 VLOG(1) << "Obtained proxy settings from "
1646 << ProxyConfigSourceToString(cached_config_
.source());
1648 // If gconf proxy mode is "none", meaning direct, then we take
1649 // that to be a valid config and will not check environment
1650 // variables. The alternative would have been to look for a proxy
1651 // whereever we can find one.
1654 // Keep a copy of the config for use from this thread for
1655 // comparison with updated settings when we get notifications.
1656 reference_config_
= cached_config_
;
1657 reference_config_
.set_id(1); // Mark it as valid.
1659 // We only set up notifications if we have IO and file loops available.
1660 // We do this after getting the initial configuration so that we don't have
1661 // to worry about cancelling it if the initial fetch above fails. Note that
1662 // setting up notifications has the side effect of simulating a change, so
1663 // that we won't lose any updates that may have happened after the initial
1664 // fetch and before setting up notifications. We'll detect the common case
1665 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1666 if (io_thread_task_runner
&& file_loop
) {
1667 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1668 setting_getter_
->GetNotificationTaskRunner();
1669 if (!required_loop
|| required_loop
->BelongsToCurrentThread()) {
1670 // In this case we are already on an acceptable thread.
1671 SetUpNotifications();
1673 // Post a task to set up notifications. We don't wait for success.
1674 required_loop
->PostTask(FROM_HERE
, base::Bind(
1675 &ProxyConfigServiceLinux::Delegate::SetUpNotifications
, this));
1681 // We fall back on environment variables.
1683 // Consulting environment variables doesn't need to be done from the
1684 // default glib main loop, but it's a tiny enough amount of work.
1685 if (GetConfigFromEnv(&cached_config_
)) {
1686 cached_config_
.set_source(PROXY_CONFIG_SOURCE_ENV
);
1687 cached_config_
.set_id(1); // Mark it as valid.
1688 VLOG(1) << "Obtained proxy settings from environment variables";
1693 // Depending on the SettingGetter in use, this method will be called
1694 // on either the UI thread (GConf) or the file thread (KDE).
1695 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1696 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1697 setting_getter_
->GetNotificationTaskRunner();
1698 DCHECK(!required_loop
|| required_loop
->BelongsToCurrentThread());
1699 if (!setting_getter_
->SetUpNotifications(this))
1700 LOG(ERROR
) << "Unable to set up proxy configuration change notifications";
1703 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer
* observer
) {
1704 observers_
.AddObserver(observer
);
1707 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer
* observer
) {
1708 observers_
.RemoveObserver(observer
);
1711 ProxyConfigService::ConfigAvailability
1712 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1713 ProxyConfig
* config
) {
1714 // This is called from the IO thread.
1715 DCHECK(!io_thread_task_runner_
||
1716 io_thread_task_runner_
->BelongsToCurrentThread());
1718 // Simply return the last proxy configuration that glib_default_loop
1720 if (cached_config_
.is_valid()) {
1721 *config
= cached_config_
;
1723 *config
= ProxyConfig::CreateDirect();
1724 config
->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED
);
1727 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1728 // going to be available since we initialized eagerly on the UI thread.
1729 // TODO(eroman): do lazy initialization instead, so we no longer need
1730 // to construct ProxyConfigServiceLinux on the UI thread.
1731 // In which case, we may return false here.
1732 return CONFIG_VALID
;
1735 // Depending on the SettingGetter in use, this method will be called
1736 // on either the UI thread (GConf) or the file thread (KDE).
1737 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1738 scoped_refptr
<base::SingleThreadTaskRunner
> required_loop
=
1739 setting_getter_
->GetNotificationTaskRunner();
1740 DCHECK(!required_loop
|| required_loop
->BelongsToCurrentThread());
1741 ProxyConfig new_config
;
1742 bool valid
= GetConfigFromSettings(&new_config
);
1744 new_config
.set_id(1); // mark it as valid
1746 // See if it is different from what we had before.
1747 if (new_config
.is_valid() != reference_config_
.is_valid() ||
1748 !new_config
.Equals(reference_config_
)) {
1749 // Post a task to the IO thread with the new configuration, so it can
1750 // update |cached_config_|.
1751 io_thread_task_runner_
->PostTask(FROM_HERE
, base::Bind(
1752 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig
,
1754 // Update the thread-private copy in |reference_config_| as well.
1755 reference_config_
= new_config
;
1757 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1761 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1762 const ProxyConfig
& new_config
) {
1763 DCHECK(io_thread_task_runner_
->BelongsToCurrentThread());
1764 VLOG(1) << "Proxy configuration changed";
1765 cached_config_
= new_config
;
1767 Observer
, observers_
,
1768 OnProxyConfigChanged(new_config
, ProxyConfigService::CONFIG_VALID
));
1771 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1772 if (!setting_getter_
.get())
1774 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1775 setting_getter_
->GetNotificationTaskRunner();
1776 if (!shutdown_loop
|| shutdown_loop
->BelongsToCurrentThread()) {
1777 // Already on the right thread, call directly.
1778 // This is the case for the unittests.
1781 // Post to shutdown thread. Note that on browser shutdown, we may quit
1782 // this MessageLoop and exit the program before ever running this.
1783 shutdown_loop
->PostTask(FROM_HERE
, base::Bind(
1784 &ProxyConfigServiceLinux::Delegate::OnDestroy
, this));
1787 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1788 scoped_refptr
<base::SingleThreadTaskRunner
> shutdown_loop
=
1789 setting_getter_
->GetNotificationTaskRunner();
1790 DCHECK(!shutdown_loop
|| shutdown_loop
->BelongsToCurrentThread());
1791 setting_getter_
->ShutDown();
1794 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1795 : delegate_(new Delegate(base::Environment::Create())) {
1798 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1799 delegate_
->PostDestroyTask();
1802 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1803 base::Environment
* env_var_getter
)
1804 : delegate_(new Delegate(env_var_getter
)) {
1807 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1808 base::Environment
* env_var_getter
, SettingGetter
* setting_getter
)
1809 : delegate_(new Delegate(env_var_getter
, setting_getter
)) {
1812 void ProxyConfigServiceLinux::AddObserver(Observer
* observer
) {
1813 delegate_
->AddObserver(observer
);
1816 void ProxyConfigServiceLinux::RemoveObserver(Observer
* observer
) {
1817 delegate_
->RemoveObserver(observer
);
1820 ProxyConfigService::ConfigAvailability
1821 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig
* config
) {
1822 return delegate_
->GetLatestProxyConfig(config
);