Update AppListModel when the app list state changes.
[chromium-blink-merge.git] / net / proxy / proxy_config_service_android.cc
blobf1a0b6cca54f702b924b969ba320d691b61b1108
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.
5 #include "net/proxy/proxy_config_service_android.h"
7 #include <sys/system_properties.h>
9 #include "base/android/jni_array.h"
10 #include "base/android/jni_string.h"
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/observer_list.h"
19 #include "base/sequenced_task_runner.h"
20 #include "base/strings/string_tokenizer.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "jni/ProxyChangeListener_jni.h"
24 #include "net/base/host_port_pair.h"
25 #include "net/proxy/proxy_config.h"
26 #include "url/url_parse.h"
28 using base::android::AttachCurrentThread;
29 using base::android::ConvertUTF8ToJavaString;
30 using base::android::ConvertJavaStringToUTF8;
31 using base::android::CheckException;
32 using base::android::ClearException;
33 using base::android::ScopedJavaGlobalRef;
35 namespace net {
37 namespace {
39 typedef ProxyConfigServiceAndroid::GetPropertyCallback GetPropertyCallback;
41 // Returns whether the provided string was successfully converted to a port.
42 bool ConvertStringToPort(const std::string& port, int* output) {
43 url::Component component(0, port.size());
44 int result = url::ParsePort(port.c_str(), component);
45 if (result == url::PORT_INVALID || result == url::PORT_UNSPECIFIED)
46 return false;
47 *output = result;
48 return true;
51 ProxyServer ConstructProxyServer(ProxyServer::Scheme scheme,
52 const std::string& proxy_host,
53 const std::string& proxy_port) {
54 DCHECK(!proxy_host.empty());
55 int port_as_int = 0;
56 if (proxy_port.empty())
57 port_as_int = ProxyServer::GetDefaultPortForScheme(scheme);
58 else if (!ConvertStringToPort(proxy_port, &port_as_int))
59 return ProxyServer();
60 DCHECK(port_as_int > 0);
61 return ProxyServer(
62 scheme,
63 HostPortPair(proxy_host, static_cast<uint16>(port_as_int)));
66 ProxyServer LookupProxy(const std::string& prefix,
67 const GetPropertyCallback& get_property,
68 ProxyServer::Scheme scheme) {
69 DCHECK(!prefix.empty());
70 std::string proxy_host = get_property.Run(prefix + ".proxyHost");
71 if (!proxy_host.empty()) {
72 std::string proxy_port = get_property.Run(prefix + ".proxyPort");
73 return ConstructProxyServer(scheme, proxy_host, proxy_port);
75 // Fall back to default proxy, if any.
76 proxy_host = get_property.Run("proxyHost");
77 if (!proxy_host.empty()) {
78 std::string proxy_port = get_property.Run("proxyPort");
79 return ConstructProxyServer(scheme, proxy_host, proxy_port);
81 return ProxyServer();
84 ProxyServer LookupSocksProxy(const GetPropertyCallback& get_property) {
85 std::string proxy_host = get_property.Run("socksProxyHost");
86 if (!proxy_host.empty()) {
87 std::string proxy_port = get_property.Run("socksProxyPort");
88 return ConstructProxyServer(ProxyServer::SCHEME_SOCKS5, proxy_host,
89 proxy_port);
91 return ProxyServer();
94 void AddBypassRules(const std::string& scheme,
95 const GetPropertyCallback& get_property,
96 ProxyBypassRules* bypass_rules) {
97 // The format of a hostname pattern is a list of hostnames that are separated
98 // by | and that use * as a wildcard. For example, setting the
99 // http.nonProxyHosts property to *.android.com|*.kernel.org will cause
100 // requests to http://developer.android.com to be made without a proxy.
101 std::string non_proxy_hosts =
102 get_property.Run(scheme + ".nonProxyHosts");
103 if (non_proxy_hosts.empty())
104 return;
105 base::StringTokenizer tokenizer(non_proxy_hosts, "|");
106 while (tokenizer.GetNext()) {
107 std::string token = tokenizer.token();
108 std::string pattern;
109 base::TrimWhitespaceASCII(token, base::TRIM_ALL, &pattern);
110 if (pattern.empty())
111 continue;
112 // '?' is not one of the specified pattern characters above.
113 DCHECK_EQ(std::string::npos, pattern.find('?'));
114 bypass_rules->AddRuleForHostname(scheme, pattern, -1);
118 // Returns true if a valid proxy was found.
119 bool GetProxyRules(const GetPropertyCallback& get_property,
120 ProxyConfig::ProxyRules* rules) {
121 // See libcore/luni/src/main/java/java/net/ProxySelectorImpl.java for the
122 // mostly equivalent Android implementation. There is one intentional
123 // difference: by default Chromium uses the HTTP port (80) for HTTPS
124 // connections via proxy. This default is identical on other platforms.
125 // On the opposite, Java spec suggests to use HTTPS port (443) by default (the
126 // default value of https.proxyPort).
127 rules->type = ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME;
128 rules->proxies_for_http.SetSingleProxyServer(
129 LookupProxy("http", get_property, ProxyServer::SCHEME_HTTP));
130 rules->proxies_for_https.SetSingleProxyServer(
131 LookupProxy("https", get_property, ProxyServer::SCHEME_HTTP));
132 rules->proxies_for_ftp.SetSingleProxyServer(
133 LookupProxy("ftp", get_property, ProxyServer::SCHEME_HTTP));
134 rules->fallback_proxies.SetSingleProxyServer(LookupSocksProxy(get_property));
135 rules->bypass_rules.Clear();
136 AddBypassRules("ftp", get_property, &rules->bypass_rules);
137 AddBypassRules("http", get_property, &rules->bypass_rules);
138 AddBypassRules("https", get_property, &rules->bypass_rules);
139 // We know a proxy was found if not all of the proxy lists are empty.
140 return !(rules->proxies_for_http.IsEmpty() &&
141 rules->proxies_for_https.IsEmpty() &&
142 rules->proxies_for_ftp.IsEmpty() &&
143 rules->fallback_proxies.IsEmpty());
146 void GetLatestProxyConfigInternal(const GetPropertyCallback& get_property,
147 ProxyConfig* config) {
148 if (!GetProxyRules(get_property, &config->proxy_rules()))
149 *config = ProxyConfig::CreateDirect();
152 std::string GetJavaProperty(const std::string& property) {
153 // Use Java System.getProperty to get configuration information.
154 // TODO(pliard): Conversion to/from UTF8 ok here?
155 JNIEnv* env = AttachCurrentThread();
156 ScopedJavaLocalRef<jstring> str = ConvertUTF8ToJavaString(env, property);
157 ScopedJavaLocalRef<jstring> result =
158 Java_ProxyChangeListener_getProperty(env, str.obj());
159 return result.is_null() ?
160 std::string() : ConvertJavaStringToUTF8(env, result.obj());
163 void CreateStaticProxyConfig(const std::string& host,
164 int port,
165 const std::string& pac_url,
166 const std::vector<std::string>& exclusion_list,
167 ProxyConfig* config) {
168 if (!pac_url.empty()) {
169 config->set_pac_url(GURL(pac_url));
170 config->set_pac_mandatory(false);
171 } else if (port != 0) {
172 std::string rules = base::StringPrintf("%s:%d", host.c_str(), port);
173 config->proxy_rules().ParseFromString(rules);
174 config->proxy_rules().bypass_rules.Clear();
176 std::vector<std::string>::const_iterator it;
177 for (it = exclusion_list.begin(); it != exclusion_list.end(); ++it) {
178 std::string pattern;
179 base::TrimWhitespaceASCII(*it, base::TRIM_ALL, &pattern);
180 if (pattern.empty())
181 continue;
182 config->proxy_rules().bypass_rules.AddRuleForHostname("", pattern, -1);
184 } else {
185 *config = ProxyConfig::CreateDirect();
189 } // namespace
191 class ProxyConfigServiceAndroid::Delegate
192 : public base::RefCountedThreadSafe<Delegate> {
193 public:
194 Delegate(const scoped_refptr<base::SequencedTaskRunner>& network_task_runner,
195 const scoped_refptr<base::SequencedTaskRunner>& jni_task_runner,
196 const GetPropertyCallback& get_property_callback)
197 : jni_delegate_(this),
198 network_task_runner_(network_task_runner),
199 jni_task_runner_(jni_task_runner),
200 get_property_callback_(get_property_callback) {
203 void SetupJNI() {
204 DCHECK(OnJNIThread());
205 JNIEnv* env = AttachCurrentThread();
206 if (java_proxy_change_listener_.is_null()) {
207 java_proxy_change_listener_.Reset(
208 Java_ProxyChangeListener_create(
209 env, base::android::GetApplicationContext()));
210 CHECK(!java_proxy_change_listener_.is_null());
212 Java_ProxyChangeListener_start(
213 env,
214 java_proxy_change_listener_.obj(),
215 reinterpret_cast<intptr_t>(&jni_delegate_));
218 void FetchInitialConfig() {
219 DCHECK(OnJNIThread());
220 ProxyConfig proxy_config;
221 GetLatestProxyConfigInternal(get_property_callback_, &proxy_config);
222 network_task_runner_->PostTask(
223 FROM_HERE,
224 base::Bind(&Delegate::SetNewConfigOnNetworkThread, this, proxy_config));
227 void Shutdown() {
228 if (OnJNIThread()) {
229 ShutdownOnJNIThread();
230 } else {
231 jni_task_runner_->PostTask(
232 FROM_HERE,
233 base::Bind(&Delegate::ShutdownOnJNIThread, this));
237 // Called only on the network thread.
238 void AddObserver(Observer* observer) {
239 DCHECK(OnNetworkThread());
240 observers_.AddObserver(observer);
243 void RemoveObserver(Observer* observer) {
244 DCHECK(OnNetworkThread());
245 observers_.RemoveObserver(observer);
248 ConfigAvailability GetLatestProxyConfig(ProxyConfig* config) {
249 DCHECK(OnNetworkThread());
250 if (!config)
251 return ProxyConfigService::CONFIG_UNSET;
252 *config = proxy_config_;
253 return ProxyConfigService::CONFIG_VALID;
256 // Called on the JNI thread.
257 void ProxySettingsChanged() {
258 DCHECK(OnJNIThread());
259 ProxyConfig proxy_config;
260 GetLatestProxyConfigInternal(get_property_callback_, &proxy_config);
261 network_task_runner_->PostTask(
262 FROM_HERE,
263 base::Bind(
264 &Delegate::SetNewConfigOnNetworkThread, this, proxy_config));
267 // Called on the JNI thread.
268 void ProxySettingsChangedTo(const std::string& host,
269 int port,
270 const std::string& pac_url,
271 const std::vector<std::string>& exclusion_list) {
272 DCHECK(OnJNIThread());
273 ProxyConfig proxy_config;
274 CreateStaticProxyConfig(host, port, pac_url, exclusion_list, &proxy_config);
275 network_task_runner_->PostTask(
276 FROM_HERE,
277 base::Bind(
278 &Delegate::SetNewConfigOnNetworkThread, this, proxy_config));
281 private:
282 friend class base::RefCountedThreadSafe<Delegate>;
284 class JNIDelegateImpl : public ProxyConfigServiceAndroid::JNIDelegate {
285 public:
286 explicit JNIDelegateImpl(Delegate* delegate) : delegate_(delegate) {}
288 // ProxyConfigServiceAndroid::JNIDelegate overrides.
289 virtual void ProxySettingsChangedTo(JNIEnv* env,
290 jobject jself,
291 jstring jhost,
292 jint jport,
293 jstring jpac_url,
294 jobjectArray jexclusion_list) override {
295 std::string host = ConvertJavaStringToUTF8(env, jhost);
296 std::string pac_url;
297 if (jpac_url)
298 ConvertJavaStringToUTF8(env, jpac_url, &pac_url);
299 std::vector<std::string> exclusion_list;
300 base::android::AppendJavaStringArrayToStringVector(
301 env, jexclusion_list, &exclusion_list);
302 delegate_->ProxySettingsChangedTo(host, jport, pac_url, exclusion_list);
305 virtual void ProxySettingsChanged(JNIEnv* env, jobject self) override {
306 delegate_->ProxySettingsChanged();
309 private:
310 Delegate* const delegate_;
313 virtual ~Delegate() {}
315 void ShutdownOnJNIThread() {
316 if (java_proxy_change_listener_.is_null())
317 return;
318 JNIEnv* env = AttachCurrentThread();
319 Java_ProxyChangeListener_stop(env, java_proxy_change_listener_.obj());
322 // Called on the network thread.
323 void SetNewConfigOnNetworkThread(const ProxyConfig& proxy_config) {
324 DCHECK(OnNetworkThread());
325 proxy_config_ = proxy_config;
326 FOR_EACH_OBSERVER(Observer, observers_,
327 OnProxyConfigChanged(proxy_config,
328 ProxyConfigService::CONFIG_VALID));
331 bool OnJNIThread() const {
332 return jni_task_runner_->RunsTasksOnCurrentThread();
335 bool OnNetworkThread() const {
336 return network_task_runner_->RunsTasksOnCurrentThread();
339 ScopedJavaGlobalRef<jobject> java_proxy_change_listener_;
341 JNIDelegateImpl jni_delegate_;
342 ObserverList<Observer> observers_;
343 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
344 scoped_refptr<base::SequencedTaskRunner> jni_task_runner_;
345 GetPropertyCallback get_property_callback_;
346 ProxyConfig proxy_config_;
348 DISALLOW_COPY_AND_ASSIGN(Delegate);
351 ProxyConfigServiceAndroid::ProxyConfigServiceAndroid(
352 const scoped_refptr<base::SequencedTaskRunner>& network_task_runner,
353 const scoped_refptr<base::SequencedTaskRunner>& jni_task_runner)
354 : delegate_(new Delegate(
355 network_task_runner, jni_task_runner, base::Bind(&GetJavaProperty))) {
356 delegate_->SetupJNI();
357 delegate_->FetchInitialConfig();
360 ProxyConfigServiceAndroid::~ProxyConfigServiceAndroid() {
361 delegate_->Shutdown();
364 // static
365 bool ProxyConfigServiceAndroid::Register(JNIEnv* env) {
366 return RegisterNativesImpl(env);
369 void ProxyConfigServiceAndroid::AddObserver(Observer* observer) {
370 delegate_->AddObserver(observer);
373 void ProxyConfigServiceAndroid::RemoveObserver(Observer* observer) {
374 delegate_->RemoveObserver(observer);
377 ProxyConfigService::ConfigAvailability
378 ProxyConfigServiceAndroid::GetLatestProxyConfig(ProxyConfig* config) {
379 return delegate_->GetLatestProxyConfig(config);
382 ProxyConfigServiceAndroid::ProxyConfigServiceAndroid(
383 const scoped_refptr<base::SequencedTaskRunner>& network_task_runner,
384 const scoped_refptr<base::SequencedTaskRunner>& jni_task_runner,
385 GetPropertyCallback get_property_callback)
386 : delegate_(new Delegate(
387 network_task_runner, jni_task_runner, get_property_callback)) {
388 delegate_->SetupJNI();
389 delegate_->FetchInitialConfig();
392 void ProxyConfigServiceAndroid::ProxySettingsChanged() {
393 delegate_->ProxySettingsChanged();
396 } // namespace net