blob: 03f0b4d5d5da6a3ba02b3810629488f241c78937 [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 {
Hugo Benichi87de0c22016-12-06 15:36:30 +090058 private static final String TAG = CaptivePortalLoginActivity.class.getSimpleName();
59 private static final boolean DBG = true;
60
Paul Jensen869868be2014-05-15 10:33:05 -040061 private static final int SOCKET_TIMEOUT_MS = 10000;
62
Paul Jensen25a217c2015-02-27 22:55:47 -050063 private enum Result { DISMISSED, UNWANTED, WANTED_AS_IS };
Paul Jensen869868be2014-05-15 10:33:05 -040064
Hugo Benichi87de0c22016-12-06 15:36:30 +090065 private URL mUrl;
Paul Jensen25a217c2015-02-27 22:55:47 -050066 private Network mNetwork;
Paul Jensen49e3edf2015-05-22 10:50:39 -040067 private CaptivePortal mCaptivePortal;
Paul Jensen8df099d2014-09-26 15:19:17 -040068 private NetworkCallback mNetworkCallback;
Paul Jensen25a217c2015-02-27 22:55:47 -050069 private ConnectivityManager mCm;
Paul Jensen65636fb2015-05-06 14:40:59 -040070 private boolean mLaunchBrowser = false;
Paul Jensene836b682015-05-19 12:30:56 -040071 private MyWebViewClient mWebViewClient;
Paul Jensen869868be2014-05-15 10:33:05 -040072
73 @Override
74 protected void onCreate(Bundle savedInstanceState) {
75 super.onCreate(savedInstanceState);
Paul Jensen25a217c2015-02-27 22:55:47 -050076 mCm = ConnectivityManager.from(this);
Paul Jensen25a217c2015-02-27 22:55:47 -050077 mNetwork = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_NETWORK);
Paul Jensen49e3edf2015-05-22 10:50:39 -040078 mCaptivePortal = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL);
Hugo Benichi87de0c22016-12-06 15:36:30 +090079 mUrl = getUrl();
80 if (mUrl == null) {
81 // getUrl() failed to parse the url provided in the intent: bail out in a way that
82 // at least provides network access.
83 done(Result.WANTED_AS_IS);
84 return;
85 }
86 if (DBG) {
87 Log.d(TAG, String.format("onCreate for %s", mUrl.toString()));
88 }
Paul Jensen869868be2014-05-15 10:33:05 -040089
Paul Jensene0bef712014-12-10 15:12:18 -050090 // Also initializes proxy system properties.
Paul Jensen25a217c2015-02-27 22:55:47 -050091 mCm.bindProcessToNetwork(mNetwork);
Paul Jensen88eb0fa2014-10-02 13:43:39 -040092
93 // Proxy system properties must be initialized before setContentView is called because
94 // setContentView initializes the WebView logic which in turn reads the system properties.
95 setContentView(R.layout.activity_captive_portal_login);
96
97 getActionBar().setDisplayShowHomeEnabled(false);
98
Paul Jensen8df099d2014-09-26 15:19:17 -040099 // Exit app if Network disappears.
Paul Jensen25a217c2015-02-27 22:55:47 -0500100 final NetworkCapabilities networkCapabilities = mCm.getNetworkCapabilities(mNetwork);
Paul Jensen8df099d2014-09-26 15:19:17 -0400101 if (networkCapabilities == null) {
Paul Jensen6a776c832016-07-19 13:19:39 -0400102 finishAndRemoveTask();
Paul Jensen8df099d2014-09-26 15:19:17 -0400103 return;
104 }
105 mNetworkCallback = new NetworkCallback() {
106 @Override
107 public void onLost(Network lostNetwork) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500108 if (mNetwork.equals(lostNetwork)) done(Result.UNWANTED);
Paul Jensen8df099d2014-09-26 15:19:17 -0400109 }
110 };
111 final NetworkRequest.Builder builder = new NetworkRequest.Builder();
112 for (int transportType : networkCapabilities.getTransportTypes()) {
113 builder.addTransportType(transportType);
114 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500115 mCm.registerNetworkCallback(builder.build(), mNetworkCallback);
Paul Jensen869868be2014-05-15 10:33:05 -0400116
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400117 final WebView myWebView = (WebView) findViewById(R.id.webview);
118 myWebView.clearCache(true);
Paul Jensen869868be2014-05-15 10:33:05 -0400119 WebSettings webSettings = myWebView.getSettings();
120 webSettings.setJavaScriptEnabled(true);
Lorenzo Colitti62516632016-10-21 18:41:25 +0900121 webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
Paul Jensene836b682015-05-19 12:30:56 -0400122 mWebViewClient = new MyWebViewClient();
123 myWebView.setWebViewClient(mWebViewClient);
Paul Jensen869868be2014-05-15 10:33:05 -0400124 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400125 // Start initial page load so WebView finishes loading proxy settings.
126 // Actual load of mUrl is initiated by MyWebViewClient.
127 myWebView.loadData("", "text/html", null);
128 }
129
130 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
131 private void setWebViewProxy() {
132 LoadedApk loadedApk = getApplication().mLoadedApk;
133 try {
134 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
135 receiversField.setAccessible(true);
136 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
137 for (Object receiverMap : receivers.values()) {
138 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
139 Class clazz = rec.getClass();
140 if (clazz.getName().contains("ProxyChangeListener")) {
141 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
142 Intent.class);
143 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
144 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
145 Log.v(TAG, "Prompting WebView proxy reload.");
146 }
147 }
148 }
149 } catch (Exception e) {
150 Log.e(TAG, "Exception while setting WebView proxy: " + e);
151 }
Paul Jensen869868be2014-05-15 10:33:05 -0400152 }
153
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 private void done(Result result) {
Hugo Benichi87de0c22016-12-06 15:36:30 +0900155 if (DBG) {
156 Log.d(TAG, String.format("Result %s for %s", result.name(), mUrl.toString()));
157 }
Paul Jensen71b645f2014-10-13 14:13:07 -0400158 if (mNetworkCallback != null) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500159 mCm.unregisterNetworkCallback(mNetworkCallback);
Paul Jensen868f6242015-05-18 12:48:28 -0400160 mNetworkCallback = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400161 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500162 switch (result) {
163 case DISMISSED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400164 mCaptivePortal.reportCaptivePortalDismissed();
Paul Jensen25a217c2015-02-27 22:55:47 -0500165 break;
166 case UNWANTED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400167 mCaptivePortal.ignoreNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500168 break;
169 case WANTED_AS_IS:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 mCaptivePortal.useNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500171 break;
172 }
Paul Jensen6a776c832016-07-19 13:19:39 -0400173 finishAndRemoveTask();
Paul Jensen869868be2014-05-15 10:33:05 -0400174 }
175
176 @Override
177 public boolean onCreateOptionsMenu(Menu menu) {
178 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
179 return true;
180 }
181
182 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400183 public void onBackPressed() {
184 WebView myWebView = (WebView) findViewById(R.id.webview);
Paul Jensene836b682015-05-19 12:30:56 -0400185 if (myWebView.canGoBack() && mWebViewClient.allowBack()) {
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400186 myWebView.goBack();
187 } else {
188 super.onBackPressed();
189 }
190 }
191
192 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400193 public boolean onOptionsItemSelected(MenuItem item) {
Hugo Benichi87de0c22016-12-06 15:36:30 +0900194 final Result result;
195 final String action;
196 final int id = item.getItemId();
197 switch (id) {
198 case R.id.action_use_network:
199 result = Result.WANTED_AS_IS;
200 action = "USE_NETWORK";
201 break;
202 case R.id.action_do_not_use_network:
203 result = Result.UNWANTED;
204 action = "DO_NOT_USE_NETWORK";
205 break;
206 default:
207 return super.onOptionsItemSelected(item);
Paul Jensen869868be2014-05-15 10:33:05 -0400208 }
Hugo Benichi87de0c22016-12-06 15:36:30 +0900209 if (DBG) {
210 Log.d(TAG, String.format("onOptionsItemSelect %s for %s", action, mUrl.toString()));
Paul Jensen869868be2014-05-15 10:33:05 -0400211 }
Hugo Benichi87de0c22016-12-06 15:36:30 +0900212 done(result);
213 return true;
Paul Jensen869868be2014-05-15 10:33:05 -0400214 }
215
Paul Jensen868f6242015-05-18 12:48:28 -0400216 @Override
217 public void onDestroy() {
218 super.onDestroy();
Paul Jensen868f6242015-05-18 12:48:28 -0400219 if (mNetworkCallback != null) {
220 mCm.unregisterNetworkCallback(mNetworkCallback);
221 mNetworkCallback = null;
222 }
Paul Jensen65636fb2015-05-06 14:40:59 -0400223 if (mLaunchBrowser) {
224 // Give time for this network to become default. After 500ms just proceed.
225 for (int i = 0; i < 5; i++) {
226 // TODO: This misses when mNetwork underlies a VPN.
227 if (mNetwork.equals(mCm.getActiveNetwork())) break;
228 try {
229 Thread.sleep(100);
230 } catch (InterruptedException e) {
231 }
232 }
Hugo Benichi87de0c22016-12-06 15:36:30 +0900233 final String url = mUrl.toString();
234 if (DBG) {
235 Log.d(TAG, "starting activity with intent ACTION_VIEW for " + url);
236 }
237 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
Paul Jensen65636fb2015-05-06 14:40:59 -0400238 }
Paul Jensen868f6242015-05-18 12:48:28 -0400239 }
240
Hugo Benichi87de0c22016-12-06 15:36:30 +0900241 private URL getUrl() {
242 String url = getIntent().getStringExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL);
243 if (url == null) {
244 url = mCm.getCaptivePortalServerUrl();
245 }
246 try {
247 return new URL(url);
248 } catch (MalformedURLException e) {
249 Log.e(TAG, "Invalid captive portal URL " + url);
250 }
251 return null;
252 }
253
Paul Jensen869868be2014-05-15 10:33:05 -0400254 private void testForCaptivePortal() {
255 new Thread(new Runnable() {
256 public void run() {
257 // Give time for captive portal to open.
258 try {
259 Thread.sleep(1000);
260 } catch (InterruptedException e) {
261 }
262 HttpURLConnection urlConnection = null;
263 int httpResponseCode = 500;
264 try {
Hugo Benichi87de0c22016-12-06 15:36:30 +0900265 urlConnection = (HttpURLConnection) mUrl.openConnection();
Paul Jensen869868be2014-05-15 10:33:05 -0400266 urlConnection.setInstanceFollowRedirects(false);
267 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
268 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
269 urlConnection.setUseCaches(false);
270 urlConnection.getInputStream();
271 httpResponseCode = urlConnection.getResponseCode();
272 } catch (IOException e) {
273 } finally {
274 if (urlConnection != null) urlConnection.disconnect();
275 }
276 if (httpResponseCode == 204) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500277 done(Result.DISMISSED);
Paul Jensen869868be2014-05-15 10:33:05 -0400278 }
279 }
280 }).start();
281 }
282
283 private class MyWebViewClient extends WebViewClient {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400284 private static final String INTERNAL_ASSETS = "file:///android_asset/";
Paul Jensen65636fb2015-05-06 14:40:59 -0400285 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
286 // How many Android device-independent-pixels per scaled-pixel
287 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
288 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
289 getResources().getDisplayMetrics()) /
290 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
291 getResources().getDisplayMetrics());
Paul Jensene836b682015-05-19 12:30:56 -0400292 private int mPagesLoaded;
293
294 // If we haven't finished cleaning up the history, don't allow going back.
295 public boolean allowBack() {
296 return mPagesLoaded > 1;
297 }
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400298
Paul Jensen869868be2014-05-15 10:33:05 -0400299 @Override
300 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400301 if (url.contains(mBrowserBailOutToken)) {
302 mLaunchBrowser = true;
303 done(Result.WANTED_AS_IS);
304 return;
305 }
Paul Jensene836b682015-05-19 12:30:56 -0400306 // The first page load is used only to cause the WebView to
307 // fetch the proxy settings. Don't update the URL bar, and
308 // don't check if the captive portal is still there.
309 if (mPagesLoaded == 0) return;
310 // For internally generated pages, leave URL bar listing prior URL as this is the URL
311 // the page refers to.
312 if (!url.startsWith(INTERNAL_ASSETS)) {
313 final TextView myUrlBar = (TextView) findViewById(R.id.url_bar);
314 myUrlBar.setText(url);
315 }
Paul Jensen869868be2014-05-15 10:33:05 -0400316 testForCaptivePortal();
317 }
318
319 @Override
320 public void onPageFinished(WebView view, String url) {
Paul Jensene836b682015-05-19 12:30:56 -0400321 mPagesLoaded++;
322 if (mPagesLoaded == 1) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400323 // Now that WebView has loaded at least one page we know it has read in the proxy
324 // settings. Now prompt the WebView read the Network-specific proxy settings.
325 setWebViewProxy();
326 // Load the real page.
Hugo Benichi87de0c22016-12-06 15:36:30 +0900327 view.loadUrl(mUrl.toString());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400328 return;
Paul Jensene836b682015-05-19 12:30:56 -0400329 } else if (mPagesLoaded == 2) {
330 // Prevent going back to empty first page.
331 view.clearHistory();
Paul Jensen5344a4a2015-05-06 07:39:36 -0400332 }
Paul Jensen869868be2014-05-15 10:33:05 -0400333 testForCaptivePortal();
334 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500335
Paul Jensen65636fb2015-05-06 14:40:59 -0400336 // Convert Android device-independent-pixels (dp) to HTML size.
337 private String dp(int dp) {
338 // HTML px's are scaled just like dp's, so just add "px" suffix.
339 return Integer.toString(dp) + "px";
340 }
341
342 // Convert Android scaled-pixels (sp) to HTML size.
343 private String sp(int sp) {
344 // Convert sp to dp's.
345 float dp = sp * mDpPerSp;
346 // Apply a scale factor to make things look right.
347 dp *= 1.3;
348 // Convert dp's to HTML size.
349 return dp((int)dp);
350 }
351
Paul Jensenfc8022f2014-12-09 15:18:40 -0500352 // A web page consisting of a large broken lock icon to indicate SSL failure.
Paul Jensen65636fb2015-05-06 14:40:59 -0400353 private final String SSL_ERROR_HTML = "<html><head><style>" +
354 "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; " +
355 "margin-top:" + dp(96) + "; background-color:#fafafa; }" +
356 "img { width:" + dp(48) + "; height:" + dp(48) + "; }" +
357 "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; " +
358 " opacity:0.87; line-height:1.28; }" +
359 "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; " +
360 " opacity:0.54; line-height:1.21905; }" +
361 "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; " +
362 " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; " +
363 " height:" + dp(48) + "; font-weight:bold; }" +
364 "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>" +
365 "<div class=warn>%s</div>" +
366 "<div class=example>%s</div>" +
367 "<a href=%s>%s</a></body></html>";
Paul Jensenfc8022f2014-12-09 15:18:40 -0500368
369 @Override
370 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Paul Jensen41ff5242015-06-09 08:55:06 -0400371 Log.w(TAG, "SSL error (error: " + error.getPrimaryError() + " host: " +
372 // Only show host to avoid leaking private info.
373 Uri.parse(error.getUrl()).getHost() + " certificate: " +
374 error.getCertificate() + "); displaying SSL warning.");
Paul Jensen65636fb2015-05-06 14:40:59 -0400375 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
376 getString(R.string.ssl_error_example), mBrowserBailOutToken,
377 getString(R.string.ssl_error_continue));
378 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
Paul Jensenfc8022f2014-12-09 15:18:40 -0500379 }
Paul Jensenfd54da92015-06-09 07:50:51 -0400380
381 @Override
382 public boolean shouldOverrideUrlLoading (WebView view, String url) {
383 if (url.startsWith("tel:")) {
384 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
385 return true;
386 }
387 return false;
388 }
Paul Jensen869868be2014-05-15 10:33:05 -0400389 }
390
391 private class MyWebChromeClient extends WebChromeClient {
392 @Override
393 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400394 final ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
Paul Jensen8f333f12014-08-05 22:52:16 -0400395 myProgressBar.setProgress(newProgress);
Paul Jensen869868be2014-05-15 10:33:05 -0400396 }
397 }
398}