blob: bb8eb2cd0797714210ec08eb51666b778155404c [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);
Lorenzo Colitti62516632016-10-21 18:41:25 +0900118 webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
Paul Jensene836b682015-05-19 12:30:56 -0400119 mWebViewClient = new MyWebViewClient();
120 myWebView.setWebViewClient(mWebViewClient);
Paul Jensen869868be2014-05-15 10:33:05 -0400121 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400122 // Start initial page load so WebView finishes loading proxy settings.
123 // Actual load of mUrl is initiated by MyWebViewClient.
124 myWebView.loadData("", "text/html", null);
125 }
126
127 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
128 private void setWebViewProxy() {
129 LoadedApk loadedApk = getApplication().mLoadedApk;
130 try {
131 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
132 receiversField.setAccessible(true);
133 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
134 for (Object receiverMap : receivers.values()) {
135 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
136 Class clazz = rec.getClass();
137 if (clazz.getName().contains("ProxyChangeListener")) {
138 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
139 Intent.class);
140 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
141 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
142 Log.v(TAG, "Prompting WebView proxy reload.");
143 }
144 }
145 }
146 } catch (Exception e) {
147 Log.e(TAG, "Exception while setting WebView proxy: " + e);
148 }
Paul Jensen869868be2014-05-15 10:33:05 -0400149 }
150
Paul Jensen25a217c2015-02-27 22:55:47 -0500151 private void done(Result result) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400152 if (mNetworkCallback != null) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500153 mCm.unregisterNetworkCallback(mNetworkCallback);
Paul Jensen868f6242015-05-18 12:48:28 -0400154 mNetworkCallback = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400155 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500156 switch (result) {
157 case DISMISSED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400158 mCaptivePortal.reportCaptivePortalDismissed();
Paul Jensen25a217c2015-02-27 22:55:47 -0500159 break;
160 case UNWANTED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400161 mCaptivePortal.ignoreNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500162 break;
163 case WANTED_AS_IS:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400164 mCaptivePortal.useNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500165 break;
166 }
Paul Jensen6a776c832016-07-19 13:19:39 -0400167 finishAndRemoveTask();
Paul Jensen869868be2014-05-15 10:33:05 -0400168 }
169
170 @Override
171 public boolean onCreateOptionsMenu(Menu menu) {
172 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
173 return true;
174 }
175
176 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400177 public void onBackPressed() {
178 WebView myWebView = (WebView) findViewById(R.id.webview);
Paul Jensene836b682015-05-19 12:30:56 -0400179 if (myWebView.canGoBack() && mWebViewClient.allowBack()) {
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400180 myWebView.goBack();
181 } else {
182 super.onBackPressed();
183 }
184 }
185
186 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400187 public boolean onOptionsItemSelected(MenuItem item) {
188 int id = item.getItemId();
189 if (id == R.id.action_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500190 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -0400191 return true;
192 }
193 if (id == R.id.action_do_not_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500194 done(Result.UNWANTED);
Paul Jensen869868be2014-05-15 10:33:05 -0400195 return true;
196 }
197 return super.onOptionsItemSelected(item);
198 }
199
Paul Jensen868f6242015-05-18 12:48:28 -0400200 @Override
201 public void onDestroy() {
202 super.onDestroy();
203
204 if (mNetworkCallback != null) {
205 mCm.unregisterNetworkCallback(mNetworkCallback);
206 mNetworkCallback = null;
207 }
Paul Jensen65636fb2015-05-06 14:40:59 -0400208 if (mLaunchBrowser) {
209 // Give time for this network to become default. After 500ms just proceed.
210 for (int i = 0; i < 5; i++) {
211 // TODO: This misses when mNetwork underlies a VPN.
212 if (mNetwork.equals(mCm.getActiveNetwork())) break;
213 try {
214 Thread.sleep(100);
215 } catch (InterruptedException e) {
216 }
217 }
218 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mURL.toString())));
219 }
Paul Jensen868f6242015-05-18 12:48:28 -0400220 }
221
Paul Jensen869868be2014-05-15 10:33:05 -0400222 private void testForCaptivePortal() {
223 new Thread(new Runnable() {
224 public void run() {
225 // Give time for captive portal to open.
226 try {
227 Thread.sleep(1000);
228 } catch (InterruptedException e) {
229 }
230 HttpURLConnection urlConnection = null;
231 int httpResponseCode = 500;
232 try {
233 urlConnection = (HttpURLConnection) mURL.openConnection();
234 urlConnection.setInstanceFollowRedirects(false);
235 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
236 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
237 urlConnection.setUseCaches(false);
238 urlConnection.getInputStream();
239 httpResponseCode = urlConnection.getResponseCode();
240 } catch (IOException e) {
241 } finally {
242 if (urlConnection != null) urlConnection.disconnect();
243 }
244 if (httpResponseCode == 204) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500245 done(Result.DISMISSED);
Paul Jensen869868be2014-05-15 10:33:05 -0400246 }
247 }
248 }).start();
249 }
250
251 private class MyWebViewClient extends WebViewClient {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400252 private static final String INTERNAL_ASSETS = "file:///android_asset/";
Paul Jensen65636fb2015-05-06 14:40:59 -0400253 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
254 // How many Android device-independent-pixels per scaled-pixel
255 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
256 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
257 getResources().getDisplayMetrics()) /
258 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
259 getResources().getDisplayMetrics());
Paul Jensene836b682015-05-19 12:30:56 -0400260 private int mPagesLoaded;
261
262 // If we haven't finished cleaning up the history, don't allow going back.
263 public boolean allowBack() {
264 return mPagesLoaded > 1;
265 }
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400266
Paul Jensen869868be2014-05-15 10:33:05 -0400267 @Override
268 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400269 if (url.contains(mBrowserBailOutToken)) {
270 mLaunchBrowser = true;
271 done(Result.WANTED_AS_IS);
272 return;
273 }
Paul Jensene836b682015-05-19 12:30:56 -0400274 // The first page load is used only to cause the WebView to
275 // fetch the proxy settings. Don't update the URL bar, and
276 // don't check if the captive portal is still there.
277 if (mPagesLoaded == 0) return;
278 // For internally generated pages, leave URL bar listing prior URL as this is the URL
279 // the page refers to.
280 if (!url.startsWith(INTERNAL_ASSETS)) {
281 final TextView myUrlBar = (TextView) findViewById(R.id.url_bar);
282 myUrlBar.setText(url);
283 }
Paul Jensen869868be2014-05-15 10:33:05 -0400284 testForCaptivePortal();
285 }
286
287 @Override
288 public void onPageFinished(WebView view, String url) {
Paul Jensene836b682015-05-19 12:30:56 -0400289 mPagesLoaded++;
290 if (mPagesLoaded == 1) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400291 // Now that WebView has loaded at least one page we know it has read in the proxy
292 // settings. Now prompt the WebView read the Network-specific proxy settings.
293 setWebViewProxy();
294 // Load the real page.
295 view.loadUrl(mURL.toString());
296 return;
Paul Jensene836b682015-05-19 12:30:56 -0400297 } else if (mPagesLoaded == 2) {
298 // Prevent going back to empty first page.
299 view.clearHistory();
Paul Jensen5344a4a2015-05-06 07:39:36 -0400300 }
Paul Jensen869868be2014-05-15 10:33:05 -0400301 testForCaptivePortal();
302 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500303
Paul Jensen65636fb2015-05-06 14:40:59 -0400304 // Convert Android device-independent-pixels (dp) to HTML size.
305 private String dp(int dp) {
306 // HTML px's are scaled just like dp's, so just add "px" suffix.
307 return Integer.toString(dp) + "px";
308 }
309
310 // Convert Android scaled-pixels (sp) to HTML size.
311 private String sp(int sp) {
312 // Convert sp to dp's.
313 float dp = sp * mDpPerSp;
314 // Apply a scale factor to make things look right.
315 dp *= 1.3;
316 // Convert dp's to HTML size.
317 return dp((int)dp);
318 }
319
Paul Jensenfc8022f2014-12-09 15:18:40 -0500320 // A web page consisting of a large broken lock icon to indicate SSL failure.
Paul Jensen65636fb2015-05-06 14:40:59 -0400321 private final String SSL_ERROR_HTML = "<html><head><style>" +
322 "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; " +
323 "margin-top:" + dp(96) + "; background-color:#fafafa; }" +
324 "img { width:" + dp(48) + "; height:" + dp(48) + "; }" +
325 "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; " +
326 " opacity:0.87; line-height:1.28; }" +
327 "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; " +
328 " opacity:0.54; line-height:1.21905; }" +
329 "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; " +
330 " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; " +
331 " height:" + dp(48) + "; font-weight:bold; }" +
332 "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>" +
333 "<div class=warn>%s</div>" +
334 "<div class=example>%s</div>" +
335 "<a href=%s>%s</a></body></html>";
Paul Jensenfc8022f2014-12-09 15:18:40 -0500336
337 @Override
338 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Paul Jensen41ff5242015-06-09 08:55:06 -0400339 Log.w(TAG, "SSL error (error: " + error.getPrimaryError() + " host: " +
340 // Only show host to avoid leaking private info.
341 Uri.parse(error.getUrl()).getHost() + " certificate: " +
342 error.getCertificate() + "); displaying SSL warning.");
Paul Jensen65636fb2015-05-06 14:40:59 -0400343 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
344 getString(R.string.ssl_error_example), mBrowserBailOutToken,
345 getString(R.string.ssl_error_continue));
346 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
Paul Jensenfc8022f2014-12-09 15:18:40 -0500347 }
Paul Jensenfd54da92015-06-09 07:50:51 -0400348
349 @Override
350 public boolean shouldOverrideUrlLoading (WebView view, String url) {
351 if (url.startsWith("tel:")) {
352 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
353 return true;
354 }
355 return false;
356 }
Paul Jensen869868be2014-05-15 10:33:05 -0400357 }
358
359 private class MyWebChromeClient extends WebChromeClient {
360 @Override
361 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400362 final ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
Paul Jensen8f333f12014-08-05 22:52:16 -0400363 myProgressBar.setProgress(newProgress);
Paul Jensen869868be2014-05-15 10:33:05 -0400364 }
365 }
366}