Upgrade ReadPixels to ES3 semantic in command buffer.
[chromium-blink-merge.git] / net / proxy / proxy_config_service_linux.cc
blobc26c0e11eedbbea27c6eda9a0bba5cfe7a9ea319
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_split.h"
33 #include "base/strings/string_tokenizer.h"
34 #include "base/strings/string_util.h"
35 #include "base/threading/thread_restrictions.h"
36 #include "base/timer/timer.h"
37 #include "net/base/net_errors.h"
38 #include "net/http/http_util.h"
39 #include "net/proxy/proxy_config.h"
40 #include "net/proxy/proxy_server.h"
41 #include "url/url_canon.h"
43 #if defined(USE_GIO)
44 #include "library_loaders/libgio.h"
45 #endif // defined(USE_GIO)
47 namespace net {
49 namespace {
51 // Given a proxy hostname from a setting, returns that hostname with
52 // an appropriate proxy server scheme prefix.
53 // scheme indicates the desired proxy scheme: usually http, with
54 // socks 4 or 5 as special cases.
55 // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
56 std::string FixupProxyHostScheme(ProxyServer::Scheme scheme,
57 std::string host) {
58 if (scheme == ProxyServer::SCHEME_SOCKS5 &&
59 base::StartsWith(host, "socks4://",
60 base::CompareCase::INSENSITIVE_ASCII)) {
61 // We default to socks 5, but if the user specifically set it to
62 // socks4://, then use that.
63 scheme = ProxyServer::SCHEME_SOCKS4;
65 // Strip the scheme if any.
66 std::string::size_type colon = host.find("://");
67 if (colon != std::string::npos)
68 host = host.substr(colon + 3);
69 // If a username and perhaps password are specified, give a warning.
70 std::string::size_type at_sign = host.find("@");
71 // Should this be supported?
72 if (at_sign != std::string::npos) {
73 // ProxyConfig does not support authentication parameters, but Chrome
74 // will prompt for the password later. Disregard the
75 // authentication parameters and continue with this hostname.
76 LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
77 host = host.substr(at_sign + 1);
79 // If this is a socks proxy, prepend a scheme so as to tell
80 // ProxyServer. This also allows ProxyServer to choose the right
81 // default port.
82 if (scheme == ProxyServer::SCHEME_SOCKS4)
83 host = "socks4://" + host;
84 else if (scheme == ProxyServer::SCHEME_SOCKS5)
85 host = "socks5://" + host;
86 // If there is a trailing slash, remove it so |host| will parse correctly
87 // even if it includes a port number (since the slash is not numeric).
88 if (host.length() && host[host.length() - 1] == '/')
89 host.resize(host.length() - 1);
90 return host;
93 } // namespace
95 ProxyConfigServiceLinux::Delegate::~Delegate() {
98 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
99 const char* variable, ProxyServer::Scheme scheme,
100 ProxyServer* result_server) {
101 std::string env_value;
102 if (env_var_getter_->GetVar(variable, &env_value)) {
103 if (!env_value.empty()) {
104 env_value = FixupProxyHostScheme(scheme, env_value);
105 ProxyServer proxy_server =
106 ProxyServer::FromURI(env_value, ProxyServer::SCHEME_HTTP);
107 if (proxy_server.is_valid() && !proxy_server.is_direct()) {
108 *result_server = proxy_server;
109 return true;
110 } else {
111 LOG(ERROR) << "Failed to parse environment variable " << variable;
115 return false;
118 bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
119 const char* variable, ProxyServer* result_server) {
120 return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
121 result_server);
124 bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig* config) {
125 // Check for automatic configuration first, in
126 // "auto_proxy". Possibly only the "environment_proxy" firefox
127 // extension has ever used this, but it still sounds like a good
128 // idea.
129 std::string auto_proxy;
130 if (env_var_getter_->GetVar("auto_proxy", &auto_proxy)) {
131 if (auto_proxy.empty()) {
132 // Defined and empty => autodetect
133 config->set_auto_detect(true);
134 } else {
135 // specified autoconfig URL
136 config->set_pac_url(GURL(auto_proxy));
138 return true;
140 // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
141 ProxyServer proxy_server;
142 if (GetProxyFromEnvVar("all_proxy", &proxy_server)) {
143 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
144 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
145 } else {
146 bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_server);
147 if (have_http)
148 config->proxy_rules().proxies_for_http.SetSingleProxyServer(proxy_server);
149 // It would be tempting to let http_proxy apply for all protocols
150 // if https_proxy and ftp_proxy are not defined. Googling turns up
151 // several documents that mention only http_proxy. But then the
152 // user really might not want to proxy https. And it doesn't seem
153 // like other apps do this. So we will refrain.
154 bool have_https = GetProxyFromEnvVar("https_proxy", &proxy_server);
155 if (have_https)
156 config->proxy_rules().proxies_for_https.
157 SetSingleProxyServer(proxy_server);
158 bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_server);
159 if (have_ftp)
160 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_server);
161 if (have_http || have_https || have_ftp) {
162 // mustn't change type unless some rules are actually set.
163 config->proxy_rules().type =
164 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
167 if (config->proxy_rules().empty()) {
168 // If the above were not defined, try for socks.
169 // For environment variables, we default to version 5, per the gnome
170 // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
171 ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
172 std::string env_version;
173 if (env_var_getter_->GetVar("SOCKS_VERSION", &env_version)
174 && env_version == "4")
175 scheme = ProxyServer::SCHEME_SOCKS4;
176 if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_server)) {
177 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
178 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
181 // Look for the proxy bypass list.
182 std::string no_proxy;
183 env_var_getter_->GetVar("no_proxy", &no_proxy);
184 if (config->proxy_rules().empty()) {
185 // Having only "no_proxy" set, presumably to "*", makes it
186 // explicit that env vars do specify a configuration: having no
187 // rules specified only means the user explicitly asks for direct
188 // connections.
189 return !no_proxy.empty();
191 // Note that this uses "suffix" matching. So a bypass of "google.com"
192 // is understood to mean a bypass of "*google.com".
193 config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
194 no_proxy);
195 return true;
198 namespace {
200 const int kDebounceTimeoutMilliseconds = 250;
202 #if defined(USE_GCONF)
203 // This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
204 class SettingGetterImplGConf : public ProxyConfigServiceLinux::SettingGetter {
205 public:
206 SettingGetterImplGConf()
207 : client_(NULL),
208 system_proxy_id_(0),
209 system_http_proxy_id_(0),
210 notify_delegate_(NULL),
211 debounce_timer_(new base::OneShotTimer<SettingGetterImplGConf>()) {
214 ~SettingGetterImplGConf() override {
215 // client_ should have been released before now, from
216 // Delegate::OnDestroy(), while running on the UI thread. However
217 // on exiting the process, it may happen that Delegate::OnDestroy()
218 // task is left pending on the glib loop after the loop was quit,
219 // and pending tasks may then be deleted without being run.
220 if (client_) {
221 // gconf client was not cleaned up.
222 if (task_runner_->BelongsToCurrentThread()) {
223 // We are on the UI thread so we can clean it safely. This is
224 // the case at least for ui_tests running under Valgrind in
225 // bug 16076.
226 VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
227 ShutDown();
228 } else {
229 // This is very bad! We are deleting the setting getter but we're not on
230 // the UI thread. This is not supposed to happen: the setting getter is
231 // owned by the proxy config service's delegate, which is supposed to be
232 // destroyed on the UI thread only. We will get change notifications to
233 // a deleted object if we continue here, so fail now.
234 LOG(FATAL) << "~SettingGetterImplGConf: deleting on wrong thread!";
237 DCHECK(!client_);
240 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
241 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
242 override {
243 DCHECK(glib_task_runner->BelongsToCurrentThread());
244 DCHECK(!client_);
245 DCHECK(!task_runner_.get());
246 task_runner_ = glib_task_runner;
247 client_ = gconf_client_get_default();
248 if (!client_) {
249 // It's not clear whether/when this can return NULL.
250 LOG(ERROR) << "Unable to create a gconf client";
251 task_runner_ = NULL;
252 return false;
254 GError* error = NULL;
255 bool added_system_proxy = false;
256 // We need to add the directories for which we'll be asking
257 // for notifications, and we might as well ask to preload them.
258 // These need to be removed again in ShutDown(); we are careful
259 // here to only leave client_ non-NULL if both have been added.
260 gconf_client_add_dir(client_, "/system/proxy",
261 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
262 if (error == NULL) {
263 added_system_proxy = true;
264 gconf_client_add_dir(client_, "/system/http_proxy",
265 GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
267 if (error != NULL) {
268 LOG(ERROR) << "Error requesting gconf directory: " << error->message;
269 g_error_free(error);
270 if (added_system_proxy)
271 gconf_client_remove_dir(client_, "/system/proxy", NULL);
272 g_object_unref(client_);
273 client_ = NULL;
274 task_runner_ = NULL;
275 return false;
277 return true;
280 void ShutDown() override {
281 if (client_) {
282 DCHECK(task_runner_->BelongsToCurrentThread());
283 // We must explicitly disable gconf notifications here, because the gconf
284 // client will be shared between all setting getters, and they do not all
285 // have the same lifetimes. (For instance, incognito sessions get their
286 // own, which is destroyed when the session ends.)
287 gconf_client_notify_remove(client_, system_http_proxy_id_);
288 gconf_client_notify_remove(client_, system_proxy_id_);
289 gconf_client_remove_dir(client_, "/system/http_proxy", NULL);
290 gconf_client_remove_dir(client_, "/system/proxy", NULL);
291 g_object_unref(client_);
292 client_ = NULL;
293 task_runner_ = NULL;
295 debounce_timer_.reset();
298 bool SetUpNotifications(
299 ProxyConfigServiceLinux::Delegate* delegate) override {
300 DCHECK(client_);
301 DCHECK(task_runner_->BelongsToCurrentThread());
302 GError* error = NULL;
303 notify_delegate_ = delegate;
304 // We have to keep track of the IDs returned by gconf_client_notify_add() so
305 // that we can remove them in ShutDown(). (Otherwise, notifications will be
306 // delivered to this object after it is deleted, which is bad, m'kay?)
307 system_proxy_id_ = gconf_client_notify_add(
308 client_, "/system/proxy",
309 OnGConfChangeNotification, this,
310 NULL, &error);
311 if (error == NULL) {
312 system_http_proxy_id_ = gconf_client_notify_add(
313 client_, "/system/http_proxy",
314 OnGConfChangeNotification, this,
315 NULL, &error);
317 if (error != NULL) {
318 LOG(ERROR) << "Error requesting gconf notifications: " << error->message;
319 g_error_free(error);
320 ShutDown();
321 return false;
323 // Simulate a change to avoid possibly losing updates before this point.
324 OnChangeNotification();
325 return true;
328 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
329 override {
330 return task_runner_;
333 ProxyConfigSource GetConfigSource() override {
334 return PROXY_CONFIG_SOURCE_GCONF;
337 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 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 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 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 bool BypassListIsReversed() override {
388 // This is a KDE-specific setting.
389 return false;
392 bool MatchHostsUsingSuffixMatching() override { return false; }
394 private:
395 bool GetStringByPath(const char* key, std::string* result) {
396 DCHECK(client_);
397 DCHECK(task_runner_->BelongsToCurrentThread());
398 GError* error = NULL;
399 gchar* value = gconf_client_get_string(client_, key, &error);
400 if (HandleGError(error, key))
401 return false;
402 if (!value)
403 return false;
404 *result = value;
405 g_free(value);
406 return true;
408 bool GetBoolByPath(const char* key, bool* result) {
409 DCHECK(client_);
410 DCHECK(task_runner_->BelongsToCurrentThread());
411 GError* error = NULL;
412 // We want to distinguish unset values from values defaulting to
413 // false. For that we need to use the type-generic
414 // gconf_client_get() rather than gconf_client_get_bool().
415 GConfValue* gconf_value = gconf_client_get(client_, key, &error);
416 if (HandleGError(error, key))
417 return false;
418 if (!gconf_value) {
419 // Unset.
420 return false;
422 if (gconf_value->type != GCONF_VALUE_BOOL) {
423 gconf_value_free(gconf_value);
424 return false;
426 gboolean bool_value = gconf_value_get_bool(gconf_value);
427 *result = static_cast<bool>(bool_value);
428 gconf_value_free(gconf_value);
429 return true;
431 bool GetIntByPath(const char* key, int* result) {
432 DCHECK(client_);
433 DCHECK(task_runner_->BelongsToCurrentThread());
434 GError* error = NULL;
435 int value = gconf_client_get_int(client_, key, &error);
436 if (HandleGError(error, key))
437 return false;
438 // We don't bother to distinguish an unset value because callers
439 // don't care. 0 is returned if unset.
440 *result = value;
441 return true;
443 bool GetStringListByPath(const char* key, std::vector<std::string>* result) {
444 DCHECK(client_);
445 DCHECK(task_runner_->BelongsToCurrentThread());
446 GError* error = NULL;
447 GSList* list = gconf_client_get_list(client_, key,
448 GCONF_VALUE_STRING, &error);
449 if (HandleGError(error, key))
450 return false;
451 if (!list)
452 return false;
453 for (GSList *it = list; it; it = it->next) {
454 result->push_back(static_cast<char*>(it->data));
455 g_free(it->data);
457 g_slist_free(list);
458 return true;
461 // Logs and frees a glib error. Returns false if there was no error
462 // (error is NULL).
463 bool HandleGError(GError* error, const char* key) {
464 if (error != NULL) {
465 LOG(ERROR) << "Error getting gconf value for " << key
466 << ": " << error->message;
467 g_error_free(error);
468 return true;
470 return false;
473 // This is the callback from the debounce timer.
474 void OnDebouncedNotification() {
475 DCHECK(task_runner_->BelongsToCurrentThread());
476 CHECK(notify_delegate_);
477 // Forward to a method on the proxy config service delegate object.
478 notify_delegate_->OnCheckProxyConfigSettings();
481 void OnChangeNotification() {
482 // We don't use Reset() because the timer may not yet be running.
483 // (In that case Stop() is a no-op.)
484 debounce_timer_->Stop();
485 debounce_timer_->Start(FROM_HERE,
486 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
487 this, &SettingGetterImplGConf::OnDebouncedNotification);
490 // gconf notification callback, dispatched on the default glib main loop.
491 static void OnGConfChangeNotification(GConfClient* client, guint cnxn_id,
492 GConfEntry* entry, gpointer user_data) {
493 VLOG(1) << "gconf change notification for key "
494 << gconf_entry_get_key(entry);
495 // We don't track which key has changed, just that something did change.
496 SettingGetterImplGConf* setting_getter =
497 reinterpret_cast<SettingGetterImplGConf*>(user_data);
498 setting_getter->OnChangeNotification();
501 GConfClient* client_;
502 // These ids are the values returned from gconf_client_notify_add(), which we
503 // will need in order to later call gconf_client_notify_remove().
504 guint system_proxy_id_;
505 guint system_http_proxy_id_;
507 ProxyConfigServiceLinux::Delegate* notify_delegate_;
508 scoped_ptr<base::OneShotTimer<SettingGetterImplGConf> > debounce_timer_;
510 // Task runner for the thread that we make gconf calls on. It should
511 // be the UI thread and all our methods should be called on this
512 // thread. Only for assertions.
513 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
515 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf);
517 #endif // defined(USE_GCONF)
519 #if defined(USE_GIO)
520 const char kProxyGConfSchema[] = "org.gnome.system.proxy";
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),
533 debounce_timer_(new base::OneShotTimer<SettingGetterImplGSettings>()) {
536 ~SettingGetterImplGSettings() override {
537 // client_ should have been released before now, from
538 // Delegate::OnDestroy(), while running on the UI thread. However
539 // on exiting the process, it may happen that
540 // Delegate::OnDestroy() task is left pending on the glib loop
541 // after the loop was quit, and pending tasks may then be deleted
542 // without being run.
543 if (client_) {
544 // gconf client was not cleaned up.
545 if (task_runner_->BelongsToCurrentThread()) {
546 // We are on the UI thread so we can clean it safely. This is
547 // the case at least for ui_tests running under Valgrind in
548 // bug 16076.
549 VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
550 ShutDown();
551 } else {
552 LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
553 client_ = NULL;
556 DCHECK(!client_);
559 bool SchemaExists(const char* schema_name) {
560 const gchar* const* schemas = libgio_loader_.g_settings_list_schemas();
561 while (*schemas) {
562 if (strcmp(schema_name, static_cast<const char*>(*schemas)) == 0)
563 return true;
564 schemas++;
566 return false;
569 // LoadAndCheckVersion() must be called *before* Init()!
570 bool LoadAndCheckVersion(base::Environment* env);
572 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
573 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
574 override {
575 DCHECK(glib_task_runner->BelongsToCurrentThread());
576 DCHECK(!client_);
577 DCHECK(!task_runner_.get());
579 if (!SchemaExists(kProxyGConfSchema) ||
580 !(client_ = libgio_loader_.g_settings_new(kProxyGConfSchema))) {
581 // It's not clear whether/when this can return NULL.
582 LOG(ERROR) << "Unable to create a gsettings client";
583 return false;
585 task_runner_ = glib_task_runner;
586 // We assume these all work if the above call worked.
587 http_client_ = libgio_loader_.g_settings_get_child(client_, "http");
588 https_client_ = libgio_loader_.g_settings_get_child(client_, "https");
589 ftp_client_ = libgio_loader_.g_settings_get_child(client_, "ftp");
590 socks_client_ = libgio_loader_.g_settings_get_child(client_, "socks");
591 DCHECK(http_client_ && https_client_ && ftp_client_ && socks_client_);
592 return true;
595 void ShutDown() override {
596 if (client_) {
597 DCHECK(task_runner_->BelongsToCurrentThread());
598 // This also disables gsettings notifications.
599 g_object_unref(socks_client_);
600 g_object_unref(ftp_client_);
601 g_object_unref(https_client_);
602 g_object_unref(http_client_);
603 g_object_unref(client_);
604 // We only need to null client_ because it's the only one that we check.
605 client_ = NULL;
606 task_runner_ = NULL;
608 debounce_timer_.reset();
611 bool SetUpNotifications(
612 ProxyConfigServiceLinux::Delegate* delegate) override {
613 DCHECK(client_);
614 DCHECK(task_runner_->BelongsToCurrentThread());
615 notify_delegate_ = delegate;
616 // We could watch for the change-event signal instead of changed, but
617 // since we have to watch more than one object, we'd still have to
618 // debounce change notifications. This is conceptually simpler.
619 g_signal_connect(G_OBJECT(client_), "changed",
620 G_CALLBACK(OnGSettingsChangeNotification), this);
621 g_signal_connect(G_OBJECT(http_client_), "changed",
622 G_CALLBACK(OnGSettingsChangeNotification), this);
623 g_signal_connect(G_OBJECT(https_client_), "changed",
624 G_CALLBACK(OnGSettingsChangeNotification), this);
625 g_signal_connect(G_OBJECT(ftp_client_), "changed",
626 G_CALLBACK(OnGSettingsChangeNotification), this);
627 g_signal_connect(G_OBJECT(socks_client_), "changed",
628 G_CALLBACK(OnGSettingsChangeNotification), this);
629 // Simulate a change to avoid possibly losing updates before this point.
630 OnChangeNotification();
631 return true;
634 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
635 override {
636 return task_runner_;
639 ProxyConfigSource GetConfigSource() override {
640 return PROXY_CONFIG_SOURCE_GSETTINGS;
643 bool GetString(StringSetting key, std::string* result) override {
644 DCHECK(client_);
645 switch (key) {
646 case PROXY_MODE:
647 return GetStringByPath(client_, "mode", result);
648 case PROXY_AUTOCONF_URL:
649 return GetStringByPath(client_, "autoconfig-url", result);
650 case PROXY_HTTP_HOST:
651 return GetStringByPath(http_client_, "host", result);
652 case PROXY_HTTPS_HOST:
653 return GetStringByPath(https_client_, "host", result);
654 case PROXY_FTP_HOST:
655 return GetStringByPath(ftp_client_, "host", result);
656 case PROXY_SOCKS_HOST:
657 return GetStringByPath(socks_client_, "host", result);
659 return false; // Placate compiler.
661 bool GetBool(BoolSetting key, bool* result) override {
662 DCHECK(client_);
663 switch (key) {
664 case PROXY_USE_HTTP_PROXY:
665 // Although there is an "enabled" boolean in http_client_, it is not set
666 // to true by the proxy config utility. We ignore it and return false.
667 return false;
668 case PROXY_USE_SAME_PROXY:
669 // Similarly, although there is a "use-same-proxy" boolean in client_,
670 // it is never set to false by the proxy config utility. We ignore it.
671 return false;
672 case PROXY_USE_AUTHENTICATION:
673 // There is also no way to set this in the proxy config utility, but it
674 // doesn't hurt us to get the actual setting (unlike the two above).
675 return GetBoolByPath(http_client_, "use-authentication", result);
677 return false; // Placate compiler.
679 bool GetInt(IntSetting key, int* result) override {
680 DCHECK(client_);
681 switch (key) {
682 case PROXY_HTTP_PORT:
683 return GetIntByPath(http_client_, "port", result);
684 case PROXY_HTTPS_PORT:
685 return GetIntByPath(https_client_, "port", result);
686 case PROXY_FTP_PORT:
687 return GetIntByPath(ftp_client_, "port", result);
688 case PROXY_SOCKS_PORT:
689 return GetIntByPath(socks_client_, "port", result);
691 return false; // Placate compiler.
693 bool GetStringList(StringListSetting key,
694 std::vector<std::string>* result) override {
695 DCHECK(client_);
696 switch (key) {
697 case PROXY_IGNORE_HOSTS:
698 return GetStringListByPath(client_, "ignore-hosts", result);
700 return false; // Placate compiler.
703 bool BypassListIsReversed() override {
704 // This is a KDE-specific setting.
705 return false;
708 bool MatchHostsUsingSuffixMatching() override { return false; }
710 private:
711 bool GetStringByPath(GSettings* client, const char* key,
712 std::string* result) {
713 DCHECK(task_runner_->BelongsToCurrentThread());
714 gchar* value = libgio_loader_.g_settings_get_string(client, key);
715 if (!value)
716 return false;
717 *result = value;
718 g_free(value);
719 return true;
721 bool GetBoolByPath(GSettings* client, const char* key, bool* result) {
722 DCHECK(task_runner_->BelongsToCurrentThread());
723 *result = static_cast<bool>(
724 libgio_loader_.g_settings_get_boolean(client, key));
725 return true;
727 bool GetIntByPath(GSettings* client, const char* key, int* result) {
728 DCHECK(task_runner_->BelongsToCurrentThread());
729 *result = libgio_loader_.g_settings_get_int(client, key);
730 return true;
732 bool GetStringListByPath(GSettings* client, const char* key,
733 std::vector<std::string>* result) {
734 DCHECK(task_runner_->BelongsToCurrentThread());
735 gchar** list = libgio_loader_.g_settings_get_strv(client, key);
736 if (!list)
737 return false;
738 for (size_t i = 0; list[i]; ++i) {
739 result->push_back(static_cast<char*>(list[i]));
740 g_free(list[i]);
742 g_free(list);
743 return true;
746 // This is the callback from the debounce timer.
747 void OnDebouncedNotification() {
748 DCHECK(task_runner_->BelongsToCurrentThread());
749 CHECK(notify_delegate_);
750 // Forward to a method on the proxy config service delegate object.
751 notify_delegate_->OnCheckProxyConfigSettings();
754 void OnChangeNotification() {
755 // We don't use Reset() because the timer may not yet be running.
756 // (In that case Stop() is a no-op.)
757 debounce_timer_->Stop();
758 debounce_timer_->Start(FROM_HERE,
759 base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
760 this, &SettingGetterImplGSettings::OnDebouncedNotification);
763 // gsettings notification callback, dispatched on the default glib main loop.
764 static void OnGSettingsChangeNotification(GSettings* client, gchar* key,
765 gpointer user_data) {
766 VLOG(1) << "gsettings change notification for key " << key;
767 // We don't track which key has changed, just that something did change.
768 SettingGetterImplGSettings* setting_getter =
769 reinterpret_cast<SettingGetterImplGSettings*>(user_data);
770 setting_getter->OnChangeNotification();
773 GSettings* client_;
774 GSettings* http_client_;
775 GSettings* https_client_;
776 GSettings* ftp_client_;
777 GSettings* socks_client_;
778 ProxyConfigServiceLinux::Delegate* notify_delegate_;
779 scoped_ptr<base::OneShotTimer<SettingGetterImplGSettings> > debounce_timer_;
781 // Task runner for the thread that we make gsettings calls on. It should
782 // be the UI thread and all our methods should be called on this
783 // thread. Only for assertions.
784 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
786 LibGioLoader libgio_loader_;
788 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings);
791 bool SettingGetterImplGSettings::LoadAndCheckVersion(
792 base::Environment* env) {
793 // LoadAndCheckVersion() must be called *before* Init()!
794 DCHECK(!client_);
796 // The APIs to query gsettings were introduced after the minimum glib
797 // version we target, so we can't link directly against them. We load them
798 // dynamically at runtime, and if they don't exist, return false here. (We
799 // support linking directly via gyp flags though.) Additionally, even when
800 // they are present, we do two additional checks to make sure we should use
801 // them and not gconf. First, we attempt to load the schema for proxy
802 // settings. Second, we check for the program that was used in older
803 // versions of GNOME to configure proxy settings, and return false if it
804 // exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
805 // but don't use gsettings for proxy settings, but they do have the old
806 // binary, so we detect these systems that way.
809 // TODO(phajdan.jr): Redesign the code to load library on different thread.
810 base::ThreadRestrictions::ScopedAllowIO allow_io;
812 // Try also without .0 at the end; on some systems this may be required.
813 if (!libgio_loader_.Load("libgio-2.0.so.0") &&
814 !libgio_loader_.Load("libgio-2.0.so")) {
815 VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
816 return false;
820 GSettings* client = NULL;
821 if (SchemaExists(kProxyGConfSchema)) {
822 ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/380782
823 client = libgio_loader_.g_settings_new(kProxyGConfSchema);
825 if (!client) {
826 VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
827 return false;
829 g_object_unref(client);
831 std::string path;
832 if (!env->GetVar("PATH", &path)) {
833 LOG(ERROR) << "No $PATH variable. Assuming no gnome-network-properties.";
834 } else {
835 // Yes, we're on the UI thread. Yes, we're accessing the file system.
836 // Sadly, we don't have much choice. We need the proxy settings and we
837 // need them now, and to figure out where to get them, we have to check
838 // for this binary. See http://crbug.com/69057 for additional details.
839 base::ThreadRestrictions::ScopedAllowIO allow_io;
841 for (const base::StringPiece& path_str : base::SplitStringPiece(
842 path, ":", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
843 base::FilePath file(path_str);
844 if (base::PathExists(file.Append("gnome-network-properties"))) {
845 VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
846 return false;
851 VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
852 return true;
854 #endif // defined(USE_GIO)
856 // This is the KDE version that reads kioslaverc and simulates gconf.
857 // Doing this allows the main Delegate code, as well as the unit tests
858 // for it, to stay the same - and the settings map fairly well besides.
859 class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter,
860 public base::MessagePumpLibevent::Watcher {
861 public:
862 explicit SettingGetterImplKDE(base::Environment* env_var_getter)
863 : inotify_fd_(-1),
864 notify_delegate_(NULL),
865 debounce_timer_(new base::OneShotTimer<SettingGetterImplKDE>()),
866 indirect_manual_(false),
867 auto_no_pac_(false),
868 reversed_bypass_list_(false),
869 env_var_getter_(env_var_getter),
870 file_task_runner_(NULL) {
871 // This has to be called on the UI thread (http://crbug.com/69057).
872 base::ThreadRestrictions::ScopedAllowIO allow_io;
874 // Derive the location of the kde config dir from the environment.
875 std::string home;
876 if (env_var_getter->GetVar("KDEHOME", &home) && !home.empty()) {
877 // $KDEHOME is set. Use it unconditionally.
878 kde_config_dir_ = KDEHomeToConfigPath(base::FilePath(home));
879 } else {
880 // $KDEHOME is unset. Try to figure out what to use. This seems to be
881 // the common case on most distributions.
882 if (!env_var_getter->GetVar(base::env_vars::kHome, &home))
883 // User has no $HOME? Give up. Later we'll report the failure.
884 return;
885 if (base::nix::GetDesktopEnvironment(env_var_getter) ==
886 base::nix::DESKTOP_ENVIRONMENT_KDE3) {
887 // KDE3 always uses .kde for its configuration.
888 base::FilePath kde_path = base::FilePath(home).Append(".kde");
889 kde_config_dir_ = KDEHomeToConfigPath(kde_path);
890 } else {
891 // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
892 // both can be installed side-by-side. Sadly they don't all do this, and
893 // they don't always do this: some distributions have started switching
894 // back as well. So if there is a .kde4 directory, check the timestamps
895 // of the config directories within and use the newest one.
896 // Note that we should currently be running in the UI thread, because in
897 // the gconf version, that is the only thread that can access the proxy
898 // settings (a gconf restriction). As noted below, the initial read of
899 // the proxy settings will be done in this thread anyway, so we check
900 // for .kde4 here in this thread as well.
901 base::FilePath kde3_path = base::FilePath(home).Append(".kde");
902 base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
903 base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
904 base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
905 bool use_kde4 = false;
906 if (base::DirectoryExists(kde4_path)) {
907 base::File::Info kde3_info;
908 base::File::Info kde4_info;
909 if (base::GetFileInfo(kde4_config, &kde4_info)) {
910 if (base::GetFileInfo(kde3_config, &kde3_info)) {
911 use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
912 } else {
913 use_kde4 = true;
917 if (use_kde4) {
918 kde_config_dir_ = KDEHomeToConfigPath(kde4_path);
919 } else {
920 kde_config_dir_ = KDEHomeToConfigPath(kde3_path);
926 ~SettingGetterImplKDE() override {
927 // inotify_fd_ should have been closed before now, from
928 // Delegate::OnDestroy(), while running on the file thread. However
929 // on exiting the process, it may happen that Delegate::OnDestroy()
930 // task is left pending on the file loop after the loop was quit,
931 // and pending tasks may then be deleted without being run.
932 // Here in the KDE version, we can safely close the file descriptor
933 // anyway. (Not that it really matters; the process is exiting.)
934 if (inotify_fd_ >= 0)
935 ShutDown();
936 DCHECK(inotify_fd_ < 0);
939 bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
940 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
941 override {
942 // This has to be called on the UI thread (http://crbug.com/69057).
943 base::ThreadRestrictions::ScopedAllowIO allow_io;
944 DCHECK(inotify_fd_ < 0);
945 inotify_fd_ = inotify_init();
946 if (inotify_fd_ < 0) {
947 PLOG(ERROR) << "inotify_init failed";
948 return false;
950 int flags = fcntl(inotify_fd_, F_GETFL);
951 if (fcntl(inotify_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
952 PLOG(ERROR) << "fcntl failed";
953 close(inotify_fd_);
954 inotify_fd_ = -1;
955 return false;
957 file_task_runner_ = file_task_runner;
958 // The initial read is done on the current thread, not
959 // |file_task_runner_|, since we will need to have it for
960 // SetUpAndFetchInitialConfig().
961 UpdateCachedSettings();
962 return true;
965 void ShutDown() override {
966 if (inotify_fd_ >= 0) {
967 ResetCachedSettings();
968 inotify_watcher_.StopWatchingFileDescriptor();
969 close(inotify_fd_);
970 inotify_fd_ = -1;
972 debounce_timer_.reset();
975 bool SetUpNotifications(
976 ProxyConfigServiceLinux::Delegate* delegate) override {
977 DCHECK(inotify_fd_ >= 0);
978 DCHECK(file_task_runner_->BelongsToCurrentThread());
979 // We can't just watch the kioslaverc file directly, since KDE will write
980 // a new copy of it and then rename it whenever settings are changed and
981 // inotify watches inodes (so we'll be watching the old deleted file after
982 // the first change, and it will never change again). So, we watch the
983 // directory instead. We then act only on changes to the kioslaverc entry.
984 if (inotify_add_watch(inotify_fd_, kde_config_dir_.value().c_str(),
985 IN_MODIFY | IN_MOVED_TO) < 0) {
986 return false;
988 notify_delegate_ = delegate;
989 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
990 inotify_fd_, true, base::MessageLoopForIO::WATCH_READ,
991 &inotify_watcher_, this)) {
992 return false;
994 // Simulate a change to avoid possibly losing updates before this point.
995 OnChangeNotification();
996 return true;
999 const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
1000 override {
1001 return file_task_runner_;
1004 // Implement base::MessagePumpLibevent::Watcher.
1005 void OnFileCanReadWithoutBlocking(int fd) override {
1006 DCHECK_EQ(fd, inotify_fd_);
1007 DCHECK(file_task_runner_->BelongsToCurrentThread());
1008 OnChangeNotification();
1010 void OnFileCanWriteWithoutBlocking(int fd) override { NOTREACHED(); }
1012 ProxyConfigSource GetConfigSource() override {
1013 return PROXY_CONFIG_SOURCE_KDE;
1016 bool GetString(StringSetting key, std::string* result) override {
1017 string_map_type::iterator it = string_table_.find(key);
1018 if (it == string_table_.end())
1019 return false;
1020 *result = it->second;
1021 return true;
1023 bool GetBool(BoolSetting key, bool* result) override {
1024 // We don't ever have any booleans.
1025 return false;
1027 bool GetInt(IntSetting key, int* result) override {
1028 // We don't ever have any integers. (See AddProxy() below about ports.)
1029 return false;
1031 bool GetStringList(StringListSetting key,
1032 std::vector<std::string>* result) override {
1033 strings_map_type::iterator it = strings_table_.find(key);
1034 if (it == strings_table_.end())
1035 return false;
1036 *result = it->second;
1037 return true;
1040 bool BypassListIsReversed() override { return reversed_bypass_list_; }
1042 bool MatchHostsUsingSuffixMatching() override { return true; }
1044 private:
1045 void ResetCachedSettings() {
1046 string_table_.clear();
1047 strings_table_.clear();
1048 indirect_manual_ = false;
1049 auto_no_pac_ = false;
1050 reversed_bypass_list_ = false;
1053 base::FilePath KDEHomeToConfigPath(const base::FilePath& kde_home) {
1054 return kde_home.Append("share").Append("config");
1057 void AddProxy(StringSetting host_key, const std::string& value) {
1058 if (value.empty() || value.substr(0, 3) == "//:")
1059 // No proxy.
1060 return;
1061 size_t space = value.find(' ');
1062 if (space != std::string::npos) {
1063 // Newer versions of KDE use a space rather than a colon to separate the
1064 // port number from the hostname. If we find this, we need to convert it.
1065 std::string fixed = value;
1066 fixed[space] = ':';
1067 string_table_[host_key] = fixed;
1068 } else {
1069 // We don't need to parse the port number out; GetProxyFromSettings()
1070 // would only append it right back again. So we just leave the port
1071 // number right in the host string.
1072 string_table_[host_key] = value;
1076 void AddHostList(StringListSetting key, const std::string& value) {
1077 std::vector<std::string> tokens;
1078 base::StringTokenizer tk(value, ", ");
1079 while (tk.GetNext()) {
1080 std::string token = tk.token();
1081 if (!token.empty())
1082 tokens.push_back(token);
1084 strings_table_[key] = tokens;
1087 void AddKDESetting(const std::string& key, const std::string& value) {
1088 if (key == "ProxyType") {
1089 const char* mode = "none";
1090 indirect_manual_ = false;
1091 auto_no_pac_ = false;
1092 int int_value;
1093 base::StringToInt(value, &int_value);
1094 switch (int_value) {
1095 case 0: // No proxy, or maybe kioslaverc syntax error.
1096 break;
1097 case 1: // Manual configuration.
1098 mode = "manual";
1099 break;
1100 case 2: // PAC URL.
1101 mode = "auto";
1102 break;
1103 case 3: // WPAD.
1104 mode = "auto";
1105 auto_no_pac_ = true;
1106 break;
1107 case 4: // Indirect manual via environment variables.
1108 mode = "manual";
1109 indirect_manual_ = true;
1110 break;
1112 string_table_[PROXY_MODE] = mode;
1113 } else if (key == "Proxy Config Script") {
1114 string_table_[PROXY_AUTOCONF_URL] = value;
1115 } else if (key == "httpProxy") {
1116 AddProxy(PROXY_HTTP_HOST, value);
1117 } else if (key == "httpsProxy") {
1118 AddProxy(PROXY_HTTPS_HOST, value);
1119 } else if (key == "ftpProxy") {
1120 AddProxy(PROXY_FTP_HOST, value);
1121 } else if (key == "socksProxy") {
1122 // Older versions of KDE configure SOCKS in a weird way involving
1123 // LD_PRELOAD and a library that intercepts network calls to SOCKSify
1124 // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
1125 AddProxy(PROXY_SOCKS_HOST, value);
1126 } else if (key == "ReversedException") {
1127 // We count "true" or any nonzero number as true, otherwise false.
1128 // Note that if the value is not actually numeric StringToInt()
1129 // will return 0, which we count as false.
1130 int int_value;
1131 base::StringToInt(value, &int_value);
1132 reversed_bypass_list_ = (value == "true" || int_value);
1133 } else if (key == "NoProxyFor") {
1134 AddHostList(PROXY_IGNORE_HOSTS, value);
1135 } else if (key == "AuthMode") {
1136 // Check for authentication, just so we can warn.
1137 int mode;
1138 base::StringToInt(value, &mode);
1139 if (mode) {
1140 // ProxyConfig does not support authentication parameters, but
1141 // Chrome will prompt for the password later. So we ignore this.
1142 LOG(WARNING) <<
1143 "Proxy authentication parameters ignored, see bug 16709";
1148 void ResolveIndirect(StringSetting key) {
1149 string_map_type::iterator it = string_table_.find(key);
1150 if (it != string_table_.end()) {
1151 std::string value;
1152 if (env_var_getter_->GetVar(it->second.c_str(), &value))
1153 it->second = value;
1154 else
1155 string_table_.erase(it);
1159 void ResolveIndirectList(StringListSetting key) {
1160 strings_map_type::iterator it = strings_table_.find(key);
1161 if (it != strings_table_.end()) {
1162 std::string value;
1163 if (!it->second.empty() &&
1164 env_var_getter_->GetVar(it->second[0].c_str(), &value))
1165 AddHostList(key, value);
1166 else
1167 strings_table_.erase(it);
1171 // The settings in kioslaverc could occur in any order, but some affect
1172 // others. Rather than read the whole file in and then query them in an
1173 // order that allows us to handle that, we read the settings in whatever
1174 // order they occur and do any necessary tweaking after we finish.
1175 void ResolveModeEffects() {
1176 if (indirect_manual_) {
1177 ResolveIndirect(PROXY_HTTP_HOST);
1178 ResolveIndirect(PROXY_HTTPS_HOST);
1179 ResolveIndirect(PROXY_FTP_HOST);
1180 ResolveIndirectList(PROXY_IGNORE_HOSTS);
1182 if (auto_no_pac_) {
1183 // Remove the PAC URL; we're not supposed to use it.
1184 string_table_.erase(PROXY_AUTOCONF_URL);
1188 // Reads kioslaverc one line at a time and calls AddKDESetting() to add
1189 // each relevant name-value pair to the appropriate value table.
1190 void UpdateCachedSettings() {
1191 base::FilePath kioslaverc = kde_config_dir_.Append("kioslaverc");
1192 base::ScopedFILE input(base::OpenFile(kioslaverc, "r"));
1193 if (!input.get())
1194 return;
1195 ResetCachedSettings();
1196 bool in_proxy_settings = false;
1197 bool line_too_long = false;
1198 char line[BUFFER_SIZE];
1199 // fgets() will return NULL on EOF or error.
1200 while (fgets(line, sizeof(line), input.get())) {
1201 // fgets() guarantees the line will be properly terminated.
1202 size_t length = strlen(line);
1203 if (!length)
1204 continue;
1205 // This should be true even with CRLF endings.
1206 if (line[length - 1] != '\n') {
1207 line_too_long = true;
1208 continue;
1210 if (line_too_long) {
1211 // The previous line had no line ending, but this done does. This is
1212 // the end of the line that was too long, so warn here and skip it.
1213 LOG(WARNING) << "skipped very long line in " << kioslaverc.value();
1214 line_too_long = false;
1215 continue;
1217 // Remove the LF at the end, and the CR if there is one.
1218 line[--length] = '\0';
1219 if (length && line[length - 1] == '\r')
1220 line[--length] = '\0';
1221 // Now parse the line.
1222 if (line[0] == '[') {
1223 // Switching sections. All we care about is whether this is
1224 // the (a?) proxy settings section, for both KDE3 and KDE4.
1225 in_proxy_settings = !strncmp(line, "[Proxy Settings]", 16);
1226 } else if (in_proxy_settings) {
1227 // A regular line, in the (a?) proxy settings section.
1228 char* split = strchr(line, '=');
1229 // Skip this line if it does not contain an = sign.
1230 if (!split)
1231 continue;
1232 // Split the line on the = and advance |split|.
1233 *(split++) = 0;
1234 std::string key = line;
1235 std::string value = split;
1236 base::TrimWhitespaceASCII(key, base::TRIM_ALL, &key);
1237 base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
1238 // Skip this line if the key name is empty.
1239 if (key.empty())
1240 continue;
1241 // Is the value name localized?
1242 if (key[key.length() - 1] == ']') {
1243 // Find the matching bracket.
1244 length = key.rfind('[');
1245 // Skip this line if the localization indicator is malformed.
1246 if (length == std::string::npos)
1247 continue;
1248 // Trim the localization indicator off.
1249 key.resize(length);
1250 // Remove any resulting trailing whitespace.
1251 base::TrimWhitespaceASCII(key, base::TRIM_TRAILING, &key);
1252 // Skip this line if the key name is now empty.
1253 if (key.empty())
1254 continue;
1256 // Now fill in the tables.
1257 AddKDESetting(key, value);
1260 if (ferror(input.get()))
1261 LOG(ERROR) << "error reading " << kioslaverc.value();
1262 ResolveModeEffects();
1265 // This is the callback from the debounce timer.
1266 void OnDebouncedNotification() {
1267 DCHECK(file_task_runner_->BelongsToCurrentThread());
1268 VLOG(1) << "inotify change notification for kioslaverc";
1269 UpdateCachedSettings();
1270 CHECK(notify_delegate_);
1271 // Forward to a method on the proxy config service delegate object.
1272 notify_delegate_->OnCheckProxyConfigSettings();
1275 // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
1276 // from the inotify file descriptor and starts up a debounce timer if
1277 // an event for kioslaverc is seen.
1278 void OnChangeNotification() {
1279 DCHECK_GE(inotify_fd_, 0);
1280 DCHECK(file_task_runner_->BelongsToCurrentThread());
1281 char event_buf[(sizeof(inotify_event) + NAME_MAX + 1) * 4];
1282 bool kioslaverc_touched = false;
1283 ssize_t r;
1284 while ((r = read(inotify_fd_, event_buf, sizeof(event_buf))) > 0) {
1285 // inotify returns variable-length structures, which is why we have
1286 // this strange-looking loop instead of iterating through an array.
1287 char* event_ptr = event_buf;
1288 while (event_ptr < event_buf + r) {
1289 inotify_event* event = reinterpret_cast<inotify_event*>(event_ptr);
1290 // The kernel always feeds us whole events.
1291 CHECK_LE(event_ptr + sizeof(inotify_event), event_buf + r);
1292 CHECK_LE(event->name + event->len, event_buf + r);
1293 if (!strcmp(event->name, "kioslaverc"))
1294 kioslaverc_touched = true;
1295 // Advance the pointer just past the end of the filename.
1296 event_ptr = event->name + event->len;
1298 // We keep reading even if |kioslaverc_touched| is true to drain the
1299 // inotify event queue.
1301 if (!r)
1302 // Instead of returning -1 and setting errno to EINVAL if there is not
1303 // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
1304 // new behavior (EINVAL) so we can reuse the code below.
1305 errno = EINVAL;
1306 if (errno != EAGAIN) {
1307 PLOG(WARNING) << "error reading inotify file descriptor";
1308 if (errno == EINVAL) {
1309 // Our buffer is not large enough to read the next event. This should
1310 // not happen (because its size is calculated to always be sufficiently
1311 // large), but if it does we'd warn continuously since |inotify_fd_|
1312 // would be forever ready to read. Close it and stop watching instead.
1313 LOG(ERROR) << "inotify failure; no longer watching kioslaverc!";
1314 inotify_watcher_.StopWatchingFileDescriptor();
1315 close(inotify_fd_);
1316 inotify_fd_ = -1;
1319 if (kioslaverc_touched) {
1320 // We don't use Reset() because the timer may not yet be running.
1321 // (In that case Stop() is a no-op.)
1322 debounce_timer_->Stop();
1323 debounce_timer_->Start(FROM_HERE, base::TimeDelta::FromMilliseconds(
1324 kDebounceTimeoutMilliseconds), this,
1325 &SettingGetterImplKDE::OnDebouncedNotification);
1329 typedef std::map<StringSetting, std::string> string_map_type;
1330 typedef std::map<StringListSetting,
1331 std::vector<std::string> > strings_map_type;
1333 int inotify_fd_;
1334 base::MessagePumpLibevent::FileDescriptorWatcher inotify_watcher_;
1335 ProxyConfigServiceLinux::Delegate* notify_delegate_;
1336 scoped_ptr<base::OneShotTimer<SettingGetterImplKDE> > debounce_timer_;
1337 base::FilePath kde_config_dir_;
1338 bool indirect_manual_;
1339 bool auto_no_pac_;
1340 bool reversed_bypass_list_;
1341 // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
1342 // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
1343 // same lifetime.
1344 base::Environment* env_var_getter_;
1346 // We cache these settings whenever we re-read the kioslaverc file.
1347 string_map_type string_table_;
1348 strings_map_type strings_table_;
1350 // Task runner of the file thread, for reading kioslaverc. If NULL,
1351 // just read it directly (for testing). We also handle inotify events
1352 // on this thread.
1353 scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_;
1355 DISALLOW_COPY_AND_ASSIGN(SettingGetterImplKDE);
1358 } // namespace
1360 bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
1361 SettingGetter::StringSetting host_key,
1362 ProxyServer* result_server) {
1363 std::string host;
1364 if (!setting_getter_->GetString(host_key, &host) || host.empty()) {
1365 // Unset or empty.
1366 return false;
1368 // Check for an optional port.
1369 int port = 0;
1370 SettingGetter::IntSetting port_key =
1371 SettingGetter::HostSettingToPortSetting(host_key);
1372 setting_getter_->GetInt(port_key, &port);
1373 if (port != 0) {
1374 // If a port is set and non-zero:
1375 host += ":" + base::IntToString(port);
1378 // gconf settings do not appear to distinguish between SOCKS version. We
1379 // default to version 5. For more information on this policy decision, see:
1380 // http://code.google.com/p/chromium/issues/detail?id=55912#c2
1381 ProxyServer::Scheme scheme = (host_key == SettingGetter::PROXY_SOCKS_HOST) ?
1382 ProxyServer::SCHEME_SOCKS5 : ProxyServer::SCHEME_HTTP;
1383 host = FixupProxyHostScheme(scheme, host);
1384 ProxyServer proxy_server = ProxyServer::FromURI(host,
1385 ProxyServer::SCHEME_HTTP);
1386 if (proxy_server.is_valid()) {
1387 *result_server = proxy_server;
1388 return true;
1390 return false;
1393 bool ProxyConfigServiceLinux::Delegate::GetConfigFromSettings(
1394 ProxyConfig* config) {
1395 std::string mode;
1396 if (!setting_getter_->GetString(SettingGetter::PROXY_MODE, &mode)) {
1397 // We expect this to always be set, so if we don't see it then we
1398 // probably have a gconf/gsettings problem, and so we don't have a valid
1399 // proxy config.
1400 return false;
1402 if (mode == "none") {
1403 // Specifically specifies no proxy.
1404 return true;
1407 if (mode == "auto") {
1408 // Automatic proxy config.
1409 std::string pac_url_str;
1410 if (setting_getter_->GetString(SettingGetter::PROXY_AUTOCONF_URL,
1411 &pac_url_str)) {
1412 if (!pac_url_str.empty()) {
1413 // If the PAC URL is actually a file path, then put file:// in front.
1414 if (pac_url_str[0] == '/')
1415 pac_url_str = "file://" + pac_url_str;
1416 GURL pac_url(pac_url_str);
1417 if (!pac_url.is_valid())
1418 return false;
1419 config->set_pac_url(pac_url);
1420 return true;
1423 config->set_auto_detect(true);
1424 return true;
1427 if (mode != "manual") {
1428 // Mode is unrecognized.
1429 return false;
1431 bool use_http_proxy;
1432 if (setting_getter_->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY,
1433 &use_http_proxy)
1434 && !use_http_proxy) {
1435 // Another master switch for some reason. If set to false, then no
1436 // proxy. But we don't panic if the key doesn't exist.
1437 return true;
1440 bool same_proxy = false;
1441 // Indicates to use the http proxy for all protocols. This one may
1442 // not exist (presumably on older versions); we assume false in that
1443 // case.
1444 setting_getter_->GetBool(SettingGetter::PROXY_USE_SAME_PROXY,
1445 &same_proxy);
1447 ProxyServer proxy_for_http;
1448 ProxyServer proxy_for_https;
1449 ProxyServer proxy_for_ftp;
1450 ProxyServer socks_proxy; // (socks)
1452 // This counts how many of the above ProxyServers were defined and valid.
1453 size_t num_proxies_specified = 0;
1455 // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
1456 // specified for the scheme, then the resulting ProxyServer will be invalid.
1457 if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST, &proxy_for_http))
1458 num_proxies_specified++;
1459 if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST, &proxy_for_https))
1460 num_proxies_specified++;
1461 if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST, &proxy_for_ftp))
1462 num_proxies_specified++;
1463 if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST, &socks_proxy))
1464 num_proxies_specified++;
1466 if (same_proxy) {
1467 if (proxy_for_http.is_valid()) {
1468 // Use the http proxy for all schemes.
1469 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1470 config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_for_http);
1472 } else if (num_proxies_specified > 0) {
1473 if (socks_proxy.is_valid() && num_proxies_specified == 1) {
1474 // If the only proxy specified was for SOCKS, use it for all schemes.
1475 config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
1476 config->proxy_rules().single_proxies.SetSingleProxyServer(socks_proxy);
1477 } else {
1478 // Otherwise use the indicated proxies per-scheme.
1479 config->proxy_rules().type =
1480 ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
1481 config->proxy_rules().proxies_for_http.
1482 SetSingleProxyServer(proxy_for_http);
1483 config->proxy_rules().proxies_for_https.
1484 SetSingleProxyServer(proxy_for_https);
1485 config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_for_ftp);
1486 config->proxy_rules().fallback_proxies.SetSingleProxyServer(socks_proxy);
1490 if (config->proxy_rules().empty()) {
1491 // Manual mode but we couldn't parse any rules.
1492 return false;
1495 // Check for authentication, just so we can warn.
1496 bool use_auth = false;
1497 setting_getter_->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION,
1498 &use_auth);
1499 if (use_auth) {
1500 // ProxyConfig does not support authentication parameters, but
1501 // Chrome will prompt for the password later. So we ignore
1502 // /system/http_proxy/*auth* settings.
1503 LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
1506 // Now the bypass list.
1507 std::vector<std::string> ignore_hosts_list;
1508 config->proxy_rules().bypass_rules.Clear();
1509 if (setting_getter_->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS,
1510 &ignore_hosts_list)) {
1511 std::vector<std::string>::const_iterator it(ignore_hosts_list.begin());
1512 for (; it != ignore_hosts_list.end(); ++it) {
1513 if (setting_getter_->MatchHostsUsingSuffixMatching()) {
1514 config->proxy_rules().bypass_rules.
1515 AddRuleFromStringUsingSuffixMatching(*it);
1516 } else {
1517 config->proxy_rules().bypass_rules.AddRuleFromString(*it);
1521 // Note that there are no settings with semantics corresponding to
1522 // bypass of local names in GNOME. In KDE, "<local>" is supported
1523 // as a hostname rule.
1525 // KDE allows one to reverse the bypass rules.
1526 config->proxy_rules().reverse_bypass =
1527 setting_getter_->BypassListIsReversed();
1529 return true;
1532 ProxyConfigServiceLinux::Delegate::Delegate(base::Environment* env_var_getter)
1533 : env_var_getter_(env_var_getter) {
1534 // Figure out which SettingGetterImpl to use, if any.
1535 switch (base::nix::GetDesktopEnvironment(env_var_getter)) {
1536 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
1537 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
1538 #if defined(USE_GIO)
1540 scoped_ptr<SettingGetterImplGSettings> gs_getter(
1541 new SettingGetterImplGSettings());
1542 // We have to load symbols and check the GNOME version in use to decide
1543 // if we should use the gsettings getter. See LoadAndCheckVersion().
1544 if (gs_getter->LoadAndCheckVersion(env_var_getter))
1545 setting_getter_.reset(gs_getter.release());
1547 #endif
1548 #if defined(USE_GCONF)
1549 // Fall back on gconf if gsettings is unavailable or incorrect.
1550 if (!setting_getter_.get())
1551 setting_getter_.reset(new SettingGetterImplGConf());
1552 #endif
1553 break;
1554 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
1555 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
1556 setting_getter_.reset(new SettingGetterImplKDE(env_var_getter));
1557 break;
1558 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
1559 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
1560 break;
1564 ProxyConfigServiceLinux::Delegate::Delegate(
1565 base::Environment* env_var_getter, SettingGetter* setting_getter)
1566 : env_var_getter_(env_var_getter), setting_getter_(setting_getter) {
1569 void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
1570 const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
1571 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
1572 const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner) {
1573 // We should be running on the default glib main loop thread right
1574 // now. gconf can only be accessed from this thread.
1575 DCHECK(glib_task_runner->BelongsToCurrentThread());
1576 glib_task_runner_ = glib_task_runner;
1577 io_task_runner_ = io_task_runner;
1579 // If we are passed a NULL |io_task_runner| or |file_task_runner|, then we
1580 // don't set up proxy setting change notifications. This should not be the
1581 // usual case but is intended to/ simplify test setups.
1582 if (!io_task_runner_.get() || !file_task_runner.get())
1583 VLOG(1) << "Monitoring of proxy setting changes is disabled";
1585 // Fetch and cache the current proxy config. The config is left in
1586 // cached_config_, where GetLatestProxyConfig() running on the IO thread
1587 // will expect to find it. This is safe to do because we return
1588 // before this ProxyConfigServiceLinux is passed on to
1589 // the ProxyService.
1591 // Note: It would be nice to prioritize environment variables
1592 // and only fall back to gconf if env vars were unset. But
1593 // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
1594 // does so even if the proxy mode is set to auto, which would
1595 // mislead us.
1597 bool got_config = false;
1598 if (setting_getter_.get() &&
1599 setting_getter_->Init(glib_task_runner, file_task_runner) &&
1600 GetConfigFromSettings(&cached_config_)) {
1601 cached_config_.set_id(1); // Mark it as valid.
1602 cached_config_.set_source(setting_getter_->GetConfigSource());
1603 VLOG(1) << "Obtained proxy settings from "
1604 << ProxyConfigSourceToString(cached_config_.source());
1606 // If gconf proxy mode is "none", meaning direct, then we take
1607 // that to be a valid config and will not check environment
1608 // variables. The alternative would have been to look for a proxy
1609 // whereever we can find one.
1610 got_config = true;
1612 // Keep a copy of the config for use from this thread for
1613 // comparison with updated settings when we get notifications.
1614 reference_config_ = cached_config_;
1615 reference_config_.set_id(1); // Mark it as valid.
1617 // We only set up notifications if we have IO and file loops available.
1618 // We do this after getting the initial configuration so that we don't have
1619 // to worry about cancelling it if the initial fetch above fails. Note that
1620 // setting up notifications has the side effect of simulating a change, so
1621 // that we won't lose any updates that may have happened after the initial
1622 // fetch and before setting up notifications. We'll detect the common case
1623 // of no changes in OnCheckProxyConfigSettings() (or sooner) and ignore it.
1624 if (io_task_runner.get() && file_task_runner.get()) {
1625 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1626 setting_getter_->GetNotificationTaskRunner();
1627 if (!required_loop.get() || required_loop->BelongsToCurrentThread()) {
1628 // In this case we are already on an acceptable thread.
1629 SetUpNotifications();
1630 } else {
1631 // Post a task to set up notifications. We don't wait for success.
1632 required_loop->PostTask(FROM_HERE, base::Bind(
1633 &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this));
1638 if (!got_config) {
1639 // We fall back on environment variables.
1641 // Consulting environment variables doesn't need to be done from the
1642 // default glib main loop, but it's a tiny enough amount of work.
1643 if (GetConfigFromEnv(&cached_config_)) {
1644 cached_config_.set_source(PROXY_CONFIG_SOURCE_ENV);
1645 cached_config_.set_id(1); // Mark it as valid.
1646 VLOG(1) << "Obtained proxy settings from environment variables";
1651 // Depending on the SettingGetter in use, this method will be called
1652 // on either the UI thread (GConf) or the file thread (KDE).
1653 void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
1654 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1655 setting_getter_->GetNotificationTaskRunner();
1656 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1657 if (!setting_getter_->SetUpNotifications(this))
1658 LOG(ERROR) << "Unable to set up proxy configuration change notifications";
1661 void ProxyConfigServiceLinux::Delegate::AddObserver(Observer* observer) {
1662 observers_.AddObserver(observer);
1665 void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer* observer) {
1666 observers_.RemoveObserver(observer);
1669 ProxyConfigService::ConfigAvailability
1670 ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
1671 ProxyConfig* config) {
1672 // This is called from the IO thread.
1673 DCHECK(!io_task_runner_.get() ||
1674 io_task_runner_->BelongsToCurrentThread());
1676 // Simply return the last proxy configuration that glib_default_loop
1677 // notified us of.
1678 if (cached_config_.is_valid()) {
1679 *config = cached_config_;
1680 } else {
1681 *config = ProxyConfig::CreateDirect();
1682 config->set_source(PROXY_CONFIG_SOURCE_SYSTEM_FAILED);
1685 // We return CONFIG_VALID to indicate that *config was filled in. It is always
1686 // going to be available since we initialized eagerly on the UI thread.
1687 // TODO(eroman): do lazy initialization instead, so we no longer need
1688 // to construct ProxyConfigServiceLinux on the UI thread.
1689 // In which case, we may return false here.
1690 return CONFIG_VALID;
1693 // Depending on the SettingGetter in use, this method will be called
1694 // on either the UI thread (GConf) or the file thread (KDE).
1695 void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
1696 scoped_refptr<base::SingleThreadTaskRunner> required_loop =
1697 setting_getter_->GetNotificationTaskRunner();
1698 DCHECK(!required_loop.get() || required_loop->BelongsToCurrentThread());
1699 ProxyConfig new_config;
1700 bool valid = GetConfigFromSettings(&new_config);
1701 if (valid)
1702 new_config.set_id(1); // mark it as valid
1704 // See if it is different from what we had before.
1705 if (new_config.is_valid() != reference_config_.is_valid() ||
1706 !new_config.Equals(reference_config_)) {
1707 // Post a task to the IO thread with the new configuration, so it can
1708 // update |cached_config_|.
1709 io_task_runner_->PostTask(FROM_HERE, base::Bind(
1710 &ProxyConfigServiceLinux::Delegate::SetNewProxyConfig,
1711 this, new_config));
1712 // Update the thread-private copy in |reference_config_| as well.
1713 reference_config_ = new_config;
1714 } else {
1715 VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
1719 void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
1720 const ProxyConfig& new_config) {
1721 DCHECK(io_task_runner_->BelongsToCurrentThread());
1722 VLOG(1) << "Proxy configuration changed";
1723 cached_config_ = new_config;
1724 FOR_EACH_OBSERVER(
1725 Observer, observers_,
1726 OnProxyConfigChanged(new_config, ProxyConfigService::CONFIG_VALID));
1729 void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
1730 if (!setting_getter_.get())
1731 return;
1732 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1733 setting_getter_->GetNotificationTaskRunner();
1734 if (!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread()) {
1735 // Already on the right thread, call directly.
1736 // This is the case for the unittests.
1737 OnDestroy();
1738 } else {
1739 // Post to shutdown thread. Note that on browser shutdown, we may quit
1740 // this MessageLoop and exit the program before ever running this.
1741 shutdown_loop->PostTask(FROM_HERE, base::Bind(
1742 &ProxyConfigServiceLinux::Delegate::OnDestroy, this));
1745 void ProxyConfigServiceLinux::Delegate::OnDestroy() {
1746 scoped_refptr<base::SingleThreadTaskRunner> shutdown_loop =
1747 setting_getter_->GetNotificationTaskRunner();
1748 DCHECK(!shutdown_loop.get() || shutdown_loop->BelongsToCurrentThread());
1749 setting_getter_->ShutDown();
1752 ProxyConfigServiceLinux::ProxyConfigServiceLinux()
1753 : delegate_(new Delegate(base::Environment::Create())) {
1756 ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
1757 delegate_->PostDestroyTask();
1760 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1761 base::Environment* env_var_getter)
1762 : delegate_(new Delegate(env_var_getter)) {
1765 ProxyConfigServiceLinux::ProxyConfigServiceLinux(
1766 base::Environment* env_var_getter, SettingGetter* setting_getter)
1767 : delegate_(new Delegate(env_var_getter, setting_getter)) {
1770 void ProxyConfigServiceLinux::AddObserver(Observer* observer) {
1771 delegate_->AddObserver(observer);
1774 void ProxyConfigServiceLinux::RemoveObserver(Observer* observer) {
1775 delegate_->RemoveObserver(observer);
1778 ProxyConfigService::ConfigAvailability
1779 ProxyConfigServiceLinux::GetLatestProxyConfig(ProxyConfig* config) {
1780 return delegate_->GetLatestProxyConfig(config);
1783 } // namespace net