proxy_config_service_linux.cc 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  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. #include "net/proxy_resolution/proxy_config_service_linux.h"
  5. #include <errno.h>
  6. #include <limits.h>
  7. #include <sys/inotify.h>
  8. #include <unistd.h>
  9. #include <map>
  10. #include <memory>
  11. #include <utility>
  12. #include "base/bind.h"
  13. #include "base/files/file_descriptor_watcher_posix.h"
  14. #include "base/files/file_path.h"
  15. #include "base/files/file_util.h"
  16. #include "base/files/scoped_file.h"
  17. #include "base/logging.h"
  18. #include "base/memory/ptr_util.h"
  19. #include "base/memory/raw_ptr.h"
  20. #include "base/nix/xdg_util.h"
  21. #include "base/observer_list.h"
  22. #include "base/strings/string_number_conversions.h"
  23. #include "base/strings/string_split.h"
  24. #include "base/strings/string_tokenizer.h"
  25. #include "base/strings/string_util.h"
  26. #include "base/task/sequenced_task_runner.h"
  27. #include "base/task/single_thread_task_runner.h"
  28. #include "base/task/task_traits.h"
  29. #include "base/task/thread_pool.h"
  30. #include "base/threading/thread_restrictions.h"
  31. #include "base/timer/timer.h"
  32. #include "net/base/proxy_server.h"
  33. #include "net/base/proxy_string_util.h"
  34. #if defined(USE_GIO)
  35. #include <gio/gio.h>
  36. #endif // defined(USE_GIO)
  37. namespace net {
  38. namespace {
  39. // This turns all rules with a hostname into wildcard matches, which will
  40. // match not just the indicated hostname but also any hostname that ends with
  41. // it.
  42. void RewriteRulesForSuffixMatching(ProxyBypassRules* out) {
  43. // Prepend a wildcard (*) to any hostname based rules, provided it isn't an IP
  44. // address.
  45. for (size_t i = 0; i < out->rules().size(); ++i) {
  46. if (!out->rules()[i]->IsHostnamePatternRule())
  47. continue;
  48. const SchemeHostPortMatcherHostnamePatternRule* prev_rule =
  49. static_cast<const SchemeHostPortMatcherHostnamePatternRule*>(
  50. out->rules()[i].get());
  51. out->ReplaceRule(i, prev_rule->GenerateSuffixMatchingRule());
  52. }
  53. }
  54. // Given a proxy hostname from a setting, returns that hostname with
  55. // an appropriate proxy server scheme prefix.
  56. // scheme indicates the desired proxy scheme: usually http, with
  57. // socks 4 or 5 as special cases.
  58. // TODO(arindam): Remove URI string manipulation by using MapUrlSchemeToProxy.
  59. std::string FixupProxyHostScheme(ProxyServer::Scheme scheme,
  60. std::string host) {
  61. if (scheme == ProxyServer::SCHEME_SOCKS5 &&
  62. base::StartsWith(host, "socks4://",
  63. base::CompareCase::INSENSITIVE_ASCII)) {
  64. // We default to socks 5, but if the user specifically set it to
  65. // socks4://, then use that.
  66. scheme = ProxyServer::SCHEME_SOCKS4;
  67. }
  68. // Strip the scheme if any.
  69. std::string::size_type colon = host.find("://");
  70. if (colon != std::string::npos)
  71. host = host.substr(colon + 3);
  72. // If a username and perhaps password are specified, give a warning.
  73. std::string::size_type at_sign = host.find("@");
  74. // Should this be supported?
  75. if (at_sign != std::string::npos) {
  76. // ProxyConfig does not support authentication parameters, but Chrome
  77. // will prompt for the password later. Disregard the
  78. // authentication parameters and continue with this hostname.
  79. LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
  80. host = host.substr(at_sign + 1);
  81. }
  82. // If this is a socks proxy, prepend a scheme so as to tell
  83. // ProxyServer. This also allows ProxyServer to choose the right
  84. // default port.
  85. if (scheme == ProxyServer::SCHEME_SOCKS4)
  86. host = "socks4://" + host;
  87. else if (scheme == ProxyServer::SCHEME_SOCKS5)
  88. host = "socks5://" + host;
  89. // If there is a trailing slash, remove it so |host| will parse correctly
  90. // even if it includes a port number (since the slash is not numeric).
  91. if (!host.empty() && host.back() == '/')
  92. host.resize(host.length() - 1);
  93. return host;
  94. }
  95. ProxyConfigWithAnnotation GetConfigOrDirect(
  96. const absl::optional<ProxyConfigWithAnnotation>& optional_config) {
  97. if (optional_config)
  98. return optional_config.value();
  99. ProxyConfigWithAnnotation config = ProxyConfigWithAnnotation::CreateDirect();
  100. return config;
  101. }
  102. } // namespace
  103. ProxyConfigServiceLinux::Delegate::~Delegate() = default;
  104. bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
  105. base::StringPiece variable,
  106. ProxyServer::Scheme scheme,
  107. ProxyServer* result_server) {
  108. std::string env_value;
  109. if (!env_var_getter_->GetVar(variable, &env_value))
  110. return false;
  111. if (env_value.empty())
  112. return false;
  113. env_value = FixupProxyHostScheme(scheme, env_value);
  114. ProxyServer proxy_server =
  115. ProxyUriToProxyServer(env_value, ProxyServer::SCHEME_HTTP);
  116. if (proxy_server.is_valid() && !proxy_server.is_direct()) {
  117. *result_server = proxy_server;
  118. return true;
  119. }
  120. LOG(ERROR) << "Failed to parse environment variable " << variable;
  121. return false;
  122. }
  123. bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
  124. base::StringPiece variable,
  125. ProxyServer* result_server) {
  126. return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
  127. result_server);
  128. }
  129. absl::optional<ProxyConfigWithAnnotation>
  130. ProxyConfigServiceLinux::Delegate::GetConfigFromEnv() {
  131. ProxyConfig config;
  132. // Check for automatic configuration first, in
  133. // "auto_proxy". Possibly only the "environment_proxy" firefox
  134. // extension has ever used this, but it still sounds like a good
  135. // idea.
  136. std::string auto_proxy;
  137. if (env_var_getter_->GetVar("auto_proxy", &auto_proxy)) {
  138. if (auto_proxy.empty()) {
  139. // Defined and empty => autodetect
  140. config.set_auto_detect(true);
  141. } else {
  142. // specified autoconfig URL
  143. config.set_pac_url(GURL(auto_proxy));
  144. }
  145. return ProxyConfigWithAnnotation(
  146. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  147. }
  148. // "all_proxy" is a shortcut to avoid defining {http,https,ftp}_proxy.
  149. ProxyServer proxy_server;
  150. if (GetProxyFromEnvVar("all_proxy", &proxy_server)) {
  151. config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
  152. config.proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
  153. } else {
  154. bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_server);
  155. if (have_http)
  156. config.proxy_rules().proxies_for_http.SetSingleProxyServer(proxy_server);
  157. // It would be tempting to let http_proxy apply for all protocols
  158. // if https_proxy and ftp_proxy are not defined. Googling turns up
  159. // several documents that mention only http_proxy. But then the
  160. // user really might not want to proxy https. And it doesn't seem
  161. // like other apps do this. So we will refrain.
  162. bool have_https = GetProxyFromEnvVar("https_proxy", &proxy_server);
  163. if (have_https)
  164. config.proxy_rules().proxies_for_https.SetSingleProxyServer(proxy_server);
  165. bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_server);
  166. if (have_ftp)
  167. config.proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_server);
  168. if (have_http || have_https || have_ftp) {
  169. // mustn't change type unless some rules are actually set.
  170. config.proxy_rules().type =
  171. ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME;
  172. }
  173. }
  174. if (config.proxy_rules().empty()) {
  175. // If the above were not defined, try for socks.
  176. // For environment variables, we default to version 5, per the gnome
  177. // documentation: http://library.gnome.org/devel/gnet/stable/gnet-socks.html
  178. ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
  179. std::string env_version;
  180. if (env_var_getter_->GetVar("SOCKS_VERSION", &env_version)
  181. && env_version == "4")
  182. scheme = ProxyServer::SCHEME_SOCKS4;
  183. if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_server)) {
  184. config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
  185. config.proxy_rules().single_proxies.SetSingleProxyServer(proxy_server);
  186. }
  187. }
  188. // Look for the proxy bypass list.
  189. std::string no_proxy;
  190. env_var_getter_->GetVar("no_proxy", &no_proxy);
  191. if (config.proxy_rules().empty()) {
  192. // Having only "no_proxy" set, presumably to "*", makes it
  193. // explicit that env vars do specify a configuration: having no
  194. // rules specified only means the user explicitly asks for direct
  195. // connections.
  196. return !no_proxy.empty()
  197. ? ProxyConfigWithAnnotation(
  198. config, NetworkTrafficAnnotationTag(traffic_annotation_))
  199. : absl::optional<ProxyConfigWithAnnotation>();
  200. }
  201. // Note that this uses "suffix" matching. So a bypass of "google.com"
  202. // is understood to mean a bypass of "*google.com".
  203. config.proxy_rules().bypass_rules.ParseFromString(no_proxy);
  204. RewriteRulesForSuffixMatching(&config.proxy_rules().bypass_rules);
  205. return ProxyConfigWithAnnotation(
  206. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  207. }
  208. namespace {
  209. const int kDebounceTimeoutMilliseconds = 250;
  210. #if defined(USE_GIO)
  211. const char kProxyGSettingsSchema[] = "org.gnome.system.proxy";
  212. // This setting getter uses gsettings, as used in most GNOME 3 desktops.
  213. class SettingGetterImplGSettings
  214. : public ProxyConfigServiceLinux::SettingGetter {
  215. public:
  216. SettingGetterImplGSettings()
  217. : debounce_timer_(std::make_unique<base::OneShotTimer>()) {}
  218. SettingGetterImplGSettings(const SettingGetterImplGSettings&) = delete;
  219. SettingGetterImplGSettings& operator=(const SettingGetterImplGSettings&) =
  220. delete;
  221. ~SettingGetterImplGSettings() override {
  222. // client_ should have been released before now, from
  223. // Delegate::OnDestroy(), while running on the UI thread. However
  224. // on exiting the process, it may happen that
  225. // Delegate::OnDestroy() task is left pending on the glib loop
  226. // after the loop was quit, and pending tasks may then be deleted
  227. // without being run.
  228. if (client_) {
  229. // gsettings client was not cleaned up.
  230. if (task_runner_->RunsTasksInCurrentSequence()) {
  231. // We are on the UI thread so we can clean it safely.
  232. VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
  233. ShutDown();
  234. } else {
  235. LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
  236. client_ = nullptr;
  237. }
  238. }
  239. DCHECK(!client_);
  240. }
  241. // CheckVersion() must be called *before* Init()!
  242. bool CheckVersion(base::Environment* env);
  243. bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner)
  244. override {
  245. DCHECK(glib_task_runner->RunsTasksInCurrentSequence());
  246. DCHECK(!client_);
  247. DCHECK(!task_runner_.get());
  248. if (!g_settings_schema_source_lookup(g_settings_schema_source_get_default(),
  249. kProxyGSettingsSchema, FALSE) ||
  250. !(client_ = g_settings_new(kProxyGSettingsSchema))) {
  251. // It's not clear whether/when this can return NULL.
  252. LOG(ERROR) << "Unable to create a gsettings client";
  253. return false;
  254. }
  255. task_runner_ = glib_task_runner;
  256. // We assume these all work if the above call worked.
  257. http_client_ = g_settings_get_child(client_, "http");
  258. https_client_ = g_settings_get_child(client_, "https");
  259. ftp_client_ = g_settings_get_child(client_, "ftp");
  260. socks_client_ = g_settings_get_child(client_, "socks");
  261. DCHECK(http_client_ && https_client_ && ftp_client_ && socks_client_);
  262. return true;
  263. }
  264. void ShutDown() override {
  265. if (client_) {
  266. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  267. // This also disables gsettings notifications.
  268. g_object_unref(socks_client_);
  269. g_object_unref(ftp_client_);
  270. g_object_unref(https_client_);
  271. g_object_unref(http_client_);
  272. g_object_unref(client_);
  273. // We only need to null client_ because it's the only one that we check.
  274. client_ = nullptr;
  275. task_runner_ = nullptr;
  276. }
  277. debounce_timer_.reset();
  278. }
  279. bool SetUpNotifications(
  280. ProxyConfigServiceLinux::Delegate* delegate) override {
  281. DCHECK(client_);
  282. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  283. notify_delegate_ = delegate;
  284. // We could watch for the change-event signal instead of changed, but
  285. // since we have to watch more than one object, we'd still have to
  286. // debounce change notifications. This is conceptually simpler.
  287. g_signal_connect(G_OBJECT(client_.get()), "changed",
  288. G_CALLBACK(OnGSettingsChangeNotification), this);
  289. g_signal_connect(G_OBJECT(http_client_.get()), "changed",
  290. G_CALLBACK(OnGSettingsChangeNotification), this);
  291. g_signal_connect(G_OBJECT(https_client_.get()), "changed",
  292. G_CALLBACK(OnGSettingsChangeNotification), this);
  293. g_signal_connect(G_OBJECT(ftp_client_.get()), "changed",
  294. G_CALLBACK(OnGSettingsChangeNotification), this);
  295. g_signal_connect(G_OBJECT(socks_client_.get()), "changed",
  296. G_CALLBACK(OnGSettingsChangeNotification), this);
  297. // Simulate a change to avoid possibly losing updates before this point.
  298. OnChangeNotification();
  299. return true;
  300. }
  301. const scoped_refptr<base::SequencedTaskRunner>& GetNotificationTaskRunner()
  302. override {
  303. return task_runner_;
  304. }
  305. bool GetString(StringSetting key, std::string* result) override {
  306. DCHECK(client_);
  307. switch (key) {
  308. case PROXY_MODE:
  309. return GetStringByPath(client_, "mode", result);
  310. case PROXY_AUTOCONF_URL:
  311. return GetStringByPath(client_, "autoconfig-url", result);
  312. case PROXY_HTTP_HOST:
  313. return GetStringByPath(http_client_, "host", result);
  314. case PROXY_HTTPS_HOST:
  315. return GetStringByPath(https_client_, "host", result);
  316. case PROXY_FTP_HOST:
  317. return GetStringByPath(ftp_client_, "host", result);
  318. case PROXY_SOCKS_HOST:
  319. return GetStringByPath(socks_client_, "host", result);
  320. }
  321. return false; // Placate compiler.
  322. }
  323. bool GetBool(BoolSetting key, bool* result) override {
  324. DCHECK(client_);
  325. switch (key) {
  326. case PROXY_USE_HTTP_PROXY:
  327. // Although there is an "enabled" boolean in http_client_, it is not set
  328. // to true by the proxy config utility. We ignore it and return false.
  329. return false;
  330. case PROXY_USE_SAME_PROXY:
  331. // Similarly, although there is a "use-same-proxy" boolean in client_,
  332. // it is never set to false by the proxy config utility. We ignore it.
  333. return false;
  334. case PROXY_USE_AUTHENTICATION:
  335. // There is also no way to set this in the proxy config utility, but it
  336. // doesn't hurt us to get the actual setting (unlike the two above).
  337. return GetBoolByPath(http_client_, "use-authentication", result);
  338. }
  339. return false; // Placate compiler.
  340. }
  341. bool GetInt(IntSetting key, int* result) override {
  342. DCHECK(client_);
  343. switch (key) {
  344. case PROXY_HTTP_PORT:
  345. return GetIntByPath(http_client_, "port", result);
  346. case PROXY_HTTPS_PORT:
  347. return GetIntByPath(https_client_, "port", result);
  348. case PROXY_FTP_PORT:
  349. return GetIntByPath(ftp_client_, "port", result);
  350. case PROXY_SOCKS_PORT:
  351. return GetIntByPath(socks_client_, "port", result);
  352. }
  353. return false; // Placate compiler.
  354. }
  355. bool GetStringList(StringListSetting key,
  356. std::vector<std::string>* result) override {
  357. DCHECK(client_);
  358. switch (key) {
  359. case PROXY_IGNORE_HOSTS:
  360. return GetStringListByPath(client_, "ignore-hosts", result);
  361. }
  362. return false; // Placate compiler.
  363. }
  364. bool BypassListIsReversed() override {
  365. // This is a KDE-specific setting.
  366. return false;
  367. }
  368. bool UseSuffixMatching() override { return false; }
  369. private:
  370. bool GetStringByPath(GSettings* client,
  371. base::StringPiece key,
  372. std::string* result) {
  373. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  374. gchar* value = g_settings_get_string(client, key.data());
  375. if (!value)
  376. return false;
  377. *result = value;
  378. g_free(value);
  379. return true;
  380. }
  381. bool GetBoolByPath(GSettings* client, base::StringPiece key, bool* result) {
  382. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  383. *result = static_cast<bool>(g_settings_get_boolean(client, key.data()));
  384. return true;
  385. }
  386. bool GetIntByPath(GSettings* client, base::StringPiece key, int* result) {
  387. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  388. *result = g_settings_get_int(client, key.data());
  389. return true;
  390. }
  391. bool GetStringListByPath(GSettings* client,
  392. base::StringPiece key,
  393. std::vector<std::string>* result) {
  394. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  395. gchar** list = g_settings_get_strv(client, key.data());
  396. if (!list)
  397. return false;
  398. for (size_t i = 0; list[i]; ++i) {
  399. result->push_back(static_cast<char*>(list[i]));
  400. g_free(list[i]);
  401. }
  402. g_free(list);
  403. return true;
  404. }
  405. // This is the callback from the debounce timer.
  406. void OnDebouncedNotification() {
  407. DCHECK(task_runner_->RunsTasksInCurrentSequence());
  408. CHECK(notify_delegate_);
  409. // Forward to a method on the proxy config service delegate object.
  410. notify_delegate_->OnCheckProxyConfigSettings();
  411. }
  412. void OnChangeNotification() {
  413. // We don't use Reset() because the timer may not yet be running.
  414. // (In that case Stop() is a no-op.)
  415. debounce_timer_->Stop();
  416. debounce_timer_->Start(
  417. FROM_HERE, base::Milliseconds(kDebounceTimeoutMilliseconds), this,
  418. &SettingGetterImplGSettings::OnDebouncedNotification);
  419. }
  420. // gsettings notification callback, dispatched on the default glib main loop.
  421. static void OnGSettingsChangeNotification(GSettings* client, gchar* key,
  422. gpointer user_data) {
  423. VLOG(1) << "gsettings change notification for key " << key;
  424. // We don't track which key has changed, just that something did change.
  425. SettingGetterImplGSettings* setting_getter =
  426. reinterpret_cast<SettingGetterImplGSettings*>(user_data);
  427. setting_getter->OnChangeNotification();
  428. }
  429. raw_ptr<GSettings> client_ = nullptr;
  430. raw_ptr<GSettings> http_client_ = nullptr;
  431. raw_ptr<GSettings> https_client_ = nullptr;
  432. raw_ptr<GSettings> ftp_client_ = nullptr;
  433. raw_ptr<GSettings> socks_client_ = nullptr;
  434. raw_ptr<ProxyConfigServiceLinux::Delegate> notify_delegate_ = nullptr;
  435. std::unique_ptr<base::OneShotTimer> debounce_timer_;
  436. // Task runner for the thread that we make gsettings calls on. It should
  437. // be the UI thread and all our methods should be called on this
  438. // thread. Only for assertions.
  439. scoped_refptr<base::SequencedTaskRunner> task_runner_;
  440. };
  441. bool SettingGetterImplGSettings::CheckVersion(
  442. base::Environment* env) {
  443. // CheckVersion() must be called *before* Init()!
  444. DCHECK(!client_);
  445. GSettings* client = nullptr;
  446. if (g_settings_schema_source_lookup(g_settings_schema_source_get_default(),
  447. kProxyGSettingsSchema, FALSE)) {
  448. client = g_settings_new(kProxyGSettingsSchema);
  449. }
  450. if (!client) {
  451. VLOG(1) << "Cannot create gsettings client.";
  452. return false;
  453. }
  454. g_object_unref(client);
  455. VLOG(1) << "All gsettings tests OK. Will get proxy config from gsettings.";
  456. return true;
  457. }
  458. #endif // defined(USE_GIO)
  459. // Converts |value| from a decimal string to an int. If there was a failure
  460. // parsing, returns |default_value|.
  461. int StringToIntOrDefault(base::StringPiece value, int default_value) {
  462. int result;
  463. if (base::StringToInt(value, &result))
  464. return result;
  465. return default_value;
  466. }
  467. // This is the KDE version that reads kioslaverc and simulates gsettings.
  468. // Doing this allows the main Delegate code, as well as the unit tests
  469. // for it, to stay the same - and the settings map fairly well besides.
  470. class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter {
  471. public:
  472. explicit SettingGetterImplKDE(base::Environment* env_var_getter)
  473. : debounce_timer_(std::make_unique<base::OneShotTimer>()),
  474. env_var_getter_(env_var_getter) {
  475. // This has to be called on the UI thread (http://crbug.com/69057).
  476. base::ThreadRestrictions::ScopedAllowIO allow_io;
  477. // Derive the location(s) of the kde config dir from the environment.
  478. std::string home;
  479. if (env_var_getter->GetVar("KDEHOME", &home) && !home.empty()) {
  480. // $KDEHOME is set. Use it unconditionally.
  481. kde_config_dirs_.emplace_back(KDEHomeToConfigPath(base::FilePath(home)));
  482. } else {
  483. // $KDEHOME is unset. Try to figure out what to use. This seems to be
  484. // the common case on most distributions.
  485. if (!env_var_getter->GetVar(base::env_vars::kHome, &home))
  486. // User has no $HOME? Give up. Later we'll report the failure.
  487. return;
  488. if (base::nix::GetDesktopEnvironment(env_var_getter) ==
  489. base::nix::DESKTOP_ENVIRONMENT_KDE3) {
  490. // KDE3 always uses .kde for its configuration.
  491. base::FilePath kde_path = base::FilePath(home).Append(".kde");
  492. kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde_path));
  493. } else if (base::nix::GetDesktopEnvironment(env_var_getter) ==
  494. base::nix::DESKTOP_ENVIRONMENT_KDE4) {
  495. // Some distributions patch KDE4 to use .kde4 instead of .kde, so that
  496. // both can be installed side-by-side. Sadly they don't all do this, and
  497. // they don't always do this: some distributions have started switching
  498. // back as well. So if there is a .kde4 directory, check the timestamps
  499. // of the config directories within and use the newest one.
  500. // Note that we should currently be running in the UI thread, because in
  501. // the gsettings version, that is the only thread that can access the
  502. // proxy settings (a gsettings restriction). As noted below, the initial
  503. // read of the proxy settings will be done in this thread anyway, so we
  504. // check for .kde4 here in this thread as well.
  505. base::FilePath kde3_path = base::FilePath(home).Append(".kde");
  506. base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
  507. base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
  508. base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
  509. bool use_kde4 = false;
  510. if (base::DirectoryExists(kde4_path)) {
  511. base::File::Info kde3_info;
  512. base::File::Info kde4_info;
  513. if (base::GetFileInfo(kde4_config, &kde4_info)) {
  514. if (base::GetFileInfo(kde3_config, &kde3_info)) {
  515. use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
  516. } else {
  517. use_kde4 = true;
  518. }
  519. }
  520. }
  521. if (use_kde4) {
  522. kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde4_path));
  523. } else {
  524. kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde3_path));
  525. }
  526. } else {
  527. // KDE 5 migrated to ~/.config for storing kioslaverc.
  528. kde_config_dirs_.emplace_back(base::FilePath(home).Append(".config"));
  529. // kioslaverc also can be stored in any of XDG_CONFIG_DIRS
  530. std::string config_dirs;
  531. if (env_var_getter_->GetVar("XDG_CONFIG_DIRS", &config_dirs)) {
  532. auto dirs = base::SplitString(config_dirs, ":", base::KEEP_WHITESPACE,
  533. base::SPLIT_WANT_NONEMPTY);
  534. for (const auto& dir : dirs) {
  535. kde_config_dirs_.emplace_back(dir);
  536. }
  537. }
  538. // Reverses the order of paths to store them in ascending order of
  539. // priority
  540. std::reverse(kde_config_dirs_.begin(), kde_config_dirs_.end());
  541. }
  542. }
  543. }
  544. SettingGetterImplKDE(const SettingGetterImplKDE&) = delete;
  545. SettingGetterImplKDE& operator=(const SettingGetterImplKDE&) = delete;
  546. ~SettingGetterImplKDE() override {
  547. // inotify_fd_ should have been closed before now, from
  548. // Delegate::OnDestroy(), while running on the file thread. However
  549. // on exiting the process, it may happen that Delegate::OnDestroy()
  550. // task is left pending on the file loop after the loop was quit,
  551. // and pending tasks may then be deleted without being run.
  552. // Here in the KDE version, we can safely close the file descriptor
  553. // anyway. (Not that it really matters; the process is exiting.)
  554. if (inotify_fd_ >= 0)
  555. ShutDown();
  556. DCHECK_LT(inotify_fd_, 0);
  557. }
  558. bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner)
  559. override {
  560. // This has to be called on the UI thread (http://crbug.com/69057).
  561. base::ThreadRestrictions::ScopedAllowIO allow_io;
  562. DCHECK_LT(inotify_fd_, 0);
  563. inotify_fd_ = inotify_init();
  564. if (inotify_fd_ < 0) {
  565. PLOG(ERROR) << "inotify_init failed";
  566. return false;
  567. }
  568. if (!base::SetNonBlocking(inotify_fd_)) {
  569. PLOG(ERROR) << "base::SetNonBlocking failed";
  570. close(inotify_fd_);
  571. inotify_fd_ = -1;
  572. return false;
  573. }
  574. constexpr base::TaskTraits kTraits = {base::TaskPriority::USER_VISIBLE,
  575. base::MayBlock()};
  576. file_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(kTraits);
  577. // The initial read is done on the current thread, not
  578. // |file_task_runner_|, since we will need to have it for
  579. // SetUpAndFetchInitialConfig().
  580. UpdateCachedSettings();
  581. return true;
  582. }
  583. void ShutDown() override {
  584. if (inotify_fd_ >= 0) {
  585. ResetCachedSettings();
  586. inotify_watcher_.reset();
  587. close(inotify_fd_);
  588. inotify_fd_ = -1;
  589. }
  590. debounce_timer_.reset();
  591. }
  592. bool SetUpNotifications(
  593. ProxyConfigServiceLinux::Delegate* delegate) override {
  594. DCHECK_GE(inotify_fd_, 0);
  595. DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
  596. // We can't just watch the kioslaverc file directly, since KDE will write
  597. // a new copy of it and then rename it whenever settings are changed and
  598. // inotify watches inodes (so we'll be watching the old deleted file after
  599. // the first change, and it will never change again). So, we watch the
  600. // directory instead. We then act only on changes to the kioslaverc entry.
  601. // TODO(eroman): What if the file is deleted? (handle with IN_DELETE).
  602. size_t failed_dirs = 0;
  603. for (const auto& kde_config_dir : kde_config_dirs_) {
  604. if (inotify_add_watch(inotify_fd_, kde_config_dir.value().c_str(),
  605. IN_MODIFY | IN_MOVED_TO) < 0) {
  606. ++failed_dirs;
  607. }
  608. }
  609. // Fail if inotify_add_watch failed with every directory
  610. if (failed_dirs == kde_config_dirs_.size()) {
  611. return false;
  612. }
  613. notify_delegate_ = delegate;
  614. inotify_watcher_ = base::FileDescriptorWatcher::WatchReadable(
  615. inotify_fd_,
  616. base::BindRepeating(&SettingGetterImplKDE::OnChangeNotification,
  617. base::Unretained(this)));
  618. // Simulate a change to avoid possibly losing updates before this point.
  619. OnChangeNotification();
  620. return true;
  621. }
  622. const scoped_refptr<base::SequencedTaskRunner>& GetNotificationTaskRunner()
  623. override {
  624. return file_task_runner_;
  625. }
  626. bool GetString(StringSetting key, std::string* result) override {
  627. auto it = string_table_.find(key);
  628. if (it == string_table_.end())
  629. return false;
  630. *result = it->second;
  631. return true;
  632. }
  633. bool GetBool(BoolSetting key, bool* result) override {
  634. // We don't ever have any booleans.
  635. return false;
  636. }
  637. bool GetInt(IntSetting key, int* result) override {
  638. // We don't ever have any integers. (See AddProxy() below about ports.)
  639. return false;
  640. }
  641. bool GetStringList(StringListSetting key,
  642. std::vector<std::string>* result) override {
  643. auto it = strings_table_.find(key);
  644. if (it == strings_table_.end())
  645. return false;
  646. *result = it->second;
  647. return true;
  648. }
  649. bool BypassListIsReversed() override { return reversed_bypass_list_; }
  650. bool UseSuffixMatching() override { return true; }
  651. private:
  652. void ResetCachedSettings() {
  653. string_table_.clear();
  654. strings_table_.clear();
  655. indirect_manual_ = false;
  656. auto_no_pac_ = false;
  657. reversed_bypass_list_ = false;
  658. }
  659. base::FilePath KDEHomeToConfigPath(const base::FilePath& kde_home) {
  660. return kde_home.Append("share").Append("config");
  661. }
  662. void AddProxy(StringSetting host_key, const std::string& value) {
  663. if (value.empty() || value.substr(0, 3) == "//:")
  664. // No proxy.
  665. return;
  666. size_t space = value.find(' ');
  667. if (space != std::string::npos) {
  668. // Newer versions of KDE use a space rather than a colon to separate the
  669. // port number from the hostname. If we find this, we need to convert it.
  670. std::string fixed = value;
  671. fixed[space] = ':';
  672. string_table_[host_key] = fixed;
  673. } else {
  674. // We don't need to parse the port number out; GetProxyFromSettings()
  675. // would only append it right back again. So we just leave the port
  676. // number right in the host string.
  677. string_table_[host_key] = value;
  678. }
  679. }
  680. void AddHostList(StringListSetting key, const std::string& value) {
  681. std::vector<std::string> tokens;
  682. base::StringTokenizer tk(value, ", ");
  683. while (tk.GetNext()) {
  684. std::string token = tk.token();
  685. if (!token.empty())
  686. tokens.push_back(token);
  687. }
  688. strings_table_[key] = tokens;
  689. }
  690. void AddKDESetting(const std::string& key, const std::string& value) {
  691. if (key == "ProxyType") {
  692. const char* mode = "none";
  693. indirect_manual_ = false;
  694. auto_no_pac_ = false;
  695. int int_value = StringToIntOrDefault(value, 0);
  696. switch (int_value) {
  697. case 1: // Manual configuration.
  698. mode = "manual";
  699. break;
  700. case 2: // PAC URL.
  701. mode = "auto";
  702. break;
  703. case 3: // WPAD.
  704. mode = "auto";
  705. auto_no_pac_ = true;
  706. break;
  707. case 4: // Indirect manual via environment variables.
  708. mode = "manual";
  709. indirect_manual_ = true;
  710. break;
  711. default: // No proxy, or maybe kioslaverc syntax error.
  712. break;
  713. }
  714. string_table_[PROXY_MODE] = mode;
  715. } else if (key == "Proxy Config Script") {
  716. string_table_[PROXY_AUTOCONF_URL] = value;
  717. } else if (key == "httpProxy") {
  718. AddProxy(PROXY_HTTP_HOST, value);
  719. } else if (key == "httpsProxy") {
  720. AddProxy(PROXY_HTTPS_HOST, value);
  721. } else if (key == "ftpProxy") {
  722. AddProxy(PROXY_FTP_HOST, value);
  723. } else if (key == "socksProxy") {
  724. // Older versions of KDE configure SOCKS in a weird way involving
  725. // LD_PRELOAD and a library that intercepts network calls to SOCKSify
  726. // them. We don't support it. KDE 4.8 added a proper SOCKS setting.
  727. AddProxy(PROXY_SOCKS_HOST, value);
  728. } else if (key == "ReversedException") {
  729. // We count "true" or any nonzero number as true, otherwise false.
  730. // A failure parsing the integer will also mean false.
  731. reversed_bypass_list_ =
  732. (value == "true" || StringToIntOrDefault(value, 0) != 0);
  733. } else if (key == "NoProxyFor") {
  734. AddHostList(PROXY_IGNORE_HOSTS, value);
  735. } else if (key == "AuthMode") {
  736. // Check for authentication, just so we can warn.
  737. int mode = StringToIntOrDefault(value, 0);
  738. if (mode) {
  739. // ProxyConfig does not support authentication parameters, but
  740. // Chrome will prompt for the password later. So we ignore this.
  741. LOG(WARNING) <<
  742. "Proxy authentication parameters ignored, see bug 16709";
  743. }
  744. }
  745. }
  746. void ResolveIndirect(StringSetting key) {
  747. auto it = string_table_.find(key);
  748. if (it != string_table_.end()) {
  749. std::string value;
  750. if (env_var_getter_->GetVar(it->second.c_str(), &value))
  751. it->second = value;
  752. else
  753. string_table_.erase(it);
  754. }
  755. }
  756. void ResolveIndirectList(StringListSetting key) {
  757. auto it = strings_table_.find(key);
  758. if (it != strings_table_.end()) {
  759. std::string value;
  760. if (!it->second.empty() &&
  761. env_var_getter_->GetVar(it->second[0].c_str(), &value))
  762. AddHostList(key, value);
  763. else
  764. strings_table_.erase(it);
  765. }
  766. }
  767. // The settings in kioslaverc could occur in any order, but some affect
  768. // others. Rather than read the whole file in and then query them in an
  769. // order that allows us to handle that, we read the settings in whatever
  770. // order they occur and do any necessary tweaking after we finish.
  771. void ResolveModeEffects() {
  772. if (indirect_manual_) {
  773. ResolveIndirect(PROXY_HTTP_HOST);
  774. ResolveIndirect(PROXY_HTTPS_HOST);
  775. ResolveIndirect(PROXY_FTP_HOST);
  776. ResolveIndirect(PROXY_SOCKS_HOST);
  777. ResolveIndirectList(PROXY_IGNORE_HOSTS);
  778. }
  779. if (auto_no_pac_) {
  780. // Remove the PAC URL; we're not supposed to use it.
  781. string_table_.erase(PROXY_AUTOCONF_URL);
  782. }
  783. }
  784. // Reads kioslaverc from all paths one line at a time and calls
  785. // AddKDESetting() to add each relevant name-value pair to the appropriate
  786. // value table. Each value can be overwritten by values from configs from
  787. // the following paths.
  788. void UpdateCachedSettings() {
  789. bool at_least_one_kioslaverc_opened = false;
  790. for (const auto& kde_config_dir : kde_config_dirs_) {
  791. base::FilePath kioslaverc = kde_config_dir.Append("kioslaverc");
  792. base::ScopedFILE input(base::OpenFile(kioslaverc, "r"));
  793. if (!input.get())
  794. continue;
  795. // Reset cached settings once only if some config was successfully opened
  796. if (!at_least_one_kioslaverc_opened) {
  797. ResetCachedSettings();
  798. }
  799. at_least_one_kioslaverc_opened = true;
  800. bool in_proxy_settings = false;
  801. bool line_too_long = false;
  802. char line[BUFFER_SIZE];
  803. // fgets() will return NULL on EOF or error.
  804. while (fgets(line, sizeof(line), input.get())) {
  805. // fgets() guarantees the line will be properly terminated.
  806. size_t length = strlen(line);
  807. if (!length)
  808. continue;
  809. // This should be true even with CRLF endings.
  810. if (line[length - 1] != '\n') {
  811. line_too_long = true;
  812. continue;
  813. }
  814. if (line_too_long) {
  815. // The previous line had no line ending, but this one does. This is
  816. // the end of the line that was too long, so warn here and skip it.
  817. LOG(WARNING) << "skipped very long line in " << kioslaverc.value();
  818. line_too_long = false;
  819. continue;
  820. }
  821. // Remove the LF at the end, and the CR if there is one.
  822. line[--length] = '\0';
  823. if (length && line[length - 1] == '\r')
  824. line[--length] = '\0';
  825. // Now parse the line.
  826. if (line[0] == '[') {
  827. // Switching sections. All we care about is whether this is
  828. // the (a?) proxy settings section, for both KDE3 and KDE4.
  829. in_proxy_settings = !strncmp(line, "[Proxy Settings]", 16);
  830. } else if (in_proxy_settings) {
  831. // A regular line, in the (a?) proxy settings section.
  832. char* split = strchr(line, '=');
  833. // Skip this line if it does not contain an = sign.
  834. if (!split)
  835. continue;
  836. // Split the line on the = and advance |split|.
  837. *(split++) = 0;
  838. std::string key = line;
  839. std::string value = split;
  840. base::TrimWhitespaceASCII(key, base::TRIM_ALL, &key);
  841. base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
  842. // Skip this line if the key name is empty.
  843. if (key.empty())
  844. continue;
  845. // Is the value name localized?
  846. if (key[key.length() - 1] == ']') {
  847. // Find the matching bracket.
  848. length = key.rfind('[');
  849. // Skip this line if the localization indicator is malformed.
  850. if (length == std::string::npos)
  851. continue;
  852. // Trim the localization indicator off.
  853. key.resize(length);
  854. // Remove any resulting trailing whitespace.
  855. base::TrimWhitespaceASCII(key, base::TRIM_TRAILING, &key);
  856. // Skip this line if the key name is now empty.
  857. if (key.empty())
  858. continue;
  859. }
  860. // Now fill in the tables.
  861. AddKDESetting(key, value);
  862. }
  863. }
  864. if (ferror(input.get()))
  865. LOG(ERROR) << "error reading " << kioslaverc.value();
  866. }
  867. if (at_least_one_kioslaverc_opened) {
  868. ResolveModeEffects();
  869. }
  870. }
  871. // This is the callback from the debounce timer.
  872. void OnDebouncedNotification() {
  873. DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
  874. VLOG(1) << "inotify change notification for kioslaverc";
  875. UpdateCachedSettings();
  876. CHECK(notify_delegate_);
  877. // Forward to a method on the proxy config service delegate object.
  878. notify_delegate_->OnCheckProxyConfigSettings();
  879. }
  880. // Called by OnFileCanReadWithoutBlocking() on the file thread. Reads
  881. // from the inotify file descriptor and starts up a debounce timer if
  882. // an event for kioslaverc is seen.
  883. void OnChangeNotification() {
  884. DCHECK_GE(inotify_fd_, 0);
  885. DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
  886. char event_buf[(sizeof(inotify_event) + NAME_MAX + 1) * 4];
  887. bool kioslaverc_touched = false;
  888. ssize_t r;
  889. while ((r = read(inotify_fd_, event_buf, sizeof(event_buf))) > 0) {
  890. // inotify returns variable-length structures, which is why we have
  891. // this strange-looking loop instead of iterating through an array.
  892. char* event_ptr = event_buf;
  893. while (event_ptr < event_buf + r) {
  894. inotify_event* event = reinterpret_cast<inotify_event*>(event_ptr);
  895. // The kernel always feeds us whole events.
  896. CHECK_LE(event_ptr + sizeof(inotify_event), event_buf + r);
  897. CHECK_LE(event->name + event->len, event_buf + r);
  898. if (!strcmp(event->name, "kioslaverc"))
  899. kioslaverc_touched = true;
  900. // Advance the pointer just past the end of the filename.
  901. event_ptr = event->name + event->len;
  902. }
  903. // We keep reading even if |kioslaverc_touched| is true to drain the
  904. // inotify event queue.
  905. }
  906. if (!r)
  907. // Instead of returning -1 and setting errno to EINVAL if there is not
  908. // enough buffer space, older kernels (< 2.6.21) return 0. Simulate the
  909. // new behavior (EINVAL) so we can reuse the code below.
  910. errno = EINVAL;
  911. if (errno != EAGAIN) {
  912. PLOG(WARNING) << "error reading inotify file descriptor";
  913. if (errno == EINVAL) {
  914. // Our buffer is not large enough to read the next event. This should
  915. // not happen (because its size is calculated to always be sufficiently
  916. // large), but if it does we'd warn continuously since |inotify_fd_|
  917. // would be forever ready to read. Close it and stop watching instead.
  918. LOG(ERROR) << "inotify failure; no longer watching kioslaverc!";
  919. inotify_watcher_.reset();
  920. close(inotify_fd_);
  921. inotify_fd_ = -1;
  922. }
  923. }
  924. if (kioslaverc_touched) {
  925. LOG(ERROR) << "kioslaverc_touched";
  926. // We don't use Reset() because the timer may not yet be running.
  927. // (In that case Stop() is a no-op.)
  928. debounce_timer_->Stop();
  929. debounce_timer_->Start(
  930. FROM_HERE, base::Milliseconds(kDebounceTimeoutMilliseconds), this,
  931. &SettingGetterImplKDE::OnDebouncedNotification);
  932. }
  933. }
  934. typedef std::map<StringSetting, std::string> string_map_type;
  935. typedef std::map<StringListSetting,
  936. std::vector<std::string> > strings_map_type;
  937. int inotify_fd_ = -1;
  938. std::unique_ptr<base::FileDescriptorWatcher::Controller> inotify_watcher_;
  939. raw_ptr<ProxyConfigServiceLinux::Delegate> notify_delegate_ = nullptr;
  940. std::unique_ptr<base::OneShotTimer> debounce_timer_;
  941. std::vector<base::FilePath> kde_config_dirs_;
  942. bool indirect_manual_ = false;
  943. bool auto_no_pac_ = false;
  944. bool reversed_bypass_list_ = false;
  945. // We don't own |env_var_getter_|. It's safe to hold a pointer to it, since
  946. // both it and us are owned by ProxyConfigServiceLinux::Delegate, and have the
  947. // same lifetime.
  948. raw_ptr<base::Environment> env_var_getter_;
  949. // We cache these settings whenever we re-read the kioslaverc file.
  950. string_map_type string_table_;
  951. strings_map_type strings_table_;
  952. // Task runner for doing blocking file IO on, as well as handling inotify
  953. // events on.
  954. scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
  955. };
  956. } // namespace
  957. bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
  958. SettingGetter::StringSetting host_key,
  959. ProxyServer* result_server) {
  960. std::string host;
  961. if (!setting_getter_->GetString(host_key, &host) || host.empty()) {
  962. // Unset or empty.
  963. return false;
  964. }
  965. // Check for an optional port.
  966. int port = 0;
  967. SettingGetter::IntSetting port_key =
  968. SettingGetter::HostSettingToPortSetting(host_key);
  969. setting_getter_->GetInt(port_key, &port);
  970. if (port != 0) {
  971. // If a port is set and non-zero:
  972. host += ":" + base::NumberToString(port);
  973. }
  974. // gsettings settings do not appear to distinguish between SOCKS version. We
  975. // default to version 5. For more information on this policy decision, see:
  976. // http://code.google.com/p/chromium/issues/detail?id=55912#c2
  977. ProxyServer::Scheme scheme = (host_key == SettingGetter::PROXY_SOCKS_HOST) ?
  978. ProxyServer::SCHEME_SOCKS5 : ProxyServer::SCHEME_HTTP;
  979. host = FixupProxyHostScheme(scheme, host);
  980. ProxyServer proxy_server =
  981. ProxyUriToProxyServer(host, ProxyServer::SCHEME_HTTP);
  982. if (proxy_server.is_valid()) {
  983. *result_server = proxy_server;
  984. return true;
  985. }
  986. return false;
  987. }
  988. absl::optional<ProxyConfigWithAnnotation>
  989. ProxyConfigServiceLinux::Delegate::GetConfigFromSettings() {
  990. ProxyConfig config;
  991. config.set_from_system(true);
  992. std::string mode;
  993. if (!setting_getter_->GetString(SettingGetter::PROXY_MODE, &mode)) {
  994. // We expect this to always be set, so if we don't see it then we probably
  995. // have a gsettings problem, and so we don't have a valid proxy config.
  996. return absl::nullopt;
  997. }
  998. if (mode == "none") {
  999. // Specifically specifies no proxy.
  1000. return ProxyConfigWithAnnotation(
  1001. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  1002. }
  1003. if (mode == "auto") {
  1004. // Automatic proxy config.
  1005. std::string pac_url_str;
  1006. if (setting_getter_->GetString(SettingGetter::PROXY_AUTOCONF_URL,
  1007. &pac_url_str)) {
  1008. if (!pac_url_str.empty()) {
  1009. // If the PAC URL is actually a file path, then put file:// in front.
  1010. if (pac_url_str[0] == '/')
  1011. pac_url_str = "file://" + pac_url_str;
  1012. GURL pac_url(pac_url_str);
  1013. if (!pac_url.is_valid())
  1014. return absl::nullopt;
  1015. config.set_pac_url(pac_url);
  1016. return ProxyConfigWithAnnotation(
  1017. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  1018. }
  1019. }
  1020. config.set_auto_detect(true);
  1021. return ProxyConfigWithAnnotation(
  1022. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  1023. }
  1024. if (mode != "manual") {
  1025. // Mode is unrecognized.
  1026. return absl::nullopt;
  1027. }
  1028. bool use_http_proxy;
  1029. if (setting_getter_->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY,
  1030. &use_http_proxy)
  1031. && !use_http_proxy) {
  1032. // Another master switch for some reason. If set to false, then no
  1033. // proxy. But we don't panic if the key doesn't exist.
  1034. return ProxyConfigWithAnnotation(
  1035. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  1036. }
  1037. bool same_proxy = false;
  1038. // Indicates to use the http proxy for all protocols. This one may
  1039. // not exist (presumably on older versions); we assume false in that
  1040. // case.
  1041. setting_getter_->GetBool(SettingGetter::PROXY_USE_SAME_PROXY,
  1042. &same_proxy);
  1043. ProxyServer proxy_for_http;
  1044. ProxyServer proxy_for_https;
  1045. ProxyServer proxy_for_ftp;
  1046. ProxyServer socks_proxy; // (socks)
  1047. // This counts how many of the above ProxyServers were defined and valid.
  1048. size_t num_proxies_specified = 0;
  1049. // Extract the per-scheme proxies. If we failed to parse it, or no proxy was
  1050. // specified for the scheme, then the resulting ProxyServer will be invalid.
  1051. if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST, &proxy_for_http))
  1052. num_proxies_specified++;
  1053. if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST, &proxy_for_https))
  1054. num_proxies_specified++;
  1055. if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST, &proxy_for_ftp))
  1056. num_proxies_specified++;
  1057. if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST, &socks_proxy))
  1058. num_proxies_specified++;
  1059. if (same_proxy) {
  1060. if (proxy_for_http.is_valid()) {
  1061. // Use the http proxy for all schemes.
  1062. config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
  1063. config.proxy_rules().single_proxies.SetSingleProxyServer(proxy_for_http);
  1064. }
  1065. } else if (num_proxies_specified > 0) {
  1066. if (socks_proxy.is_valid() && num_proxies_specified == 1) {
  1067. // If the only proxy specified was for SOCKS, use it for all schemes.
  1068. config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
  1069. config.proxy_rules().single_proxies.SetSingleProxyServer(socks_proxy);
  1070. } else {
  1071. // Otherwise use the indicated proxies per-scheme.
  1072. config.proxy_rules().type =
  1073. ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME;
  1074. config.proxy_rules().proxies_for_http.SetSingleProxyServer(
  1075. proxy_for_http);
  1076. config.proxy_rules().proxies_for_https.SetSingleProxyServer(
  1077. proxy_for_https);
  1078. config.proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_for_ftp);
  1079. config.proxy_rules().fallback_proxies.SetSingleProxyServer(socks_proxy);
  1080. }
  1081. }
  1082. if (config.proxy_rules().empty()) {
  1083. // Manual mode but we couldn't parse any rules.
  1084. return absl::nullopt;
  1085. }
  1086. // Check for authentication, just so we can warn.
  1087. bool use_auth = false;
  1088. setting_getter_->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION,
  1089. &use_auth);
  1090. if (use_auth) {
  1091. // ProxyConfig does not support authentication parameters, but
  1092. // Chrome will prompt for the password later. So we ignore
  1093. // /system/http_proxy/*auth* settings.
  1094. LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
  1095. }
  1096. // Now the bypass list.
  1097. std::vector<std::string> ignore_hosts_list;
  1098. config.proxy_rules().bypass_rules.Clear();
  1099. if (setting_getter_->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS,
  1100. &ignore_hosts_list)) {
  1101. for (const auto& rule : ignore_hosts_list) {
  1102. config.proxy_rules().bypass_rules.AddRuleFromString(rule);
  1103. }
  1104. }
  1105. if (setting_getter_->UseSuffixMatching()) {
  1106. RewriteRulesForSuffixMatching(&config.proxy_rules().bypass_rules);
  1107. }
  1108. // Note that there are no settings with semantics corresponding to
  1109. // bypass of local names in GNOME. In KDE, "<local>" is supported
  1110. // as a hostname rule.
  1111. // KDE allows one to reverse the bypass rules.
  1112. config.proxy_rules().reverse_bypass = setting_getter_->BypassListIsReversed();
  1113. return ProxyConfigWithAnnotation(
  1114. config, NetworkTrafficAnnotationTag(traffic_annotation_));
  1115. }
  1116. ProxyConfigServiceLinux::Delegate::Delegate(
  1117. std::unique_ptr<base::Environment> env_var_getter,
  1118. absl::optional<std::unique_ptr<SettingGetter>> setting_getter,
  1119. absl::optional<NetworkTrafficAnnotationTag> traffic_annotation)
  1120. : env_var_getter_(std::move(env_var_getter)) {
  1121. if (traffic_annotation) {
  1122. traffic_annotation_ =
  1123. MutableNetworkTrafficAnnotationTag(traffic_annotation.value());
  1124. }
  1125. if (setting_getter) {
  1126. setting_getter_ = std::move(setting_getter.value());
  1127. return;
  1128. }
  1129. // Figure out which SettingGetterImpl to use, if any.
  1130. switch (base::nix::GetDesktopEnvironment(env_var_getter_.get())) {
  1131. case base::nix::DESKTOP_ENVIRONMENT_CINNAMON:
  1132. case base::nix::DESKTOP_ENVIRONMENT_DEEPIN:
  1133. case base::nix::DESKTOP_ENVIRONMENT_GNOME:
  1134. case base::nix::DESKTOP_ENVIRONMENT_PANTHEON:
  1135. case base::nix::DESKTOP_ENVIRONMENT_UKUI:
  1136. case base::nix::DESKTOP_ENVIRONMENT_UNITY:
  1137. #if defined(USE_GIO)
  1138. {
  1139. auto gs_getter = std::make_unique<SettingGetterImplGSettings>();
  1140. // We have to load symbols and check the GNOME version in use to decide
  1141. // if we should use the gsettings getter. See CheckVersion().
  1142. if (gs_getter->CheckVersion(env_var_getter_.get()))
  1143. setting_getter_ = std::move(gs_getter);
  1144. }
  1145. #endif
  1146. break;
  1147. case base::nix::DESKTOP_ENVIRONMENT_KDE3:
  1148. case base::nix::DESKTOP_ENVIRONMENT_KDE4:
  1149. case base::nix::DESKTOP_ENVIRONMENT_KDE5:
  1150. setting_getter_ =
  1151. std::make_unique<SettingGetterImplKDE>(env_var_getter_.get());
  1152. break;
  1153. case base::nix::DESKTOP_ENVIRONMENT_XFCE:
  1154. case base::nix::DESKTOP_ENVIRONMENT_OTHER:
  1155. break;
  1156. }
  1157. }
  1158. void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
  1159. const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
  1160. const scoped_refptr<base::SequencedTaskRunner>& main_task_runner,
  1161. const NetworkTrafficAnnotationTag& traffic_annotation) {
  1162. traffic_annotation_ = MutableNetworkTrafficAnnotationTag(traffic_annotation);
  1163. // We should be running on the default glib main loop thread right
  1164. // now. gsettings can only be accessed from this thread.
  1165. DCHECK(glib_task_runner->RunsTasksInCurrentSequence());
  1166. glib_task_runner_ = glib_task_runner;
  1167. main_task_runner_ = main_task_runner;
  1168. // If we are passed a NULL |main_task_runner|, then don't set up proxy
  1169. // setting change notifications. This should not be the usual case but is
  1170. // intended to/ simplify test setups.
  1171. if (!main_task_runner_.get())
  1172. VLOG(1) << "Monitoring of proxy setting changes is disabled";
  1173. // Fetch and cache the current proxy config. The config is left in
  1174. // cached_config_, where GetLatestProxyConfig() running on the main TaskRunner
  1175. // will expect to find it. This is safe to do because we return
  1176. // before this ProxyConfigServiceLinux is passed on to
  1177. // the ConfiguredProxyResolutionService.
  1178. // Note: It would be nice to prioritize environment variables
  1179. // and only fall back to gsettings if env vars were unset. But
  1180. // gnome-terminal "helpfully" sets http_proxy and no_proxy, and it
  1181. // does so even if the proxy mode is set to auto, which would
  1182. // mislead us.
  1183. cached_config_ = absl::nullopt;
  1184. if (setting_getter_ && setting_getter_->Init(glib_task_runner)) {
  1185. cached_config_ = GetConfigFromSettings();
  1186. }
  1187. if (cached_config_) {
  1188. VLOG(1) << "Obtained proxy settings from annotation hash code "
  1189. << cached_config_->traffic_annotation().unique_id_hash_code;
  1190. // If gsettings proxy mode is "none", meaning direct, then we take
  1191. // that to be a valid config and will not check environment
  1192. // variables. The alternative would have been to look for a proxy
  1193. // wherever we can find one.
  1194. // Keep a copy of the config for use from this thread for
  1195. // comparison with updated settings when we get notifications.
  1196. reference_config_ = cached_config_;
  1197. // We only set up notifications if we have the main and file loops
  1198. // available. We do this after getting the initial configuration so that we
  1199. // don't have to worry about cancelling it if the initial fetch above fails.
  1200. // Note that setting up notifications has the side effect of simulating a
  1201. // change, so that we won't lose any updates that may have happened after
  1202. // the initial fetch and before setting up notifications. We'll detect the
  1203. // common case of no changes in OnCheckProxyConfigSettings() (or sooner) and
  1204. // ignore it.
  1205. if (main_task_runner.get()) {
  1206. scoped_refptr<base::SequencedTaskRunner> required_loop =
  1207. setting_getter_->GetNotificationTaskRunner();
  1208. if (!required_loop.get() || required_loop->RunsTasksInCurrentSequence()) {
  1209. // In this case we are already on an acceptable thread.
  1210. SetUpNotifications();
  1211. } else {
  1212. // Post a task to set up notifications. We don't wait for success.
  1213. required_loop->PostTask(
  1214. FROM_HERE,
  1215. base::BindOnce(
  1216. &ProxyConfigServiceLinux::Delegate::SetUpNotifications, this));
  1217. }
  1218. }
  1219. }
  1220. if (!cached_config_) {
  1221. // We fall back on environment variables.
  1222. //
  1223. // Consulting environment variables doesn't need to be done from the
  1224. // default glib main loop, but it's a tiny enough amount of work.
  1225. cached_config_ = GetConfigFromEnv();
  1226. if (cached_config_) {
  1227. VLOG(1) << "Obtained proxy settings from environment variables";
  1228. }
  1229. }
  1230. }
  1231. // Depending on the SettingGetter in use, this method will be called
  1232. // on either the UI thread (GSettings) or the file thread (KDE).
  1233. void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
  1234. scoped_refptr<base::SequencedTaskRunner> required_loop =
  1235. setting_getter_->GetNotificationTaskRunner();
  1236. DCHECK(!required_loop.get() || required_loop->RunsTasksInCurrentSequence());
  1237. if (!setting_getter_->SetUpNotifications(this))
  1238. LOG(ERROR) << "Unable to set up proxy configuration change notifications";
  1239. }
  1240. void ProxyConfigServiceLinux::Delegate::AddObserver(Observer* observer) {
  1241. observers_.AddObserver(observer);
  1242. }
  1243. void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer* observer) {
  1244. observers_.RemoveObserver(observer);
  1245. }
  1246. ProxyConfigService::ConfigAvailability
  1247. ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
  1248. ProxyConfigWithAnnotation* config) {
  1249. // This is called from the main TaskRunner.
  1250. DCHECK(!main_task_runner_.get() ||
  1251. main_task_runner_->RunsTasksInCurrentSequence());
  1252. // Simply return the last proxy configuration that glib_default_loop
  1253. // notified us of.
  1254. *config = GetConfigOrDirect(cached_config_);
  1255. // We return CONFIG_VALID to indicate that *config was filled in. It is always
  1256. // going to be available since we initialized eagerly on the UI thread.
  1257. // TODO(eroman): do lazy initialization instead, so we no longer need
  1258. // to construct ProxyConfigServiceLinux on the UI thread.
  1259. // In which case, we may return false here.
  1260. return CONFIG_VALID;
  1261. }
  1262. // Depending on the SettingGetter in use, this method will be called
  1263. // on either the UI thread (GSettings) or the file thread (KDE).
  1264. void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
  1265. scoped_refptr<base::SequencedTaskRunner> required_loop =
  1266. setting_getter_->GetNotificationTaskRunner();
  1267. DCHECK(!required_loop.get() || required_loop->RunsTasksInCurrentSequence());
  1268. absl::optional<ProxyConfigWithAnnotation> new_config =
  1269. GetConfigFromSettings();
  1270. // See if it is different from what we had before.
  1271. if (new_config.has_value() != reference_config_.has_value() ||
  1272. (new_config.has_value() &&
  1273. !new_config->value().Equals(reference_config_->value()))) {
  1274. // Post a task to the main TaskRunner with the new configuration, so it can
  1275. // update |cached_config_|.
  1276. main_task_runner_->PostTask(
  1277. FROM_HERE,
  1278. base::BindOnce(&ProxyConfigServiceLinux::Delegate::SetNewProxyConfig,
  1279. this, new_config));
  1280. // Update the thread-private copy in |reference_config_| as well.
  1281. reference_config_ = new_config;
  1282. } else {
  1283. VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
  1284. }
  1285. }
  1286. void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
  1287. const absl::optional<ProxyConfigWithAnnotation>& new_config) {
  1288. DCHECK(main_task_runner_->RunsTasksInCurrentSequence());
  1289. VLOG(1) << "Proxy configuration changed";
  1290. cached_config_ = new_config;
  1291. for (auto& observer : observers_) {
  1292. observer.OnProxyConfigChanged(GetConfigOrDirect(new_config),
  1293. ProxyConfigService::CONFIG_VALID);
  1294. }
  1295. }
  1296. void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
  1297. if (!setting_getter_)
  1298. return;
  1299. scoped_refptr<base::SequencedTaskRunner> shutdown_loop =
  1300. setting_getter_->GetNotificationTaskRunner();
  1301. if (!shutdown_loop.get() || shutdown_loop->RunsTasksInCurrentSequence()) {
  1302. // Already on the right thread, call directly.
  1303. // This is the case for the unittests.
  1304. OnDestroy();
  1305. } else {
  1306. // Post to shutdown thread. Note that on browser shutdown, we may quit
  1307. // this MessageLoop and exit the program before ever running this.
  1308. shutdown_loop->PostTask(
  1309. FROM_HERE,
  1310. base::BindOnce(&ProxyConfigServiceLinux::Delegate::OnDestroy, this));
  1311. }
  1312. }
  1313. void ProxyConfigServiceLinux::Delegate::OnDestroy() {
  1314. scoped_refptr<base::SequencedTaskRunner> shutdown_loop =
  1315. setting_getter_->GetNotificationTaskRunner();
  1316. DCHECK(!shutdown_loop.get() || shutdown_loop->RunsTasksInCurrentSequence());
  1317. setting_getter_->ShutDown();
  1318. }
  1319. ProxyConfigServiceLinux::ProxyConfigServiceLinux()
  1320. : delegate_(base::MakeRefCounted<Delegate>(base::Environment::Create(),
  1321. absl::nullopt,
  1322. absl::nullopt)) {}
  1323. ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
  1324. delegate_->PostDestroyTask();
  1325. }
  1326. ProxyConfigServiceLinux::ProxyConfigServiceLinux(
  1327. std::unique_ptr<base::Environment> env_var_getter,
  1328. const NetworkTrafficAnnotationTag& traffic_annotation)
  1329. : delegate_(base::MakeRefCounted<Delegate>(std::move(env_var_getter),
  1330. absl::nullopt,
  1331. traffic_annotation)) {}
  1332. ProxyConfigServiceLinux::ProxyConfigServiceLinux(
  1333. std::unique_ptr<base::Environment> env_var_getter,
  1334. std::unique_ptr<SettingGetter> setting_getter,
  1335. const NetworkTrafficAnnotationTag& traffic_annotation)
  1336. : delegate_(base::MakeRefCounted<Delegate>(std::move(env_var_getter),
  1337. std::move(setting_getter),
  1338. traffic_annotation)) {}
  1339. void ProxyConfigServiceLinux::AddObserver(Observer* observer) {
  1340. delegate_->AddObserver(observer);
  1341. }
  1342. void ProxyConfigServiceLinux::RemoveObserver(Observer* observer) {
  1343. delegate_->RemoveObserver(observer);
  1344. }
  1345. ProxyConfigService::ConfigAvailability
  1346. ProxyConfigServiceLinux::GetLatestProxyConfig(
  1347. ProxyConfigWithAnnotation* config) {
  1348. return delegate_->GetLatestProxyConfig(config);
  1349. }
  1350. } // namespace net