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