forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_config_service_linux.cc
1769 lines (1633 loc) · 67.1 KB
/
proxy_config_service_linux.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy/proxy_config_service_linux.h"
#include <errno.h>
#include <fcntl.h>
#if defined(USE_GCONF)
#include <gconf/gconf-client.h>
#endif // defined(USE_GCONF)
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <map>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/debug/leak_annotations.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/nix/xdg_util.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/timer/timer.h"
#include "net/base/net_errors.h"
#include "net/http/http_util.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_server.h"
#include "url/url_canon.h"
#if defined(USE_GIO)
#include "library_loaders/libgio.h"
#endif // defined(USE_GIO)
namespace net {
namespace {
// Given a proxy hostname from a setting, returns that hostname with
// an appropriate proxy server scheme prefix.
// scheme indicates the desired proxy scheme: usually http, with
// socks 4 or 5 as special cases.
// TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
std::string FixupProxyHostScheme(ProxyServer::Scheme scheme,
std::string host) {
if (scheme == ProxyServer::SCHEME_SOCKS5 &&
StartsWithASCII(host, "socks4://", false)) {
// We default to socks 5, but if the user specifically set it to
// socks4://, then use that.
scheme = ProxyServer::SCHEME_SOCKS4;
}
// Strip the scheme if any.
std::string::size_type colon = host.find("://");
if (colon != std::string::npos)
host = host.substr(colon + 3);
// If a username and perhaps password are specified, give a warning.
std::string::size_type at_sign = host.find("@");
// Should this be supported?
if (at_sign != std::string::npos) {
// ProxyConfig does not support authentication parameters, but Chrome
// will prompt for the password later. Disregard the
// authentication parameters and continue with this hostname.
LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
host = host.substr(at_sign + 1);
}
// If this is a socks proxy, prepend a scheme so as to tell
// ProxyServer. This also allows ProxyServer to choose the right
// default port.
if (scheme == ProxyServer::SCHEME_SOCKS4)
host = "socks4://" + host;
else if (scheme == ProxyServer::SCHEME_SOCKS5)
host = "socks5://" + host;
// If there is a trailing slash, remove it so |host| will parse correctly
// even if it includes a port number (since the slash is not numeric).
if (host.length() && host[host.length() - 1] == '/')
host.resize(host.length() - 1);
return host;
}
} // namespace
ProxyConfigServiceLinux::Delegate::~Delegate() {
}
bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
const char* variable, ProxyServer::Scheme scheme,
ProxyServer* result_server) {
std::string env_value;
if (env_var_getter_->GetVar(variable, &env_value)) {
if (!env_value.empty()) {
env_value = FixupProxyHostScheme(scheme, env_value);
ProxyServer proxy_server =
ProxyServer::FromURI(env_value, ProxyServer::SCHEME_HTTP);
if (proxy_server.is_valid() && !proxy_server.is_direct()) {
*result_server = proxy_server;
return true;
} else {
LOG(ERROR) << "Failed to parse environment variable " << variable;
}
}
}
return false;
}
bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
const char* variable, ProxyServer* result_server) {
return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
result_server);
}
bool ProxyConfigServiceLinux::Delegate::GetConfigFromEnv(ProxyConfig* config) {
// Check for automatic configuration first, in
// "auto_proxy". Possibly only the "environment_proxy" firefox
// extension has ever used this, but it still sounds like a good
// idea.
std::string auto_proxy;
if (env_var_getter_->GetVar("auto_proxy", &auto_proxy)) {
if (auto_proxy.empty()) {
// Defined and empty => autodetect
config->set_auto_detect(true);
} else {
// specified autoconfig URL
config->set_pac_url(GURL(auto_proxy));
}
return true;
}
// "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
ProxyServer proxy_server;
if (GetProxyFromEnvVar("all_proxy", &proxy_server)) {
config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
} else {
bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_server);
if (have_http)
config->proxy_rules().proxies_for_http.SetSingleProxyServer(proxy_server);
// It would be tempting to let http_proxy apply for all protocols
// if https_proxy and ftp_proxy are not defined. Googling turns up
// several documents that mention only http_proxy. But then the
// user really might not want to proxy https. And it doesn't seem
// like other apps do this. So we will refrain.
bool have_https = GetProxyFromEnvVar("https_proxy", &proxy_server);
if (have_https)
config->proxy_rules().proxies_for_https.
SetSingleProxyServer(proxy_server);
bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_server);
if (have_ftp)
config->proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_server);
if (have_http || have_https || have_ftp) {
// mustn't change type unless some rules are actually set.
config->proxy_rules().type =
ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
}
}
if (config->proxy_rules().empty()) {
// If the above were not defined, try for socks.
// For environment variables, we default to version 5, per the gnome
// documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
std::string env_version;
if (env_var_getter_->GetVar("SOCKS_VERSION", &env_version)
&& env_version == "4")
scheme = ProxyServer::SCHEME_SOCKS4;
if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_server)) {
config->proxy_rules().type = ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY;
config->proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
}
}
// Look for the proxy bypass list.
std::string no_proxy;
env_var_getter_->GetVar("no_proxy", &no_proxy);
if (config->proxy_rules().empty()) {
// Having only "no_proxy" set, presumably to "*", makes it
// explicit that env vars do specify a configuration: having no
// rules specified only means the user explicitly asks for direct
// connections.
return !no_proxy.empty();
}
// Note that this uses "suffix" matching. So a bypass of "google.com"
// is understood to mean a bypass of "*google.com".
config->proxy_rules().bypass_rules.ParseFromStringUsingSuffixMatching(
no_proxy);
return true;
}
namespace {
const int kDebounceTimeoutMilliseconds = 250;
#if defined(USE_GCONF)
// This setting getter uses gconf, as used in GNOME 2 and some GNOME 3 desktops.
class SettingGetterImplGConf : public ProxyConfigServiceLinux::SettingGetter {
public:
SettingGetterImplGConf()
: client_(NULL), system_proxy_id_(0), system_http_proxy_id_(0),
notify_delegate_(NULL) {
}
~SettingGetterImplGConf() override {
// client_ should have been released before now, from
// Delegate::OnDestroy(), while running on the UI thread. However
// on exiting the process, it may happen that Delegate::OnDestroy()
// task is left pending on the glib loop after the loop was quit,
// and pending tasks may then be deleted without being run.
if (client_) {
// gconf client was not cleaned up.
if (task_runner_->BelongsToCurrentThread()) {
// We are on the UI thread so we can clean it safely. This is
// the case at least for ui_tests running under Valgrind in
// bug 16076.
VLOG(1) << "~SettingGetterImplGConf: releasing gconf client";
ShutDown();
} else {
// This is very bad! We are deleting the setting getter but we're not on
// the UI thread. This is not supposed to happen: the setting getter is
// owned by the proxy config service's delegate, which is supposed to be
// destroyed on the UI thread only. We will get change notifications to
// a deleted object if we continue here, so fail now.
LOG(FATAL) << "~SettingGetterImplGConf: deleting on wrong thread!";
}
}
DCHECK(!client_);
}
bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
override {
DCHECK(glib_task_runner->BelongsToCurrentThread());
DCHECK(!client_);
DCHECK(!task_runner_.get());
task_runner_ = glib_task_runner;
client_ = gconf_client_get_default();
if (!client_) {
// It's not clear whether/when this can return NULL.
LOG(ERROR) << "Unable to create a gconf client";
task_runner_ = NULL;
return false;
}
GError* error = NULL;
bool added_system_proxy = false;
// We need to add the directories for which we'll be asking
// for notifications, and we might as well ask to preload them.
// These need to be removed again in ShutDown(); we are careful
// here to only leave client_ non-NULL if both have been added.
gconf_client_add_dir(client_, "/system/proxy",
GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
if (error == NULL) {
added_system_proxy = true;
gconf_client_add_dir(client_, "/system/http_proxy",
GCONF_CLIENT_PRELOAD_ONELEVEL, &error);
}
if (error != NULL) {
LOG(ERROR) << "Error requesting gconf directory: " << error->message;
g_error_free(error);
if (added_system_proxy)
gconf_client_remove_dir(client_, "/system/proxy", NULL);
g_object_unref(client_);
client_ = NULL;
task_runner_ = NULL;
return false;
}
return true;
}
void ShutDown() override {
if (client_) {
DCHECK(task_runner_->BelongsToCurrentThread());
// We must explicitly disable gconf notifications here, because the gconf
// client will be shared between all setting getters, and they do not all
// have the same lifetimes. (For instance, incognito sessions get their
// own, which is destroyed when the session ends.)
gconf_client_notify_remove(client_, system_http_proxy_id_);
gconf_client_notify_remove(client_, system_proxy_id_);
gconf_client_remove_dir(client_, "/system/http_proxy", NULL);
gconf_client_remove_dir(client_, "/system/proxy", NULL);
g_object_unref(client_);
client_ = NULL;
task_runner_ = NULL;
}
}
bool SetUpNotifications(
ProxyConfigServiceLinux::Delegate* delegate) override {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
GError* error = NULL;
notify_delegate_ = delegate;
// We have to keep track of the IDs returned by gconf_client_notify_add() so
// that we can remove them in ShutDown(). (Otherwise, notifications will be
// delivered to this object after it is deleted, which is bad, m'kay?)
system_proxy_id_ = gconf_client_notify_add(
client_, "/system/proxy",
OnGConfChangeNotification, this,
NULL, &error);
if (error == NULL) {
system_http_proxy_id_ = gconf_client_notify_add(
client_, "/system/http_proxy",
OnGConfChangeNotification, this,
NULL, &error);
}
if (error != NULL) {
LOG(ERROR) << "Error requesting gconf notifications: " << error->message;
g_error_free(error);
ShutDown();
return false;
}
// Simulate a change to avoid possibly losing updates before this point.
OnChangeNotification();
return true;
}
const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
override {
return task_runner_;
}
ProxyConfigSource GetConfigSource() override {
return PROXY_CONFIG_SOURCE_GCONF;
}
bool GetString(StringSetting key, std::string* result) override {
switch (key) {
case PROXY_MODE:
return GetStringByPath("/system/proxy/mode", result);
case PROXY_AUTOCONF_URL:
return GetStringByPath("/system/proxy/autoconfig_url", result);
case PROXY_HTTP_HOST:
return GetStringByPath("/system/http_proxy/host", result);
case PROXY_HTTPS_HOST:
return GetStringByPath("/system/proxy/secure_host", result);
case PROXY_FTP_HOST:
return GetStringByPath("/system/proxy/ftp_host", result);
case PROXY_SOCKS_HOST:
return GetStringByPath("/system/proxy/socks_host", result);
}
return false; // Placate compiler.
}
bool GetBool(BoolSetting key, bool* result) override {
switch (key) {
case PROXY_USE_HTTP_PROXY:
return GetBoolByPath("/system/http_proxy/use_http_proxy", result);
case PROXY_USE_SAME_PROXY:
return GetBoolByPath("/system/http_proxy/use_same_proxy", result);
case PROXY_USE_AUTHENTICATION:
return GetBoolByPath("/system/http_proxy/use_authentication", result);
}
return false; // Placate compiler.
}
bool GetInt(IntSetting key, int* result) override {
switch (key) {
case PROXY_HTTP_PORT:
return GetIntByPath("/system/http_proxy/port", result);
case PROXY_HTTPS_PORT:
return GetIntByPath("/system/proxy/secure_port", result);
case PROXY_FTP_PORT:
return GetIntByPath("/system/proxy/ftp_port", result);
case PROXY_SOCKS_PORT:
return GetIntByPath("/system/proxy/socks_port", result);
}
return false; // Placate compiler.
}
bool GetStringList(StringListSetting key,
std::vector<std::string>* result) override {
switch (key) {
case PROXY_IGNORE_HOSTS:
return GetStringListByPath("/system/http_proxy/ignore_hosts", result);
}
return false; // Placate compiler.
}
bool BypassListIsReversed() override {
// This is a KDE-specific setting.
return false;
}
bool MatchHostsUsingSuffixMatching() override { return false; }
private:
bool GetStringByPath(const char* key, std::string* result) {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
GError* error = NULL;
gchar* value = gconf_client_get_string(client_, key, &error);
if (HandleGError(error, key))
return false;
if (!value)
return false;
*result = value;
g_free(value);
return true;
}
bool GetBoolByPath(const char* key, bool* result) {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
GError* error = NULL;
// We want to distinguish unset values from values defaulting to
// false. For that we need to use the type-generic
// gconf_client_get() rather than gconf_client_get_bool().
GConfValue* gconf_value = gconf_client_get(client_, key, &error);
if (HandleGError(error, key))
return false;
if (!gconf_value) {
// Unset.
return false;
}
if (gconf_value->type != GCONF_VALUE_BOOL) {
gconf_value_free(gconf_value);
return false;
}
gboolean bool_value = gconf_value_get_bool(gconf_value);
*result = static_cast<bool>(bool_value);
gconf_value_free(gconf_value);
return true;
}
bool GetIntByPath(const char* key, int* result) {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
GError* error = NULL;
int value = gconf_client_get_int(client_, key, &error);
if (HandleGError(error, key))
return false;
// We don't bother to distinguish an unset value because callers
// don't care. 0 is returned if unset.
*result = value;
return true;
}
bool GetStringListByPath(const char* key, std::vector<std::string>* result) {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
GError* error = NULL;
GSList* list = gconf_client_get_list(client_, key,
GCONF_VALUE_STRING, &error);
if (HandleGError(error, key))
return false;
if (!list)
return false;
for (GSList *it = list; it; it = it->next) {
result->push_back(static_cast<char*>(it->data));
g_free(it->data);
}
g_slist_free(list);
return true;
}
// Logs and frees a glib error. Returns false if there was no error
// (error is NULL).
bool HandleGError(GError* error, const char* key) {
if (error != NULL) {
LOG(ERROR) << "Error getting gconf value for " << key
<< ": " << error->message;
g_error_free(error);
return true;
}
return false;
}
// This is the callback from the debounce timer.
void OnDebouncedNotification() {
DCHECK(task_runner_->BelongsToCurrentThread());
CHECK(notify_delegate_);
// Forward to a method on the proxy config service delegate object.
notify_delegate_->OnCheckProxyConfigSettings();
}
void OnChangeNotification() {
// We don't use Reset() because the timer may not yet be running.
// (In that case Stop() is a no-op.)
debounce_timer_.Stop();
debounce_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
this, &SettingGetterImplGConf::OnDebouncedNotification);
}
// gconf notification callback, dispatched on the default glib main loop.
static void OnGConfChangeNotification(GConfClient* client, guint cnxn_id,
GConfEntry* entry, gpointer user_data) {
VLOG(1) << "gconf change notification for key "
<< gconf_entry_get_key(entry);
// We don't track which key has changed, just that something did change.
SettingGetterImplGConf* setting_getter =
reinterpret_cast<SettingGetterImplGConf*>(user_data);
setting_getter->OnChangeNotification();
}
GConfClient* client_;
// These ids are the values returned from gconf_client_notify_add(), which we
// will need in order to later call gconf_client_notify_remove().
guint system_proxy_id_;
guint system_http_proxy_id_;
ProxyConfigServiceLinux::Delegate* notify_delegate_;
base::OneShotTimer<SettingGetterImplGConf> debounce_timer_;
// Task runner for the thread that we make gconf calls on. It should
// be the UI thread and all our methods should be called on this
// thread. Only for assertions.
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGConf);
};
#endif // defined(USE_GCONF)
#if defined(USE_GIO)
const char kProxyGConfSchema[] = "org.gnome.system.proxy";
// This setting getter uses gsettings, as used in most GNOME 3 desktops.
class SettingGetterImplGSettings
: public ProxyConfigServiceLinux::SettingGetter {
public:
SettingGetterImplGSettings() :
client_(NULL),
http_client_(NULL),
https_client_(NULL),
ftp_client_(NULL),
socks_client_(NULL),
notify_delegate_(NULL) {
}
~SettingGetterImplGSettings() override {
// client_ should have been released before now, from
// Delegate::OnDestroy(), while running on the UI thread. However
// on exiting the process, it may happen that
// Delegate::OnDestroy() task is left pending on the glib loop
// after the loop was quit, and pending tasks may then be deleted
// without being run.
if (client_) {
// gconf client was not cleaned up.
if (task_runner_->BelongsToCurrentThread()) {
// We are on the UI thread so we can clean it safely. This is
// the case at least for ui_tests running under Valgrind in
// bug 16076.
VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
ShutDown();
} else {
LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
client_ = NULL;
}
}
DCHECK(!client_);
}
bool SchemaExists(const char* schema_name) {
const gchar* const* schemas = libgio_loader_.g_settings_list_schemas();
while (*schemas) {
if (strcmp(schema_name, static_cast<const char*>(*schemas)) == 0)
return true;
schemas++;
}
return false;
}
// LoadAndCheckVersion() must be called *before* Init()!
bool LoadAndCheckVersion(base::Environment* env);
bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
override {
DCHECK(glib_task_runner->BelongsToCurrentThread());
DCHECK(!client_);
DCHECK(!task_runner_.get());
if (!SchemaExists(kProxyGConfSchema) ||
!(client_ = libgio_loader_.g_settings_new(kProxyGConfSchema))) {
// It's not clear whether/when this can return NULL.
LOG(ERROR) << "Unable to create a gsettings client";
return false;
}
task_runner_ = glib_task_runner;
// We assume these all work if the above call worked.
http_client_ = libgio_loader_.g_settings_get_child(client_, "http");
https_client_ = libgio_loader_.g_settings_get_child(client_, "https");
ftp_client_ = libgio_loader_.g_settings_get_child(client_, "ftp");
socks_client_ = libgio_loader_.g_settings_get_child(client_, "socks");
DCHECK(http_client_ && https_client_ && ftp_client_ && socks_client_);
return true;
}
void ShutDown() override {
if (client_) {
DCHECK(task_runner_->BelongsToCurrentThread());
// This also disables gsettings notifications.
g_object_unref(socks_client_);
g_object_unref(ftp_client_);
g_object_unref(https_client_);
g_object_unref(http_client_);
g_object_unref(client_);
// We only need to null client_ because it's the only one that we check.
client_ = NULL;
task_runner_ = NULL;
}
}
bool SetUpNotifications(
ProxyConfigServiceLinux::Delegate* delegate) override {
DCHECK(client_);
DCHECK(task_runner_->BelongsToCurrentThread());
notify_delegate_ = delegate;
// We could watch for the change-event signal instead of changed, but
// since we have to watch more than one object, we'd still have to
// debounce change notifications. This is conceptually simpler.
g_signal_connect(G_OBJECT(client_), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(http_client_), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(https_client_), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(ftp_client_), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(socks_client_), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
// Simulate a change to avoid possibly losing updates before this point.
OnChangeNotification();
return true;
}
const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
override {
return task_runner_;
}
ProxyConfigSource GetConfigSource() override {
return PROXY_CONFIG_SOURCE_GSETTINGS;
}
bool GetString(StringSetting key, std::string* result) override {
DCHECK(client_);
switch (key) {
case PROXY_MODE:
return GetStringByPath(client_, "mode", result);
case PROXY_AUTOCONF_URL:
return GetStringByPath(client_, "autoconfig-url", result);
case PROXY_HTTP_HOST:
return GetStringByPath(http_client_, "host", result);
case PROXY_HTTPS_HOST:
return GetStringByPath(https_client_, "host", result);
case PROXY_FTP_HOST:
return GetStringByPath(ftp_client_, "host", result);
case PROXY_SOCKS_HOST:
return GetStringByPath(socks_client_, "host", result);
}
return false; // Placate compiler.
}
bool GetBool(BoolSetting key, bool* result) override {
DCHECK(client_);
switch (key) {
case PROXY_USE_HTTP_PROXY:
// Although there is an "enabled" boolean in http_client_, it is not set
// to true by the proxy config utility. We ignore it and return false.
return false;
case PROXY_USE_SAME_PROXY:
// Similarly, although there is a "use-same-proxy" boolean in client_,
// it is never set to false by the proxy config utility. We ignore it.
return false;
case PROXY_USE_AUTHENTICATION:
// There is also no way to set this in the proxy config utility, but it
// doesn't hurt us to get the actual setting (unlike the two above).
return GetBoolByPath(http_client_, "use-authentication", result);
}
return false; // Placate compiler.
}
bool GetInt(IntSetting key, int* result) override {
DCHECK(client_);
switch (key) {
case PROXY_HTTP_PORT:
return GetIntByPath(http_client_, "port", result);
case PROXY_HTTPS_PORT:
return GetIntByPath(https_client_, "port", result);
case PROXY_FTP_PORT:
return GetIntByPath(ftp_client_, "port", result);
case PROXY_SOCKS_PORT:
return GetIntByPath(socks_client_, "port", result);
}
return false; // Placate compiler.
}
bool GetStringList(StringListSetting key,
std::vector<std::string>* result) override {
DCHECK(client_);
switch (key) {
case PROXY_IGNORE_HOSTS:
return GetStringListByPath(client_, "ignore-hosts", result);
}
return false; // Placate compiler.
}
bool BypassListIsReversed() override {
// This is a KDE-specific setting.
return false;
}
bool MatchHostsUsingSuffixMatching() override { return false; }
private:
bool GetStringByPath(GSettings* client, const char* key,
std::string* result) {
DCHECK(task_runner_->BelongsToCurrentThread());
gchar* value = libgio_loader_.g_settings_get_string(client, key);
if (!value)
return false;
*result = value;
g_free(value);
return true;
}
bool GetBoolByPath(GSettings* client, const char* key, bool* result) {
DCHECK(task_runner_->BelongsToCurrentThread());
*result = static_cast<bool>(
libgio_loader_.g_settings_get_boolean(client, key));
return true;
}
bool GetIntByPath(GSettings* client, const char* key, int* result) {
DCHECK(task_runner_->BelongsToCurrentThread());
*result = libgio_loader_.g_settings_get_int(client, key);
return true;
}
bool GetStringListByPath(GSettings* client, const char* key,
std::vector<std::string>* result) {
DCHECK(task_runner_->BelongsToCurrentThread());
gchar** list = libgio_loader_.g_settings_get_strv(client, key);
if (!list)
return false;
for (size_t i = 0; list[i]; ++i) {
result->push_back(static_cast<char*>(list[i]));
g_free(list[i]);
}
g_free(list);
return true;
}
// This is the callback from the debounce timer.
void OnDebouncedNotification() {
DCHECK(task_runner_->BelongsToCurrentThread());
CHECK(notify_delegate_);
// Forward to a method on the proxy config service delegate object.
notify_delegate_->OnCheckProxyConfigSettings();
}
void OnChangeNotification() {
// We don't use Reset() because the timer may not yet be running.
// (In that case Stop() is a no-op.)
debounce_timer_.Stop();
debounce_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kDebounceTimeoutMilliseconds),
this, &SettingGetterImplGSettings::OnDebouncedNotification);
}
// gsettings notification callback, dispatched on the default glib main loop.
static void OnGSettingsChangeNotification(GSettings* client, gchar* key,
gpointer user_data) {
VLOG(1) << "gsettings change notification for key " << key;
// We don't track which key has changed, just that something did change.
SettingGetterImplGSettings* setting_getter =
reinterpret_cast<SettingGetterImplGSettings*>(user_data);
setting_getter->OnChangeNotification();
}
GSettings* client_;
GSettings* http_client_;
GSettings* https_client_;
GSettings* ftp_client_;
GSettings* socks_client_;
ProxyConfigServiceLinux::Delegate* notify_delegate_;
base::OneShotTimer<SettingGetterImplGSettings> debounce_timer_;
// Task runner for the thread that we make gsettings calls on. It should
// be the UI thread and all our methods should be called on this
// thread. Only for assertions.
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
LibGioLoader libgio_loader_;
DISALLOW_COPY_AND_ASSIGN(SettingGetterImplGSettings);
};
bool SettingGetterImplGSettings::LoadAndCheckVersion(
base::Environment* env) {
// LoadAndCheckVersion() must be called *before* Init()!
DCHECK(!client_);
// The APIs to query gsettings were introduced after the minimum glib
// version we target, so we can't link directly against them. We load them
// dynamically at runtime, and if they don't exist, return false here. (We
// support linking directly via gyp flags though.) Additionally, even when
// they are present, we do two additional checks to make sure we should use
// them and not gconf. First, we attempt to load the schema for proxy
// settings. Second, we check for the program that was used in older
// versions of GNOME to configure proxy settings, and return false if it
// exists. Some distributions (e.g. Ubuntu 11.04) have the API and schema
// but don't use gsettings for proxy settings, but they do have the old
// binary, so we detect these systems that way.
{
// TODO(phajdan.jr): Redesign the code to load library on different thread.
base::ThreadRestrictions::ScopedAllowIO allow_io;
// Try also without .0 at the end; on some systems this may be required.
if (!libgio_loader_.Load("libgio-2.0.so.0") &&
!libgio_loader_.Load("libgio-2.0.so")) {
VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
return false;
}
}
GSettings* client = NULL;
if (SchemaExists(kProxyGConfSchema)) {
ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/380782
client = libgio_loader_.g_settings_new(kProxyGConfSchema);
}
if (!client) {
VLOG(1) << "Cannot create gsettings client. Will fall back to gconf.";
return false;
}
g_object_unref(client);
std::string path;
if (!env->GetVar("PATH", &path)) {
LOG(ERROR) << "No $PATH variable. Assuming no gnome-network-properties.";
} else {
// Yes, we're on the UI thread. Yes, we're accessing the file system.
// Sadly, we don't have much choice. We need the proxy settings and we
// need them now, and to figure out where to get them, we have to check
// for this binary. See http://crbug.com/69057 for additional details.
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::vector<std::string> paths;
Tokenize(path, ":", &paths);
for (size_t i = 0; i < paths.size(); ++i) {
base::FilePath file(paths[i]);
if (base::PathExists(file.Append("gnome-network-properties"))) {
VLOG(1) << "Found gnome-network-properties. Will fall back to gconf.";
return false;
}
}
}
VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
return true;
}
#endif // defined(USE_GIO)
// This is the KDE version that reads kioslaverc and simulates gconf.
// Doing this allows the main Delegate code, as well as the unit tests
// for it, to stay the same - and the settings map fairly well besides.
class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter,
public base::MessagePumpLibevent::Watcher {
public:
explicit SettingGetterImplKDE(base::Environment* env_var_getter)
: inotify_fd_(-1), notify_delegate_(NULL), indirect_manual_(false),
auto_no_pac_(false), reversed_bypass_list_(false),
env_var_getter_(env_var_getter), file_task_runner_(NULL) {
// This has to be called on the UI thread (http://crbug.com/69057).
base::ThreadRestrictions::ScopedAllowIO allow_io;
// Derive the location of the kde config dir from the environment.
std::string home;
if (env_var_getter->GetVar("KDEHOME", &home) && !home.empty()) {
// $KDEHOME is set. Use it unconditionally.
kde_config_dir_ = KDEHomeToConfigPath(base::FilePath(home));
} else {
// $KDEHOME is unset. Try to figure out what to use. This seems to be
// the common case on most distributions.
if (!env_var_getter->GetVar(base::env_vars::kHome, &home))
// User has no $HOME? Give up. Later we'll report the failure.
return;
if (base::nix::GetDesktopEnvironment(env_var_getter) ==
base::nix::DESKTOP_ENVIRONMENT_KDE3) {
// KDE3 always uses .kde for its configuration.
base::FilePath kde_path = base::FilePath(home).Append(".kde");
kde_config_dir_ = KDEHomeToConfigPath(kde_path);
} else {
// Some distributions patch KDE4 to use .kde4 instead of .kde, so that
// both can be installed side-by-side. Sadly they don't all do this, and
// they don't always do this: some distributions have started switching
// back as well. So if there is a .kde4 directory, check the timestamps
// of the config directories within and use the newest one.
// Note that we should currently be running in the UI thread, because in
// the gconf version, that is the only thread that can access the proxy
// settings (a gconf restriction). As noted below, the initial read of
// the proxy settings will be done in this thread anyway, so we check
// for .kde4 here in this thread as well.
base::FilePath kde3_path = base::FilePath(home).Append(".kde");
base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
bool use_kde4 = false;
if (base::DirectoryExists(kde4_path)) {
base::File::Info kde3_info;
base::File::Info kde4_info;
if (base::GetFileInfo(kde4_config, &kde4_info)) {
if (base::GetFileInfo(kde3_config, &kde3_info)) {
use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
} else {
use_kde4 = true;
}
}
}
if (use_kde4) {
kde_config_dir_ = KDEHomeToConfigPath(kde4_path);
} else {
kde_config_dir_ = KDEHomeToConfigPath(kde3_path);
}
}
}
}
~SettingGetterImplKDE() override {
// inotify_fd_ should have been closed before now, from
// Delegate::OnDestroy(), while running on the file thread. However
// on exiting the process, it may happen that Delegate::OnDestroy()
// task is left pending on the file loop after the loop was quit,
// and pending tasks may then be deleted without being run.
// Here in the KDE version, we can safely close the file descriptor
// anyway. (Not that it really matters; the process is exiting.)
if (inotify_fd_ >= 0)
ShutDown();
DCHECK(inotify_fd_ < 0);
}
bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& file_task_runner)
override {
// This has to be called on the UI thread (http://crbug.com/69057).
base::ThreadRestrictions::ScopedAllowIO allow_io;
DCHECK(inotify_fd_ < 0);
inotify_fd_ = inotify_init();
if (inotify_fd_ < 0) {
PLOG(ERROR) << "inotify_init failed";
return false;
}
int flags = fcntl(inotify_fd_, F_GETFL);
if (fcntl(inotify_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
PLOG(ERROR) << "fcntl failed";
close(inotify_fd_);
inotify_fd_ = -1;
return false;
}
file_task_runner_ = file_task_runner;
// The initial read is done on the current thread, not
// |file_task_runner_|, since we will need to have it for
// SetUpAndFetchInitialConfig().
UpdateCachedSettings();
return true;
}
void ShutDown() override {
if (inotify_fd_ >= 0) {
ResetCachedSettings();
inotify_watcher_.StopWatchingFileDescriptor();
close(inotify_fd_);
inotify_fd_ = -1;
}
}
bool SetUpNotifications(
ProxyConfigServiceLinux::Delegate* delegate) override {
DCHECK(inotify_fd_ >= 0);
DCHECK(file_task_runner_->BelongsToCurrentThread());
// We can't just watch the kioslaverc file directly, since KDE will write
// a new copy of it and then rename it whenever settings are changed and
// inotify watches inodes (so we'll be watching the old deleted file after
// the first change, and it will never change again). So, we watch the
// directory instead. We then act only on changes to the kioslaverc entry.
if (inotify_add_watch(inotify_fd_, kde_config_dir_.value().c_str(),
IN_MODIFY | IN_MOVED_TO) < 0) {
return false;
}
notify_delegate_ = delegate;
if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
inotify_fd_, true, base::MessageLoopForIO::WATCH_READ,
&inotify_watcher_, this)) {
return false;
}
// Simulate a change to avoid possibly losing updates before this point.
OnChangeNotification();
return true;
}
const scoped_refptr<base::SingleThreadTaskRunner>& GetNotificationTaskRunner()
override {
return file_task_runner_;
}
// Implement base::MessagePumpLibevent::Watcher.
void OnFileCanReadWithoutBlocking(int fd) override {
DCHECK_EQ(fd, inotify_fd_);
DCHECK(file_task_runner_->BelongsToCurrentThread());
OnChangeNotification();
}
void OnFileCanWriteWithoutBlocking(int fd) override { NOTREACHED(); }
ProxyConfigSource GetConfigSource() override {
return PROXY_CONFIG_SOURCE_KDE;
}