blob: a489f94ea698840c31424c53705c9e50ed92b5b2 [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";
Lorenzo Colitticd29cb62015-01-14 00:16:03 +090059 private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
Paul Jensen869868be2014-05-15 10:33:05 -040060 private static final int SOCKET_TIMEOUT_MS = 10000;
61
Paul Jensen25a217c2015-02-27 22:55:47 -050062 private enum Result { DISMISSED, UNWANTED, WANTED_AS_IS };
Paul Jensen869868be2014-05-15 10:33:05 -040063
64 private URL mURL;
Paul Jensen25a217c2015-02-27 22:55:47 -050065 private Network mNetwork;
Paul Jensen49e3edf2015-05-22 10:50:39 -040066 private CaptivePortal mCaptivePortal;
Paul Jensen8df099d2014-09-26 15:19:17 -040067 private NetworkCallback mNetworkCallback;
Paul Jensen25a217c2015-02-27 22:55:47 -050068 private ConnectivityManager mCm;
Paul Jensen65636fb2015-05-06 14:40:59 -040069 private boolean mLaunchBrowser = false;
Paul Jensene836b682015-05-19 12:30:56 -040070 private MyWebViewClient mWebViewClient;
Paul Jensen869868be2014-05-15 10:33:05 -040071
72 @Override
73 protected void onCreate(Bundle savedInstanceState) {
74 super.onCreate(savedInstanceState);
75
76 String server = Settings.Global.getString(getContentResolver(), "captive_portal_server");
77 if (server == null) server = DEFAULT_SERVER;
Paul Jensen25a217c2015-02-27 22:55:47 -050078 mCm = ConnectivityManager.from(this);
Paul Jensen869868be2014-05-15 10:33:05 -040079 try {
Paul Jensen71b645f2014-10-13 14:13:07 -040080 mURL = new URL("http", server, "/generate_204");
Paul Jensen25a217c2015-02-27 22:55:47 -050081 } catch (MalformedURLException e) {
Paul Jensen71b645f2014-10-13 14:13:07 -040082 // System misconfigured, bail out in a way that at least provides network access.
Paul Jensen25a217c2015-02-27 22:55:47 -050083 Log.e(TAG, "Invalid captive portal URL, server=" + server);
84 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -040085 }
Paul Jensen25a217c2015-02-27 22:55:47 -050086 mNetwork = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_NETWORK);
Paul Jensen49e3edf2015-05-22 10:50:39 -040087 mCaptivePortal = getIntent().getParcelableExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL);
Paul Jensen869868be2014-05-15 10:33:05 -040088
Paul Jensene0bef712014-12-10 15:12:18 -050089 // Also initializes proxy system properties.
Paul Jensen25a217c2015-02-27 22:55:47 -050090 mCm.bindProcessToNetwork(mNetwork);
Paul Jensen88eb0fa2014-10-02 13:43:39 -040091
92 // Proxy system properties must be initialized before setContentView is called because
93 // setContentView initializes the WebView logic which in turn reads the system properties.
94 setContentView(R.layout.activity_captive_portal_login);
95
96 getActionBar().setDisplayShowHomeEnabled(false);
97
Paul Jensen8df099d2014-09-26 15:19:17 -040098 // Exit app if Network disappears.
Paul Jensen25a217c2015-02-27 22:55:47 -050099 final NetworkCapabilities networkCapabilities = mCm.getNetworkCapabilities(mNetwork);
Paul Jensen8df099d2014-09-26 15:19:17 -0400100 if (networkCapabilities == null) {
101 finish();
102 return;
103 }
104 mNetworkCallback = new NetworkCallback() {
105 @Override
106 public void onLost(Network lostNetwork) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500107 if (mNetwork.equals(lostNetwork)) done(Result.UNWANTED);
Paul Jensen8df099d2014-09-26 15:19:17 -0400108 }
109 };
110 final NetworkRequest.Builder builder = new NetworkRequest.Builder();
111 for (int transportType : networkCapabilities.getTransportTypes()) {
112 builder.addTransportType(transportType);
113 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500114 mCm.registerNetworkCallback(builder.build(), mNetworkCallback);
Paul Jensen869868be2014-05-15 10:33:05 -0400115
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400116 final WebView myWebView = (WebView) findViewById(R.id.webview);
117 myWebView.clearCache(true);
Paul Jensen869868be2014-05-15 10:33:05 -0400118 WebSettings webSettings = myWebView.getSettings();
119 webSettings.setJavaScriptEnabled(true);
Paul Jensene836b682015-05-19 12:30:56 -0400120 mWebViewClient = new MyWebViewClient();
121 myWebView.setWebViewClient(mWebViewClient);
Paul Jensen869868be2014-05-15 10:33:05 -0400122 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400123 // Start initial page load so WebView finishes loading proxy settings.
124 // Actual load of mUrl is initiated by MyWebViewClient.
125 myWebView.loadData("", "text/html", null);
126 }
127
128 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
129 private void setWebViewProxy() {
130 LoadedApk loadedApk = getApplication().mLoadedApk;
131 try {
132 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
133 receiversField.setAccessible(true);
134 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
135 for (Object receiverMap : receivers.values()) {
136 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
137 Class clazz = rec.getClass();
138 if (clazz.getName().contains("ProxyChangeListener")) {
139 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
140 Intent.class);
141 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
142 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
143 Log.v(TAG, "Prompting WebView proxy reload.");
144 }
145 }
146 }
147 } catch (Exception e) {
148 Log.e(TAG, "Exception while setting WebView proxy: " + e);
149 }
Paul Jensen869868be2014-05-15 10:33:05 -0400150 }
151
Paul Jensen25a217c2015-02-27 22:55:47 -0500152 private void done(Result result) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400153 if (mNetworkCallback != null) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 mCm.unregisterNetworkCallback(mNetworkCallback);
Paul Jensen868f6242015-05-18 12:48:28 -0400155 mNetworkCallback = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400156 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500157 switch (result) {
158 case DISMISSED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400159 mCaptivePortal.reportCaptivePortalDismissed();
Paul Jensen25a217c2015-02-27 22:55:47 -0500160 break;
161 case UNWANTED:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400162 mCaptivePortal.ignoreNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500163 break;
164 case WANTED_AS_IS:
Paul Jensen49e3edf2015-05-22 10:50:39 -0400165 mCaptivePortal.useNetwork();
Paul Jensen25a217c2015-02-27 22:55:47 -0500166 break;
167 }
Paul Jensen869868be2014-05-15 10:33:05 -0400168 finish();
169 }
170
171 @Override
172 public boolean onCreateOptionsMenu(Menu menu) {
173 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
174 return true;
175 }
176
177 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400178 public void onBackPressed() {
179 WebView myWebView = (WebView) findViewById(R.id.webview);
Paul Jensene836b682015-05-19 12:30:56 -0400180 if (myWebView.canGoBack() && mWebViewClient.allowBack()) {
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400181 myWebView.goBack();
182 } else {
183 super.onBackPressed();
184 }
185 }
186
187 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400188 public boolean onOptionsItemSelected(MenuItem item) {
189 int id = item.getItemId();
190 if (id == R.id.action_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500191 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -0400192 return true;
193 }
194 if (id == R.id.action_do_not_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500195 done(Result.UNWANTED);
Paul Jensen869868be2014-05-15 10:33:05 -0400196 return true;
197 }
198 return super.onOptionsItemSelected(item);
199 }
200
Paul Jensen868f6242015-05-18 12:48:28 -0400201 @Override
202 public void onDestroy() {
203 super.onDestroy();
204
205 if (mNetworkCallback != null) {
206 mCm.unregisterNetworkCallback(mNetworkCallback);
207 mNetworkCallback = null;
208 }
Paul Jensen65636fb2015-05-06 14:40:59 -0400209 if (mLaunchBrowser) {
210 // Give time for this network to become default. After 500ms just proceed.
211 for (int i = 0; i < 5; i++) {
212 // TODO: This misses when mNetwork underlies a VPN.
213 if (mNetwork.equals(mCm.getActiveNetwork())) break;
214 try {
215 Thread.sleep(100);
216 } catch (InterruptedException e) {
217 }
218 }
219 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mURL.toString())));
220 }
Paul Jensen868f6242015-05-18 12:48:28 -0400221 }
222
Paul Jensen869868be2014-05-15 10:33:05 -0400223 private void testForCaptivePortal() {
224 new Thread(new Runnable() {
225 public void run() {
226 // Give time for captive portal to open.
227 try {
228 Thread.sleep(1000);
229 } catch (InterruptedException e) {
230 }
231 HttpURLConnection urlConnection = null;
232 int httpResponseCode = 500;
233 try {
234 urlConnection = (HttpURLConnection) mURL.openConnection();
235 urlConnection.setInstanceFollowRedirects(false);
236 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
237 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
238 urlConnection.setUseCaches(false);
239 urlConnection.getInputStream();
240 httpResponseCode = urlConnection.getResponseCode();
241 } catch (IOException e) {
242 } finally {
243 if (urlConnection != null) urlConnection.disconnect();
244 }
245 if (httpResponseCode == 204) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500246 done(Result.DISMISSED);
Paul Jensen869868be2014-05-15 10:33:05 -0400247 }
248 }
249 }).start();
250 }
251
252 private class MyWebViewClient extends WebViewClient {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400253 private static final String INTERNAL_ASSETS = "file:///android_asset/";
Paul Jensen65636fb2015-05-06 14:40:59 -0400254 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
255 // How many Android device-independent-pixels per scaled-pixel
256 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
257 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
258 getResources().getDisplayMetrics()) /
259 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
260 getResources().getDisplayMetrics());
Paul Jensene836b682015-05-19 12:30:56 -0400261 private int mPagesLoaded;
262
263 // If we haven't finished cleaning up the history, don't allow going back.
264 public boolean allowBack() {
265 return mPagesLoaded > 1;
266 }
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400267
Paul Jensen869868be2014-05-15 10:33:05 -0400268 @Override
269 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400270 if (url.contains(mBrowserBailOutToken)) {
271 mLaunchBrowser = true;
272 done(Result.WANTED_AS_IS);
273 return;
274 }
Paul Jensene836b682015-05-19 12:30:56 -0400275 // The first page load is used only to cause the WebView to
276 // fetch the proxy settings. Don't update the URL bar, and
277 // don't check if the captive portal is still there.
278 if (mPagesLoaded == 0) return;
279 // For internally generated pages, leave URL bar listing prior URL as this is the URL
280 // the page refers to.
281 if (!url.startsWith(INTERNAL_ASSETS)) {
282 final TextView myUrlBar = (TextView) findViewById(R.id.url_bar);
283 myUrlBar.setText(url);
284 }
Paul Jensen869868be2014-05-15 10:33:05 -0400285 testForCaptivePortal();
286 }
287
288 @Override
289 public void onPageFinished(WebView view, String url) {
Paul Jensene836b682015-05-19 12:30:56 -0400290 mPagesLoaded++;
291 if (mPagesLoaded == 1) {
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400292 // Now that WebView has loaded at least one page we know it has read in the proxy
293 // settings. Now prompt the WebView read the Network-specific proxy settings.
294 setWebViewProxy();
295 // Load the real page.
296 view.loadUrl(mURL.toString());
297 return;
Paul Jensene836b682015-05-19 12:30:56 -0400298 } else if (mPagesLoaded == 2) {
299 // Prevent going back to empty first page.
300 view.clearHistory();
Paul Jensen5344a4a2015-05-06 07:39:36 -0400301 }
Paul Jensen869868be2014-05-15 10:33:05 -0400302 testForCaptivePortal();
303 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500304
Paul Jensen65636fb2015-05-06 14:40:59 -0400305 // Convert Android device-independent-pixels (dp) to HTML size.
306 private String dp(int dp) {
307 // HTML px's are scaled just like dp's, so just add "px" suffix.
308 return Integer.toString(dp) + "px";
309 }
310
311 // Convert Android scaled-pixels (sp) to HTML size.
312 private String sp(int sp) {
313 // Convert sp to dp's.
314 float dp = sp * mDpPerSp;
315 // Apply a scale factor to make things look right.
316 dp *= 1.3;
317 // Convert dp's to HTML size.
318 return dp((int)dp);
319 }
320
Paul Jensenfc8022f2014-12-09 15:18:40 -0500321 // A web page consisting of a large broken lock icon to indicate SSL failure.
Paul Jensen65636fb2015-05-06 14:40:59 -0400322 private final String SSL_ERROR_HTML = "<html><head><style>" +
323 "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; " +
324 "margin-top:" + dp(96) + "; background-color:#fafafa; }" +
325 "img { width:" + dp(48) + "; height:" + dp(48) + "; }" +
326 "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; " +
327 " opacity:0.87; line-height:1.28; }" +
328 "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; " +
329 " opacity:0.54; line-height:1.21905; }" +
330 "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; " +
331 " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; " +
332 " height:" + dp(48) + "; font-weight:bold; }" +
333 "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>" +
334 "<div class=warn>%s</div>" +
335 "<div class=example>%s</div>" +
336 "<a href=%s>%s</a></body></html>";
Paul Jensenfc8022f2014-12-09 15:18:40 -0500337
338 @Override
339 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Paul Jensen41ff5242015-06-09 08:55:06 -0400340 Log.w(TAG, "SSL error (error: " + error.getPrimaryError() + " host: " +
341 // Only show host to avoid leaking private info.
342 Uri.parse(error.getUrl()).getHost() + " certificate: " +
343 error.getCertificate() + "); displaying SSL warning.");
Paul Jensen65636fb2015-05-06 14:40:59 -0400344 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
345 getString(R.string.ssl_error_example), mBrowserBailOutToken,
346 getString(R.string.ssl_error_continue));
347 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
Paul Jensenfc8022f2014-12-09 15:18:40 -0500348 }
Paul Jensenfd54da92015-06-09 07:50:51 -0400349
350 @Override
351 public boolean shouldOverrideUrlLoading (WebView view, String url) {
352 if (url.startsWith("tel:")) {
353 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
354 return true;
355 }
356 return false;
357 }
Paul Jensen869868be2014-05-15 10:33:05 -0400358 }
359
360 private class MyWebChromeClient extends WebChromeClient {
361 @Override
362 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400363 final ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
Paul Jensen8f333f12014-08-05 22:52:16 -0400364 myProgressBar.setProgress(newProgress);
Paul Jensen869868be2014-05-15 10:33:05 -0400365 }
366 }
367}