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