Rename InputLatency::ScrollUpdate to Latency::ScrollUpdate
[chromium-blink-merge.git] / net / proxy / proxy_config_service_linux.cc
blobbe8068d672c3d8cf36764bf9683db400dfd268fc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/proxy/proxy_config_service_linux.h"
7 #include <errno.h>
8 #include <fcntl.h>
9 #if defined(USE_GCONF)
10 #include <gconf/gconf-client.h>
11 #endif // defined(USE_GCONF)
12 #include <limits.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/inotify.h>
16 #include <unistd.h>
18 #include <map>
20 #include "base/bind.h"
21 #include "base/compiler_specific.h"
22 #include "base/debug/leak_annotations.h"
23 #include "base/environment.h"
24 #include "base/files/file_path.h"
25 #include "base/files/file_util.h"
26 #include "base/files/scoped_file.h"
27 #include "base/logging.h"
28 #include "base/message_loop/message_loop.h"
29 #include "base/nix/xdg_util.h"
30 #include "base/single_thread_task_runner.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_tokenizer.h"
33 #include "base/strings/string_util.h"
34 #include "base/threading/thread_restrictions.h"
35 #include "base/timer/timer.h"
36 #include "net/base/net_errors.h"
37 #include "net/http/http_util.h"
38 #include "net/proxy/proxy_config.h"
39 #include "net/proxy/proxy_server.h"
40 #include "url/url_canon.h"
42 #if defined(USE_GIO)
43 #include "library_loaders/libgio.h"
44 #endif // defined(USE_GIO)
46 namespace net {
48 namespace {
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,
56 std::string host) {
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
79 // default port.
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);
88 return host;
91 } // namespace
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;
107 return true;
108 } else {
109 LOG(ERROR) << "Failed to parse environment variable " << variable;
113 return false;
116 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
117 const char* variable, ProxyServer* result_server) {
118 return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
119 result_server);
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
126 // idea.
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);
132 } else {
133 // specified autoconfig URL
134 config->set_pac_url(GURL(auto_proxy));
136 return true;
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_proxies.SetSingleProxyServer(proxy_server);
143 } else {
144 bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_server);
145 if (have_http)
146 config->proxy_rules().proxies_for_http.SetSingleProxyServer(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);
153 if (have_https)
154 config->proxy_rules().proxies_for_https.
155 SetSingleProxyServer(proxy_server);
156 bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_server);
157 if (have_ftp)
158 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_server);
159 if (have_http || have_https || have_ftp) {
160 // mustn't change type unless some rules are actually set.
161 config->proxy_rules().type =
162 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
165 if (config->proxy_rules().empty()) {
166 // If the above were not defined, try for socks.
167 // For environment variables, we default to version 5, per the gnome
168 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
169 ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
170 std::string env_version;
171 if (env_var_getter_->GetVar("SOCKS_VERSION", &env_version)
172 && env_version == "4")
173 scheme = ProxyServer::SCHEME_SOCKS4;
174 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_server)) {
175 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
176 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
179 // Look for the proxy bypass list.
180 std::string no_proxy;
181 env_var_getter_->GetVar("no_proxy", &no_proxy);
182 if (config->proxy_rules().empty()) {
183 // Having only "no_proxy" set, presumably to "*", makes it
184 // explicit that env vars do specify a configuration: having no
185 // rules specified only means the user explicitly asks for direct
186 // connections.
187 return !no_proxy.empty();
189 // Note that this uses "suffix" matching. So a bypass of "google.com"
190 // is understood to mean a bypass of "*google.com".
191 config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
192 no_proxy);
193 return true;
196 namespace {
198 const int kDebounceTimeoutMilliseconds = 250;
200 #if defined(USE_GCONF)
201 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
202 class SettingGetterImplGConf : public ProxyConfigServiceLinux::SettingGetter {
203 public:
204 SettingGetterImplGConf()
205 : client_(NULL),
206 system_proxy_id_(0),
207 system_http_proxy_id_(0),
208 notify_delegate_(NULL),
209 debounce_timer_(new base::OneShotTimer<SettingGetterImplGConf>()) {
212 ~SettingGetterImplGConf() override {
213 // client_ should have been released before now, from
214 // Delegate::OnDestroy(), while running on the UI thread. However
215 // on exiting the process, it may happen that Delegate::OnDestroy()
216 // task is left pending on the glib loop after the loop was quit,
217 // and pending tasks may then be deleted without being run.
218 if (client_) {
219 // gconf client was not cleaned up.
220 if (task_runner_->BelongsToCurrentThread()) {
221 // We are on the UI thread so we can clean it safely. This is
222 // the case at least for ui_tests running under Valgrind in
223 // bug 16076.
224 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
225 ShutDown();
226 } else {
227 // This is very bad! We are deleting the setting getter but we're not on
228 // the UI thread. This is not supposed to happen: the setting getter is
229 // owned by the proxy config service's delegate, which is supposed to be
230 // destroyed on the UI thread only. We will get change notifications to
231 // a deleted object if we continue here, so fail now.
232 LOG(FATAL) << "~SettingGetterImplGConf: deleting on wrong thread!";
235 DCHECK(!client_);
238 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
239 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
240 override {
241 DCHECK(glib_task_runner->BelongsToCurrentThread());
242 DCHECK(!client_);
243 DCHECK(!task_runner_.get());
244 task_runner_ = glib_task_runner;
245 client_ = gconf_client_get_default();
246 if (!client_) {
247 // It's not clear whether/when this can return NULL.
248 LOG(ERROR) << "Unable to create a gconf client";
249 task_runner_ = NULL;
250 return false;
252 GError* error = NULL;
253 bool added_system_proxy = false;
254 // We need to add the directories for which we'll be asking
255 // for notifications, and we might as well ask to preload them.
256 // These need to be removed again in ShutDown(); we are careful
257 // here to only leave client_ non-NULL if both have been added.
258 gconf_client_add_dir(client_, "/system/proxy",
259 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
260 if (error == NULL) {
261 added_system_proxy = true;
262 gconf_client_add_dir(client_, "/system/http_proxy",
263 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
265 if (error != NULL) {
266 LOG(ERROR) << "Error requesting gconf directory: " << error->message;
267 g_error_free(error);
268 if (added_system_proxy)
269 gconf_client_remove_dir(client_, "/system/proxy", NULL);
270 g_object_unref(client_);
271 client_ = NULL;
272 task_runner_ = NULL;
273 return false;
275 return true;
278 void ShutDown() override {
279 if (client_) {
280 DCHECK(task_runner_->BelongsToCurrentThread());
281 // We must explicitly disable gconf notifications here, because the gconf
282 // client will be shared between all setting getters, and they do not all
283 // have the same lifetimes. (For instance, incognito sessions get their
284 // own, which is destroyed when the session ends.)
285 gconf_client_notify_remove(client_, system_http_proxy_id_);
286 gconf_client_notify_remove(client_, system_proxy_id_);
287 gconf_client_remove_dir(client_, "/system/http_proxy", NULL);
288 gconf_client_remove_dir(client_, "/system/proxy", NULL);
289 g_object_unref(client_);
290 client_ = NULL;
291 task_runner_ = NULL;
293 debounce_timer_.reset();
296 bool SetUpNotifications(
297 ProxyConfigServiceLinux::Delegate* delegate) override {
298 DCHECK(client_);
299 DCHECK(task_runner_->BelongsToCurrentThread());
300 GError* error = NULL;
301 notify_delegate_ = delegate;
302 // We have to keep track of the IDs returned by gconf_client_notify_add() so
303 // that we can remove them in ShutDown(). (Otherwise, notifications will be
304 // delivered to this object after it is deleted, which is bad, m'kay?)
305 system_proxy_id_ = gconf_client_notify_add(
306 client_, "/system/proxy",
307 OnGConfChangeNotification, this,
308 NULL, &error);
309 if (error == NULL) {
310 system_http_proxy_id_ = gconf_client_notify_add(
311 client_, "/system/http_proxy",
312 OnGConfChangeNotification, this,
313 NULL, &error);
315 if (error != NULL) {
316 LOG(ERROR) << "Error requesting gconf notifications: " << error->message;
317 g_error_free(error);
318 ShutDown();
319 return false;
321 // Simulate a change to avoid possibly losing updates before this point.
322 OnChangeNotification();
323 return true;
326 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
327 override {
328 return task_runner_;
331 ProxyConfigSource GetConfigSource() override {
332 return PROXY_CONFIG_SOURCE_GCONF;
335 bool GetString(StringSetting key, std::string* result) override {
336 switch (key) {
337 case PROXY_MODE:
338 return GetStringByPath("/system/proxy/mode", result);
339 case PROXY_AUTOCONF_URL:
340 return GetStringByPath("/system/proxy/autoconfig_url", result);
341 case PROXY_HTTP_HOST:
342 return GetStringByPath("/system/http_proxy/host", result);
343 case PROXY_HTTPS_HOST:
344 return GetStringByPath("/system/proxy/secure_host", result);
345 case PROXY_FTP_HOST:
346 return GetStringByPath("/system/proxy/ftp_host", result);
347 case PROXY_SOCKS_HOST:
348 return GetStringByPath("/system/proxy/socks_host", result);
350 return false; // Placate compiler.
352 bool GetBool(BoolSetting key, bool* result) override {
353 switch (key) {
354 case PROXY_USE_HTTP_PROXY:
355 return GetBoolByPath("/system/http_proxy/use_http_proxy", result);
356 case PROXY_USE_SAME_PROXY:
357 return GetBoolByPath("/system/http_proxy/use_same_proxy", result);
358 case PROXY_USE_AUTHENTICATION:
359 return GetBoolByPath("/system/http_proxy/use_authentication", result);
361 return false; // Placate compiler.
363 bool GetInt(IntSetting key, int* result) override {
364 switch (key) {
365 case PROXY_HTTP_PORT:
366 return GetIntByPath("/system/http_proxy/port", result);
367 case PROXY_HTTPS_PORT:
368 return GetIntByPath("/system/proxy/secure_port", result);
369 case PROXY_FTP_PORT:
370 return GetIntByPath("/system/proxy/ftp_port", result);
371 case PROXY_SOCKS_PORT:
372 return GetIntByPath("/system/proxy/socks_port", result);
374 return false; // Placate compiler.
376 bool GetStringList(StringListSetting key,
377 std::vector<std::string>* result) override {
378 switch (key) {
379 case PROXY_IGNORE_HOSTS:
380 return GetStringListByPath("/system/http_proxy/ignore_hosts", result);
382 return false; // Placate compiler.
385 bool BypassListIsReversed() override {
386 // This is a KDE-specific setting.
387 return false;
390 bool MatchHostsUsingSuffixMatching() override { return false; }
392 private:
393 bool GetStringByPath(const char* key, std::string* result) {
394 DCHECK(client_);
395 DCHECK(task_runner_->BelongsToCurrentThread());
396 GError* error = NULL;
397 gchar* value = gconf_client_get_string(client_, key, &error);
398 if (HandleGError(error, key))
399 return false;
400 if (!value)
401 return false;
402 *result = value;
403 g_free(value);
404 return true;
406 bool GetBoolByPath(const char* key, bool* result) {
407 DCHECK(client_);
408 DCHECK(task_runner_->BelongsToCurrentThread());
409 GError* error = NULL;
410 // We want to distinguish unset values from values defaulting to
411 // false. For that we need to use the type-generic
412 // gconf_client_get() rather than gconf_client_get_bool().
413 GConfValue* gconf_value = gconf_client_get(client_, key, &error);
414 if (HandleGError(error, key))
415 return false;
416 if (!gconf_value) {
417 // Unset.
418 return false;
420 if (gconf_value->type != GCONF_VALUE_BOOL) {
421 gconf_value_free(gconf_value);
422 return false;
424 gboolean bool_value = gconf_value_get_bool(gconf_value);
425 *result = static_cast<bool>(bool_value);
426 gconf_value_free(gconf_value);
427 return true;
429 bool GetIntByPath(const char* key, int* result) {
430 DCHECK(client_);
431 DCHECK(task_runner_->BelongsToCurrentThread());
432 GError* error = NULL;
433 int value = gconf_client_get_int(client_, key, &error);
434 if (HandleGError(error, key))
435 return false;
436 // We don't bother to distinguish an unset value because callers
437 // don't care. 0 is returned if unset.
438 *result = value;
439 return true;
441 bool GetStringListByPath(const char* key, std::vector<std::string>* result) {
442 DCHECK(client_);
443 DCHECK(task_runner_->BelongsToCurrentThread());
444 GError* error = NULL;
445 GSList* list = gconf_client_get_list(client_, key,
446 GCONF_VALUE_STRING, &error);
447 if (HandleGError(error, key))
448 return false;
449 if (!list)
450 return false;
451 for (GSList *it = list; it; it = it->next) {
452 result->push_back(static_cast<char*>(it->data));
453 g_free(it->data);
455 g_slist_free(list);
456 return true;
459 // Logs and frees a glib error. Returns false if there was no error
460 // (error is NULL).
461 bool HandleGError(GError* error, const char* key) {
462 if (error != NULL) {
463 LOG(ERROR) << "Error getting gconf value for " << key
464 << ": " << error->message;
465 g_error_free(error);
466 return true;
468 return false;
471 // This is the callback from the debounce timer.
472 void OnDebouncedNotification() {
473 DCHECK(task_runner_->BelongsToCurrentThread());
474 CHECK(notify_delegate_);
475 // Forward to a method on the proxy config service delegate object.
476 notify_delegate_->OnCheckProxyConfigSettings();
479 void OnChangeNotification() {
480 // We don't use Reset() because the timer may not yet be running.
481 // (In that case Stop() is a no-op.)
482 debounce_timer_->Stop();
483 debounce_timer_->Start(FROM_HERE,
484 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
485 this, &SettingGetterImplGConf::OnDebouncedNotification);
488 // gconf notification callback, dispatched on the default glib main loop.
489 static void OnGConfChangeNotification(GConfClient* client, guint cnxn_id,
490 GConfEntry* entry, gpointer user_data) {
491 VLOG(1) << "gconf change notification for key "
492 << gconf_entry_get_key(entry);
493 // We don't track which key has changed, just that something did change.
494 SettingGetterImplGConf* setting_getter =
495 reinterpret_cast<SettingGetterImplGConf*>(user_data);
496 setting_getter->OnChangeNotification();
499 GConfClient* client_;
500 // These ids are the values returned from gconf_client_notify_add(), which we
501 // will need in order to later call gconf_client_notify_remove().
502 guint system_proxy_id_;
503 guint system_http_proxy_id_;
505 ProxyConfigServiceLinux::Delegate* notify_delegate_;
506 scoped_ptr<base::OneShotTimer<SettingGetterImplGConf> > debounce_timer_;
508 // Task runner for the thread that we make gconf calls on. It should
509 // be the UI thread and all our methods should be called on this
510 // thread. Only for assertions.
511 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
513 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf);
515 #endif // defined(USE_GCONF)
517 #if defined(USE_GIO)
518 const char kProxyGConfSchema[] = "org.gnome.system.proxy";
520 // This setting getter uses gsettings, as used in most GNOME 3 desktops.
521 class SettingGetterImplGSettings
522 : public ProxyConfigServiceLinux::SettingGetter {
523 public:
524 SettingGetterImplGSettings() :
525 client_(NULL),
526 http_client_(NULL),
527 https_client_(NULL),
528 ftp_client_(NULL),
529 socks_client_(NULL),
530 notify_delegate_(NULL),
531 debounce_timer_(new base::OneShotTimer<SettingGetterImplGSettings>()) {
534 ~SettingGetterImplGSettings() override {
535 // client_ should have been released before now, from
536 // Delegate::OnDestroy(), while running on the UI thread. However
537 // on exiting the process, it may happen that
538 // Delegate::OnDestroy() task is left pending on the glib loop
539 // after the loop was quit, and pending tasks may then be deleted
540 // without being run.
541 if (client_) {
542 // gconf client was not cleaned up.
543 if (task_runner_->BelongsToCurrentThread()) {
544 // We are on the UI thread so we can clean it safely. This is
545 // the case at least for ui_tests running under Valgrind in
546 // bug 16076.
547 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
548 ShutDown();
549 } else {
550 LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
551 client_ = NULL;
554 DCHECK(!client_);
557 bool SchemaExists(const char* schema_name) {
558 const gchar* const* schemas = libgio_loader_.g_settings_list_schemas();
559 while (*schemas) {
560 if (strcmp(schema_name, static_cast<const char*>(*schemas)) == 0)
561 return true;
562 schemas++;
564 return false;
567 // LoadAndCheckVersion() must be called *before* Init()!
568 bool LoadAndCheckVersion(base::Environment* env);
570 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
571 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
572 override {
573 DCHECK(glib_task_runner->BelongsToCurrentThread());
574 DCHECK(!client_);
575 DCHECK(!task_runner_.get());
577 if (!SchemaExists(kProxyGConfSchema) ||
578 !(client_ = libgio_loader_.g_settings_new(kProxyGConfSchema))) {
579 // It's not clear whether/when this can return NULL.
580 LOG(ERROR) << "Unable to create a gsettings client";
581 return false;
583 task_runner_ = glib_task_runner;
584 // We assume these all work if the above call worked.
585 http_client_ = libgio_loader_.g_settings_get_child(client_, "http");
586 https_client_ = libgio_loader_.g_settings_get_child(client_, "https");
587 ftp_client_ = libgio_loader_.g_settings_get_child(client_, "ftp");
588 socks_client_ = libgio_loader_.g_settings_get_child(client_, "socks");
589 DCHECK(http_client_ && https_client_ && ftp_client_ && socks_client_);
590 return true;
593 void ShutDown() override {
594 if (client_) {
595 DCHECK(task_runner_->BelongsToCurrentThread());
596 // This also disables gsettings notifications.
597 g_object_unref(socks_client_);
598 g_object_unref(ftp_client_);
599 g_object_unref(https_client_);
600 g_object_unref(http_client_);
601 g_object_unref(client_);
602 // We only need to null client_ because it's the only one that we check.
603 client_ = NULL;
604 task_runner_ = NULL;
606 debounce_timer_.reset();
609 bool SetUpNotifications(
610 ProxyConfigServiceLinux::Delegate* delegate) override {
611 DCHECK(client_);
612 DCHECK(task_runner_->BelongsToCurrentThread());
613 notify_delegate_ = delegate;
614 // We could watch for the change-event signal instead of changed, but
615 // since we have to watch more than one object, we'd still have to
616 // debounce change notifications. This is conceptually simpler.
617 g_signal_connect(G_OBJECT(client_), "changed",
618 G_CALLBACK(OnGSettingsChangeNotification), this);
619 g_signal_connect(G_OBJECT(http_client_), "changed",
620 G_CALLBACK(OnGSettingsChangeNotification), this);
621 g_signal_connect(G_OBJECT(https_client_), "changed",
622 G_CALLBACK(OnGSettingsChangeNotification), this);
623 g_signal_connect(G_OBJECT(ftp_client_), "changed",
624 G_CALLBACK(OnGSettingsChangeNotification), this);
625 g_signal_connect(G_OBJECT(socks_client_), "changed",
626 G_CALLBACK(OnGSettingsChangeNotification), this);
627 // Simulate a change to avoid possibly losing updates before this point.
628 OnChangeNotification();
629 return true;
632 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
633 override {
634 return task_runner_;
637 ProxyConfigSource GetConfigSource() override {
638 return PROXY_CONFIG_SOURCE_GSETTINGS;
641 bool GetString(StringSetting key, std::string* result) override {
642 DCHECK(client_);
643 switch (key) {
644 case PROXY_MODE:
645 return GetStringByPath(client_, "mode", result);
646 case PROXY_AUTOCONF_URL:
647 return GetStringByPath(client_, "autoconfig-url", result);
648 case PROXY_HTTP_HOST:
649 return GetStringByPath(http_client_, "host", result);
650 case PROXY_HTTPS_HOST:
651 return GetStringByPath(https_client_, "host", result);
652 case PROXY_FTP_HOST:
653 return GetStringByPath(ftp_client_, "host", result);
654 case PROXY_SOCKS_HOST:
655 return GetStringByPath(socks_client_, "host", result);
657 return false; // Placate compiler.
659 bool GetBool(BoolSetting key, bool* result) override {
660 DCHECK(client_);
661 switch (key) {
662 case PROXY_USE_HTTP_PROXY:
663 // Although there is an "enabled" boolean in http_client_, it is not set
664 // to true by the proxy config utility. We ignore it and return false.
665 return false;
666 case PROXY_USE_SAME_PROXY:
667 // Similarly, although there is a "use-same-proxy" boolean in client_,
668 // it is never set to false by the proxy config utility. We ignore it.
669 return false;
670 case PROXY_USE_AUTHENTICATION:
671 // There is also no way to set this in the proxy config utility, but it
672 // doesn't hurt us to get the actual setting (unlike the two above).
673 return GetBoolByPath(http_client_, "use-authentication", result);
675 return false; // Placate compiler.
677 bool GetInt(IntSetting key, int* result) override {
678 DCHECK(client_);
679 switch (key) {
680 case PROXY_HTTP_PORT:
681 return GetIntByPath(http_client_, "port", result);
682 case PROXY_HTTPS_PORT:
683 return GetIntByPath(https_client_, "port", result);
684 case PROXY_FTP_PORT:
685 return GetIntByPath(ftp_client_, "port", result);
686 case PROXY_SOCKS_PORT:
687 return GetIntByPath(socks_client_, "port", result);
689 return false; // Placate compiler.
691 bool GetStringList(StringListSetting key,
692 std::vector<std::string>* result) override {
693 DCHECK(client_);
694 switch (key) {
695 case PROXY_IGNORE_HOSTS:
696 return GetStringListByPath(client_, "ignore-hosts", result);
698 return false; // Placate compiler.
701 bool BypassListIsReversed() override {
702 // This is a KDE-specific setting.
703 return false;
706 bool MatchHostsUsingSuffixMatching() override { return false; }
708 private:
709 bool GetStringByPath(GSettings* client, const char* key,
710 std::string* result) {
711 DCHECK(task_runner_->BelongsToCurrentThread());
712 gchar* value = libgio_loader_.g_settings_get_string(client, key);
713 if (!value)
714 return false;
715 *result = value;
716 g_free(value);
717 return true;
719 bool GetBoolByPath(GSettings* client, const char* key, bool* result) {
720 DCHECK(task_runner_->BelongsToCurrentThread());
721 *result = static_cast<bool>(
722 libgio_loader_.g_settings_get_boolean(client, key));
723 return true;
725 bool GetIntByPath(GSettings* client, const char* key, int* result) {
726 DCHECK(task_runner_->BelongsToCurrentThread());
727 *result = libgio_loader_.g_settings_get_int(client, key);
728 return true;
730 bool GetStringListByPath(GSettings* client, const char* key,
731 std::vector<std::string>* result) {
732 DCHECK(task_runner_->BelongsToCurrentThread());
733 gchar** list = libgio_loader_.g_settings_get_strv(client, key);
734 if (!list)
735 return false;
736 for (size_t i = 0; list[i]; ++i) {
737 result->push_back(static_cast<char*>(list[i]));
738 g_free(list[i]);
740 g_free(list);
741 return true;
744 // This is the callback from the debounce timer.
745 void OnDebouncedNotification() {
746 DCHECK(task_runner_->BelongsToCurrentThread());
747 CHECK(notify_delegate_);
748 // Forward to a method on the proxy config service delegate object.
749 notify_delegate_->OnCheckProxyConfigSettings();
752 void OnChangeNotification() {
753 // We don't use Reset() because the timer may not yet be running.
754 // (In that case Stop() is a no-op.)
755 debounce_timer_->Stop();
756 debounce_timer_->Start(FROM_HERE,
757 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
758 this, &SettingGetterImplGSettings::OnDebouncedNotification);
761 // gsettings notification callback, dispatched on the default glib main loop.
762 static void OnGSettingsChangeNotification(GSettings* client, gchar* key,
763 gpointer user_data) {
764 VLOG(1) << "gsettings change notification for key " << key;
765 // We don't track which key has changed, just that something did change.
766 SettingGetterImplGSettings* setting_getter =
767 reinterpret_cast<SettingGetterImplGSettings*>(user_data);
768 setting_getter->OnChangeNotification();
771 GSettings* client_;
772 GSettings* http_client_;
773 GSettings* https_client_;
774 GSettings* ftp_client_;
775 GSettings* socks_client_;
776 ProxyConfigServiceLinux::Delegate* notify_delegate_;
777 scoped_ptr<base::OneShotTimer<SettingGetterImplGSettings> > debounce_timer_;
779 // Task runner for the thread that we make gsettings calls on. It should
780 // be the UI thread and all our methods should be called on this
781 // thread. Only for assertions.
782 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
784 LibGioLoader libgio_loader_;
786 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings);
789 bool SettingGetterImplGSettings::LoadAndCheckVersion(
790 base::Environment* env) {
791 // LoadAndCheckVersion() must be called *before* Init()!
792 DCHECK(!client_);
794 // The APIs to query gsettings were introduced after the minimum glib
795 // version we target, so we can't link directly against them. We load them
796 // dynamically at runtime, and if they don't exist, return false here. (We
797 // support linking directly via gyp flags though.) Additionally, even when
798 // they are present, we do two additional checks to make sure we should use
799 // them and not gconf. First, we attempt to load the schema for proxy
800 // settings. Second, we check for the program that was used in older
801 // versions of GNOME to configure proxy settings, and return false if it
802 // exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
803 // but don't use gsettings for proxy settings, but they do have the old
804 // binary, so we detect these systems that way.
807 // TODO(phajdan.jr): Redesign the code to load library on different thread.
808 base::ThreadRestrictions::ScopedAllowIO allow_io;
810 // Try also without .0 at the end; on some systems this may be required.
811 if (!libgio_loader_.Load("libgio-2.0.so.0") &&
812 !libgio_loader_.Load("libgio-2.0.so")) {
813 VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
814 return false;
818 GSettings* client = NULL;
819 if (SchemaExists(kProxyGConfSchema)) {
820 ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/380782
821 client = libgio_loader_.g_settings_new(kProxyGConfSchema);
823 if (!client) {
824 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
825 return false;
827 g_object_unref(client);
829 std::string path;
830 if (!env->GetVar("PATH", &path)) {
831 LOG(ERROR) << "No $PATH variable. Assuming no gnome-network-properties.";
832 } else {
833 // Yes, we're on the UI thread. Yes, we're accessing the file system.
834 // Sadly, we don't have much choice. We need the proxy settings and we
835 // need them now, and to figure out where to get them, we have to check
836 // for this binary. See http://crbug.com/69057 for additional details.
837 base::ThreadRestrictions::ScopedAllowIO allow_io;
838 std::vector<std::string> paths;
839 Tokenize(path, ":", &paths);
840 for (size_t i = 0; i < paths.size(); ++i) {
841 base::FilePath file(paths[i]);
842 if (base::PathExists(file.Append("gnome-network-properties"))) {
843 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
844 return false;
849 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
850 return true;
852 #endif // defined(USE_GIO)
854 // This is the KDE version that reads kioslaverc and simulates gconf.
855 // Doing this allows the main Delegate code, as well as the unit tests
856 // for it, to stay the same - and the settings map fairly well besides.
857 class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter,
858 public base::MessagePumpLibevent::Watcher {
859 public:
860 explicit SettingGetterImplKDE(base::Environment* env_var_getter)
861 : inotify_fd_(-1),
862 notify_delegate_(NULL),
863 debounce_timer_(new base::OneShotTimer<SettingGetterImplKDE>()),
864 indirect_manual_(false),
865 auto_no_pac_(false),
866 reversed_bypass_list_(false),
867 env_var_getter_(env_var_getter),
868 file_task_runner_(NULL) {
869 // This has to be called on the UI thread (http://crbug.com/69057).
870 base::ThreadRestrictions::ScopedAllowIO allow_io;
872 // Derive the location of the kde config dir from the environment.
873 std::string home;
874 if (env_var_getter->GetVar("KDEHOME", &home) && !home.empty()) {
875 // $KDEHOME is set. Use it unconditionally.
876 kde_config_dir_ = KDEHomeToConfigPath(base::FilePath(home));
877 } else {
878 // $KDEHOME is unset. Try to figure out what to use. This seems to be
879 // the common case on most distributions.
880 if (!env_var_getter->GetVar(base::env_vars::kHome, &home))
881 // User has no $HOME? Give up. Later we'll report the failure.
882 return;
883 if (base::nix::GetDesktopEnvironment(env_var_getter) ==
884 base::nix::DESKTOP_ENVIRONMENT_KDE3) {
885 // KDE3 always uses .kde for its configuration.
886 base::FilePath kde_path = base::FilePath(home).Append(".kde");
887 kde_config_dir_ = KDEHomeToConfigPath(kde_path);
888 } else {
889 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
890 // both can be installed side-by-side. Sadly they don't all do this, and
891 // they don't always do this: some distributions have started switching
892 // back as well. So if there is a .kde4 directory, check the timestamps
893 // of the config directories within and use the newest one.
894 // Note that we should currently be running in the UI thread, because in
895 // the gconf version, that is the only thread that can access the proxy
896 // settings (a gconf restriction). As noted below, the initial read of
897 // the proxy settings will be done in this thread anyway, so we check
898 // for .kde4 here in this thread as well.
899 base::FilePath kde3_path = base::FilePath(home).Append(".kde");
900 base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
901 base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
902 base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
903 bool use_kde4 = false;
904 if (base::DirectoryExists(kde4_path)) {
905 base::File::Info kde3_info;
906 base::File::Info kde4_info;
907 if (base::GetFileInfo(kde4_config, &kde4_info)) {
908 if (base::GetFileInfo(kde3_config, &kde3_info)) {
909 use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
910 } else {
911 use_kde4 = true;
915 if (use_kde4) {
916 kde_config_dir_ = KDEHomeToConfigPath(kde4_path);
917 } else {
918 kde_config_dir_ = KDEHomeToConfigPath(kde3_path);
924 ~SettingGetterImplKDE() override {
925 // inotify_fd_ should have been closed before now, from
926 // Delegate::OnDestroy(), while running on the file thread. However
927 // on exiting the process, it may happen that Delegate::OnDestroy()
928 // task is left pending on the file loop after the loop was quit,
929 // and pending tasks may then be deleted without being run.
930 // Here in the KDE version, we can safely close the file descriptor
931 // anyway. (Not that it really matters; the process is exiting.)
932 if (inotify_fd_ >= 0)
933 ShutDown();
934 DCHECK(inotify_fd_ < 0);
937 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
938 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
939 override {
940 // This has to be called on the UI thread (http://crbug.com/69057).
941 base::ThreadRestrictions::ScopedAllowIO allow_io;
942 DCHECK(inotify_fd_ < 0);
943 inotify_fd_ = inotify_init();
944 if (inotify_fd_ < 0) {
945 PLOG(ERROR) << "inotify_init failed";
946 return false;
948 int flags = fcntl(inotify_fd_, F_GETFL);
949 if (fcntl(inotify_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
950 PLOG(ERROR) << "fcntl failed";
951 close(inotify_fd_);
952 inotify_fd_ = -1;
953 return false;
955 file_task_runner_ = file_task_runner;
956 // The initial read is done on the current thread, not
957 // |file_task_runner_|, since we will need to have it for
958 // SetUpAndFetchInitialConfig().
959 UpdateCachedSettings();
960 return true;
963 void ShutDown() override {
964 if (inotify_fd_ >= 0) {
965 ResetCachedSettings();
966 inotify_watcher_.StopWatchingFileDescriptor();
967 close(inotify_fd_);
968 inotify_fd_ = -1;
970 debounce_timer_.reset();
973 bool SetUpNotifications(
974 ProxyConfigServiceLinux::Delegate* delegate) override {
975 DCHECK(inotify_fd_ >= 0);
976 DCHECK(file_task_runner_->BelongsToCurrentThread());
977 // We can't just watch the kioslaverc file directly, since KDE will write
978 // a new copy of it and then rename it whenever settings are changed and
979 // inotify watches inodes (so we'll be watching the old deleted file after
980 // the first change, and it will never change again). So, we watch the
981 // directory instead. We then act only on changes to the kioslaverc entry.
982 if (inotify_add_watch(inotify_fd_, kde_config_dir_.value().c_str(),
983 IN_MODIFY | IN_MOVED_TO) < 0) {
984 return false;
986 notify_delegate_ = delegate;
987 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
988 inotify_fd_, true, base::MessageLoopForIO::WATCH_READ,
989 &inotify_watcher_, this)) {
990 return false;
992 // Simulate a change to avoid possibly losing updates before this point.
993 OnChangeNotification();
994 return true;
997 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
998 override {
999 return file_task_runner_;
1002 // Implement base::MessagePumpLibevent::Watcher.
1003 void OnFileCanReadWithoutBlocking(int fd) override {
1004 DCHECK_EQ(fd, inotify_fd_);
1005 DCHECK(file_task_runner_->BelongsToCurrentThread());
1006 OnChangeNotification();
1008 void OnFileCanWriteWithoutBlocking(int fd) override { NOTREACHED(); }
1010 ProxyConfigSource GetConfigSource() override {
1011 return PROXY_CONFIG_SOURCE_KDE;
1014 bool GetString(StringSetting key, std::string* result) override {
1015 string_map_type::iterator it = string_table_.find(key);
1016 if (it == string_table_.end())
1017 return false;
1018 *result = it->second;
1019 return true;
1021 bool GetBool(BoolSetting key, bool* result) override {
1022 // We don't ever have any booleans.
1023 return false;
1025 bool GetInt(IntSetting key, int* result) override {
1026 // We don't ever have any integers. (See AddProxy() below about ports.)
1027 return false;
1029 bool GetStringList(StringListSetting key,
1030 std::vector<std::string>* result) override {
1031 strings_map_type::iterator it = strings_table_.find(key);
1032 if (it == strings_table_.end())
1033 return false;
1034 *result = it->second;
1035 return true;
1038 bool BypassListIsReversed() override { return reversed_bypass_list_; }
1040 bool MatchHostsUsingSuffixMatching() override { return true; }
1042 private:
1043 void ResetCachedSettings() {
1044 string_table_.clear();
1045 strings_table_.clear();
1046 indirect_manual_ = false;
1047 auto_no_pac_ = false;
1048 reversed_bypass_list_ = false;
1051 base::FilePath KDEHomeToConfigPath(const base::FilePath& kde_home) {
1052 return kde_home.Append("share").Append("config");
1055 void AddProxy(StringSetting host_key, const std::string& value) {
1056 if (value.empty() || value.substr(0, 3) == "//:")
1057 // No proxy.
1058 return;
1059 size_t space = value.find(' ');
1060 if (space != std::string::npos) {
1061 // Newer versions of KDE use a space rather than a colon to separate the
1062 // port number from the hostname. If we find this, we need to convert it.
1063 std::string fixed = value;
1064 fixed[space] = ':';
1065 string_table_[host_key] = fixed;
1066 } else {
1067 // We don't need to parse the port number out; GetProxyFromSettings()
1068 // would only append it right back again. So we just leave the port
1069 // number right in the host string.
1070 string_table_[host_key] = value;
1074 void AddHostList(StringListSetting key, const std::string& value) {
1075 std::vector<std::string> tokens;
1076 base::StringTokenizer tk(value, ", ");
1077 while (tk.GetNext()) {
1078 std::string token = tk.token();
1079 if (!token.empty())
1080 tokens.push_back(token);
1082 strings_table_[key] = tokens;
1085 void AddKDESetting(const std::string& key, const std::string& value) {
1086 if (key == "ProxyType") {
1087 const char* mode = "none";
1088 indirect_manual_ = false;
1089 auto_no_pac_ = false;
1090 int int_value;
1091 base::StringToInt(value, &int_value);
1092 switch (int_value) {
1093 case 0: // No proxy, or maybe kioslaverc syntax error.
1094 break;
1095 case 1: // Manual configuration.
1096 mode = "manual";
1097 break;
1098 case 2: // PAC URL.
1099 mode = "auto";
1100 break;
1101 case 3: // WPAD.
1102 mode = "auto";
1103 auto_no_pac_ = true;
1104 break;
1105 case 4: // Indirect manual via environment variables.
1106 mode = "manual";
1107 indirect_manual_ = true;
1108 break;
1110 string_table_[PROXY_MODE] = mode;
1111 } else if (key == "Proxy Config Script") {
1112 string_table_[PROXY_AUTOCONF_URL] = value;
1113 } else if (key == "httpProxy") {
1114 AddProxy(PROXY_HTTP_HOST, value);
1115 } else if (key == "httpsProxy") {
1116 AddProxy(PROXY_HTTPS_HOST, value);
1117 } else if (key == "ftpProxy") {
1118 AddProxy(PROXY_FTP_HOST, value);
1119 } else if (key == "socksProxy") {
1120 // Older versions of KDE configure SOCKS in a weird way involving
1121 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1122 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1123 AddProxy(PROXY_SOCKS_HOST, value);
1124 } else if (key == "ReversedException") {
1125 // We count "true" or any nonzero number as true, otherwise false.
1126 // Note that if the value is not actually numeric StringToInt()
1127 // will return 0, which we count as false.
1128 int int_value;
1129 base::StringToInt(value, &int_value);
1130 reversed_bypass_list_ = (value == "true" || int_value);
1131 } else if (key == "NoProxyFor") {
1132 AddHostList(PROXY_IGNORE_HOSTS, value);
1133 } else if (key == "AuthMode") {
1134 // Check for authentication, just so we can warn.
1135 int mode;
1136 base::StringToInt(value, &mode);
1137 if (mode) {
1138 // ProxyConfig does not support authentication parameters, but
1139 // Chrome will prompt for the password later. So we ignore this.
1140 LOG(WARNING) <<
1141 "Proxy authentication parameters ignored, see bug 16709";
1146 void ResolveIndirect(StringSetting key) {
1147 string_map_type::iterator it = string_table_.find(key);
1148 if (it != string_table_.end()) {
1149 std::string value;
1150 if (env_var_getter_->GetVar(it->second.c_str(), &value))
1151 it->second = value;
1152 else
1153 string_table_.erase(it);
1157 void ResolveIndirectList(StringListSetting key) {
1158 strings_map_type::iterator it = strings_table_.find(key);
1159 if (it != strings_table_.end()) {
1160 std::string value;
1161 if (!it->second.empty() &&
1162 env_var_getter_->GetVar(it->second[0].c_str(), &value))
1163 AddHostList(key, value);
1164 else
1165 strings_table_.erase(it);
1169 // The settings in kioslaverc could occur in any order, but some affect
1170 // others. Rather than read the whole file in and then query them in an
1171 // order that allows us to handle that, we read the settings in whatever
1172 // order they occur and do any necessary tweaking after we finish.
1173 void ResolveModeEffects() {
1174 if (indirect_manual_) {
1175 ResolveIndirect(PROXY_HTTP_HOST);
1176 ResolveIndirect(PROXY_HTTPS_HOST);
1177 ResolveIndirect(PROXY_FTP_HOST);
1178 ResolveIndirectList(PROXY_IGNORE_HOSTS);
1180 if (auto_no_pac_) {
1181 // Remove the PAC URL; we're not supposed to use it.
1182 string_table_.erase(PROXY_AUTOCONF_URL);
1186 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1187 // each relevant name-value pair to the appropriate value table.
1188 void UpdateCachedSettings() {
1189 base::FilePath kioslaverc = kde_config_dir_.Append("kioslaverc");
1190 base::ScopedFILE input(base::OpenFile(kioslaverc, "r"));
1191 if (!input.get())
1192 return;
1193 ResetCachedSettings();
1194 bool in_proxy_settings = false;
1195 bool line_too_long = false;
1196 char line[BUFFER_SIZE];
1197 // fgets() will return NULL on EOF or error.
1198 while (fgets(line, sizeof(line), input.get())) {
1199 // fgets() guarantees the line will be properly terminated.
1200 size_t length = strlen(line);
1201 if (!length)
1202 continue;
1203 // This should be true even with CRLF endings.
1204 if (line[length - 1] != '\n') {
1205 line_too_long = true;
1206 continue;
1208 if (line_too_long) {
1209 // The previous line had no line ending, but this done does. This is
1210 // the end of the line that was too long, so warn here and skip it.
1211 LOG(WARNING) << "skipped very long line in " << kioslaverc.value();
1212 line_too_long = false;
1213 continue;
1215 // Remove the LF at the end, and the CR if there is one.
1216 line[--length] = '\0';
1217 if (length && line[length - 1] == '\r')
1218 line[--length] = '\0';
1219 // Now parse the line.
1220 if (line[0] == '[') {
1221 // Switching sections. All we care about is whether this is
1222 // the (a?) proxy settings section, for both KDE3 and KDE4.
1223 in_proxy_settings = !strncmp(line, "[Proxy Settings]", 16);
1224 } else if (in_proxy_settings) {
1225 // A regular line, in the (a?) proxy settings section.
1226 char* split = strchr(line, '=');
1227 // Skip this line if it does not contain an = sign.
1228 if (!split)
1229 continue;
1230 // Split the line on the = and advance |split|.
1231 *(split++) = 0;
1232 std::string key = line;
1233 std::string value = split;
1234 base::TrimWhitespaceASCII(key, base::TRIM_ALL, &key);
1235 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
1236 // Skip this line if the key name is empty.
1237 if (key.empty())
1238 continue;
1239 // Is the value name localized?
1240 if (key[key.length() - 1] == ']') {
1241 // Find the matching bracket.
1242 length = key.rfind('[');
1243 // Skip this line if the localization indicator is malformed.
1244 if (length == std::string::npos)
1245 continue;
1246 // Trim the localization indicator off.
1247 key.resize(length);
1248 // Remove any resulting trailing whitespace.
1249 base::TrimWhitespaceASCII(key, base::TRIM_TRAILING, &key);
1250 // Skip this line if the key name is now empty.
1251 if (key.empty())
1252 continue;
1254 // Now fill in the tables.
1255 AddKDESetting(key, value);
1258 if (ferror(input.get()))
1259 LOG(ERROR) << "error reading " << kioslaverc.value();
1260 ResolveModeEffects();
1263 // This is the callback from the debounce timer.
1264 void OnDebouncedNotification() {
1265 DCHECK(file_task_runner_->BelongsToCurrentThread());
1266 VLOG(1) << "inotify change notification for kioslaverc";
1267 UpdateCachedSettings();
1268 CHECK(notify_delegate_);
1269 // Forward to a method on the proxy config service delegate object.
1270 notify_delegate_->OnCheckProxyConfigSettings();
1273 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1274 // from the inotify file descriptor and starts up a debounce timer if
1275 // an event for kioslaverc is seen.
1276 void OnChangeNotification() {
1277 DCHECK_GE(inotify_fd_, 0);
1278 DCHECK(file_task_runner_->BelongsToCurrentThread());
1279 char event_buf[(sizeof(inotify_event) + NAME_MAX + 1) * 4];
1280 bool kioslaverc_touched = false;
1281 ssize_t r;
1282 while ((r = read(inotify_fd_, event_buf, sizeof(event_buf))) > 0) {
1283 // inotify returns variable-length structures, which is why we have
1284 // this strange-looking loop instead of iterating through an array.
1285 char* event_ptr = event_buf;
1286 while (event_ptr < event_buf + r) {
1287 inotify_event* event = reinterpret_cast<inotify_event*>(event_ptr);
1288 // The kernel always feeds us whole events.
1289 CHECK_LE(event_ptr + sizeof(inotify_event), event_buf + r);
1290 CHECK_LE(event->name + event->len, event_buf + r);
1291 if (!strcmp(event->name, "kioslaverc"))
1292 kioslaverc_touched = true;
1293 // Advance the pointer just past the end of the filename.
1294 event_ptr = event->name + event->len;
1296 // We keep reading even if |kioslaverc_touched| is true to drain the
1297 // inotify event queue.
1299 if (!r)
1300 // Instead of returning -1 and setting errno to EINVAL if there is not
1301 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1302 // new behavior (EINVAL) so we can reuse the code below.
1303 errno = EINVAL;
1304 if (errno != EAGAIN) {
1305 PLOG(WARNING) << "error reading inotify file descriptor";
1306 if (errno == EINVAL) {
1307 // Our buffer is not large enough to read the next event. This should
1308 // not happen (because its size is calculated to always be sufficiently
1309 // large), but if it does we'd warn continuously since |inotify_fd_|
1310 // would be forever ready to read. Close it and stop watching instead.
1311 LOG(ERROR) << "inotify failure; no longer watching kioslaverc!";
1312 inotify_watcher_.StopWatchingFileDescriptor();
1313 close(inotify_fd_);
1314 inotify_fd_ = -1;
1317 if (kioslaverc_touched) {
1318 // We don't use Reset() because the timer may not yet be running.
1319 // (In that case Stop() is a no-op.)
1320 debounce_timer_->Stop();
1321 debounce_timer_->Start(FROM_HERE, base::TimeDelta::FromMilliseconds(
1322 kDebounceTimeoutMilliseconds), this,
1323 &SettingGetterImplKDE::OnDebouncedNotification);
1327 typedef std::map<StringSetting, std::string> string_map_type;
1328 typedef std::map<StringListSetting,
1329 std::vector<std::string> > strings_map_type;
1331 int inotify_fd_;
1332 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_;
1333 ProxyConfigServiceLinux::Delegate* notify_delegate_;
1334 scoped_ptr<base::OneShotTimer<SettingGetterImplKDE> > debounce_timer_;
1335 base::FilePath kde_config_dir_;
1336 bool indirect_manual_;
1337 bool auto_no_pac_;
1338 bool reversed_bypass_list_;
1339 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1340 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1341 // same lifetime.
1342 base::Environment* env_var_getter_;
1344 // We cache these settings whenever we re-read the kioslaverc file.
1345 string_map_type string_table_;
1346 strings_map_type strings_table_;
1348 // Task runner of the file thread, for reading kioslaverc. If NULL,
1349 // just read it directly (for testing). We also handle inotify events
1350 // on this thread.
1351 scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_;
1353 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE);
1356 } // namespace
1358 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1359 SettingGetter::StringSetting host_key,
1360 ProxyServer* result_server) {
1361 std::string host;
1362 if (!setting_getter_->GetString(host_key, &host) || host.empty()) {
1363 // Unset or empty.
1364 return false;
1366 // Check for an optional port.
1367 int port = 0;
1368 SettingGetter::IntSetting port_key =
1369 SettingGetter::HostSettingToPortSetting(host_key);
1370 setting_getter_->GetInt(port_key, &port);
1371 if (port != 0) {
1372 // If a port is set and non-zero:
1373 host += ":" + base::IntToString(port);
1376 // gconf settings do not appear to distinguish between SOCKS version. We
1377 // default to version 5. For more information on this policy decision, see:
1378 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1379 ProxyServer::Scheme scheme = (host_key == SettingGetter::PROXY_SOCKS_HOST) ?
1380 ProxyServer::SCHEME_SOCKS5 : ProxyServer::SCHEME_HTTP;
1381 host = FixupProxyHostScheme(scheme, host);
1382 ProxyServer proxy_server = ProxyServer::FromURI(host,
1383 ProxyServer::SCHEME_HTTP);
1384 if (proxy_server.is_valid()) {
1385 *result_server = proxy_server;
1386 return true;
1388 return false;
1391 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1392 ProxyConfig* config) {
1393 std::string mode;
1394 if (!setting_getter_->GetString(SettingGetter::PROXY_MODE, &mode)) {
1395 // We expect this to always be set, so if we don't see it then we
1396 // probably have a gconf/gsettings problem, and so we don't have a valid
1397 // proxy config.
1398 return false;
1400 if (mode == "none") {
1401 // Specifically specifies no proxy.
1402 return true;
1405 if (mode == "auto") {
1406 // Automatic proxy config.
1407 std::string pac_url_str;
1408 if (setting_getter_->GetString(SettingGetter::PROXY_AUTOCONF_URL,
1409 &pac_url_str)) {
1410 if (!pac_url_str.empty()) {
1411 // If the PAC URL is actually a file path, then put file:// in front.
1412 if (pac_url_str[0] == '/')
1413 pac_url_str = "file://" + pac_url_str;
1414 GURL pac_url(pac_url_str);
1415 if (!pac_url.is_valid())
1416 return false;
1417 config->set_pac_url(pac_url);
1418 return true;
1421 config->set_auto_detect(true);
1422 return true;
1425 if (mode != "manual") {
1426 // Mode is unrecognized.
1427 return false;
1429 bool use_http_proxy;
1430 if (setting_getter_->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY,
1431 &use_http_proxy)
1432 && !use_http_proxy) {
1433 // Another master switch for some reason. If set to false, then no
1434 // proxy. But we don't panic if the key doesn't exist.
1435 return true;
1438 bool same_proxy = false;
1439 // Indicates to use the http proxy for all protocols. This one may
1440 // not exist (presumably on older versions); we assume false in that
1441 // case.
1442 setting_getter_->GetBool(SettingGetter::PROXY_USE_SAME_PROXY,
1443 &same_proxy);
1445 ProxyServer proxy_for_http;
1446 ProxyServer proxy_for_https;
1447 ProxyServer proxy_for_ftp;
1448 ProxyServer socks_proxy; // (socks)
1450 // This counts how many of the above ProxyServers were defined and valid.
1451 size_t num_proxies_specified = 0;
1453 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1454 // specified for the scheme, then the resulting ProxyServer will be invalid.
1455 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST, &proxy_for_http))
1456 num_proxies_specified++;
1457 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST, &proxy_for_https))
1458 num_proxies_specified++;
1459 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST, &proxy_for_ftp))
1460 num_proxies_specified++;
1461 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST, &socks_proxy))
1462 num_proxies_specified++;
1464 if (same_proxy) {
1465 if (proxy_for_http.is_valid()) {
1466 // Use the http proxy for all schemes.
1467 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1468 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_for_http);
1470 } else if (num_proxies_specified > 0) {
1471 if (socks_proxy.is_valid() && num_proxies_specified == 1) {
1472 // If the only proxy specified was for SOCKS, use it for all schemes.
1473 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1474 config->proxy_rules().single_proxies.SetSingleProxyServer(socks_proxy);
1475 } else {
1476 // Otherwise use the indicated proxies per-scheme.
1477 config->proxy_rules().type =
1478 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
1479 config->proxy_rules().proxies_for_http.
1480 SetSingleProxyServer(proxy_for_http);
1481 config->proxy_rules().proxies_for_https.
1482 SetSingleProxyServer(proxy_for_https);
1483 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_for_ftp);
1484 config->proxy_rules().fallback_proxies.SetSingleProxyServer(socks_proxy);
1488 if (config->proxy_rules().empty()) {
1489 // Manual mode but we couldn't parse any rules.
1490 return false;
1493 // Check for authentication, just so we can warn.
1494 bool use_auth = false;
1495 setting_getter_->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION,
1496 &use_auth);
1497 if (use_auth) {
1498 // ProxyConfig does not support authentication parameters, but
1499 // Chrome will prompt for the password later. So we ignore
1500 // /system/http_proxy/*auth* settings.
1501 LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
1504 // Now the bypass list.
1505 std::vector<std::string> ignore_hosts_list;
1506 config->proxy_rules().bypass_rules.Clear();
1507 if (setting_getter_->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS,
1508 &ignore_hosts_list)) {
1509 std::vector<std::string>::const_iterator it(ignore_hosts_list.begin());
1510 for (; it != ignore_hosts_list.end(); ++it) {
1511 if (setting_getter_->MatchHostsUsingSuffixMatching()) {
1512 config->proxy_rules().bypass_rules.
1513 AddRuleFromStringUsingSuffixMatching(*it);
1514 } else {
1515 config->proxy_rules().bypass_rules.AddRuleFromString(*it);
1519 // Note that there are no settings with semantics corresponding to
1520 // bypass of local names in GNOME. In KDE, "<local>" is supported
1521 // as a hostname rule.
1523 // KDE allows one to reverse the bypass rules.
1524 config->proxy_rules().reverse_bypass =
1525 setting_getter_->BypassListIsReversed();
1527 return true;
1530 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment* env_var_getter)
1531 : env_var_getter_(env_var_getter) {
1532 // Figure out which SettingGetterImpl to use, if any.
1533 switch (base::nix::GetDesktopEnvironment(env_var_getter)) {
1534 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
1535 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
1536 #if defined(USE_GIO)
1538 scoped_ptr<SettingGetterImplGSettings> gs_getter(
1539 new SettingGetterImplGSettings());
1540 // We have to load symbols and check the GNOME version in use to decide
1541 // if we should use the gsettings getter. See LoadAndCheckVersion().
1542 if (gs_getter->LoadAndCheckVersion(env_var_getter))
1543 setting_getter_.reset(gs_getter.release());
1545 #endif
1546 #if defined(USE_GCONF)
1547 // Fall back on gconf if gsettings is unavailable or incorrect.
1548 if (!setting_getter_.get())
1549 setting_getter_.reset(new SettingGetterImplGConf());
1550 #endif
1551 break;
1552 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
1553 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
1554 setting_getter_.reset(new SettingGetterImplKDE(env_var_getter));
1555 break;
1556 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
1557 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
1558 break;
1562 ProxyConfigServiceLinux::Delegate::Delegate(
1563 base::Environment* env_var_getter, SettingGetter* setting_getter)
1564 : env_var_getter_(env_var_getter), setting_getter_(setting_getter) {
1567 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1568 const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
1569 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
1570 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner) {
1571 // We should be running on the default glib main loop thread right
1572 // now. gconf can only be accessed from this thread.
1573 DCHECK(glib_task_runner->BelongsToCurrentThread());
1574 glib_task_runner_ = glib_task_runner;
1575 io_task_runner_ = io_task_runner;
1577 // If we are passed a NULL |io_task_runner| or |file_task_runner|, then we
1578 // don't set up proxy setting change notifications. This should not be the
1579 // usual case but is intended to/ simplify test setups.
1580 if (!io_task_runner_.get() || !file_task_runner.get())
1581 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1583 // Fetch and cache the current proxy config. The config is left in
1584 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1585 // will expect to find it. This is safe to do because we return
1586 // before this ProxyConfigServiceLinux is passed on to
1587 // the ProxyService.
1589 // Note: It would be nice to prioritize environment variables
1590 // and only fall back to gconf if env vars were unset. But
1591 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1592 // does so even if the proxy mode is set to auto, which would
1593 // mislead us.
1595 bool got_config = false;
1596 if (setting_getter_.get() &&
1597 setting_getter_->Init(glib_task_runner, file_task_runner) &&
1598 GetConfigFromSettings(&cached_config_)) {
1599 cached_config_.set_id(1); // Mark it as valid.
1600 cached_config_.set_source(setting_getter_->GetConfigSource());
1601 VLOG(1) << "Obtained proxy settings from "
1602 << ProxyConfigSourceToString(cached_config_.source());
1604 // If gconf proxy mode is "none", meaning direct, then we take
1605 // that to be a valid config and will not check environment
1606 // variables. The alternative would have been to look for a proxy
1607 // whereever we can find one.
1608 got_config = true;
1610 // Keep a copy of the config for use from this thread for
1611 // comparison with updated settings when we get notifications.
1612 reference_config_ = cached_config_;
1613 reference_config_.set_id(1); // Mark it as valid.
1615 // We only set up notifications if we have IO and file loops available.
1616 // We do this after getting the initial configuration so that we don't have
1617 // to worry about cancelling it if the initial fetch above fails. Note that
1618 // setting up notifications has the side effect of simulating a change, so
1619 // that we won't lose any updates that may have happened after the initial
1620 // fetch and before setting up notifications. We'll detect the common case
1621 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1622 if (io_task_runner.get() && file_task_runner.get()) {
1623 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1624 setting_getter_->GetNotificationTaskRunner();
1625 if (!required_loop.get() || required_loop->BelongsToCurrentThread()) {
1626 // In this case we are already on an acceptable thread.
1627 SetUpNotifications();
1628 } else {
1629 // Post a task to set up notifications. We don't wait for success.
1630 required_loop->PostTask(FROM_HERE, base::Bind(
1631 &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this));
1636 if (!got_config) {
1637 // We fall back on environment variables.
1639 // Consulting environment variables doesn't need to be done from the
1640 // default glib main loop, but it's a tiny enough amount of work.
1641 if (GetConfigFromEnv(&cached_config_)) {
1642 cached_config_.set_source(PROXY_CONFIG_SOURCE_ENV);
1643 cached_config_.set_id(1); // Mark it as valid.
1644 VLOG(1) << "Obtained proxy settings from environment variables";
1649 // Depending on the SettingGetter in use, this method will be called
1650 // on either the UI thread (GConf) or the file thread (KDE).
1651 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1652 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1653 setting_getter_->GetNotificationTaskRunner();
1654 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1655 if (!setting_getter_->SetUpNotifications(this))
1656 LOG(ERROR) << "Unable to set up proxy configuration change notifications";
1659 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer* observer) {
1660 observers_.AddObserver(observer);
1663 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer* observer) {
1664 observers_.RemoveObserver(observer);
1667 ProxyConfigService::ConfigAvailability
1668 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1669 ProxyConfig* config) {
1670 // This is called from the IO thread.
1671 DCHECK(!io_task_runner_.get() ||
1672 io_task_runner_->BelongsToCurrentThread());
1674 // Simply return the last proxy configuration that glib_default_loop
1675 // notified us of.
1676 if (cached_config_.is_valid()) {
1677 *config = cached_config_;
1678 } else {
1679 *config = ProxyConfig::CreateDirect();
1680 config->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED);
1683 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1684 // going to be available since we initialized eagerly on the UI thread.
1685 // TODO(eroman): do lazy initialization instead, so we no longer need
1686 // to construct ProxyConfigServiceLinux on the UI thread.
1687 // In which case, we may return false here.
1688 return CONFIG_VALID;
1691 // Depending on the SettingGetter in use, this method will be called
1692 // on either the UI thread (GConf) or the file thread (KDE).
1693 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1694 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1695 setting_getter_->GetNotificationTaskRunner();
1696 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1697 ProxyConfig new_config;
1698 bool valid = GetConfigFromSettings(&new_config);
1699 if (valid)
1700 new_config.set_id(1); // mark it as valid
1702 // See if it is different from what we had before.
1703 if (new_config.is_valid() != reference_config_.is_valid() ||
1704 !new_config.Equals(reference_config_)) {
1705 // Post a task to the IO thread with the new configuration, so it can
1706 // update |cached_config_|.
1707 io_task_runner_->PostTask(FROM_HERE, base::Bind(
1708 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig,
1709 this, new_config));
1710 // Update the thread-private copy in |reference_config_| as well.
1711 reference_config_ = new_config;
1712 } else {
1713 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1717 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1718 const ProxyConfig& new_config) {
1719 DCHECK(io_task_runner_->BelongsToCurrentThread());
1720 VLOG(1) << "Proxy configuration changed";
1721 cached_config_ = new_config;
1722 FOR_EACH_OBSERVER(
1723 Observer, observers_,
1724 OnProxyConfigChanged(new_config, ProxyConfigService::CONFIG_VALID));
1727 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1728 if (!setting_getter_.get())
1729 return;
1730 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1731 setting_getter_->GetNotificationTaskRunner();
1732 if (!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread()) {
1733 // Already on the right thread, call directly.
1734 // This is the case for the unittests.
1735 OnDestroy();
1736 } else {
1737 // Post to shutdown thread. Note that on browser shutdown, we may quit
1738 // this MessageLoop and exit the program before ever running this.
1739 shutdown_loop->PostTask(FROM_HERE, base::Bind(
1740 &ProxyConfigServiceLinux::Delegate::OnDestroy, this));
1743 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1744 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1745 setting_getter_->GetNotificationTaskRunner();
1746 DCHECK(!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread());
1747 setting_getter_->ShutDown();
1750 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1751 : delegate_(new Delegate(base::Environment::Create())) {
1754 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1755 delegate_->PostDestroyTask();
1758 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1759 base::Environment* env_var_getter)
1760 : delegate_(new Delegate(env_var_getter)) {
1763 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1764 base::Environment* env_var_getter, SettingGetter* setting_getter)
1765 : delegate_(new Delegate(env_var_getter, setting_getter)) {
1768 void ProxyConfigServiceLinux::AddObserver(Observer* observer) {
1769 delegate_->AddObserver(observer);
1772 void ProxyConfigServiceLinux::RemoveObserver(Observer* observer) {
1773 delegate_->RemoveObserver(observer);
1776 ProxyConfigService::ConfigAvailability
1777 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig* config) {
1778 return delegate_->GetLatestProxyConfig(config);
1781 } // namespace net