blob: 4c907a31dd601232c426beb025d5a54511c6e6b8 [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 Jensen869868be2014-05-15 10:33:05 -040026import android.net.Network;
Paul Jensen8df099d2014-09-26 15:19:17 -040027import android.net.NetworkCapabilities;
28import android.net.NetworkRequest;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040029import android.net.Proxy;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040030import android.net.Uri;
Paul Jensenfc8022f2014-12-09 15:18:40 -050031import android.net.http.SslError;
Paul Jensen869868be2014-05-15 10:33:05 -040032import android.os.Bundle;
33import android.provider.Settings;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040034import android.util.ArrayMap;
35import android.util.Log;
Paul Jensen65636fb2015-05-06 14:40:59 -040036import android.util.TypedValue;
Paul Jensen869868be2014-05-15 10:33:05 -040037import android.view.Menu;
38import android.view.MenuItem;
Paul Jensenfc8022f2014-12-09 15:18:40 -050039import android.webkit.SslErrorHandler;
Paul Jensen869868be2014-05-15 10:33:05 -040040import android.webkit.WebChromeClient;
41import android.webkit.WebSettings;
42import android.webkit.WebView;
43import android.webkit.WebViewClient;
Paul Jensen8f333f12014-08-05 22:52:16 -040044import android.widget.ProgressBar;
Paul Jensen5344a4a2015-05-06 07:39:36 -040045import android.widget.TextView;
Paul Jensen869868be2014-05-15 10:33:05 -040046
47import java.io.IOException;
48import java.net.HttpURLConnection;
49import java.net.MalformedURLException;
50import java.net.URL;
51import java.lang.InterruptedException;
Paul Jensen88eb0fa2014-10-02 13:43:39 -040052import java.lang.reflect.Field;
53import java.lang.reflect.Method;
Paul Jensen65636fb2015-05-06 14:40:59 -040054import java.util.Random;
Paul Jensen869868be2014-05-15 10:33:05 -040055
56public class CaptivePortalLoginActivity extends Activity {
Paul Jensen88eb0fa2014-10-02 13:43:39 -040057 private static final String TAG = "CaptivePortalLogin";
Lorenzo Colitticd29cb62015-01-14 00:16:03 +090058 private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
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 Jensen71b645f2014-10-13 14:13:07 -040065 private String mResponseToken;
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 Jensen869868be2014-05-15 10:33:05 -040069
70 @Override
71 protected void onCreate(Bundle savedInstanceState) {
72 super.onCreate(savedInstanceState);
73
74 String server = Settings.Global.getString(getContentResolver(), "captive_portal_server");
75 if (server == null) server = DEFAULT_SERVER;
Paul Jensen25a217c2015-02-27 22:55:47 -050076 mCm = ConnectivityManager.from(this);
Paul Jensen869868be2014-05-15 10:33:05 -040077 try {
Paul Jensen71b645f2014-10-13 14:13:07 -040078 mURL = new URL("http", server, "/generate_204");
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.
Paul Jensen25a217c2015-02-27 22:55:47 -050081 Log.e(TAG, "Invalid captive portal URL, server=" + server);
82 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);
85 mResponseToken = getIntent().getStringExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_TOKEN);
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) {
99 finish();
100 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);
118 myWebView.setWebViewClient(new MyWebViewClient());
119 myWebView.setWebChromeClient(new MyWebChromeClient());
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400120 // Start initial page load so WebView finishes loading proxy settings.
121 // Actual load of mUrl is initiated by MyWebViewClient.
122 myWebView.loadData("", "text/html", null);
123 }
124
125 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
126 private void setWebViewProxy() {
127 LoadedApk loadedApk = getApplication().mLoadedApk;
128 try {
129 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
130 receiversField.setAccessible(true);
131 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
132 for (Object receiverMap : receivers.values()) {
133 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
134 Class clazz = rec.getClass();
135 if (clazz.getName().contains("ProxyChangeListener")) {
136 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
137 Intent.class);
138 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
139 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
140 Log.v(TAG, "Prompting WebView proxy reload.");
141 }
142 }
143 }
144 } catch (Exception e) {
145 Log.e(TAG, "Exception while setting WebView proxy: " + e);
146 }
Paul Jensen869868be2014-05-15 10:33:05 -0400147 }
148
Paul Jensen25a217c2015-02-27 22:55:47 -0500149 private void done(Result result) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400150 if (mNetworkCallback != null) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500151 mCm.unregisterNetworkCallback(mNetworkCallback);
Paul Jensen868f6242015-05-18 12:48:28 -0400152 mNetworkCallback = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400153 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500154 switch (result) {
155 case DISMISSED:
156 mCm.reportCaptivePortalDismissed(mNetwork, mResponseToken);
157 break;
158 case UNWANTED:
159 mCm.ignoreNetworkWithCaptivePortal(mNetwork, mResponseToken);
160 break;
161 case WANTED_AS_IS:
162 mCm.useNetworkWithCaptivePortal(mNetwork, mResponseToken);
163 break;
164 }
Paul Jensen869868be2014-05-15 10:33:05 -0400165 finish();
166 }
167
168 @Override
169 public boolean onCreateOptionsMenu(Menu menu) {
170 getMenuInflater().inflate(R.menu.captive_portal_login, menu);
171 return true;
172 }
173
174 @Override
Paul Jensenb6ea9ee2014-07-18 12:27:23 -0400175 public void onBackPressed() {
176 WebView myWebView = (WebView) findViewById(R.id.webview);
177 if (myWebView.canGoBack()) {
178 myWebView.goBack();
179 } else {
180 super.onBackPressed();
181 }
182 }
183
184 @Override
Paul Jensen869868be2014-05-15 10:33:05 -0400185 public boolean onOptionsItemSelected(MenuItem item) {
186 int id = item.getItemId();
187 if (id == R.id.action_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500188 done(Result.WANTED_AS_IS);
Paul Jensen869868be2014-05-15 10:33:05 -0400189 return true;
190 }
191 if (id == R.id.action_do_not_use_network) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500192 done(Result.UNWANTED);
Paul Jensen869868be2014-05-15 10:33:05 -0400193 return true;
194 }
195 return super.onOptionsItemSelected(item);
196 }
197
Paul Jensen868f6242015-05-18 12:48:28 -0400198 @Override
199 public void onDestroy() {
200 super.onDestroy();
201
202 if (mNetworkCallback != null) {
203 mCm.unregisterNetworkCallback(mNetworkCallback);
204 mNetworkCallback = null;
205 }
Paul Jensen65636fb2015-05-06 14:40:59 -0400206 if (mLaunchBrowser) {
207 // Give time for this network to become default. After 500ms just proceed.
208 for (int i = 0; i < 5; i++) {
209 // TODO: This misses when mNetwork underlies a VPN.
210 if (mNetwork.equals(mCm.getActiveNetwork())) break;
211 try {
212 Thread.sleep(100);
213 } catch (InterruptedException e) {
214 }
215 }
216 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mURL.toString())));
217 }
Paul Jensen868f6242015-05-18 12:48:28 -0400218 }
219
Paul Jensen869868be2014-05-15 10:33:05 -0400220 private void testForCaptivePortal() {
221 new Thread(new Runnable() {
222 public void run() {
223 // Give time for captive portal to open.
224 try {
225 Thread.sleep(1000);
226 } catch (InterruptedException e) {
227 }
228 HttpURLConnection urlConnection = null;
229 int httpResponseCode = 500;
230 try {
231 urlConnection = (HttpURLConnection) mURL.openConnection();
232 urlConnection.setInstanceFollowRedirects(false);
233 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
234 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
235 urlConnection.setUseCaches(false);
236 urlConnection.getInputStream();
237 httpResponseCode = urlConnection.getResponseCode();
238 } catch (IOException e) {
239 } finally {
240 if (urlConnection != null) urlConnection.disconnect();
241 }
242 if (httpResponseCode == 204) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500243 done(Result.DISMISSED);
Paul Jensen869868be2014-05-15 10:33:05 -0400244 }
245 }
246 }).start();
247 }
248
249 private class MyWebViewClient extends WebViewClient {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400250 private static final String INTERNAL_ASSETS = "file:///android_asset/";
Paul Jensen65636fb2015-05-06 14:40:59 -0400251 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
252 // How many Android device-independent-pixels per scaled-pixel
253 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
254 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
255 getResources().getDisplayMetrics()) /
256 TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
257 getResources().getDisplayMetrics());
258 private boolean mFirstPageLoad = true;
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400259
Paul Jensen869868be2014-05-15 10:33:05 -0400260 @Override
261 public void onPageStarted(WebView view, String url, Bitmap favicon) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400262 if (url.contains(mBrowserBailOutToken)) {
263 mLaunchBrowser = true;
264 done(Result.WANTED_AS_IS);
265 return;
266 }
267 if (mFirstPageLoad) return;
Paul Jensen869868be2014-05-15 10:33:05 -0400268 testForCaptivePortal();
269 }
270
271 @Override
272 public void onPageFinished(WebView view, String url) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400273 if (mFirstPageLoad) {
274 mFirstPageLoad = false;
Paul Jensen88eb0fa2014-10-02 13:43:39 -0400275 // Now that WebView has loaded at least one page we know it has read in the proxy
276 // settings. Now prompt the WebView read the Network-specific proxy settings.
277 setWebViewProxy();
278 // Load the real page.
279 view.loadUrl(mURL.toString());
280 return;
281 }
Paul Jensen5344a4a2015-05-06 07:39:36 -0400282 // For internally generated pages, leave URL bar listing prior URL as this is the URL
283 // the page refers to.
284 if (!url.startsWith(INTERNAL_ASSETS)) {
285 final TextView myUrlBar = (TextView) findViewById(R.id.url_bar);
286 myUrlBar.setText(url);
287 }
Paul Jensen869868be2014-05-15 10:33:05 -0400288 testForCaptivePortal();
289 }
Paul Jensenfc8022f2014-12-09 15:18:40 -0500290
Paul Jensen65636fb2015-05-06 14:40:59 -0400291 // Convert Android device-independent-pixels (dp) to HTML size.
292 private String dp(int dp) {
293 // HTML px's are scaled just like dp's, so just add "px" suffix.
294 return Integer.toString(dp) + "px";
295 }
296
297 // Convert Android scaled-pixels (sp) to HTML size.
298 private String sp(int sp) {
299 // Convert sp to dp's.
300 float dp = sp * mDpPerSp;
301 // Apply a scale factor to make things look right.
302 dp *= 1.3;
303 // Convert dp's to HTML size.
304 return dp((int)dp);
305 }
306
Paul Jensenfc8022f2014-12-09 15:18:40 -0500307 // A web page consisting of a large broken lock icon to indicate SSL failure.
Paul Jensen65636fb2015-05-06 14:40:59 -0400308 private final String SSL_ERROR_HTML = "<html><head><style>" +
309 "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; " +
310 "margin-top:" + dp(96) + "; background-color:#fafafa; }" +
311 "img { width:" + dp(48) + "; height:" + dp(48) + "; }" +
312 "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; " +
313 " opacity:0.87; line-height:1.28; }" +
314 "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; " +
315 " opacity:0.54; line-height:1.21905; }" +
316 "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; " +
317 " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; " +
318 " height:" + dp(48) + "; font-weight:bold; }" +
319 "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>" +
320 "<div class=warn>%s</div>" +
321 "<div class=example>%s</div>" +
322 "<a href=%s>%s</a></body></html>";
Paul Jensenfc8022f2014-12-09 15:18:40 -0500323
324 @Override
325 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Paul Jensen65636fb2015-05-06 14:40:59 -0400326 Log.w(TAG, "SSL error; displaying SSL warning.");
327 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
328 getString(R.string.ssl_error_example), mBrowserBailOutToken,
329 getString(R.string.ssl_error_continue));
330 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
Paul Jensenfc8022f2014-12-09 15:18:40 -0500331 }
Paul Jensen869868be2014-05-15 10:33:05 -0400332 }
333
334 private class MyWebChromeClient extends WebChromeClient {
335 @Override
336 public void onProgressChanged(WebView view, int newProgress) {
Paul Jensen5344a4a2015-05-06 07:39:36 -0400337 final ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
Paul Jensen8f333f12014-08-05 22:52:16 -0400338 myProgressBar.setProgress(newProgress);
Paul Jensen869868be2014-05-15 10:33:05 -0400339 }
340 }
341}