#include "net/proxy_resolution/proxy_config_service_linux.h"
#include <errno.h>
#include <limits.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <map>
#include <memory>
#include <optional>
#include <utility>
#include "base/compiler_specific.h"
#include "base/files/file_descriptor_watcher_posix.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/nix/xdg_util.h"
#include "base/observer_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/timer/timer.h"
#include "net/base/proxy_server.h"
#include "net/base/proxy_string_util.h"
#if defined(USE_GIO)
#include <gio/gio.h>
#include "ui/base/glib/gsettings.h"
#include "ui/base/glib/scoped_gobject.h"
#endif
namespace net {
class ScopedAllowBlockingForSettingGetter : public base::ScopedAllowBlocking {};
namespace {
void RewriteRulesForSuffixMatching(ProxyHostMatchingRules* out) {
for (size_t i = 0; i < out->rules().size(); ++i) {
if (!out->rules()[i]->IsHostnamePatternRule())
continue;
const SchemeHostPortMatcherHostnamePatternRule* prev_rule =
static_cast<const SchemeHostPortMatcherHostnamePatternRule*>(
out->rules()[i].get());
out->ReplaceRule(i, prev_rule->GenerateSuffixMatchingRule());
}
}
std::string FixupProxyHostScheme(ProxyServer::Scheme scheme,
std::string host) {
if (scheme == ProxyServer::SCHEME_SOCKS5 &&
base::StartsWith(host, "socks4://",
base::CompareCase::INSENSITIVE_ASCII)) {
scheme = ProxyServer::SCHEME_SOCKS4;
}
std::string::size_type colon = host.find("://");
if (colon != std::string::npos)
host = host.substr(colon + 3);
std::string::size_type at_sign = host.find("@");
if (at_sign != std::string::npos) {
LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
host = host.substr(at_sign + 1);
}
if (scheme == ProxyServer::SCHEME_SOCKS4)
host = "socks4://" + host;
else if (scheme == ProxyServer::SCHEME_SOCKS5)
host = "socks5://" + host;
if (!host.empty() && host.back() == '/')
host.resize(host.length() - 1);
return host;
}
ProxyConfigWithAnnotation GetConfigOrDirect(
const std::optional<ProxyConfigWithAnnotation>& optional_config) {
if (optional_config)
return optional_config.value();
ProxyConfigWithAnnotation config = ProxyConfigWithAnnotation::CreateDirect();
return config;
}
}
ProxyConfigServiceLinux::Delegate::~Delegate() = default;
bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVarForScheme(
base::cstring_view variable,
ProxyServer::Scheme scheme,
ProxyChain* result_chain) {
std::optional<std::string> env_value = env_var_getter_->GetVar(variable);
if (!env_value.has_value() || env_value->empty()) {
return false;
}
std::string fixed_host =
FixupProxyHostScheme(scheme, std::move(env_value.value()));
ProxyChain proxy_chain =
ProxyUriToProxyChain(fixed_host, ProxyServer::SCHEME_HTTP);
if (proxy_chain.IsValid() &&
(proxy_chain.is_direct() || proxy_chain.is_single_proxy())) {
*result_chain = proxy_chain;
return true;
}
LOG(ERROR) << "Failed to parse environment variable " << variable;
return false;
}
bool ProxyConfigServiceLinux::Delegate::GetProxyFromEnvVar(
base::cstring_view variable,
ProxyChain* result_chain) {
return GetProxyFromEnvVarForScheme(variable, ProxyServer::SCHEME_HTTP,
result_chain);
}
std::optional<ProxyConfigWithAnnotation>
ProxyConfigServiceLinux::Delegate::GetConfigFromEnv() {
ProxyConfig config;
std::optional<std::string> auto_proxy = env_var_getter_->GetVar("auto_proxy");
if (auto_proxy.has_value()) {
if (auto_proxy->empty()) {
config.set_auto_detect(true);
} else {
config.set_pac_url(GURL(auto_proxy.value()));
}
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
ProxyChain proxy_chain;
if (GetProxyFromEnvVar("all_proxy", &proxy_chain)) {
config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
config.proxy_rules().single_proxies.SetSingleProxyChain(proxy_chain);
} else {
bool have_http = GetProxyFromEnvVar("http_proxy", &proxy_chain);
if (have_http)
config.proxy_rules().proxies_for_http.SetSingleProxyChain(proxy_chain);
bool have_https = GetProxyFromEnvVar("https_proxy", &proxy_chain);
if (have_https)
config.proxy_rules().proxies_for_https.SetSingleProxyChain(proxy_chain);
bool have_ftp = GetProxyFromEnvVar("ftp_proxy", &proxy_chain);
if (have_ftp)
config.proxy_rules().proxies_for_ftp.SetSingleProxyChain(proxy_chain);
if (have_http || have_https || have_ftp) {
config.proxy_rules().type =
ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME;
}
}
if (config.proxy_rules().empty()) {
ProxyServer::Scheme scheme = ProxyServer::SCHEME_SOCKS5;
std::optional<std::string> env_version =
env_var_getter_->GetVar("SOCKS_VERSION");
if (env_version.has_value() && env_version.value() == "4") {
scheme = ProxyServer::SCHEME_SOCKS4;
}
if (GetProxyFromEnvVarForScheme("SOCKS_SERVER", scheme, &proxy_chain)) {
config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
config.proxy_rules().single_proxies.SetSingleProxyChain(proxy_chain);
}
}
std::string no_proxy = env_var_getter_->GetVar("no_proxy").value_or("");
if (config.proxy_rules().empty()) {
return !no_proxy.empty()
? ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_))
: std::optional<ProxyConfigWithAnnotation>();
}
config.proxy_rules().bypass_rules.ParseFromString(no_proxy);
RewriteRulesForSuffixMatching(&config.proxy_rules().bypass_rules);
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
namespace {
const int kDebounceTimeoutMilliseconds = 250;
#if defined(USE_GIO)
const char kProxyGSettingsSchema[] = "org.gnome.system.proxy";
class SettingGetterImplGSettings
: public ProxyConfigServiceLinux::SettingGetter {
public:
SettingGetterImplGSettings()
: debounce_timer_(std::make_unique<base::OneShotTimer>()) {}
SettingGetterImplGSettings(const SettingGetterImplGSettings&) = delete;
SettingGetterImplGSettings& operator=(const SettingGetterImplGSettings&) =
delete;
~SettingGetterImplGSettings() override {
if (client_) {
if (task_runner_->RunsTasksInCurrentSequence()) {
VLOG(1) << "~SettingGetterImplGSettings: releasing gsettings client";
ShutDown();
} else {
LOG(WARNING) << "~SettingGetterImplGSettings: leaking gsettings client";
client_.release();
}
}
DCHECK(!client_);
}
bool CheckVersion();
bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner)
override {
DCHECK(glib_task_runner->RunsTasksInCurrentSequence());
DCHECK(!client_);
DCHECK(!task_runner_.get());
client_ = ui::GSettingsNew(kProxyGSettingsSchema);
if (!client_) {
LOG(ERROR) << "Unable to create a gsettings client";
return false;
}
task_runner_ = glib_task_runner;
http_client_ = g_settings_get_child(client_, "http");
https_client_ = g_settings_get_child(client_, "https");
ftp_client_ = g_settings_get_child(client_, "ftp");
socks_client_ = g_settings_get_child(client_, "socks");
DCHECK(http_client_ && https_client_ && ftp_client_ && socks_client_);
return true;
}
void ShutDown() override {
if (client_) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
g_object_unref(socks_client_.ExtractAsDangling());
g_object_unref(ftp_client_.ExtractAsDangling());
g_object_unref(https_client_.ExtractAsDangling());
g_object_unref(http_client_.ExtractAsDangling());
client_.Reset();
task_runner_ = nullptr;
}
debounce_timer_.reset();
}
bool SetUpNotifications(
ProxyConfigServiceLinux::Delegate* delegate) override {
DCHECK(client_);
DCHECK(task_runner_->RunsTasksInCurrentSequence());
notify_delegate_ = delegate;
g_signal_connect(G_OBJECT(client_.get()), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(http_client_.get()), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(https_client_.get()), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(ftp_client_.get()), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
g_signal_connect(G_OBJECT(socks_client_.get()), "changed",
G_CALLBACK(OnGSettingsChangeNotification), this);
OnChangeNotification();
return true;
}
const scoped_refptr<base::SequencedTaskRunner>& GetNotificationTaskRunner()
override {
return task_runner_;
}
bool GetString(StringSetting key, std::string* result) override {
DCHECK(client_);
switch (key) {
case PROXY_MODE:
return GetStringByPath(client_, "mode", result);
case PROXY_AUTOCONF_URL:
return GetStringByPath(client_, "autoconfig-url", result);
case PROXY_HTTP_HOST:
return GetStringByPath(http_client_, "host", result);
case PROXY_HTTPS_HOST:
return GetStringByPath(https_client_, "host", result);
case PROXY_FTP_HOST:
return GetStringByPath(ftp_client_, "host", result);
case PROXY_SOCKS_HOST:
return GetStringByPath(socks_client_, "host", result);
}
return false;
}
bool GetBool(BoolSetting key, bool* result) override {
DCHECK(client_);
switch (key) {
case PROXY_USE_HTTP_PROXY:
return false;
case PROXY_USE_SAME_PROXY:
return false;
case PROXY_USE_AUTHENTICATION:
return GetBoolByPath(http_client_, "use-authentication", result);
}
return false;
}
bool GetInt(IntSetting key, int* result) override {
DCHECK(client_);
switch (key) {
case PROXY_HTTP_PORT:
return GetIntByPath(http_client_, "port", result);
case PROXY_HTTPS_PORT:
return GetIntByPath(https_client_, "port", result);
case PROXY_FTP_PORT:
return GetIntByPath(ftp_client_, "port", result);
case PROXY_SOCKS_PORT:
return GetIntByPath(socks_client_, "port", result);
}
return false;
}
bool GetStringList(StringListSetting key,
std::vector<std::string>* result) override {
DCHECK(client_);
switch (key) {
case PROXY_IGNORE_HOSTS:
return GetStringListByPath(client_, "ignore-hosts", result);
}
return false;
}
bool BypassListIsReversed() override {
return false;
}
bool UseSuffixMatching() override { return false; }
private:
bool GetStringByPath(GSettings* client,
std::string_view key,
std::string* result) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
gchar* value = g_settings_get_string(client, key.data());
if (!value)
return false;
*result = value;
g_free(value);
return true;
}
bool GetBoolByPath(GSettings* client, std::string_view key, bool* result) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
*result = static_cast<bool>(g_settings_get_boolean(client, key.data()));
return true;
}
bool GetIntByPath(GSettings* client, std::string_view key, int* result) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
*result = g_settings_get_int(client, key.data());
return true;
}
bool GetStringListByPath(GSettings* client,
std::string_view key,
std::vector<std::string>* result) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
gchar** list = g_settings_get_strv(client, key.data());
if (!list)
return false;
for (size_t i = 0; UNSAFE_TODO(list[i]); ++i) {
result->push_back(static_cast<char*>(UNSAFE_TODO(list[i])));
g_free(UNSAFE_TODO(list[i]));
}
g_free(list);
return true;
}
void OnDebouncedNotification() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
CHECK(notify_delegate_);
notify_delegate_->OnCheckProxyConfigSettings();
}
void OnChangeNotification() {
debounce_timer_->Stop();
debounce_timer_->Start(
FROM_HERE, base::Milliseconds(kDebounceTimeoutMilliseconds), this,
&SettingGetterImplGSettings::OnDebouncedNotification);
}
static void OnGSettingsChangeNotification(GSettings* client, gchar* key,
gpointer user_data) {
VLOG(1) << "gsettings change notification for key " << key;
SettingGetterImplGSettings* setting_getter =
reinterpret_cast<SettingGetterImplGSettings*>(user_data);
setting_getter->OnChangeNotification();
}
ScopedGObject<GSettings> client_;
raw_ptr<GSettings> http_client_ = nullptr;
raw_ptr<GSettings> https_client_ = nullptr;
raw_ptr<GSettings> ftp_client_ = nullptr;
raw_ptr<GSettings> socks_client_ = nullptr;
raw_ptr<ProxyConfigServiceLinux::Delegate> notify_delegate_ = nullptr;
std::unique_ptr<base::OneShotTimer> debounce_timer_;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
};
bool SettingGetterImplGSettings::CheckVersion() {
DCHECK(!client_);
if (!ui::GSettingsNew(kProxyGSettingsSchema)) {
VLOG(1) << "Cannot create gsettings client.";
return false;
}
VLOG(1) << "Will get proxy config from gsettings.";
return true;
}
#endif
int StringToIntOrDefault(std::string_view value, int default_value) {
int result;
if (base::StringToInt(value, &result))
return result;
return default_value;
}
class SettingGetterImplKDE : public ProxyConfigServiceLinux::SettingGetter {
public:
explicit SettingGetterImplKDE(base::Environment* env_var_getter)
: debounce_timer_(std::make_unique<base::OneShotTimer>()),
env_var_getter_(env_var_getter) {
ScopedAllowBlockingForSettingGetter allow_blocking;
std::string home = env_var_getter->GetVar("KDEHOME").value_or("");
if (!home.empty()) {
kde_config_dirs_.emplace_back(KDEHomeToConfigPath(base::FilePath(home)));
} else {
home = env_var_getter->GetVar(base::env_vars::kHome).value_or("");
if (home.empty()) {
return;
}
auto desktop = base::nix::GetDesktopEnvironment(env_var_getter);
if (desktop == base::nix::DESKTOP_ENVIRONMENT_KDE3) {
base::FilePath kde_path = base::FilePath(home).Append(".kde");
kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde_path));
} else if (desktop == base::nix::DESKTOP_ENVIRONMENT_KDE4) {
base::FilePath kde3_path = base::FilePath(home).Append(".kde");
base::FilePath kde3_config = KDEHomeToConfigPath(kde3_path);
base::FilePath kde4_path = base::FilePath(home).Append(".kde4");
base::FilePath kde4_config = KDEHomeToConfigPath(kde4_path);
bool use_kde4 = false;
if (base::DirectoryExists(kde4_path)) {
base::File::Info kde3_info;
base::File::Info kde4_info;
if (base::GetFileInfo(kde4_config, &kde4_info)) {
if (base::GetFileInfo(kde3_config, &kde3_info)) {
use_kde4 = kde4_info.last_modified >= kde3_info.last_modified;
} else {
use_kde4 = true;
}
}
}
if (use_kde4) {
kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde4_path));
} else {
kde_config_dirs_.emplace_back(KDEHomeToConfigPath(kde3_path));
}
} else if (desktop == base::nix::DESKTOP_ENVIRONMENT_KDE5 ||
desktop == base::nix::DESKTOP_ENVIRONMENT_KDE6) {
kde_config_dirs_.emplace_back(base::FilePath(home).Append(".config"));
std::string config_dirs =
env_var_getter_->GetVar("XDG_CONFIG_DIRS").value_or("");
if (!config_dirs.empty()) {
auto dirs = base::SplitString(config_dirs, ":", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
for (const auto& dir : dirs) {
kde_config_dirs_.emplace_back(dir);
}
}
std::ranges::reverse(kde_config_dirs_);
}
}
}
SettingGetterImplKDE(const SettingGetterImplKDE&) = delete;
SettingGetterImplKDE& operator=(const SettingGetterImplKDE&) = delete;
~SettingGetterImplKDE() override {
if (inotify_fd_ >= 0)
ShutDown();
DCHECK_LT(inotify_fd_, 0);
}
bool Init(const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner)
override {
ScopedAllowBlockingForSettingGetter allow_blocking;
DCHECK_LT(inotify_fd_, 0);
inotify_fd_ = inotify_init();
if (inotify_fd_ < 0) {
PLOG(ERROR) << "inotify_init failed";
return false;
}
if (!base::SetNonBlocking(inotify_fd_)) {
PLOG(ERROR) << "base::SetNonBlocking failed";
close(inotify_fd_);
inotify_fd_ = -1;
return false;
}
constexpr base::TaskTraits kTraits = {base::TaskPriority::USER_VISIBLE,
base::MayBlock()};
file_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(kTraits);
UpdateCachedSettings();
return true;
}
void ShutDown() override {
if (inotify_fd_ >= 0) {
ResetCachedSettings();
inotify_watcher_.reset();
close(inotify_fd_);
inotify_fd_ = -1;
}
debounce_timer_.reset();
}
bool SetUpNotifications(
ProxyConfigServiceLinux::Delegate* delegate) override {
DCHECK_GE(inotify_fd_, 0);
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
size_t failed_dirs = 0;
for (const auto& kde_config_dir : kde_config_dirs_) {
if (inotify_add_watch(inotify_fd_, kde_config_dir.value().c_str(),
IN_MODIFY | IN_MOVED_TO) < 0) {
++failed_dirs;
}
}
if (failed_dirs == kde_config_dirs_.size()) {
return false;
}
notify_delegate_ = delegate;
inotify_watcher_ = base::FileDescriptorWatcher::WatchReadable(
inotify_fd_,
base::BindRepeating(&SettingGetterImplKDE::OnChangeNotification,
base::Unretained(this)));
OnChangeNotification();
return true;
}
const scoped_refptr<base::SequencedTaskRunner>& GetNotificationTaskRunner()
override {
return file_task_runner_;
}
bool GetString(StringSetting key, std::string* result) override {
auto it = string_table_.find(key);
if (it == string_table_.end())
return false;
*result = it->second;
return true;
}
bool GetBool(BoolSetting key, bool* result) override {
return false;
}
bool GetInt(IntSetting key, int* result) override {
return false;
}
bool GetStringList(StringListSetting key,
std::vector<std::string>* result) override {
auto it = strings_table_.find(key);
if (it == strings_table_.end())
return false;
*result = it->second;
return true;
}
bool BypassListIsReversed() override { return reversed_bypass_list_; }
bool UseSuffixMatching() override { return true; }
private:
void ResetCachedSettings() {
string_table_.clear();
strings_table_.clear();
indirect_manual_ = false;
auto_no_pac_ = false;
reversed_bypass_list_ = false;
}
base::FilePath KDEHomeToConfigPath(const base::FilePath& kde_home) {
return kde_home.Append("share").Append("config");
}
void AddProxy(StringSetting host_key, const std::string& value) {
if (value.empty() || value.substr(0, 3) == "//:")
return;
size_t space = value.find(' ');
if (space != std::string::npos) {
std::string fixed = value;
fixed[space] = ':';
string_table_[host_key] = std::move(fixed);
} else {
string_table_[host_key] = value;
}
}
void AddHostList(StringListSetting key, const std::string& value) {
std::vector<std::string> tokens;
base::StringTokenizer tk(value, ", ");
while (tk.GetNext()) {
std::string token = tk.token();
if (!token.empty())
tokens.push_back(token);
}
strings_table_[key] = tokens;
}
void AddKDESetting(const std::string& key, const std::string& value) {
if (key == "ProxyType") {
const char* mode = "none";
indirect_manual_ = false;
auto_no_pac_ = false;
int int_value = StringToIntOrDefault(value, 0);
switch (int_value) {
case 1:
mode = "manual";
break;
case 2:
mode = "auto";
break;
case 3:
mode = "auto";
auto_no_pac_ = true;
break;
case 4:
mode = "manual";
indirect_manual_ = true;
break;
default:
break;
}
string_table_[PROXY_MODE] = mode;
} else if (key == "Proxy Config Script") {
string_table_[PROXY_AUTOCONF_URL] = value;
} else if (key == "httpProxy") {
AddProxy(PROXY_HTTP_HOST, value);
} else if (key == "httpsProxy") {
AddProxy(PROXY_HTTPS_HOST, value);
} else if (key == "ftpProxy") {
AddProxy(PROXY_FTP_HOST, value);
} else if (key == "socksProxy") {
AddProxy(PROXY_SOCKS_HOST, value);
} else if (key == "ReversedException") {
reversed_bypass_list_ =
(value == "true" || StringToIntOrDefault(value, 0) != 0);
} else if (key == "NoProxyFor") {
AddHostList(PROXY_IGNORE_HOSTS, value);
} else if (key == "AuthMode") {
int mode = StringToIntOrDefault(value, 0);
if (mode) {
LOG(WARNING) <<
"Proxy authentication parameters ignored, see bug 16709";
}
}
}
void ResolveIndirect(StringSetting key) {
auto it = string_table_.find(key);
if (it != string_table_.end()) {
std::optional<std::string> value = env_var_getter_->GetVar(it->second);
if (value.has_value() && !value->empty()) {
it->second = value.value();
} else {
string_table_.erase(it);
}
}
}
void ResolveIndirectList(StringListSetting key) {
auto it = strings_table_.find(key);
if (it != strings_table_.end()) {
if (!it->second.empty()) {
std::optional<std::string> value =
env_var_getter_->GetVar(it->second[0]);
if (value.has_value() && !value->empty()) {
AddHostList(key, value.value());
} else {
strings_table_.erase(it);
}
} else {
strings_table_.erase(it);
}
}
}
void ResolveModeEffects() {
if (indirect_manual_) {
ResolveIndirect(PROXY_HTTP_HOST);
ResolveIndirect(PROXY_HTTPS_HOST);
ResolveIndirect(PROXY_FTP_HOST);
ResolveIndirect(PROXY_SOCKS_HOST);
ResolveIndirectList(PROXY_IGNORE_HOSTS);
}
if (auto_no_pac_) {
string_table_.erase(PROXY_AUTOCONF_URL);
}
}
void UpdateCachedSettings() {
bool at_least_one_kioslaverc_opened = false;
for (const auto& kde_config_dir : kde_config_dirs_) {
base::FilePath kioslaverc = kde_config_dir.Append("kioslaverc");
base::ScopedFILE input(base::OpenFile(kioslaverc, "r"));
if (!input.get())
continue;
if (!at_least_one_kioslaverc_opened) {
ResetCachedSettings();
}
at_least_one_kioslaverc_opened = true;
bool in_proxy_settings = false;
bool line_too_long = false;
char line[BUFFER_SIZE];
while (UNSAFE_TODO(fgets(line, sizeof(line), input.get()))) {
size_t length = strlen(line);
if (!length)
continue;
if (UNSAFE_TODO(line[length - 1]) != '\n') {
line_too_long = true;
continue;
}
if (line_too_long) {
LOG(WARNING) << "skipped very long line in " << kioslaverc.value();
line_too_long = false;
continue;
}
UNSAFE_TODO(line[--length]) = '\0';
if (length && UNSAFE_TODO(line[length - 1]) == '\r') {
UNSAFE_TODO(line[--length]) = '\0';
}
if (line[0] == '[') {
in_proxy_settings =
!UNSAFE_TODO(strncmp(line, "[Proxy Settings]", 16));
} else if (in_proxy_settings) {
char* split = UNSAFE_TODO(strchr(line, '='));
if (!split)
continue;
*(UNSAFE_TODO(split++)) = 0;
std::string key = line;
std::string value = split;
base::TrimWhitespaceASCII(key, base::TRIM_ALL, &key);
base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
if (key.empty())
continue;
if (key[key.length() - 1] == ']') {
length = key.rfind('[');
if (length == std::string::npos)
continue;
key.resize(length);
base::TrimWhitespaceASCII(key, base::TRIM_TRAILING, &key);
if (key.empty())
continue;
}
AddKDESetting(key, value);
}
}
if (ferror(input.get()))
LOG(ERROR) << "error reading " << kioslaverc.value();
}
if (at_least_one_kioslaverc_opened) {
ResolveModeEffects();
}
}
void OnDebouncedNotification() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
VLOG(1) << "inotify change notification for kioslaverc";
UpdateCachedSettings();
CHECK(notify_delegate_);
notify_delegate_->OnCheckProxyConfigSettings();
}
void OnChangeNotification() {
DCHECK_GE(inotify_fd_, 0);
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
char event_buf[(sizeof(inotify_event) + NAME_MAX + 1) * 4];
bool kioslaverc_touched = false;
ssize_t r;
while ((r = read(inotify_fd_, event_buf, sizeof(event_buf))) > 0) {
char* event_ptr = event_buf;
while (event_ptr < UNSAFE_TODO(event_buf + r)) {
inotify_event* event = reinterpret_cast<inotify_event*>(event_ptr);
UNSAFE_TODO(CHECK_LE(event_ptr + sizeof(inotify_event), event_buf + r));
UNSAFE_TODO(CHECK_LE(event->name + event->len, event_buf + r));
if (!UNSAFE_TODO(strcmp(event->name, "kioslaverc"))) {
kioslaverc_touched = true;
}
event_ptr = UNSAFE_TODO(event->name + event)->len;
}
}
if (!r)
errno = EINVAL;
if (errno != EAGAIN) {
PLOG(WARNING) << "error reading inotify file descriptor";
if (errno == EINVAL) {
LOG(ERROR) << "inotify failure; no longer watching kioslaverc!";
inotify_watcher_.reset();
close(inotify_fd_);
inotify_fd_ = -1;
}
}
if (kioslaverc_touched) {
LOG(ERROR) << "kioslaverc_touched";
debounce_timer_->Stop();
debounce_timer_->Start(
FROM_HERE, base::Milliseconds(kDebounceTimeoutMilliseconds), this,
&SettingGetterImplKDE::OnDebouncedNotification);
}
}
typedef std::map<StringSetting, std::string> string_map_type;
typedef std::map<StringListSetting,
std::vector<std::string> > strings_map_type;
int inotify_fd_ = -1;
std::unique_ptr<base::FileDescriptorWatcher::Controller> inotify_watcher_;
raw_ptr<ProxyConfigServiceLinux::Delegate> notify_delegate_ = nullptr;
std::unique_ptr<base::OneShotTimer> debounce_timer_;
std::vector<base::FilePath> kde_config_dirs_;
bool indirect_manual_ = false;
bool auto_no_pac_ = false;
bool reversed_bypass_list_ = false;
raw_ptr<base::Environment> env_var_getter_;
string_map_type string_table_;
strings_map_type strings_table_;
scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
};
}
bool ProxyConfigServiceLinux::Delegate::GetProxyFromSettings(
SettingGetter::StringSetting host_key,
ProxyServer* result_server) {
std::string host;
if (!setting_getter_->GetString(host_key, &host) || host.empty()) {
return false;
}
int port = 0;
SettingGetter::IntSetting port_key =
SettingGetter::HostSettingToPortSetting(host_key);
setting_getter_->GetInt(port_key, &port);
if (port != 0) {
host += ":" + base::NumberToString(port);
}
ProxyServer::Scheme scheme = host_key == SettingGetter::PROXY_SOCKS_HOST
? ProxyServer::SCHEME_SOCKS5
: ProxyServer::SCHEME_HTTP;
host = FixupProxyHostScheme(scheme, std::move(host));
ProxyServer proxy_server =
ProxyUriToProxyServer(host, ProxyServer::SCHEME_HTTP);
if (proxy_server.is_valid()) {
*result_server = proxy_server;
return true;
}
return false;
}
std::optional<ProxyConfigWithAnnotation>
ProxyConfigServiceLinux::Delegate::GetConfigFromSettings() {
ProxyConfig config;
config.set_from_system(true);
std::string mode;
if (!setting_getter_->GetString(SettingGetter::PROXY_MODE, &mode)) {
return std::nullopt;
}
if (mode == "none") {
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
if (mode == "auto") {
std::string pac_url_str;
if (setting_getter_->GetString(SettingGetter::PROXY_AUTOCONF_URL,
&pac_url_str)) {
if (!pac_url_str.empty()) {
if (pac_url_str[0] == '/')
pac_url_str = "file://" + pac_url_str;
GURL pac_url(pac_url_str);
if (!pac_url.is_valid())
return std::nullopt;
config.set_pac_url(pac_url);
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
}
config.set_auto_detect(true);
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
if (mode != "manual") {
return std::nullopt;
}
bool use_http_proxy;
if (setting_getter_->GetBool(SettingGetter::PROXY_USE_HTTP_PROXY,
&use_http_proxy)
&& !use_http_proxy) {
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
bool same_proxy = false;
setting_getter_->GetBool(SettingGetter::PROXY_USE_SAME_PROXY,
&same_proxy);
ProxyServer proxy_for_http;
ProxyServer proxy_for_https;
ProxyServer proxy_for_ftp;
ProxyServer socks_proxy;
size_t num_proxies_specified = 0;
if (GetProxyFromSettings(SettingGetter::PROXY_HTTP_HOST, &proxy_for_http))
num_proxies_specified++;
if (GetProxyFromSettings(SettingGetter::PROXY_HTTPS_HOST, &proxy_for_https))
num_proxies_specified++;
if (GetProxyFromSettings(SettingGetter::PROXY_FTP_HOST, &proxy_for_ftp))
num_proxies_specified++;
if (GetProxyFromSettings(SettingGetter::PROXY_SOCKS_HOST, &socks_proxy))
num_proxies_specified++;
if (same_proxy) {
if (proxy_for_http.is_valid()) {
config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
config.proxy_rules().single_proxies.SetSingleProxyServer(proxy_for_http);
}
} else if (num_proxies_specified > 0) {
if (socks_proxy.is_valid() && num_proxies_specified == 1) {
config.proxy_rules().type = ProxyConfig::ProxyRules::Type::PROXY_LIST;
config.proxy_rules().single_proxies.SetSingleProxyServer(socks_proxy);
} else {
config.proxy_rules().type =
ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME;
config.proxy_rules().proxies_for_http.SetSingleProxyServer(
proxy_for_http);
config.proxy_rules().proxies_for_https.SetSingleProxyServer(
proxy_for_https);
config.proxy_rules().proxies_for_ftp.SetSingleProxyServer(proxy_for_ftp);
config.proxy_rules().fallback_proxies.SetSingleProxyServer(socks_proxy);
}
}
if (config.proxy_rules().empty()) {
return std::nullopt;
}
bool use_auth = false;
setting_getter_->GetBool(SettingGetter::PROXY_USE_AUTHENTICATION,
&use_auth);
if (use_auth) {
LOG(WARNING) << "Proxy authentication parameters ignored, see bug 16709";
}
std::vector<std::string> ignore_hosts_list;
config.proxy_rules().bypass_rules.Clear();
if (setting_getter_->GetStringList(SettingGetter::PROXY_IGNORE_HOSTS,
&ignore_hosts_list)) {
for (const auto& rule : ignore_hosts_list) {
config.proxy_rules().bypass_rules.AddRuleFromString(rule);
}
}
if (setting_getter_->UseSuffixMatching()) {
RewriteRulesForSuffixMatching(&config.proxy_rules().bypass_rules);
}
config.proxy_rules().reverse_bypass = setting_getter_->BypassListIsReversed();
return ProxyConfigWithAnnotation(
config, NetworkTrafficAnnotationTag(traffic_annotation_));
}
ProxyConfigServiceLinux::Delegate::Delegate(
std::unique_ptr<base::Environment> env_var_getter,
std::optional<std::unique_ptr<SettingGetter>> setting_getter,
std::optional<NetworkTrafficAnnotationTag> traffic_annotation)
: env_var_getter_(std::move(env_var_getter)) {
if (traffic_annotation) {
traffic_annotation_ =
MutableNetworkTrafficAnnotationTag(traffic_annotation.value());
}
if (setting_getter) {
setting_getter_ = std::move(setting_getter.value());
return;
}
switch (base::nix::GetDesktopEnvironment(env_var_getter_.get())) {
case base::nix::DESKTOP_ENVIRONMENT_CINNAMON:
case base::nix::DESKTOP_ENVIRONMENT_DEEPIN:
case base::nix::DESKTOP_ENVIRONMENT_GNOME:
case base::nix::DESKTOP_ENVIRONMENT_PANTHEON:
case base::nix::DESKTOP_ENVIRONMENT_UKUI:
case base::nix::DESKTOP_ENVIRONMENT_UNITY:
case base::nix::DESKTOP_ENVIRONMENT_COSMIC:
#if defined(USE_GIO)
{
auto gs_getter = std::make_unique<SettingGetterImplGSettings>();
if (gs_getter->CheckVersion()) {
setting_getter_ = std::move(gs_getter);
}
}
#endif
break;
case base::nix::DESKTOP_ENVIRONMENT_KDE3:
case base::nix::DESKTOP_ENVIRONMENT_KDE4:
case base::nix::DESKTOP_ENVIRONMENT_KDE5:
case base::nix::DESKTOP_ENVIRONMENT_KDE6:
setting_getter_ =
std::make_unique<SettingGetterImplKDE>(env_var_getter_.get());
break;
case base::nix::DESKTOP_ENVIRONMENT_XFCE:
case base::nix::DESKTOP_ENVIRONMENT_LXQT:
case base::nix::DESKTOP_ENVIRONMENT_OTHER:
break;
}
}
void ProxyConfigServiceLinux::Delegate::SetUpAndFetchInitialConfig(
const scoped_refptr<base::SingleThreadTaskRunner>& glib_task_runner,
const scoped_refptr<base::SequencedTaskRunner>& main_task_runner,
const NetworkTrafficAnnotationTag& traffic_annotation) {
traffic_annotation_ = MutableNetworkTrafficAnnotationTag(traffic_annotation);
DCHECK(glib_task_runner->RunsTasksInCurrentSequence());
glib_task_runner_ = glib_task_runner;
main_task_runner_ = main_task_runner;
if (!main_task_runner_.get())
VLOG(1) << "Monitoring of proxy setting changes is disabled";
cached_config_ = std::nullopt;
if (setting_getter_ && setting_getter_->Init(glib_task_runner)) {
cached_config_ = GetConfigFromSettings();
}
if (cached_config_) {
VLOG(1) << "Obtained proxy settings from annotation hash code "
<< cached_config_->traffic_annotation().unique_id_hash_code;
reference_config_ = cached_config_;
if (main_task_runner.get()) {
scoped_refptr<base::SequencedTaskRunner> required_loop =
setting_getter_->GetNotificationTaskRunner();
if (!required_loop.get() || required_loop->RunsTasksInCurrentSequence()) {
SetUpNotifications();
} else {
required_loop->PostTask(
FROM_HERE,
base::BindOnce(
&ProxyConfigServiceLinux::Delegate::SetUpNotifications, this));
}
}
}
if (!cached_config_) {
cached_config_ = GetConfigFromEnv();
if (cached_config_) {
VLOG(1) << "Obtained proxy settings from environment variables";
}
}
}
void ProxyConfigServiceLinux::Delegate::SetUpNotifications() {
scoped_refptr<base::SequencedTaskRunner> required_loop =
setting_getter_->GetNotificationTaskRunner();
DCHECK(!required_loop.get() || required_loop->RunsTasksInCurrentSequence());
if (!setting_getter_->SetUpNotifications(this))
LOG(ERROR) << "Unable to set up proxy configuration change notifications";
}
void ProxyConfigServiceLinux::Delegate::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void ProxyConfigServiceLinux::Delegate::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
ProxyConfigService::ConfigAvailability
ProxyConfigServiceLinux::Delegate::GetLatestProxyConfig(
ProxyConfigWithAnnotation* config) {
DCHECK(!main_task_runner_.get() ||
main_task_runner_->RunsTasksInCurrentSequence());
*config = GetConfigOrDirect(cached_config_);
return CONFIG_VALID;
}
void ProxyConfigServiceLinux::Delegate::OnCheckProxyConfigSettings() {
scoped_refptr<base::SequencedTaskRunner> required_loop =
setting_getter_->GetNotificationTaskRunner();
DCHECK(!required_loop.get() || required_loop->RunsTasksInCurrentSequence());
std::optional<ProxyConfigWithAnnotation> new_config = GetConfigFromSettings();
if (new_config.has_value() != reference_config_.has_value() ||
(new_config.has_value() &&
!new_config->value().Equals(reference_config_->value()))) {
main_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&ProxyConfigServiceLinux::Delegate::SetNewProxyConfig,
this, new_config));
reference_config_ = new_config;
} else {
VLOG(1) << "Detected no-op change to proxy settings. Doing nothing.";
}
}
void ProxyConfigServiceLinux::Delegate::SetNewProxyConfig(
const std::optional<ProxyConfigWithAnnotation>& new_config) {
DCHECK(main_task_runner_->RunsTasksInCurrentSequence());
VLOG(1) << "Proxy configuration changed";
cached_config_ = new_config;
for (auto& observer : observers_) {
observer.OnProxyConfigChanged(GetConfigOrDirect(new_config),
ProxyConfigService::CONFIG_VALID);
}
}
void ProxyConfigServiceLinux::Delegate::PostDestroyTask() {
if (!setting_getter_)
return;
scoped_refptr<base::SequencedTaskRunner> shutdown_loop =
setting_getter_->GetNotificationTaskRunner();
if (!shutdown_loop.get() || shutdown_loop->RunsTasksInCurrentSequence()) {
OnDestroy();
} else {
shutdown_loop->PostTask(
FROM_HERE,
base::BindOnce(&ProxyConfigServiceLinux::Delegate::OnDestroy, this));
}
}
void ProxyConfigServiceLinux::Delegate::OnDestroy() {
scoped_refptr<base::SequencedTaskRunner> shutdown_loop =
setting_getter_->GetNotificationTaskRunner();
DCHECK(!shutdown_loop.get() || shutdown_loop->RunsTasksInCurrentSequence());
setting_getter_->ShutDown();
}
ProxyConfigServiceLinux::ProxyConfigServiceLinux()
: delegate_(base::MakeRefCounted<Delegate>(base::Environment::Create(),
std::nullopt,
std::nullopt)) {}
ProxyConfigServiceLinux::~ProxyConfigServiceLinux() {
delegate_->PostDestroyTask();
}
ProxyConfigServiceLinux::ProxyConfigServiceLinux(
std::unique_ptr<base::Environment> env_var_getter,
const NetworkTrafficAnnotationTag& traffic_annotation)
: delegate_(base::MakeRefCounted<Delegate>(std::move(env_var_getter),
std::nullopt,
traffic_annotation)) {}
ProxyConfigServiceLinux::ProxyConfigServiceLinux(
std::unique_ptr<base::Environment> env_var_getter,
std::unique_ptr<SettingGetter> setting_getter,
const NetworkTrafficAnnotationTag& traffic_annotation)
: delegate_(base::MakeRefCounted<Delegate>(std::move(env_var_getter),
std::move(setting_getter),
traffic_annotation)) {}
void ProxyConfigServiceLinux::AddObserver(Observer* observer) {
delegate_->AddObserver(observer);
}
void ProxyConfigServiceLinux::RemoveObserver(Observer* observer) {
delegate_->RemoveObserver(observer);
}
ProxyConfigService::ConfigAvailability
ProxyConfigServiceLinux::GetLatestProxyConfig(
ProxyConfigWithAnnotation* config) {
return delegate_->GetLatestProxyConfig(config);
}
}