blob: b8acb457277caa8e0b1c93e0f9213500fe27250c [file] [log] [blame]
Paul Jensen869868be2014-05-15 10:33:05 -04001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.captiveportallogin;
18
19import android.app.Activity;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040020import android.app.LoadedApk;
21import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040022import android.content.Intent;
23import android.graphics.Bitmap;
24import android.net.ConnectivityManager;
Paul Jensen8df099d2014-09-26 15:19:17 -040025import android.net.ConnectivityManager.NetworkCallback;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040026import android.net.LinkProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040027import android.net.Network;
Paul Jensen8df099d2014-09-26 15:19:17 -040028import android.net.NetworkCapabilities;
29import android.net.NetworkRequest;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040030import android.net.Proxy;
31import android.net.ProxyInfo;
32import android.net.Uri;
Paul Jensenfc8022f2014-12-09 15:18:40 -050033import android.net.http.SslError;
Paul Jensen869868be2014-05-15 10:33:05 -040034import android.os.Bundle;
35import android.provider.Settings;
36import android.provider.Settings.Global;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040037import android.util.ArrayMap;
38import android.util.Log;
Paul Jensen869868be2014-05-15 10:33:05 -040039import android.view.Menu;
40import android.view.MenuItem;
Paul Jensen8f333f12014-08-05 22:52:16 -040041import android.view.View;
Paul Jensen869868be2014-05-15 10:33:05 -040042import android.view.Window;
Paul Jensenfc8022f2014-12-09 15:18:40 -050043import android.webkit.SslErrorHandler;
Paul Jensen869868be2014-05-15 10:33:05 -040044import android.webkit.WebChromeClient;
45import android.webkit.WebSettings;
46import android.webkit.WebView;
47import android.webkit.WebViewClient;
Paul Jensen8f333f12014-08-05 22:52:16 -040048import android.widget.ProgressBar;
Paul Jensen869868be2014-05-15 10:33:05 -040049
50import java.io.IOException;
51import java.net.HttpURLConnection;
52import java.net.MalformedURLException;
53import java.net.URL;
54import java.lang.InterruptedException;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040055import java.lang.reflect.Field;
56import java.lang.reflect.Method;
Paul Jensen869868be2014-05-15 10:33:05 -040057
58public class CaptivePortalLoginActivity extends Activity {
Paul Jensen88eb0fa2014-10-02 13:43:39 -040059 private static final String TAG = "CaptivePortalLogin";
Paul Jensen869868be2014-05-15 10:33:05 -040060 private static final String DEFAULT_SERVER = "clients3.google.com";
61 private static final int SOCKET_TIMEOUT_MS = 10000;
62
63 // Keep this in sync with NetworkMonitor.
64 // Intent broadcast to ConnectivityService indicating sign-in is complete.
65 // Extras:
66 // EXTRA_TEXT = netId
Paul Jensen71b645f2014-10-13 14:13:07 -040067 // LOGGED_IN_RESULT = one of the CAPTIVE_PORTAL_APP_RETURN_* values below.
68 // RESPONSE_TOKEN = data fragment from launching Intent
Paul Jensen869868be2014-05-15 10:33:05 -040069 private static final String ACTION_CAPTIVE_PORTAL_LOGGED_IN =
70 "android.net.netmon.captive_portal_logged_in";
71 private static final String LOGGED_IN_RESULT = "result";
Paul Jensen71b645f2014-10-13 14:13:07 -040072 private static final int CAPTIVE_PORTAL_APP_RETURN_APPEASED = 0;
73 private static final int CAPTIVE_PORTAL_APP_RETURN_UNWANTED = 1;
74 private static final int CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS = 2;
75 private static final String RESPONSE_TOKEN = "response_token";
Paul Jensen869868be2014-05-15 10:33:05 -040076
77 private URL mURL;
78 private int mNetId;
Paul Jensen71b645f2014-10-13 14:13:07 -040079 private String mResponseToken;
Paul Jensen8df099d2014-09-26 15:19:17 -040080 private NetworkCallback mNetworkCallback;
Paul Jensen869868be2014-05-15 10:33:05 -040081
82 @Override
83 protected void onCreate(Bundle savedInstanceState) {
84 super.onCreate(savedInstanceState);
85
86 String server = Settings.Global.getString(getContentResolver(), "captive_portal_server");
87 if (server == null) server = DEFAULT_SERVER;
88 try {
Paul Jensen71b645f2014-10-13 14:13:07 -040089 mURL = new URL("http", server, "/generate_204");
90 final Uri dataUri = getIntent().getData();
91 if (!dataUri.getScheme().equals("netid")) {
92 throw new MalformedURLException();
93 }
94 mNetId = Integer.parseInt(dataUri.getSchemeSpecificPart());
95 mResponseToken = dataUri.getFragment();
96 } catch (MalformedURLException|NumberFormatException e) {
97 // System misconfigured, bail out in a way that at least provides network access.
98 done(CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -040099 }
100
Paul Jensen8df099d2014-09-26 15:19:17 -0400101 final Network network = new Network(mNetId);
102 ConnectivityManager.setProcessDefaultNetwork(network);
103
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400104 // Set HTTP proxy system properties to those of the selected Network.
105 final LinkProperties lp = ConnectivityManager.from(this).getLinkProperties(network);
106 if (lp != null) {
107 final ProxyInfo proxyInfo = lp.getHttpProxy();
108 String host = "";
109 String port = "";
110 String exclList = "";
111 Uri pacFileUrl = Uri.EMPTY;
112 if (proxyInfo != null) {
113 host = proxyInfo.getHost();
114 port = Integer.toString(proxyInfo.getPort());
115 exclList = proxyInfo.getExclusionListAsString();
116 pacFileUrl = proxyInfo.getPacFileUrl();
117 }
118 Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
119 Log.v(TAG, "Set proxy system properties to " + proxyInfo);
120 }
121
122 // Proxy system properties must be initialized before setContentView is called because
123 // setContentView initializes the WebView logic which in turn reads the system properties.
124 setContentView(R.layout.activity_captive_portal_login);
125
126 getActionBar().setDisplayShowHomeEnabled(false);
127
Paul Jensen8df099d2014-09-26 15:19:17 -0400128 // Exit app if Network disappears.
129 final NetworkCapabilities networkCapabilities =
130 ConnectivityManager.from(this).getNetworkCapabilities(network);
131 if (networkCapabilities == null) {
132 finish();
133 return;
134 }
135 mNetworkCallback = new NetworkCallback() {
136 @Override
137 public void onLost(Network lostNetwork) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400138 if (network.equals(lostNetwork)) done(CAPTIVE_PORTAL_APP_RETURN_UNWANTED);
Paul Jensen8df099d2014-09-26 15:19:17 -0400139 }
140 };
141 final NetworkRequest.Builder builder = new NetworkRequest.Builder();
142 for (int transportType : networkCapabilities.getTransportTypes()) {
143 builder.addTransportType(transportType);
144 }
145 ConnectivityManager.from(this).registerNetworkCallback(builder.build(), mNetworkCallback);
Paul Jensen869868be2014-05-15 10:33:05 -0400146
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400147 final WebView myWebView = (WebView) findViewById(R.id.webview);
148 myWebView.clearCache(true);
Paul Jensen869868be2014-05-15 10:33:05 -0400149 WebSettings webSettings = myWebView.getSettings();
150 webSettings.setJavaScriptEnabled(true);
151 myWebView.setWebViewClient(new MyWebViewClient());
152 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400153 // Start initial page load so WebView finishes loading proxy settings.
154 // Actual load of mUrl is initiated by MyWebViewClient.
155 myWebView.loadData("", "text/html", null);
156 }
157
158 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
159 private void setWebViewProxy() {
160 LoadedApk loadedApk = getApplication().mLoadedApk;
161 try {
162 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
163 receiversField.setAccessible(true);
164 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
165 for (Object receiverMap : receivers.values()) {
166 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
167 Class clazz = rec.getClass();
168 if (clazz.getName().contains("ProxyChangeListener")) {
169 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
170 Intent.class);
171 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
172 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
173 Log.v(TAG, "Prompting WebView proxy reload.");
174 }
175 }
176 }
177 } catch (Exception e) {
178 Log.e(TAG, "Exception while setting WebView proxy: " + e);
179 }
Paul Jensen869868be2014-05-15 10:33:05 -0400180 }
181
Paul Jensen71b645f2014-10-13 14:13:07 -0400182 private void done(int result) {
183 if (mNetworkCallback != null) {
184 ConnectivityManager.from(this).unregisterNetworkCallback(mNetworkCallback);
185 }
Paul Jensen869868be2014-05-15 10:33:05 -0400186 Intent intent = new Intent(ACTION_CAPTIVE_PORTAL_LOGGED_IN);
187 intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetId));
Paul Jensen71b645f2014-10-13 14:13:07 -0400188 intent.putExtra(LOGGED_IN_RESULT, String.valueOf(result));
189 intent.putExtra(RESPONSE_TOKEN, mResponseToken);
Paul Jensen869868be2014-05-15 10:33:05 -0400190 sendBroadcast(intent);
191 finish();
192 }
193
194 @Override
195 public boolean onCreateOptionsMenu(Menu menu) {
196 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
197 return true;
198 }
199
200 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400201 public void onBackPressed() {
202 WebView myWebView = (WebView) findViewById(R.id.webview);
203 if (myWebView.canGoBack()) {
204 myWebView.goBack();
205 } else {
206 super.onBackPressed();
207 }
208 }
209
210 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400211 public boolean onOptionsItemSelected(MenuItem item) {
212 int id = item.getItemId();
213 if (id == R.id.action_use_network) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400214 done(CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -0400215 return true;
216 }
217 if (id == R.id.action_do_not_use_network) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400218 done(CAPTIVE_PORTAL_APP_RETURN_UNWANTED);
Paul Jensen869868be2014-05-15 10:33:05 -0400219 return true;
220 }
221 return super.onOptionsItemSelected(item);
222 }
223
224 private void testForCaptivePortal() {
225 new Thread(new Runnable() {
226 public void run() {
227 // Give time for captive portal to open.
228 try {
229 Thread.sleep(1000);
230 } catch (InterruptedException e) {
231 }
232 HttpURLConnection urlConnection = null;
233 int httpResponseCode = 500;
234 try {
235 urlConnection = (HttpURLConnection) mURL.openConnection();
236 urlConnection.setInstanceFollowRedirects(false);
237 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
238 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
239 urlConnection.setUseCaches(false);
240 urlConnection.getInputStream();
241 httpResponseCode = urlConnection.getResponseCode();
242 } catch (IOException e) {
243 } finally {
244 if (urlConnection != null) urlConnection.disconnect();
245 }
246 if (httpResponseCode == 204) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400247 done(CAPTIVE_PORTAL_APP_RETURN_APPEASED);
Paul Jensen869868be2014-05-15 10:33:05 -0400248 }
249 }
250 }).start();
251 }
252
253 private class MyWebViewClient extends WebViewClient {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400254 private boolean firstPageLoad = true;
255
Paul Jensen869868be2014-05-15 10:33:05 -0400256 @Override
257 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400258 if (firstPageLoad) return;
Paul Jensen869868be2014-05-15 10:33:05 -0400259 testForCaptivePortal();
260 }
261
262 @Override
263 public void onPageFinished(WebView view, String url) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400264 if (firstPageLoad) {
265 firstPageLoad = false;
266 // Now that WebView has loaded at least one page we know it has read in the proxy
267 // settings. Now prompt the WebView read the Network-specific proxy settings.
268 setWebViewProxy();
269 // Load the real page.
270 view.loadUrl(mURL.toString());
271 return;
272 }
Paul Jensen869868be2014-05-15 10:33:05 -0400273 testForCaptivePortal();
274 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500275
276 // A web page consisting of a large broken lock icon to indicate SSL failure.
277 final static String SSL_ERROR_HTML = "<!DOCTYPE html><html><head><style>" +
278 "html { width:100%; height:100%; " +
279 " background:url(locked_page.png) center center no-repeat; }" +
280 "</style></head><body></body></html>";
281
282 @Override
283 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
284 Log.w(TAG, "SSL error; displaying broken lock icon.");
285 view.loadDataWithBaseURL("file:///android_asset/", SSL_ERROR_HTML, "text/HTML",
286 "UTF-8", null);
287 }
Paul Jensen869868be2014-05-15 10:33:05 -0400288 }
289
290 private class MyWebChromeClient extends WebChromeClient {
291 @Override
292 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen8f333f12014-08-05 22:52:16 -0400293 ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
294 myProgressBar.setProgress(newProgress);
295 myProgressBar.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
Paul Jensen869868be2014-05-15 10:33:05 -0400296 }
297 }
298}