blob: b58c87a5094d34adcd3e48ef7f82414772386250 [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;
Paul Jensen49e3edf2015-05-22 10:50:39 -040024import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040025import android.net.ConnectivityManager;
Paul Jensen8df099d2014-09-26 15:19:17 -040026import android.net.ConnectivityManager.NetworkCallback;
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;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040031import android.net.Uri;
Paul Jensenfc8022f2014-12-09 15:18:40 -050032import android.net.http.SslError;
Paul Jensen869868be2014-05-15 10:33:05 -040033import android.os.Bundle;
34import android.provider.Settings;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040035import android.util.ArrayMap;
36import android.util.Log;
Paul Jensen65636fb2015-05-06 14:40:59 -040037import android.util.TypedValue;
Paul Jensen869868be2014-05-15 10:33:05 -040038import android.view.Menu;
39import android.view.MenuItem;
Paul Jensenfc8022f2014-12-09 15:18:40 -050040import android.webkit.SslErrorHandler;
Paul Jensen869868be2014-05-15 10:33:05 -040041import android.webkit.WebChromeClient;
42import android.webkit.WebSettings;
43import android.webkit.WebView;
44import android.webkit.WebViewClient;
Paul Jensen8f333f12014-08-05 22:52:16 -040045import android.widget.ProgressBar;
Paul Jensen5344a4a2015-05-06 07:39:36 -040046import android.widget.TextView;
Paul Jensen869868be2014-05-15 10:33:05 -040047
48import java.io.IOException;
49import java.net.HttpURLConnection;
50import java.net.MalformedURLException;
51import java.net.URL;
52import java.lang.InterruptedException;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040053import java.lang.reflect.Field;
54import java.lang.reflect.Method;
Paul Jensen65636fb2015-05-06 14:40:59 -040055import java.util.Random;
Paul Jensen869868be2014-05-15 10:33:05 -040056
57public class CaptivePortalLoginActivity extends Activity {
Paul Jensen88eb0fa2014-10-02 13:43:39 -040058 private static final String TAG = "CaptivePortalLogin";
Paul Jensen869868be2014-05-15 10:33:05 -040059 private static final int SOCKET_TIMEOUT_MS = 10000;
60
Paul Jensen25a217c2015-02-27 22:55:47 -050061 private enum Result { DISMISSED, UNWANTED, WANTED_AS_IS };
Paul Jensen869868be2014-05-15 10:33:05 -040062
63 private URL mURL;
Paul Jensen25a217c2015-02-27 22:55:47 -050064 private Network mNetwork;
Paul Jensen49e3edf2015-05-22 10:50:39 -040065 private CaptivePortal mCaptivePortal;
Paul Jensen8df099d2014-09-26 15:19:17 -040066 private NetworkCallback mNetworkCallback;
Paul Jensen25a217c2015-02-27 22:55:47 -050067 private ConnectivityManager mCm;
Paul Jensen65636fb2015-05-06 14:40:59 -040068 private boolean mLaunchBrowser = false;
Paul Jensene836b682015-05-19 12:30:56 -040069 private MyWebViewClient mWebViewClient;
Paul Jensen869868be2014-05-15 10:33:05 -040070
71 @Override
72 protected void onCreate(Bundle savedInstanceState) {
73 super.onCreate(savedInstanceState);
Paul Jensen25a217c2015-02-27 22:55:47 -050074 mCm = ConnectivityManager.from(this);
Jan Nordqvist52eb29f2015-09-22 15:54:32 -070075 String url = getIntent().getStringExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL);
Udam Sainib7c24872016-01-04 12:16:14 -080076 if (url == null) url = mCm.getCaptivePortalServerUrl();
Paul Jensen869868be2014-05-15 10:33:05 -040077 try {
Udam Sainib7c24872016-01-04 12:16:14 -080078 mURL = new URL(url);
Paul Jensen25a217c2015-02-27 22:55:47 -050079 } catch (MalformedURLException e) {
Paul Jensen71b645f2014-10-13 14:13:07 -040080 // System misconfigured, bail out in a way that at least provides network access.
Udam Sainib7c24872016-01-04 12:16:14 -080081 Log.e(TAG, "Invalid captive portal URL, url=" + url);
Paul Jensen25a217c2015-02-27 22:55:47 -050082 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -040083 }
Paul Jensen25a217c2015-02-27 22:55:47 -050084 mNetwork = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_NETWORK);
Paul Jensen49e3edf2015-05-22 10:50:39 -040085 mCaptivePortal = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL);
Paul Jensen869868be2014-05-15 10:33:05 -040086
Paul Jensene0bef712014-12-10 15:12:18 -050087 // Also initializes proxy system properties.
Paul Jensen25a217c2015-02-27 22:55:47 -050088 mCm.bindProcessToNetwork(mNetwork);
Paul Jensen88eb0fa2014-10-02 13:43:39 -040089
90 // Proxy system properties must be initialized before setContentView is called because
91 // setContentView initializes the WebView logic which in turn reads the system properties.
92 setContentView(R.layout.activity_captive_portal_login);
93
94 getActionBar().setDisplayShowHomeEnabled(false);
95
Paul Jensen8df099d2014-09-26 15:19:17 -040096 // Exit app if Network disappears.
Paul Jensen25a217c2015-02-27 22:55:47 -050097 final NetworkCapabilities networkCapabilities = mCm.getNetworkCapabilities(mNetwork);
Paul Jensen8df099d2014-09-26 15:19:17 -040098 if (networkCapabilities == null) {
Paul Jensen6a776c832016-07-19 13:19:39 -040099 finishAndRemoveTask();
Paul Jensen8df099d2014-09-26 15:19:17 -0400100 return;
101 }
102 mNetworkCallback = new NetworkCallback() {
103 @Override
104 public void onLost(Network lostNetwork) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500105 if (mNetwork.equals(lostNetwork)) done(Result.UNWANTED);
Paul Jensen8df099d2014-09-26 15:19:17 -0400106 }
107 };
108 final NetworkRequest.Builder builder = new NetworkRequest.Builder();
109 for (int transportType : networkCapabilities.getTransportTypes()) {
110 builder.addTransportType(transportType);
111 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500112 mCm.registerNetworkCallback(builder.build(), mNetworkCallback);
Paul Jensen869868be2014-05-15 10:33:05 -0400113
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400114 final WebView myWebView = (WebView) findViewById(R.id.webview);
115 myWebView.clearCache(true);
Paul Jensen869868be2014-05-15 10:33:05 -0400116 WebSettings webSettings = myWebView.getSettings();
117 webSettings.setJavaScriptEnabled(true);
Paul Jensene836b682015-05-19 12:30:56 -0400118 mWebViewClient = new MyWebViewClient();
119 myWebView.setWebViewClient(mWebViewClient);
Paul Jensen869868be2014-05-15 10:33:05 -0400120 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400121 // Start initial page load so WebView finishes loading proxy settings.
122 // Actual load of mUrl is initiated by MyWebViewClient.
123 myWebView.loadData("", "text/html", null);
124 }
125
126 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
127 private void setWebViewProxy() {
128 LoadedApk loadedApk = getApplication().mLoadedApk;
129 try {
130 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
131 receiversField.setAccessible(true);
132 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
133 for (Object receiverMap : receivers.values()) {
134 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
135 Class clazz = rec.getClass();
136 if (clazz.getName().contains("ProxyChangeListener")) {
137 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
138 Intent.class);
139 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
140 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
141 Log.v(TAG, "Prompting WebView proxy reload.");
142 }
143 }
144 }
145 } catch (Exception e) {
146 Log.e(TAG, "Exception while setting WebView proxy: " + e);
147 }
Paul Jensen869868be2014-05-15 10:33:05 -0400148 }
149
Paul Jensen25a217c2015-02-27 22:55:47 -0500150 private void done(Result result) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400151 if (mNetworkCallback != null) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500152 mCm.unregisterNetworkCallback(mNetworkCallback);
Paul Jensen868f6242015-05-18 12:48:28 -0400153 mNetworkCallback = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400154 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500155 switch (result) {
156 case DISMISSED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400157 mCaptivePortal.reportCaptivePortalDismissed();
Paul Jensen25a217c2015-02-27 22:55:47 -0500158 break;
159 case UNWANTED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400160 mCaptivePortal.ignoreNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500161 break;
162 case WANTED_AS_IS:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400163 mCaptivePortal.useNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500164 break;
165 }
Paul Jensen6a776c832016-07-19 13:19:39 -0400166 finishAndRemoveTask();
Paul Jensen869868be2014-05-15 10:33:05 -0400167 }
168
169 @Override
170 public boolean onCreateOptionsMenu(Menu menu) {
171 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
172 return true;
173 }
174
175 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400176 public void onBackPressed() {
177 WebView myWebView = (WebView) findViewById(R.id.webview);
Paul Jensene836b682015-05-19 12:30:56 -0400178 if (myWebView.canGoBack() && mWebViewClient.allowBack()) {
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400179 myWebView.goBack();
180 } else {
181 super.onBackPressed();
182 }
183 }
184
185 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400186 public boolean onOptionsItemSelected(MenuItem item) {
187 int id = item.getItemId();
188 if (id == R.id.action_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500189 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -0400190 return true;
191 }
192 if (id == R.id.action_do_not_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500193 done(Result.UNWANTED);
Paul Jensen869868be2014-05-15 10:33:05 -0400194 return true;
195 }
196 return super.onOptionsItemSelected(item);
197 }
198
Paul Jensen868f6242015-05-18 12:48:28 -0400199 @Override
200 public void onDestroy() {
201 super.onDestroy();
202
203 if (mNetworkCallback != null) {
204 mCm.unregisterNetworkCallback(mNetworkCallback);
205 mNetworkCallback = null;
206 }
Paul Jensen65636fb2015-05-06 14:40:59 -0400207 if (mLaunchBrowser) {
208 // Give time for this network to become default. After 500ms just proceed.
209 for (int i = 0; i < 5; i++) {
210 // TODO: This misses when mNetwork underlies a VPN.
211 if (mNetwork.equals(mCm.getActiveNetwork())) break;
212 try {
213 Thread.sleep(100);
214 } catch (InterruptedException e) {
215 }
216 }
217 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mURL.toString())));
218 }
Paul Jensen868f6242015-05-18 12:48:28 -0400219 }
220
Paul Jensen869868be2014-05-15 10:33:05 -0400221 private void testForCaptivePortal() {
222 new Thread(new Runnable() {
223 public void run() {
224 // Give time for captive portal to open.
225 try {
226 Thread.sleep(1000);
227 } catch (InterruptedException e) {
228 }
229 HttpURLConnection urlConnection = null;
230 int httpResponseCode = 500;
231 try {
232 urlConnection = (HttpURLConnection) mURL.openConnection();
233 urlConnection.setInstanceFollowRedirects(false);
234 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
235 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
236 urlConnection.setUseCaches(false);
237 urlConnection.getInputStream();
238 httpResponseCode = urlConnection.getResponseCode();
239 } catch (IOException e) {
240 } finally {
241 if (urlConnection != null) urlConnection.disconnect();
242 }
243 if (httpResponseCode == 204) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500244 done(Result.DISMISSED);
Paul Jensen869868be2014-05-15 10:33:05 -0400245 }
246 }
247 }).start();
248 }
249
250 private class MyWebViewClient extends WebViewClient {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400251 private static final String INTERNAL_ASSETS = "file:///android_asset/";
Paul Jensen65636fb2015-05-06 14:40:59 -0400252 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
253 // How many Android device-independent-pixels per scaled-pixel
254 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
255 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
256 getResources().getDisplayMetrics()) /
257 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
258 getResources().getDisplayMetrics());
Paul Jensene836b682015-05-19 12:30:56 -0400259 private int mPagesLoaded;
260
261 // If we haven't finished cleaning up the history, don't allow going back.
262 public boolean allowBack() {
263 return mPagesLoaded > 1;
264 }
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400265
Paul Jensen869868be2014-05-15 10:33:05 -0400266 @Override
267 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400268 if (url.contains(mBrowserBailOutToken)) {
269 mLaunchBrowser = true;
270 done(Result.WANTED_AS_IS);
271 return;
272 }
Paul Jensene836b682015-05-19 12:30:56 -0400273 // The first page load is used only to cause the WebView to
274 // fetch the proxy settings. Don't update the URL bar, and
275 // don't check if the captive portal is still there.
276 if (mPagesLoaded == 0) return;
277 // For internally generated pages, leave URL bar listing prior URL as this is the URL
278 // the page refers to.
279 if (!url.startsWith(INTERNAL_ASSETS)) {
280 final TextView myUrlBar = (TextView) findViewById(R.id.url_bar);
281 myUrlBar.setText(url);
282 }
Paul Jensen869868be2014-05-15 10:33:05 -0400283 testForCaptivePortal();
284 }
285
286 @Override
287 public void onPageFinished(WebView view, String url) {
Paul Jensene836b682015-05-19 12:30:56 -0400288 mPagesLoaded++;
289 if (mPagesLoaded == 1) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400290 // Now that WebView has loaded at least one page we know it has read in the proxy
291 // settings. Now prompt the WebView read the Network-specific proxy settings.
292 setWebViewProxy();
293 // Load the real page.
294 view.loadUrl(mURL.toString());
295 return;
Paul Jensene836b682015-05-19 12:30:56 -0400296 } else if (mPagesLoaded == 2) {
297 // Prevent going back to empty first page.
298 view.clearHistory();
Paul Jensen5344a4a2015-05-06 07:39:36 -0400299 }
Paul Jensen869868be2014-05-15 10:33:05 -0400300 testForCaptivePortal();
301 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500302
Paul Jensen65636fb2015-05-06 14:40:59 -0400303 // Convert Android device-independent-pixels (dp) to HTML size.
304 private String dp(int dp) {
305 // HTML px's are scaled just like dp's, so just add "px" suffix.
306 return Integer.toString(dp) + "px";
307 }
308
309 // Convert Android scaled-pixels (sp) to HTML size.
310 private String sp(int sp) {
311 // Convert sp to dp's.
312 float dp = sp * mDpPerSp;
313 // Apply a scale factor to make things look right.
314 dp *= 1.3;
315 // Convert dp's to HTML size.
316 return dp((int)dp);
317 }
318
Paul Jensenfc8022f2014-12-09 15:18:40 -0500319 // A web page consisting of a large broken lock icon to indicate SSL failure.
Paul Jensen65636fb2015-05-06 14:40:59 -0400320 private final String SSL_ERROR_HTML = "<html><head><style>" +
321 "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; " +
322 "margin-top:" + dp(96) + "; background-color:#fafafa; }" +
323 "img { width:" + dp(48) + "; height:" + dp(48) + "; }" +
324 "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; " +
325 " opacity:0.87; line-height:1.28; }" +
326 "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; " +
327 " opacity:0.54; line-height:1.21905; }" +
328 "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; " +
329 " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; " +
330 " height:" + dp(48) + "; font-weight:bold; }" +
331 "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>" +
332 "<div class=warn>%s</div>" +
333 "<div class=example>%s</div>" +
334 "<a href=%s>%s</a></body></html>";
Paul Jensenfc8022f2014-12-09 15:18:40 -0500335
336 @Override
337 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Paul Jensen41ff5242015-06-09 08:55:06 -0400338 Log.w(TAG, "SSL error (error: " + error.getPrimaryError() + " host: " +
339 // Only show host to avoid leaking private info.
340 Uri.parse(error.getUrl()).getHost() + " certificate: " +
341 error.getCertificate() + "); displaying SSL warning.");
Paul Jensen65636fb2015-05-06 14:40:59 -0400342 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
343 getString(R.string.ssl_error_example), mBrowserBailOutToken,
344 getString(R.string.ssl_error_continue));
345 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
Paul Jensenfc8022f2014-12-09 15:18:40 -0500346 }
Paul Jensenfd54da92015-06-09 07:50:51 -0400347
348 @Override
349 public boolean shouldOverrideUrlLoading (WebView view, String url) {
350 if (url.startsWith("tel:")) {
351 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
352 return true;
353 }
354 return false;
355 }
Paul Jensen869868be2014-05-15 10:33:05 -0400356 }
357
358 private class MyWebChromeClient extends WebChromeClient {
359 @Override
360 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400361 final ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
Paul Jensen8f333f12014-08-05 22:52:16 -0400362 myProgressBar.setProgress(newProgress);
Paul Jensen869868be2014-05-15 10:33:05 -0400363 }
364 }
365}