Only commit cookie changes in prerenders after a prerender is shown
[chromium-blink-merge.git] / net / proxy / proxy_config_service_linux.cc
blob0e65b72c12acc4f561873b9e8a252ec6b7cbbd70
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/proxy/proxy_config_service_linux.h"
7 // glib >=2.40 deprecate g_settings_list_schemas in favor of
8 // g_settings_schema_source_list_schemas. This function is not available on
9 // earlier versions that we still need to support (specifically, 2.32), so
10 // disable the warning.
11 // TODO(mgiuca): Remove this suppression when we drop support for Ubuntu 13.10
12 // (saucy) and earlier. Update the code to use
13 // g_settings_schema_source_list_schemas instead.
14 #define GLIB_DISABLE_DEPRECATION_WARNINGS
16 #include <errno.h>
17 #include <fcntl.h>
18 #if defined(USE_GCONF)
19 #include <gconf/gconf-client.h>
20 #endif // defined(USE_GCONF)
21 #include <limits.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/inotify.h>
25 #include <unistd.h>
27 #include <map>
29 #include "base/bind.h"
30 #include "base/compiler_specific.h"
31 #include "base/environment.h"
32 #include "base/file_util.h"
33 #include "base/files/file_path.h"
34 #include "base/files/scoped_file.h"
35 #include "base/logging.h"
36 #include "base/message_loop/message_loop.h"
37 #include "base/nix/xdg_util.h"
38 #include "base/single_thread_task_runner.h"
39 #include "base/strings/string_number_conversions.h"
40 #include "base/strings/string_tokenizer.h"
41 #include "base/strings/string_util.h"
42 #include "base/threading/thread_restrictions.h"
43 #include "base/timer/timer.h"
44 #include "net/base/net_errors.h"
45 #include "net/http/http_util.h"
46 #include "net/proxy/proxy_config.h"
47 #include "net/proxy/proxy_server.h"
48 #include "url/url_canon.h"
50 #if defined(USE_GIO)
51 #include "library_loaders/libgio.h"
52 #endif // defined(USE_GIO)
54 namespace net {
56 namespace {
58 // Given a proxy hostname from a setting, returns that hostname with
59 // an appropriate proxy server scheme prefix.
60 // scheme indicates the desired proxy scheme: usually http, with
61 // socks 4 or 5 as special cases.
62 // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
63 std::string FixupProxyHostScheme(ProxyServer::Scheme scheme,
64 std::string host) {
65 if (scheme == ProxyServer::SCHEME_SOCKS5 &&
66 StartsWithASCII(host, "socks4://", false)) {
67 // We default to socks 5, but if the user specifically set it to
68 // socks4://, then use that.
69 scheme = ProxyServer::SCHEME_SOCKS4;
71 // Strip the scheme if any.
72 std::string::size_type colon = host.find("://");
73 if (colon != std::string::npos)
74 host = host.substr(colon + 3);
75 // If a username and perhaps password are specified, give a warning.
76 std::string::size_type at_sign = host.find("@");
77 // Should this be supported?
78 if (at_sign != std::string::npos) {
79 // ProxyConfig does not support authentication parameters, but Chrome
80 // will prompt for the password later. Disregard the
81 // authentication parameters and continue with this hostname.
82 LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
83 host = host.substr(at_sign + 1);
85 // If this is a socks proxy, prepend a scheme so as to tell
86 // ProxyServer. This also allows ProxyServer to choose the right
87 // default port.
88 if (scheme == ProxyServer::SCHEME_SOCKS4)
89 host = "socks4://" + host;
90 else if (scheme == ProxyServer::SCHEME_SOCKS5)
91 host = "socks5://" + host;
92 // If there is a trailing slash, remove it so |host| will parse correctly
93 // even if it includes a port number (since the slash is not numeric).
94 if (host.length() && host[host.length() - 1] == '/')
95 host.resize(host.length() - 1);
96 return host;
99 } // namespace
101 ProxyConfigServiceLinux::Delegate::~Delegate() {
104 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
105 const char* variable, ProxyServer::Scheme scheme,
106 ProxyServer* result_server) {
107 std::string env_value;
108 if (env_var_getter_->GetVar(variable, &env_value)) {
109 if (!env_value.empty()) {
110 env_value = FixupProxyHostScheme(scheme, env_value);
111 ProxyServer proxy_server =
112 ProxyServer::FromURI(env_value, ProxyServer::SCHEME_HTTP);
113 if (proxy_server.is_valid() && !proxy_server.is_direct()) {
114 *result_server = proxy_server;
115 return true;
116 } else {
117 LOG(ERROR) << "Failed to parse environment variable " << variable;
121 return false;
124 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
125 const char* variable, ProxyServer* result_server) {
126 return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
127 result_server);
130 bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig* config) {
131 // Check for automatic configuration first, in
132 // "auto_proxy". Possibly only the "environment_proxy" firefox
133 // extension has ever used this, but it still sounds like a good
134 // idea.
135 std::string auto_proxy;
136 if (env_var_getter_->GetVar("auto_proxy", &auto_proxy)) {
137 if (auto_proxy.empty()) {
138 // Defined and empty => autodetect
139 config->set_auto_detect(true);
140 } else {
141 // specified autoconfig URL
142 config->set_pac_url(GURL(auto_proxy));
144 return true;
146 // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
147 ProxyServer proxy_server;
148 if (GetProxyFromEnvVar("all_proxy", &proxy_server)) {
149 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
150 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
151 } else {
152 bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_server);
153 if (have_http)
154 config->proxy_rules().proxies_for_http.SetSingleProxyServer(proxy_server);
155 // It would be tempting to let http_proxy apply for all protocols
156 // if https_proxy and ftp_proxy are not defined. Googling turns up
157 // several documents that mention only http_proxy. But then the
158 // user really might not want to proxy https. And it doesn't seem
159 // like other apps do this. So we will refrain.
160 bool have_https = GetProxyFromEnvVar("https_proxy", &proxy_server);
161 if (have_https)
162 config->proxy_rules().proxies_for_https.
163 SetSingleProxyServer(proxy_server);
164 bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_server);
165 if (have_ftp)
166 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_server);
167 if (have_http || have_https || have_ftp) {
168 // mustn't change type unless some rules are actually set.
169 config->proxy_rules().type =
170 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
173 if (config->proxy_rules().empty()) {
174 // If the above were not defined, try for socks.
175 // For environment variables, we default to version 5, per the gnome
176 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
177 ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
178 std::string env_version;
179 if (env_var_getter_->GetVar("SOCKS_VERSION", &env_version)
180 && env_version == "4")
181 scheme = ProxyServer::SCHEME_SOCKS4;
182 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_server)) {
183 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
184 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
187 // Look for the proxy bypass list.
188 std::string no_proxy;
189 env_var_getter_->GetVar("no_proxy", &no_proxy);
190 if (config->proxy_rules().empty()) {
191 // Having only "no_proxy" set, presumably to "*", makes it
192 // explicit that env vars do specify a configuration: having no
193 // rules specified only means the user explicitly asks for direct
194 // connections.
195 return !no_proxy.empty();
197 // Note that this uses "suffix" matching. So a bypass of "google.com"
198 // is understood to mean a bypass of "*google.com".
199 config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
200 no_proxy);
201 return true;
204 namespace {
206 const int kDebounceTimeoutMilliseconds = 250;
208 #if defined(USE_GCONF)
209 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
210 class SettingGetterImplGConf : public ProxyConfigServiceLinux::SettingGetter {
211 public:
212 SettingGetterImplGConf()
213 : client_(NULL), system_proxy_id_(0), system_http_proxy_id_(0),
214 notify_delegate_(NULL) {
217 virtual ~SettingGetterImplGConf() {
218 // client_ should have been released before now, from
219 // Delegate::OnDestroy(), while running on the UI thread. However
220 // on exiting the process, it may happen that Delegate::OnDestroy()
221 // task is left pending on the glib loop after the loop was quit,
222 // and pending tasks may then be deleted without being run.
223 if (client_) {
224 // gconf client was not cleaned up.
225 if (task_runner_->BelongsToCurrentThread()) {
226 // We are on the UI thread so we can clean it safely. This is
227 // the case at least for ui_tests running under Valgrind in
228 // bug 16076.
229 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
230 ShutDown();
231 } else {
232 // This is very bad! We are deleting the setting getter but we're not on
233 // the UI thread. This is not supposed to happen: the setting getter is
234 // owned by the proxy config service's delegate, which is supposed to be
235 // destroyed on the UI thread only. We will get change notifications to
236 // a deleted object if we continue here, so fail now.
237 LOG(FATAL) << "~SettingGetterImplGConf: deleting on wrong thread!";
240 DCHECK(!client_);
243 virtual bool Init(base::SingleThreadTaskRunner* glib_thread_task_runner,
244 base::MessageLoopForIO* file_loop) OVERRIDE {
245 DCHECK(glib_thread_task_runner->BelongsToCurrentThread());
246 DCHECK(!client_);
247 DCHECK(!task_runner_.get());
248 task_runner_ = glib_thread_task_runner;
249 client_ = gconf_client_get_default();
250 if (!client_) {
251 // It's not clear whether/when this can return NULL.
252 LOG(ERROR) << "Unable to create a gconf client";
253 task_runner_ = NULL;
254 return false;
256 GError* error = NULL;
257 bool added_system_proxy = false;
258 // We need to add the directories for which we'll be asking
259 // for notifications, and we might as well ask to preload them.
260 // These need to be removed again in ShutDown(); we are careful
261 // here to only leave client_ non-NULL if both have been added.
262 gconf_client_add_dir(client_, "/system/proxy",
263 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
264 if (error == NULL) {
265 added_system_proxy = true;
266 gconf_client_add_dir(client_, "/system/http_proxy",
267 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
269 if (error != NULL) {
270 LOG(ERROR) << "Error requesting gconf directory: " << error->message;
271 g_error_free(error);
272 if (added_system_proxy)
273 gconf_client_remove_dir(client_, "/system/proxy", NULL);
274 g_object_unref(client_);
275 client_ = NULL;
276 task_runner_ = NULL;
277 return false;
279 return true;
282 virtual void ShutDown() OVERRIDE {
283 if (client_) {
284 DCHECK(task_runner_->BelongsToCurrentThread());
285 // We must explicitly disable gconf notifications here, because the gconf
286 // client will be shared between all setting getters, and they do not all
287 // have the same lifetimes. (For instance, incognito sessions get their
288 // own, which is destroyed when the session ends.)
289 gconf_client_notify_remove(client_, system_http_proxy_id_);
290 gconf_client_notify_remove(client_, system_proxy_id_);
291 gconf_client_remove_dir(client_, "/system/http_proxy", NULL);
292 gconf_client_remove_dir(client_, "/system/proxy", NULL);
293 g_object_unref(client_);
294 client_ = NULL;
295 task_runner_ = NULL;
299 virtual bool SetUpNotifications(
300 ProxyConfigServiceLinux::Delegate* delegate) OVERRIDE {
301 DCHECK(client_);
302 DCHECK(task_runner_->BelongsToCurrentThread());
303 GError* error = NULL;
304 notify_delegate_ = delegate;
305 // We have to keep track of the IDs returned by gconf_client_notify_add() so
306 // that we can remove them in ShutDown(). (Otherwise, notifications will be
307 // delivered to this object after it is deleted, which is bad, m'kay?)
308 system_proxy_id_ = gconf_client_notify_add(
309 client_, "/system/proxy",
310 OnGConfChangeNotification, this,
311 NULL, &error);
312 if (error == NULL) {
313 system_http_proxy_id_ = gconf_client_notify_add(
314 client_, "/system/http_proxy",
315 OnGConfChangeNotification, this,
316 NULL, &error);
318 if (error != NULL) {
319 LOG(ERROR) << "Error requesting gconf notifications: " << error->message;
320 g_error_free(error);
321 ShutDown();
322 return false;
324 // Simulate a change to avoid possibly losing updates before this point.
325 OnChangeNotification();
326 return true;
329 virtual base::SingleThreadTaskRunner* GetNotificationTaskRunner() OVERRIDE {
330 return task_runner_.get();
333 virtual ProxyConfigSource GetConfigSource() OVERRIDE {
334 return PROXY_CONFIG_SOURCE_GCONF;
337 virtual bool GetString(StringSetting key, std::string* result) OVERRIDE {
338 switch (key) {
339 case PROXY_MODE:
340 return GetStringByPath("/system/proxy/mode", result);
341 case PROXY_AUTOCONF_URL:
342 return GetStringByPath("/system/proxy/autoconfig_url", result);
343 case PROXY_HTTP_HOST:
344 return GetStringByPath("/system/http_proxy/host", result);
345 case PROXY_HTTPS_HOST:
346 return GetStringByPath("/system/proxy/secure_host", result);
347 case PROXY_FTP_HOST:
348 return GetStringByPath("/system/proxy/ftp_host", result);
349 case PROXY_SOCKS_HOST:
350 return GetStringByPath("/system/proxy/socks_host", result);
352 return false; // Placate compiler.
354 virtual bool GetBool(BoolSetting key, bool* result) OVERRIDE {
355 switch (key) {
356 case PROXY_USE_HTTP_PROXY:
357 return GetBoolByPath("/system/http_proxy/use_http_proxy", result);
358 case PROXY_USE_SAME_PROXY:
359 return GetBoolByPath("/system/http_proxy/use_same_proxy", result);
360 case PROXY_USE_AUTHENTICATION:
361 return GetBoolByPath("/system/http_proxy/use_authentication", result);
363 return false; // Placate compiler.
365 virtual bool GetInt(IntSetting key, int* result) OVERRIDE {
366 switch (key) {
367 case PROXY_HTTP_PORT:
368 return GetIntByPath("/system/http_proxy/port", result);
369 case PROXY_HTTPS_PORT:
370 return GetIntByPath("/system/proxy/secure_port", result);
371 case PROXY_FTP_PORT:
372 return GetIntByPath("/system/proxy/ftp_port", result);
373 case PROXY_SOCKS_PORT:
374 return GetIntByPath("/system/proxy/socks_port", result);
376 return false; // Placate compiler.
378 virtual bool GetStringList(StringListSetting key,
379 std::vector<std::string>* result) OVERRIDE {
380 switch (key) {
381 case PROXY_IGNORE_HOSTS:
382 return GetStringListByPath("/system/http_proxy/ignore_hosts", result);
384 return false; // Placate compiler.
387 virtual bool BypassListIsReversed() OVERRIDE {
388 // This is a KDE-specific setting.
389 return false;
392 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE {
393 return false;
396 private:
397 bool GetStringByPath(const char* key, std::string* result) {
398 DCHECK(client_);
399 DCHECK(task_runner_->BelongsToCurrentThread());
400 GError* error = NULL;
401 gchar* value = gconf_client_get_string(client_, key, &error);
402 if (HandleGError(error, key))
403 return false;
404 if (!value)
405 return false;
406 *result = value;
407 g_free(value);
408 return true;
410 bool GetBoolByPath(const char* key, bool* result) {
411 DCHECK(client_);
412 DCHECK(task_runner_->BelongsToCurrentThread());
413 GError* error = NULL;
414 // We want to distinguish unset values from values defaulting to
415 // false. For that we need to use the type-generic
416 // gconf_client_get() rather than gconf_client_get_bool().
417 GConfValue* gconf_value = gconf_client_get(client_, key, &error);
418 if (HandleGError(error, key))
419 return false;
420 if (!gconf_value) {
421 // Unset.
422 return false;
424 if (gconf_value->type != GCONF_VALUE_BOOL) {
425 gconf_value_free(gconf_value);
426 return false;
428 gboolean bool_value = gconf_value_get_bool(gconf_value);
429 *result = static_cast<bool>(bool_value);
430 gconf_value_free(gconf_value);
431 return true;
433 bool GetIntByPath(const char* key, int* result) {
434 DCHECK(client_);
435 DCHECK(task_runner_->BelongsToCurrentThread());
436 GError* error = NULL;
437 int value = gconf_client_get_int(client_, key, &error);
438 if (HandleGError(error, key))
439 return false;
440 // We don't bother to distinguish an unset value because callers
441 // don't care. 0 is returned if unset.
442 *result = value;
443 return true;
445 bool GetStringListByPath(const char* key, std::vector<std::string>* result) {
446 DCHECK(client_);
447 DCHECK(task_runner_->BelongsToCurrentThread());
448 GError* error = NULL;
449 GSList* list = gconf_client_get_list(client_, key,
450 GCONF_VALUE_STRING, &error);
451 if (HandleGError(error, key))
452 return false;
453 if (!list)
454 return false;
455 for (GSList *it = list; it; it = it->next) {
456 result->push_back(static_cast<char*>(it->data));
457 g_free(it->data);
459 g_slist_free(list);
460 return true;
463 // Logs and frees a glib error. Returns false if there was no error
464 // (error is NULL).
465 bool HandleGError(GError* error, const char* key) {
466 if (error != NULL) {
467 LOG(ERROR) << "Error getting gconf value for " << key
468 << ": " << error->message;
469 g_error_free(error);
470 return true;
472 return false;
475 // This is the callback from the debounce timer.
476 void OnDebouncedNotification() {
477 DCHECK(task_runner_->BelongsToCurrentThread());
478 CHECK(notify_delegate_);
479 // Forward to a method on the proxy config service delegate object.
480 notify_delegate_->OnCheckProxyConfigSettings();
483 void OnChangeNotification() {
484 // We don't use Reset() because the timer may not yet be running.
485 // (In that case Stop() is a no-op.)
486 debounce_timer_.Stop();
487 debounce_timer_.Start(FROM_HERE,
488 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
489 this, &SettingGetterImplGConf::OnDebouncedNotification);
492 // gconf notification callback, dispatched on the default glib main loop.
493 static void OnGConfChangeNotification(GConfClient* client, guint cnxn_id,
494 GConfEntry* entry, gpointer user_data) {
495 VLOG(1) << "gconf change notification for key "
496 << gconf_entry_get_key(entry);
497 // We don't track which key has changed, just that something did change.
498 SettingGetterImplGConf* setting_getter =
499 reinterpret_cast<SettingGetterImplGConf*>(user_data);
500 setting_getter->OnChangeNotification();
503 GConfClient* client_;
504 // These ids are the values returned from gconf_client_notify_add(), which we
505 // will need in order to later call gconf_client_notify_remove().
506 guint system_proxy_id_;
507 guint system_http_proxy_id_;
509 ProxyConfigServiceLinux::Delegate* notify_delegate_;
510 base::OneShotTimer<SettingGetterImplGConf> debounce_timer_;
512 // Task runner for the thread that we make gconf calls on. It should
513 // be the UI thread and all our methods should be called on this
514 // thread. Only for assertions.
515 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
517 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf);
519 #endif // defined(USE_GCONF)
521 #if defined(USE_GIO)
522 // This setting getter uses gsettings, as used in most GNOME 3 desktops.
523 class SettingGetterImplGSettings
524 : public ProxyConfigServiceLinux::SettingGetter {
525 public:
526 SettingGetterImplGSettings() :
527 client_(NULL),
528 http_client_(NULL),
529 https_client_(NULL),
530 ftp_client_(NULL),
531 socks_client_(NULL),
532 notify_delegate_(NULL) {
535 virtual ~SettingGetterImplGSettings() {
536 // client_ should have been released before now, from
537 // Delegate::OnDestroy(), while running on the UI thread. However
538 // on exiting the process, it may happen that
539 // Delegate::OnDestroy() task is left pending on the glib loop
540 // after the loop was quit, and pending tasks may then be deleted
541 // without being run.
542 if (client_) {
543 // gconf client was not cleaned up.
544 if (task_runner_->BelongsToCurrentThread()) {
545 // We are on the UI thread so we can clean it safely. This is
546 // the case at least for ui_tests running under Valgrind in
547 // bug 16076.
548 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
549 ShutDown();
550 } else {
551 LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
552 client_ = NULL;
555 DCHECK(!client_);
558 bool SchemaExists(const char* schema_name) {
559 const gchar* const* schemas = libgio_loader_.g_settings_list_schemas();
560 while (*schemas) {
561 if (strcmp(schema_name, static_cast<const char*>(*schemas)) == 0)
562 return true;
563 schemas++;
565 return false;
568 // LoadAndCheckVersion() must be called *before* Init()!
569 bool LoadAndCheckVersion(base::Environment* env);
571 virtual bool Init(base::SingleThreadTaskRunner* glib_thread_task_runner,
572 base::MessageLoopForIO* file_loop) OVERRIDE {
573 DCHECK(glib_thread_task_runner->BelongsToCurrentThread());
574 DCHECK(!client_);
575 DCHECK(!task_runner_.get());
577 if (!SchemaExists("org.gnome.system.proxy") ||
578 !(client_ = libgio_loader_.g_settings_new("org.gnome.system.proxy"))) {
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_thread_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 virtual 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;
608 virtual bool SetUpNotifications(
609 ProxyConfigServiceLinux::Delegate* delegate) OVERRIDE {
610 DCHECK(client_);
611 DCHECK(task_runner_->BelongsToCurrentThread());
612 notify_delegate_ = delegate;
613 // We could watch for the change-event signal instead of changed, but
614 // since we have to watch more than one object, we'd still have to
615 // debounce change notifications. This is conceptually simpler.
616 g_signal_connect(G_OBJECT(client_), "changed",
617 G_CALLBACK(OnGSettingsChangeNotification), this);
618 g_signal_connect(G_OBJECT(http_client_), "changed",
619 G_CALLBACK(OnGSettingsChangeNotification), this);
620 g_signal_connect(G_OBJECT(https_client_), "changed",
621 G_CALLBACK(OnGSettingsChangeNotification), this);
622 g_signal_connect(G_OBJECT(ftp_client_), "changed",
623 G_CALLBACK(OnGSettingsChangeNotification), this);
624 g_signal_connect(G_OBJECT(socks_client_), "changed",
625 G_CALLBACK(OnGSettingsChangeNotification), this);
626 // Simulate a change to avoid possibly losing updates before this point.
627 OnChangeNotification();
628 return true;
631 virtual base::SingleThreadTaskRunner* GetNotificationTaskRunner() OVERRIDE {
632 return task_runner_.get();
635 virtual ProxyConfigSource GetConfigSource() OVERRIDE {
636 return PROXY_CONFIG_SOURCE_GSETTINGS;
639 virtual bool GetString(StringSetting key, std::string* result) OVERRIDE {
640 DCHECK(client_);
641 switch (key) {
642 case PROXY_MODE:
643 return GetStringByPath(client_, "mode", result);
644 case PROXY_AUTOCONF_URL:
645 return GetStringByPath(client_, "autoconfig-url", result);
646 case PROXY_HTTP_HOST:
647 return GetStringByPath(http_client_, "host", result);
648 case PROXY_HTTPS_HOST:
649 return GetStringByPath(https_client_, "host", result);
650 case PROXY_FTP_HOST:
651 return GetStringByPath(ftp_client_, "host", result);
652 case PROXY_SOCKS_HOST:
653 return GetStringByPath(socks_client_, "host", result);
655 return false; // Placate compiler.
657 virtual bool GetBool(BoolSetting key, bool* result) OVERRIDE {
658 DCHECK(client_);
659 switch (key) {
660 case PROXY_USE_HTTP_PROXY:
661 // Although there is an "enabled" boolean in http_client_, it is not set
662 // to true by the proxy config utility. We ignore it and return false.
663 return false;
664 case PROXY_USE_SAME_PROXY:
665 // Similarly, although there is a "use-same-proxy" boolean in client_,
666 // it is never set to false by the proxy config utility. We ignore it.
667 return false;
668 case PROXY_USE_AUTHENTICATION:
669 // There is also no way to set this in the proxy config utility, but it
670 // doesn't hurt us to get the actual setting (unlike the two above).
671 return GetBoolByPath(http_client_, "use-authentication", result);
673 return false; // Placate compiler.
675 virtual bool GetInt(IntSetting key, int* result) OVERRIDE {
676 DCHECK(client_);
677 switch (key) {
678 case PROXY_HTTP_PORT:
679 return GetIntByPath(http_client_, "port", result);
680 case PROXY_HTTPS_PORT:
681 return GetIntByPath(https_client_, "port", result);
682 case PROXY_FTP_PORT:
683 return GetIntByPath(ftp_client_, "port", result);
684 case PROXY_SOCKS_PORT:
685 return GetIntByPath(socks_client_, "port", result);
687 return false; // Placate compiler.
689 virtual bool GetStringList(StringListSetting key,
690 std::vector<std::string>* result) OVERRIDE {
691 DCHECK(client_);
692 switch (key) {
693 case PROXY_IGNORE_HOSTS:
694 return GetStringListByPath(client_, "ignore-hosts", result);
696 return false; // Placate compiler.
699 virtual bool BypassListIsReversed() OVERRIDE {
700 // This is a KDE-specific setting.
701 return false;
704 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE {
705 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 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;
819 if (!SchemaExists("org.gnome.system.proxy") ||
820 !(client = libgio_loader_.g_settings_new("org.gnome.system.proxy"))) {
821 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
822 return false;
824 g_object_unref(client);
826 std::string path;
827 if (!env->GetVar("PATH", &path)) {
828 LOG(ERROR) << "No $PATH variable. Assuming no gnome-network-properties.";
829 } else {
830 // Yes, we're on the UI thread. Yes, we're accessing the file system.
831 // Sadly, we don't have much choice. We need the proxy settings and we
832 // need them now, and to figure out where to get them, we have to check
833 // for this binary. See http://crbug.com/69057 for additional details.
834 base::ThreadRestrictions::ScopedAllowIO allow_io;
835 std::vector<std::string> paths;
836 Tokenize(path, ":", &paths);
837 for (size_t i = 0; i < paths.size(); ++i) {
838 base::FilePath file(paths[i]);
839 if (base::PathExists(file.Append("gnome-network-properties"))) {
840 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
841 return false;
846 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
847 return true;
849 #endif // defined(USE_GIO)
851 // This is the KDE version that reads kioslaverc and simulates gconf.
852 // Doing this allows the main Delegate code, as well as the unit tests
853 // for it, to stay the same - and the settings map fairly well besides.
854 class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter,
855 public base::MessagePumpLibevent::Watcher {
856 public:
857 explicit SettingGetterImplKDE(base::Environment* env_var_getter)
858 : inotify_fd_(-1), notify_delegate_(NULL), indirect_manual_(false),
859 auto_no_pac_(false), reversed_bypass_list_(false),
860 env_var_getter_(env_var_getter), file_loop_(NULL) {
861 // This has to be called on the UI thread (http://crbug.com/69057).
862 base::ThreadRestrictions::ScopedAllowIO allow_io;
864 // Derive the location of the kde config dir from the environment.
865 std::string home;
866 if (env_var_getter->GetVar("KDEHOME", &home) && !home.empty()) {
867 // $KDEHOME is set. Use it unconditionally.
868 kde_config_dir_ = KDEHomeToConfigPath(base::FilePath(home));
869 } else {
870 // $KDEHOME is unset. Try to figure out what to use. This seems to be
871 // the common case on most distributions.
872 if (!env_var_getter->GetVar(base::env_vars::kHome, &home))
873 // User has no $HOME? Give up. Later we'll report the failure.
874 return;
875 if (base::nix::GetDesktopEnvironment(env_var_getter) ==
876 base::nix::DESKTOP_ENVIRONMENT_KDE3) {
877 // KDE3 always uses .kde for its configuration.
878 base::FilePath kde_path = base::FilePath(home).Append(".kde");
879 kde_config_dir_ = KDEHomeToConfigPath(kde_path);
880 } else {
881 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
882 // both can be installed side-by-side. Sadly they don't all do this, and
883 // they don't always do this: some distributions have started switching
884 // back as well. So if there is a .kde4 directory, check the timestamps
885 // of the config directories within and use the newest one.
886 // Note that we should currently be running in the UI thread, because in
887 // the gconf version, that is the only thread that can access the proxy
888 // settings (a gconf restriction). As noted below, the initial read of
889 // the proxy settings will be done in this thread anyway, so we check
890 // for .kde4 here in this thread as well.
891 base::FilePath kde3_path = base::FilePath(home).Append(".kde");
892 base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
893 base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
894 base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
895 bool use_kde4 = false;
896 if (base::DirectoryExists(kde4_path)) {
897 base::File::Info kde3_info;
898 base::File::Info kde4_info;
899 if (base::GetFileInfo(kde4_config, &kde4_info)) {
900 if (base::GetFileInfo(kde3_config, &kde3_info)) {
901 use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
902 } else {
903 use_kde4 = true;
907 if (use_kde4) {
908 kde_config_dir_ = KDEHomeToConfigPath(kde4_path);
909 } else {
910 kde_config_dir_ = KDEHomeToConfigPath(kde3_path);
916 virtual ~SettingGetterImplKDE() {
917 // inotify_fd_ should have been closed before now, from
918 // Delegate::OnDestroy(), while running on the file thread. However
919 // on exiting the process, it may happen that Delegate::OnDestroy()
920 // task is left pending on the file loop after the loop was quit,
921 // and pending tasks may then be deleted without being run.
922 // Here in the KDE version, we can safely close the file descriptor
923 // anyway. (Not that it really matters; the process is exiting.)
924 if (inotify_fd_ >= 0)
925 ShutDown();
926 DCHECK(inotify_fd_ < 0);
929 virtual bool Init(base::SingleThreadTaskRunner* glib_thread_task_runner,
930 base::MessageLoopForIO* file_loop) OVERRIDE {
931 // This has to be called on the UI thread (http://crbug.com/69057).
932 base::ThreadRestrictions::ScopedAllowIO allow_io;
933 DCHECK(inotify_fd_ < 0);
934 inotify_fd_ = inotify_init();
935 if (inotify_fd_ < 0) {
936 PLOG(ERROR) << "inotify_init failed";
937 return false;
939 int flags = fcntl(inotify_fd_, F_GETFL);
940 if (fcntl(inotify_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
941 PLOG(ERROR) << "fcntl failed";
942 close(inotify_fd_);
943 inotify_fd_ = -1;
944 return false;
946 file_loop_ = file_loop;
947 // The initial read is done on the current thread, not |file_loop_|,
948 // since we will need to have it for SetUpAndFetchInitialConfig().
949 UpdateCachedSettings();
950 return true;
953 virtual void ShutDown() OVERRIDE {
954 if (inotify_fd_ >= 0) {
955 ResetCachedSettings();
956 inotify_watcher_.StopWatchingFileDescriptor();
957 close(inotify_fd_);
958 inotify_fd_ = -1;
962 virtual bool SetUpNotifications(
963 ProxyConfigServiceLinux::Delegate* delegate) OVERRIDE {
964 DCHECK(inotify_fd_ >= 0);
965 DCHECK(base::MessageLoop::current() == file_loop_);
966 // We can't just watch the kioslaverc file directly, since KDE will write
967 // a new copy of it and then rename it whenever settings are changed and
968 // inotify watches inodes (so we'll be watching the old deleted file after
969 // the first change, and it will never change again). So, we watch the
970 // directory instead. We then act only on changes to the kioslaverc entry.
971 if (inotify_add_watch(inotify_fd_, kde_config_dir_.value().c_str(),
972 IN_MODIFY | IN_MOVED_TO) < 0)
973 return false;
974 notify_delegate_ = delegate;
975 if (!file_loop_->WatchFileDescriptor(inotify_fd_,
976 true,
977 base::MessageLoopForIO::WATCH_READ,
978 &inotify_watcher_,
979 this))
980 return false;
981 // Simulate a change to avoid possibly losing updates before this point.
982 OnChangeNotification();
983 return true;
986 virtual base::SingleThreadTaskRunner* GetNotificationTaskRunner() OVERRIDE {
987 return file_loop_ ? file_loop_->message_loop_proxy().get() : NULL;
990 // Implement base::MessagePumpLibevent::Watcher.
991 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE {
992 DCHECK_EQ(fd, inotify_fd_);
993 DCHECK(base::MessageLoop::current() == file_loop_);
994 OnChangeNotification();
996 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE {
997 NOTREACHED();
1000 virtual ProxyConfigSource GetConfigSource() OVERRIDE {
1001 return PROXY_CONFIG_SOURCE_KDE;
1004 virtual bool GetString(StringSetting key, std::string* result) OVERRIDE {
1005 string_map_type::iterator it = string_table_.find(key);
1006 if (it == string_table_.end())
1007 return false;
1008 *result = it->second;
1009 return true;
1011 virtual bool GetBool(BoolSetting key, bool* result) OVERRIDE {
1012 // We don't ever have any booleans.
1013 return false;
1015 virtual bool GetInt(IntSetting key, int* result) OVERRIDE {
1016 // We don't ever have any integers. (See AddProxy() below about ports.)
1017 return false;
1019 virtual bool GetStringList(StringListSetting key,
1020 std::vector<std::string>* result) OVERRIDE {
1021 strings_map_type::iterator it = strings_table_.find(key);
1022 if (it == strings_table_.end())
1023 return false;
1024 *result = it->second;
1025 return true;
1028 virtual bool BypassListIsReversed() OVERRIDE {
1029 return reversed_bypass_list_;
1032 virtual bool MatchHostsUsingSuffixMatching() OVERRIDE {
1033 return true;
1036 private:
1037 void ResetCachedSettings() {
1038 string_table_.clear();
1039 strings_table_.clear();
1040 indirect_manual_ = false;
1041 auto_no_pac_ = false;
1042 reversed_bypass_list_ = false;
1045 base::FilePath KDEHomeToConfigPath(const base::FilePath& kde_home) {
1046 return kde_home.Append("share").Append("config");
1049 void AddProxy(StringSetting host_key, const std::string& value) {
1050 if (value.empty() || value.substr(0, 3) == "//:")
1051 // No proxy.
1052 return;
1053 size_t space = value.find(' ');
1054 if (space != std::string::npos) {
1055 // Newer versions of KDE use a space rather than a colon to separate the
1056 // port number from the hostname. If we find this, we need to convert it.
1057 std::string fixed = value;
1058 fixed[space] = ':';
1059 string_table_[host_key] = fixed;
1060 } else {
1061 // We don't need to parse the port number out; GetProxyFromSettings()
1062 // would only append it right back again. So we just leave the port
1063 // number right in the host string.
1064 string_table_[host_key] = value;
1068 void AddHostList(StringListSetting key, const std::string& value) {
1069 std::vector<std::string> tokens;
1070 base::StringTokenizer tk(value, ", ");
1071 while (tk.GetNext()) {
1072 std::string token = tk.token();
1073 if (!token.empty())
1074 tokens.push_back(token);
1076 strings_table_[key] = tokens;
1079 void AddKDESetting(const std::string& key, const std::string& value) {
1080 if (key == "ProxyType") {
1081 const char* mode = "none";
1082 indirect_manual_ = false;
1083 auto_no_pac_ = false;
1084 int int_value;
1085 base::StringToInt(value, &int_value);
1086 switch (int_value) {
1087 case 0: // No proxy, or maybe kioslaverc syntax error.
1088 break;
1089 case 1: // Manual configuration.
1090 mode = "manual";
1091 break;
1092 case 2: // PAC URL.
1093 mode = "auto";
1094 break;
1095 case 3: // WPAD.
1096 mode = "auto";
1097 auto_no_pac_ = true;
1098 break;
1099 case 4: // Indirect manual via environment variables.
1100 mode = "manual";
1101 indirect_manual_ = true;
1102 break;
1104 string_table_[PROXY_MODE] = mode;
1105 } else if (key == "Proxy Config Script") {
1106 string_table_[PROXY_AUTOCONF_URL] = value;
1107 } else if (key == "httpProxy") {
1108 AddProxy(PROXY_HTTP_HOST, value);
1109 } else if (key == "httpsProxy") {
1110 AddProxy(PROXY_HTTPS_HOST, value);
1111 } else if (key == "ftpProxy") {
1112 AddProxy(PROXY_FTP_HOST, value);
1113 } else if (key == "socksProxy") {
1114 // Older versions of KDE configure SOCKS in a weird way involving
1115 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1116 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1117 AddProxy(PROXY_SOCKS_HOST, value);
1118 } else if (key == "ReversedException") {
1119 // We count "true" or any nonzero number as true, otherwise false.
1120 // Note that if the value is not actually numeric StringToInt()
1121 // will return 0, which we count as false.
1122 int int_value;
1123 base::StringToInt(value, &int_value);
1124 reversed_bypass_list_ = (value == "true" || int_value);
1125 } else if (key == "NoProxyFor") {
1126 AddHostList(PROXY_IGNORE_HOSTS, value);
1127 } else if (key == "AuthMode") {
1128 // Check for authentication, just so we can warn.
1129 int mode;
1130 base::StringToInt(value, &mode);
1131 if (mode) {
1132 // ProxyConfig does not support authentication parameters, but
1133 // Chrome will prompt for the password later. So we ignore this.
1134 LOG(WARNING) <<
1135 "Proxy authentication parameters ignored, see bug 16709";
1140 void ResolveIndirect(StringSetting key) {
1141 string_map_type::iterator it = string_table_.find(key);
1142 if (it != string_table_.end()) {
1143 std::string value;
1144 if (env_var_getter_->GetVar(it->second.c_str(), &value))
1145 it->second = value;
1146 else
1147 string_table_.erase(it);
1151 void ResolveIndirectList(StringListSetting key) {
1152 strings_map_type::iterator it = strings_table_.find(key);
1153 if (it != strings_table_.end()) {
1154 std::string value;
1155 if (!it->second.empty() &&
1156 env_var_getter_->GetVar(it->second[0].c_str(), &value))
1157 AddHostList(key, value);
1158 else
1159 strings_table_.erase(it);
1163 // The settings in kioslaverc could occur in any order, but some affect
1164 // others. Rather than read the whole file in and then query them in an
1165 // order that allows us to handle that, we read the settings in whatever
1166 // order they occur and do any necessary tweaking after we finish.
1167 void ResolveModeEffects() {
1168 if (indirect_manual_) {
1169 ResolveIndirect(PROXY_HTTP_HOST);
1170 ResolveIndirect(PROXY_HTTPS_HOST);
1171 ResolveIndirect(PROXY_FTP_HOST);
1172 ResolveIndirectList(PROXY_IGNORE_HOSTS);
1174 if (auto_no_pac_) {
1175 // Remove the PAC URL; we're not supposed to use it.
1176 string_table_.erase(PROXY_AUTOCONF_URL);
1180 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1181 // each relevant name-value pair to the appropriate value table.
1182 void UpdateCachedSettings() {
1183 base::FilePath kioslaverc = kde_config_dir_.Append("kioslaverc");
1184 base::ScopedFILE input(base::OpenFile(kioslaverc, "r"));
1185 if (!input.get())
1186 return;
1187 ResetCachedSettings();
1188 bool in_proxy_settings = false;
1189 bool line_too_long = false;
1190 char line[BUFFER_SIZE];
1191 // fgets() will return NULL on EOF or error.
1192 while (fgets(line, sizeof(line), input.get())) {
1193 // fgets() guarantees the line will be properly terminated.
1194 size_t length = strlen(line);
1195 if (!length)
1196 continue;
1197 // This should be true even with CRLF endings.
1198 if (line[length - 1] != '\n') {
1199 line_too_long = true;
1200 continue;
1202 if (line_too_long) {
1203 // The previous line had no line ending, but this done does. This is
1204 // the end of the line that was too long, so warn here and skip it.
1205 LOG(WARNING) << "skipped very long line in " << kioslaverc.value();
1206 line_too_long = false;
1207 continue;
1209 // Remove the LF at the end, and the CR if there is one.
1210 line[--length] = '\0';
1211 if (length && line[length - 1] == '\r')
1212 line[--length] = '\0';
1213 // Now parse the line.
1214 if (line[0] == '[') {
1215 // Switching sections. All we care about is whether this is
1216 // the (a?) proxy settings section, for both KDE3 and KDE4.
1217 in_proxy_settings = !strncmp(line, "[Proxy Settings]", 16);
1218 } else if (in_proxy_settings) {
1219 // A regular line, in the (a?) proxy settings section.
1220 char* split = strchr(line, '=');
1221 // Skip this line if it does not contain an = sign.
1222 if (!split)
1223 continue;
1224 // Split the line on the = and advance |split|.
1225 *(split++) = 0;
1226 std::string key = line;
1227 std::string value = split;
1228 base::TrimWhitespaceASCII(key, base::TRIM_ALL, &key);
1229 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
1230 // Skip this line if the key name is empty.
1231 if (key.empty())
1232 continue;
1233 // Is the value name localized?
1234 if (key[key.length() - 1] == ']') {
1235 // Find the matching bracket.
1236 length = key.rfind('[');
1237 // Skip this line if the localization indicator is malformed.
1238 if (length == std::string::npos)
1239 continue;
1240 // Trim the localization indicator off.
1241 key.resize(length);
1242 // Remove any resulting trailing whitespace.
1243 base::TrimWhitespaceASCII(key, base::TRIM_TRAILING, &key);
1244 // Skip this line if the key name is now empty.
1245 if (key.empty())
1246 continue;
1248 // Now fill in the tables.
1249 AddKDESetting(key, value);
1252 if (ferror(input.get()))
1253 LOG(ERROR) << "error reading " << kioslaverc.value();
1254 ResolveModeEffects();
1257 // This is the callback from the debounce timer.
1258 void OnDebouncedNotification() {
1259 DCHECK(base::MessageLoop::current() == file_loop_);
1260 VLOG(1) << "inotify change notification for kioslaverc";
1261 UpdateCachedSettings();
1262 CHECK(notify_delegate_);
1263 // Forward to a method on the proxy config service delegate object.
1264 notify_delegate_->OnCheckProxyConfigSettings();
1267 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1268 // from the inotify file descriptor and starts up a debounce timer if
1269 // an event for kioslaverc is seen.
1270 void OnChangeNotification() {
1271 DCHECK_GE(inotify_fd_, 0);
1272 DCHECK(base::MessageLoop::current() == file_loop_);
1273 char event_buf[(sizeof(inotify_event) + NAME_MAX + 1) * 4];
1274 bool kioslaverc_touched = false;
1275 ssize_t r;
1276 while ((r = read(inotify_fd_, event_buf, sizeof(event_buf))) > 0) {
1277 // inotify returns variable-length structures, which is why we have
1278 // this strange-looking loop instead of iterating through an array.
1279 char* event_ptr = event_buf;
1280 while (event_ptr < event_buf + r) {
1281 inotify_event* event = reinterpret_cast<inotify_event*>(event_ptr);
1282 // The kernel always feeds us whole events.
1283 CHECK_LE(event_ptr + sizeof(inotify_event), event_buf + r);
1284 CHECK_LE(event->name + event->len, event_buf + r);
1285 if (!strcmp(event->name, "kioslaverc"))
1286 kioslaverc_touched = true;
1287 // Advance the pointer just past the end of the filename.
1288 event_ptr = event->name + event->len;
1290 // We keep reading even if |kioslaverc_touched| is true to drain the
1291 // inotify event queue.
1293 if (!r)
1294 // Instead of returning -1 and setting errno to EINVAL if there is not
1295 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1296 // new behavior (EINVAL) so we can reuse the code below.
1297 errno = EINVAL;
1298 if (errno != EAGAIN) {
1299 PLOG(WARNING) << "error reading inotify file descriptor";
1300 if (errno == EINVAL) {
1301 // Our buffer is not large enough to read the next event. This should
1302 // not happen (because its size is calculated to always be sufficiently
1303 // large), but if it does we'd warn continuously since |inotify_fd_|
1304 // would be forever ready to read. Close it and stop watching instead.
1305 LOG(ERROR) << "inotify failure; no longer watching kioslaverc!";
1306 inotify_watcher_.StopWatchingFileDescriptor();
1307 close(inotify_fd_);
1308 inotify_fd_ = -1;
1311 if (kioslaverc_touched) {
1312 // We don't use Reset() because the timer may not yet be running.
1313 // (In that case Stop() is a no-op.)
1314 debounce_timer_.Stop();
1315 debounce_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(
1316 kDebounceTimeoutMilliseconds), this,
1317 &SettingGetterImplKDE::OnDebouncedNotification);
1321 typedef std::map<StringSetting, std::string> string_map_type;
1322 typedef std::map<StringListSetting,
1323 std::vector<std::string> > strings_map_type;
1325 int inotify_fd_;
1326 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_;
1327 ProxyConfigServiceLinux::Delegate* notify_delegate_;
1328 base::OneShotTimer<SettingGetterImplKDE> debounce_timer_;
1329 base::FilePath kde_config_dir_;
1330 bool indirect_manual_;
1331 bool auto_no_pac_;
1332 bool reversed_bypass_list_;
1333 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1334 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1335 // same lifetime.
1336 base::Environment* env_var_getter_;
1338 // We cache these settings whenever we re-read the kioslaverc file.
1339 string_map_type string_table_;
1340 strings_map_type strings_table_;
1342 // Message loop of the file thread, for reading kioslaverc. If NULL,
1343 // just read it directly (for testing). We also handle inotify events
1344 // on this thread.
1345 base::MessageLoopForIO* file_loop_;
1347 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE);
1350 } // namespace
1352 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1353 SettingGetter::StringSetting host_key,
1354 ProxyServer* result_server) {
1355 std::string host;
1356 if (!setting_getter_->GetString(host_key, &host) || host.empty()) {
1357 // Unset or empty.
1358 return false;
1360 // Check for an optional port.
1361 int port = 0;
1362 SettingGetter::IntSetting port_key =
1363 SettingGetter::HostSettingToPortSetting(host_key);
1364 setting_getter_->GetInt(port_key, &port);
1365 if (port != 0) {
1366 // If a port is set and non-zero:
1367 host += ":" + base::IntToString(port);
1370 // gconf settings do not appear to distinguish between SOCKS version. We
1371 // default to version 5. For more information on this policy decision, see:
1372 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1373 ProxyServer::Scheme scheme = (host_key == SettingGetter::PROXY_SOCKS_HOST) ?
1374 ProxyServer::SCHEME_SOCKS5 : ProxyServer::SCHEME_HTTP;
1375 host = FixupProxyHostScheme(scheme, host);
1376 ProxyServer proxy_server = ProxyServer::FromURI(host,
1377 ProxyServer::SCHEME_HTTP);
1378 if (proxy_server.is_valid()) {
1379 *result_server = proxy_server;
1380 return true;
1382 return false;
1385 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1386 ProxyConfig* config) {
1387 std::string mode;
1388 if (!setting_getter_->GetString(SettingGetter::PROXY_MODE, &mode)) {
1389 // We expect this to always be set, so if we don't see it then we
1390 // probably have a gconf/gsettings problem, and so we don't have a valid
1391 // proxy config.
1392 return false;
1394 if (mode == "none") {
1395 // Specifically specifies no proxy.
1396 return true;
1399 if (mode == "auto") {
1400 // Automatic proxy config.
1401 std::string pac_url_str;
1402 if (setting_getter_->GetString(SettingGetter::PROXY_AUTOCONF_URL,
1403 &pac_url_str)) {
1404 if (!pac_url_str.empty()) {
1405 // If the PAC URL is actually a file path, then put file:// in front.
1406 if (pac_url_str[0] == '/')
1407 pac_url_str = "file://" + pac_url_str;
1408 GURL pac_url(pac_url_str);
1409 if (!pac_url.is_valid())
1410 return false;
1411 config->set_pac_url(pac_url);
1412 return true;
1415 config->set_auto_detect(true);
1416 return true;
1419 if (mode != "manual") {
1420 // Mode is unrecognized.
1421 return false;
1423 bool use_http_proxy;
1424 if (setting_getter_->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY,
1425 &use_http_proxy)
1426 && !use_http_proxy) {
1427 // Another master switch for some reason. If set to false, then no
1428 // proxy. But we don't panic if the key doesn't exist.
1429 return true;
1432 bool same_proxy = false;
1433 // Indicates to use the http proxy for all protocols. This one may
1434 // not exist (presumably on older versions); we assume false in that
1435 // case.
1436 setting_getter_->GetBool(SettingGetter::PROXY_USE_SAME_PROXY,
1437 &same_proxy);
1439 ProxyServer proxy_for_http;
1440 ProxyServer proxy_for_https;
1441 ProxyServer proxy_for_ftp;
1442 ProxyServer socks_proxy; // (socks)
1444 // This counts how many of the above ProxyServers were defined and valid.
1445 size_t num_proxies_specified = 0;
1447 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1448 // specified for the scheme, then the resulting ProxyServer will be invalid.
1449 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST, &proxy_for_http))
1450 num_proxies_specified++;
1451 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST, &proxy_for_https))
1452 num_proxies_specified++;
1453 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST, &proxy_for_ftp))
1454 num_proxies_specified++;
1455 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST, &socks_proxy))
1456 num_proxies_specified++;
1458 if (same_proxy) {
1459 if (proxy_for_http.is_valid()) {
1460 // Use the http proxy for all schemes.
1461 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1462 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_for_http);
1464 } else if (num_proxies_specified > 0) {
1465 if (socks_proxy.is_valid() && num_proxies_specified == 1) {
1466 // If the only proxy specified was for SOCKS, use it for all schemes.
1467 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1468 config->proxy_rules().single_proxies.SetSingleProxyServer(socks_proxy);
1469 } else {
1470 // Otherwise use the indicated proxies per-scheme.
1471 config->proxy_rules().type =
1472 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
1473 config->proxy_rules().proxies_for_http.
1474 SetSingleProxyServer(proxy_for_http);
1475 config->proxy_rules().proxies_for_https.
1476 SetSingleProxyServer(proxy_for_https);
1477 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_for_ftp);
1478 config->proxy_rules().fallback_proxies.SetSingleProxyServer(socks_proxy);
1482 if (config->proxy_rules().empty()) {
1483 // Manual mode but we couldn't parse any rules.
1484 return false;
1487 // Check for authentication, just so we can warn.
1488 bool use_auth = false;
1489 setting_getter_->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION,
1490 &use_auth);
1491 if (use_auth) {
1492 // ProxyConfig does not support authentication parameters, but
1493 // Chrome will prompt for the password later. So we ignore
1494 // /system/http_proxy/*auth* settings.
1495 LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
1498 // Now the bypass list.
1499 std::vector<std::string> ignore_hosts_list;
1500 config->proxy_rules().bypass_rules.Clear();
1501 if (setting_getter_->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS,
1502 &ignore_hosts_list)) {
1503 std::vector<std::string>::const_iterator it(ignore_hosts_list.begin());
1504 for (; it != ignore_hosts_list.end(); ++it) {
1505 if (setting_getter_->MatchHostsUsingSuffixMatching()) {
1506 config->proxy_rules().bypass_rules.
1507 AddRuleFromStringUsingSuffixMatching(*it);
1508 } else {
1509 config->proxy_rules().bypass_rules.AddRuleFromString(*it);
1513 // Note that there are no settings with semantics corresponding to
1514 // bypass of local names in GNOME. In KDE, "<local>" is supported
1515 // as a hostname rule.
1517 // KDE allows one to reverse the bypass rules.
1518 config->proxy_rules().reverse_bypass =
1519 setting_getter_->BypassListIsReversed();
1521 return true;
1524 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment* env_var_getter)
1525 : env_var_getter_(env_var_getter) {
1526 // Figure out which SettingGetterImpl to use, if any.
1527 switch (base::nix::GetDesktopEnvironment(env_var_getter)) {
1528 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
1529 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
1530 #if defined(USE_GIO)
1532 scoped_ptr<SettingGetterImplGSettings> gs_getter(
1533 new SettingGetterImplGSettings());
1534 // We have to load symbols and check the GNOME version in use to decide
1535 // if we should use the gsettings getter. See LoadAndCheckVersion().
1536 if (gs_getter->LoadAndCheckVersion(env_var_getter))
1537 setting_getter_.reset(gs_getter.release());
1539 #endif
1540 #if defined(USE_GCONF)
1541 // Fall back on gconf if gsettings is unavailable or incorrect.
1542 if (!setting_getter_.get())
1543 setting_getter_.reset(new SettingGetterImplGConf());
1544 #endif
1545 break;
1546 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
1547 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
1548 setting_getter_.reset(new SettingGetterImplKDE(env_var_getter));
1549 break;
1550 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
1551 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
1552 break;
1556 ProxyConfigServiceLinux::Delegate::Delegate(
1557 base::Environment* env_var_getter, SettingGetter* setting_getter)
1558 : env_var_getter_(env_var_getter), setting_getter_(setting_getter) {
1561 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1562 base::SingleThreadTaskRunner* glib_thread_task_runner,
1563 base::SingleThreadTaskRunner* io_thread_task_runner,
1564 base::MessageLoopForIO* file_loop) {
1565 // We should be running on the default glib main loop thread right
1566 // now. gconf can only be accessed from this thread.
1567 DCHECK(glib_thread_task_runner->BelongsToCurrentThread());
1568 glib_thread_task_runner_ = glib_thread_task_runner;
1569 io_thread_task_runner_ = io_thread_task_runner;
1571 // If we are passed a NULL |io_thread_task_runner| or |file_loop|,
1572 // then we don't set up proxy setting change notifications. This
1573 // should not be the usual case but is intended to simplify test
1574 // setups.
1575 if (!io_thread_task_runner_.get() || !file_loop)
1576 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1578 // Fetch and cache the current proxy config. The config is left in
1579 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1580 // will expect to find it. This is safe to do because we return
1581 // before this ProxyConfigServiceLinux is passed on to
1582 // the ProxyService.
1584 // Note: It would be nice to prioritize environment variables
1585 // and only fall back to gconf if env vars were unset. But
1586 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1587 // does so even if the proxy mode is set to auto, which would
1588 // mislead us.
1590 bool got_config = false;
1591 if (setting_getter_.get() &&
1592 setting_getter_->Init(glib_thread_task_runner, file_loop) &&
1593 GetConfigFromSettings(&cached_config_)) {
1594 cached_config_.set_id(1); // Mark it as valid.
1595 cached_config_.set_source(setting_getter_->GetConfigSource());
1596 VLOG(1) << "Obtained proxy settings from "
1597 << ProxyConfigSourceToString(cached_config_.source());
1599 // If gconf proxy mode is "none", meaning direct, then we take
1600 // that to be a valid config and will not check environment
1601 // variables. The alternative would have been to look for a proxy
1602 // whereever we can find one.
1603 got_config = true;
1605 // Keep a copy of the config for use from this thread for
1606 // comparison with updated settings when we get notifications.
1607 reference_config_ = cached_config_;
1608 reference_config_.set_id(1); // Mark it as valid.
1610 // We only set up notifications if we have IO and file loops available.
1611 // We do this after getting the initial configuration so that we don't have
1612 // to worry about cancelling it if the initial fetch above fails. Note that
1613 // setting up notifications has the side effect of simulating a change, so
1614 // that we won't lose any updates that may have happened after the initial
1615 // fetch and before setting up notifications. We'll detect the common case
1616 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1617 if (io_thread_task_runner && file_loop) {
1618 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1619 setting_getter_->GetNotificationTaskRunner();
1620 if (!required_loop.get() || required_loop->BelongsToCurrentThread()) {
1621 // In this case we are already on an acceptable thread.
1622 SetUpNotifications();
1623 } else {
1624 // Post a task to set up notifications. We don't wait for success.
1625 required_loop->PostTask(FROM_HERE, base::Bind(
1626 &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this));
1631 if (!got_config) {
1632 // We fall back on environment variables.
1634 // Consulting environment variables doesn't need to be done from the
1635 // default glib main loop, but it's a tiny enough amount of work.
1636 if (GetConfigFromEnv(&cached_config_)) {
1637 cached_config_.set_source(PROXY_CONFIG_SOURCE_ENV);
1638 cached_config_.set_id(1); // Mark it as valid.
1639 VLOG(1) << "Obtained proxy settings from environment variables";
1644 // Depending on the SettingGetter in use, this method will be called
1645 // on either the UI thread (GConf) or the file thread (KDE).
1646 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1647 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1648 setting_getter_->GetNotificationTaskRunner();
1649 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1650 if (!setting_getter_->SetUpNotifications(this))
1651 LOG(ERROR) << "Unable to set up proxy configuration change notifications";
1654 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer* observer) {
1655 observers_.AddObserver(observer);
1658 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer* observer) {
1659 observers_.RemoveObserver(observer);
1662 ProxyConfigService::ConfigAvailability
1663 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1664 ProxyConfig* config) {
1665 // This is called from the IO thread.
1666 DCHECK(!io_thread_task_runner_.get() ||
1667 io_thread_task_runner_->BelongsToCurrentThread());
1669 // Simply return the last proxy configuration that glib_default_loop
1670 // notified us of.
1671 if (cached_config_.is_valid()) {
1672 *config = cached_config_;
1673 } else {
1674 *config = ProxyConfig::CreateDirect();
1675 config->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED);
1678 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1679 // going to be available since we initialized eagerly on the UI thread.
1680 // TODO(eroman): do lazy initialization instead, so we no longer need
1681 // to construct ProxyConfigServiceLinux on the UI thread.
1682 // In which case, we may return false here.
1683 return CONFIG_VALID;
1686 // Depending on the SettingGetter in use, this method will be called
1687 // on either the UI thread (GConf) or the file thread (KDE).
1688 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1689 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1690 setting_getter_->GetNotificationTaskRunner();
1691 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1692 ProxyConfig new_config;
1693 bool valid = GetConfigFromSettings(&new_config);
1694 if (valid)
1695 new_config.set_id(1); // mark it as valid
1697 // See if it is different from what we had before.
1698 if (new_config.is_valid() != reference_config_.is_valid() ||
1699 !new_config.Equals(reference_config_)) {
1700 // Post a task to the IO thread with the new configuration, so it can
1701 // update |cached_config_|.
1702 io_thread_task_runner_->PostTask(FROM_HERE, base::Bind(
1703 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig,
1704 this, new_config));
1705 // Update the thread-private copy in |reference_config_| as well.
1706 reference_config_ = new_config;
1707 } else {
1708 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1712 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1713 const ProxyConfig& new_config) {
1714 DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
1715 VLOG(1) << "Proxy configuration changed";
1716 cached_config_ = new_config;
1717 FOR_EACH_OBSERVER(
1718 Observer, observers_,
1719 OnProxyConfigChanged(new_config, ProxyConfigService::CONFIG_VALID));
1722 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1723 if (!setting_getter_.get())
1724 return;
1725 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1726 setting_getter_->GetNotificationTaskRunner();
1727 if (!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread()) {
1728 // Already on the right thread, call directly.
1729 // This is the case for the unittests.
1730 OnDestroy();
1731 } else {
1732 // Post to shutdown thread. Note that on browser shutdown, we may quit
1733 // this MessageLoop and exit the program before ever running this.
1734 shutdown_loop->PostTask(FROM_HERE, base::Bind(
1735 &ProxyConfigServiceLinux::Delegate::OnDestroy, this));
1738 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1739 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1740 setting_getter_->GetNotificationTaskRunner();
1741 DCHECK(!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread());
1742 setting_getter_->ShutDown();
1745 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1746 : delegate_(new Delegate(base::Environment::Create())) {
1749 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1750 delegate_->PostDestroyTask();
1753 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1754 base::Environment* env_var_getter)
1755 : delegate_(new Delegate(env_var_getter)) {
1758 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1759 base::Environment* env_var_getter, SettingGetter* setting_getter)
1760 : delegate_(new Delegate(env_var_getter, setting_getter)) {
1763 void ProxyConfigServiceLinux::AddObserver(Observer* observer) {
1764 delegate_->AddObserver(observer);
1767 void ProxyConfigServiceLinux::RemoveObserver(Observer* observer) {
1768 delegate_->RemoveObserver(observer);
1771 ProxyConfigService::ConfigAvailability
1772 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig* config) {
1773 return delegate_->GetLatestProxyConfig(config);
1776 } // namespace net