blob: 8553bcf8100a04186daeb2b44ef8abe8798c8a52 [file] [log] [blame]
fionaxuda578042017-03-10 10:16:09 -08001/*
2 * Copyright (C) 2017 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.carrierdefaultapp;
18
19import android.app.Activity;
20import android.app.LoadedApk;
21import android.content.Context;
22import android.content.Intent;
fionaxud60a9d02017-05-23 14:55:27 -070023import android.content.pm.ActivityInfo;
24import android.content.pm.PackageInfo;
25import android.content.pm.PackageManager;
fionaxuda578042017-03-10 10:16:09 -080026import android.graphics.Bitmap;
27import android.net.ConnectivityManager;
28import android.net.ConnectivityManager.NetworkCallback;
29import android.net.Network;
30import android.net.NetworkCapabilities;
31import android.net.NetworkRequest;
32import android.net.Proxy;
33import android.net.TrafficStats;
34import android.net.Uri;
35import android.net.http.SslError;
36import android.os.Bundle;
37import android.telephony.CarrierConfigManager;
38import android.telephony.Rlog;
39import android.telephony.SubscriptionManager;
fionaxud60a9d02017-05-23 14:55:27 -070040import android.text.TextUtils;
fionaxuda578042017-03-10 10:16:09 -080041import android.util.ArrayMap;
42import android.util.Log;
43import android.util.TypedValue;
44import android.webkit.SslErrorHandler;
45import android.webkit.WebChromeClient;
46import android.webkit.WebSettings;
47import android.webkit.WebView;
48import android.webkit.WebViewClient;
49import android.widget.ProgressBar;
50import android.widget.TextView;
51
52import com.android.internal.telephony.PhoneConstants;
53import com.android.internal.telephony.TelephonyIntents;
54import com.android.internal.util.ArrayUtils;
55
56import java.io.IOException;
57import java.lang.reflect.Field;
58import java.lang.reflect.Method;
59import java.net.HttpURLConnection;
60import java.net.MalformedURLException;
61import java.net.URL;
62import java.util.Random;
63
64/**
65 * Activity that launches in response to the captive portal notification
66 * @see com.android.carrierdefaultapp.CarrierActionUtils#CARRIER_ACTION_SHOW_PORTAL_NOTIFICATION
67 * This activity requests network connection if there is no available one before loading the real
68 * portal page and apply carrier actions on the portal activation result.
69 */
70public class CaptivePortalLoginActivity extends Activity {
71 private static final String TAG = CaptivePortalLoginActivity.class.getSimpleName();
72 private static final boolean DBG = true;
73
74 private static final int SOCKET_TIMEOUT_MS = 10 * 1000;
fionaxud60a9d02017-05-23 14:55:27 -070075 private static final int NETWORK_REQUEST_TIMEOUT_MS = 5 * 1000;
fionaxuda578042017-03-10 10:16:09 -080076
77 private URL mUrl;
78 private Network mNetwork;
79 private NetworkCallback mNetworkCallback;
80 private ConnectivityManager mCm;
81 private WebView mWebView;
82 private MyWebViewClient mWebViewClient;
83 private boolean mLaunchBrowser = false;
fionaxuf62e4cc2017-07-21 18:02:30 -070084 private Thread mTestingThread = null;
fionaxuda578042017-03-10 10:16:09 -080085
86 @Override
87 protected void onCreate(Bundle savedInstanceState) {
88 super.onCreate(savedInstanceState);
89 mCm = ConnectivityManager.from(this);
90 mUrl = getUrlForCaptivePortal();
91 if (mUrl == null) {
92 done(false);
93 return;
94 }
95 if (DBG) logd(String.format("onCreate for %s", mUrl.toString()));
96 setContentView(R.layout.activity_captive_portal_login);
97 getActionBar().setDisplayShowHomeEnabled(false);
98
Alan Viverette51efddb2017-04-05 10:00:01 -040099 mWebView = findViewById(R.id.webview);
fionaxuda578042017-03-10 10:16:09 -0800100 mWebView.clearCache(true);
101 WebSettings webSettings = mWebView.getSettings();
102 webSettings.setJavaScriptEnabled(true);
103 webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
fionaxu2e0915f2017-05-03 23:19:25 -0700104 webSettings.setUseWideViewPort(true);
105 webSettings.setLoadWithOverviewMode(true);
106 webSettings.setSupportZoom(true);
107 webSettings.setBuiltInZoomControls(true);
fionaxuda578042017-03-10 10:16:09 -0800108 mWebViewClient = new MyWebViewClient();
109 mWebView.setWebViewClient(mWebViewClient);
110 mWebView.setWebChromeClient(new MyWebChromeClient());
111
112 mNetwork = getNetworkForCaptivePortal();
113 if (mNetwork == null) {
114 requestNetworkForCaptivePortal();
115 } else {
116 mCm.bindProcessToNetwork(mNetwork);
117 // Start initial page load so WebView finishes loading proxy settings.
118 // Actual load of mUrl is initiated by MyWebViewClient.
119 mWebView.loadData("", "text/html", null);
120 }
121 }
122
123 @Override
124 public void onBackPressed() {
Alan Viverette51efddb2017-04-05 10:00:01 -0400125 WebView myWebView = findViewById(R.id.webview);
fionaxuda578042017-03-10 10:16:09 -0800126 if (myWebView.canGoBack() && mWebViewClient.allowBack()) {
127 myWebView.goBack();
128 } else {
129 super.onBackPressed();
130 }
131 }
132
133 @Override
134 public void onDestroy() {
fionaxuda578042017-03-10 10:16:09 -0800135 if (mLaunchBrowser) {
136 // Give time for this network to become default. After 500ms just proceed.
137 for (int i = 0; i < 5; i++) {
138 // TODO: This misses when mNetwork underlies a VPN.
139 if (mNetwork.equals(mCm.getActiveNetwork())) break;
140 try {
141 Thread.sleep(100);
142 } catch (InterruptedException e) {
143 }
144 }
145 final String url = mUrl.toString();
146 if (DBG) logd("starting activity with intent ACTION_VIEW for " + url);
147 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
148 }
fionaxuf62e4cc2017-07-21 18:02:30 -0700149
150 if (mTestingThread != null) {
151 mTestingThread.interrupt();
152 }
153 mWebView.destroy();
154 releaseNetworkRequest();
155 super.onDestroy();
fionaxuda578042017-03-10 10:16:09 -0800156 }
157
158 // Find WebView's proxy BroadcastReceiver and prompt it to read proxy system properties.
159 private void setWebViewProxy() {
160 LoadedApk loadedApk = getApplication().mLoadedApk;
161 try {
162 Field receiversField = LoadedApk.class.getDeclaredField("mReceivers");
163 receiversField.setAccessible(true);
164 ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
165 for (Object receiverMap : receivers.values()) {
166 for (Object rec : ((ArrayMap) receiverMap).keySet()) {
167 Class clazz = rec.getClass();
168 if (clazz.getName().contains("ProxyChangeListener")) {
169 Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class,
170 Intent.class);
171 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
172 onReceiveMethod.invoke(rec, getApplicationContext(), intent);
173 Log.v(TAG, "Prompting WebView proxy reload.");
174 }
175 }
176 }
177 } catch (Exception e) {
178 loge("Exception while setting WebView proxy: " + e);
179 }
180 }
181
182 private void done(boolean success) {
Qiongcheng Luofd11ce52017-08-04 14:34:34 +0800183 if (DBG) logd(String.format("Result success %b for %s", success,
184 mUrl != null ? mUrl.toString() : "null"));
fionaxuda578042017-03-10 10:16:09 -0800185 if (success) {
186 // Trigger re-evaluation upon success http response code
187 CarrierActionUtils.applyCarrierAction(
188 CarrierActionUtils.CARRIER_ACTION_ENABLE_RADIO, getIntent(),
189 getApplicationContext());
190 CarrierActionUtils.applyCarrierAction(
191 CarrierActionUtils.CARRIER_ACTION_ENABLE_METERED_APNS, getIntent(),
192 getApplicationContext());
193 CarrierActionUtils.applyCarrierAction(
194 CarrierActionUtils.CARRIER_ACTION_CANCEL_ALL_NOTIFICATIONS, getIntent(),
195 getApplicationContext());
fionaxud60a9d02017-05-23 14:55:27 -0700196 CarrierActionUtils.applyCarrierAction(
197 CarrierActionUtils.CARRIER_ACTION_DISABLE_DEFAULT_URL_HANDLER, getIntent(),
198 getApplicationContext());
199 CarrierActionUtils.applyCarrierAction(
200 CarrierActionUtils.CARRIER_ACTION_DEREGISTER_DEFAULT_NETWORK_AVAIL, getIntent(),
201 getApplicationContext());
fionaxuda578042017-03-10 10:16:09 -0800202 }
203 finishAndRemoveTask();
204 }
205
206 private URL getUrlForCaptivePortal() {
207 String url = getIntent().getStringExtra(TelephonyIntents.EXTRA_REDIRECTION_URL_KEY);
fionaxud60a9d02017-05-23 14:55:27 -0700208 if (TextUtils.isEmpty(url)) url = mCm.getCaptivePortalServerUrl();
fionaxuda578042017-03-10 10:16:09 -0800209 final CarrierConfigManager configManager = getApplicationContext()
210 .getSystemService(CarrierConfigManager.class);
211 final int subId = getIntent().getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
212 SubscriptionManager.getDefaultVoiceSubscriptionId());
213 final String[] portalURLs = configManager.getConfigForSubId(subId).getStringArray(
214 CarrierConfigManager.KEY_CARRIER_DEFAULT_REDIRECTION_URL_STRING_ARRAY);
215 if (!ArrayUtils.isEmpty(portalURLs)) {
216 for (String portalUrl : portalURLs) {
217 if (url.startsWith(portalUrl)) {
218 break;
219 }
220 }
221 url = null;
222 }
223 try {
224 return new URL(url);
225 } catch (MalformedURLException e) {
226 loge("Invalid captive portal URL " + url);
227 }
228 return null;
229 }
230
231 private void testForCaptivePortal() {
fionaxuf62e4cc2017-07-21 18:02:30 -0700232 mTestingThread = new Thread(new Runnable() {
fionaxuda578042017-03-10 10:16:09 -0800233 public void run() {
234 // Give time for captive portal to open.
235 try {
236 Thread.sleep(1000);
237 } catch (InterruptedException e) {
238 }
fionaxuf62e4cc2017-07-21 18:02:30 -0700239 if (isFinishing() || isDestroyed()) return;
fionaxuda578042017-03-10 10:16:09 -0800240 HttpURLConnection urlConnection = null;
241 int httpResponseCode = 500;
242 int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
243 try {
fionaxuc457a042017-07-10 09:34:07 -0700244 urlConnection = (HttpURLConnection) mNetwork.openConnection(
245 new URL(mCm.getCaptivePortalServerUrl()));
fionaxuda578042017-03-10 10:16:09 -0800246 urlConnection.setInstanceFollowRedirects(false);
247 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
248 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
249 urlConnection.setUseCaches(false);
250 urlConnection.getInputStream();
251 httpResponseCode = urlConnection.getResponseCode();
252 } catch (IOException e) {
fionaxuc457a042017-07-10 09:34:07 -0700253 loge(e.getMessage());
fionaxuda578042017-03-10 10:16:09 -0800254 } finally {
255 if (urlConnection != null) urlConnection.disconnect();
256 TrafficStats.setThreadStatsTag(oldTag);
257 }
258 if (httpResponseCode == 204) {
259 done(true);
260 }
261 }
fionaxuf62e4cc2017-07-21 18:02:30 -0700262 });
263 mTestingThread.start();
fionaxuda578042017-03-10 10:16:09 -0800264 }
265
266 private Network getNetworkForCaptivePortal() {
267 Network[] info = mCm.getAllNetworks();
268 if (!ArrayUtils.isEmpty(info)) {
269 for (Network nw : info) {
270 final NetworkCapabilities nc = mCm.getNetworkCapabilities(nw);
271 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
272 && nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
273 return nw;
274 }
275 }
276 }
277 return null;
278 }
279
280 private void requestNetworkForCaptivePortal() {
281 NetworkRequest request = new NetworkRequest.Builder()
282 .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
283 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
284 .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
285 .build();
286
287 mNetworkCallback = new ConnectivityManager.NetworkCallback() {
288 @Override
289 public void onAvailable(Network network) {
290 if (DBG) logd("Network available: " + network);
291 mCm.bindProcessToNetwork(network);
292 mNetwork = network;
293 runOnUiThreadIfNotFinishing(() -> {
294 // Start initial page load so WebView finishes loading proxy settings.
295 // Actual load of mUrl is initiated by MyWebViewClient.
296 mWebView.loadData("", "text/html", null);
297 });
298 }
299
300 @Override
301 public void onUnavailable() {
302 if (DBG) logd("Network unavailable");
303 runOnUiThreadIfNotFinishing(() -> {
304 // Instead of not loading anything in webview, simply load the page and return
305 // HTTP error page in the absence of network connection.
306 mWebView.loadUrl(mUrl.toString());
307 });
308 }
309 };
310 logd("request Network for captive portal");
311 mCm.requestNetwork(request, mNetworkCallback, NETWORK_REQUEST_TIMEOUT_MS);
312 }
313
314 private void releaseNetworkRequest() {
315 logd("release Network for captive portal");
316 if (mNetworkCallback != null) {
317 mCm.unregisterNetworkCallback(mNetworkCallback);
318 mNetworkCallback = null;
319 mNetwork = null;
320 }
321 }
322
323 private class MyWebViewClient extends WebViewClient {
324 private static final String INTERNAL_ASSETS = "file:///android_asset/";
325 private final String mBrowserBailOutToken = Long.toString(new Random().nextLong());
326 // How many Android device-independent-pixels per scaled-pixel
327 // dp/sp = (px/sp) / (px/dp) = (1/sp) / (1/dp)
328 private final float mDpPerSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 1,
329 getResources().getDisplayMetrics())
330 / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
331 getResources().getDisplayMetrics());
332 private int mPagesLoaded;
333
334 // If we haven't finished cleaning up the history, don't allow going back.
335 public boolean allowBack() {
336 return mPagesLoaded > 1;
337 }
338
339 @Override
340 public void onPageStarted(WebView view, String url, Bitmap favicon) {
341 if (url.contains(mBrowserBailOutToken)) {
342 mLaunchBrowser = true;
343 done(false);
344 return;
345 }
346 // The first page load is used only to cause the WebView to
347 // fetch the proxy settings. Don't update the URL bar, and
348 // don't check if the captive portal is still there.
349 if (mPagesLoaded == 0) return;
350 // For internally generated pages, leave URL bar listing prior URL as this is the URL
351 // the page refers to.
352 if (!url.startsWith(INTERNAL_ASSETS)) {
Alan Viverette51efddb2017-04-05 10:00:01 -0400353 final TextView myUrlBar = findViewById(R.id.url_bar);
fionaxuda578042017-03-10 10:16:09 -0800354 myUrlBar.setText(url);
355 }
356 if (mNetwork != null) {
357 testForCaptivePortal();
358 }
359 }
360
361 @Override
362 public void onPageFinished(WebView view, String url) {
363 mPagesLoaded++;
364 if (mPagesLoaded == 1) {
365 // Now that WebView has loaded at least one page we know it has read in the proxy
366 // settings. Now prompt the WebView read the Network-specific proxy settings.
367 setWebViewProxy();
368 // Load the real page.
369 view.loadUrl(mUrl.toString());
370 return;
371 } else if (mPagesLoaded == 2) {
372 // Prevent going back to empty first page.
373 view.clearHistory();
374 }
375 if (mNetwork != null) {
376 testForCaptivePortal();
377 }
378 }
379
380 // Convert Android device-independent-pixels (dp) to HTML size.
381 private String dp(int dp) {
382 // HTML px's are scaled just like dp's, so just add "px" suffix.
383 return Integer.toString(dp) + "px";
384 }
385
386 // Convert Android scaled-pixels (sp) to HTML size.
387 private String sp(int sp) {
388 // Convert sp to dp's.
389 float dp = sp * mDpPerSp;
390 // Apply a scale factor to make things look right.
391 dp *= 1.3;
392 // Convert dp's to HTML size.
393 return dp((int) dp);
394 }
395
396 // A web page consisting of a large broken lock icon to indicate SSL failure.
397 private final String SSL_ERROR_HTML = "<html><head><style>"
398 + "body { margin-left:" + dp(48) + "; margin-right:" + dp(48) + "; "
399 + "margin-top:" + dp(96) + "; background-color:#fafafa; }"
400 + "img { width:" + dp(48) + "; height:" + dp(48) + "; }"
401 + "div.warn { font-size:" + sp(16) + "; margin-top:" + dp(16) + "; "
402 + " opacity:0.87; line-height:1.28; }"
403 + "div.example { font-size:" + sp(14) + "; margin-top:" + dp(16) + "; "
404 + " opacity:0.54; line-height:1.21905; }"
405 + "a { font-size:" + sp(14) + "; text-decoration:none; text-transform:uppercase; "
406 + " margin-top:" + dp(24) + "; display:inline-block; color:#4285F4; "
407 + " height:" + dp(48) + "; font-weight:bold; }"
408 + "</style></head><body><p><img src=quantum_ic_warning_amber_96.png><br>"
409 + "<div class=warn>%s</div>"
410 + "<div class=example>%s</div>" + "<a href=%s>%s</a></body></html>";
411
412 @Override
413 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
414 Log.w(TAG, "SSL error (error: " + error.getPrimaryError() + " host: "
415 // Only show host to avoid leaking private info.
416 + Uri.parse(error.getUrl()).getHost() + " certificate: "
417 + error.getCertificate() + "); displaying SSL warning.");
418 final String html = String.format(SSL_ERROR_HTML, getString(R.string.ssl_error_warning),
419 getString(R.string.ssl_error_example), mBrowserBailOutToken,
420 getString(R.string.ssl_error_continue));
421 view.loadDataWithBaseURL(INTERNAL_ASSETS, html, "text/HTML", "UTF-8", null);
422 }
423
424 @Override
425 public boolean shouldOverrideUrlLoading(WebView view, String url) {
426 if (url.startsWith("tel:")) {
427 startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
428 return true;
429 }
430 return false;
431 }
432 }
433
434 private class MyWebChromeClient extends WebChromeClient {
435 @Override
436 public void onProgressChanged(WebView view, int newProgress) {
Alan Viverette51efddb2017-04-05 10:00:01 -0400437 final ProgressBar myProgressBar = findViewById(R.id.progress_bar);
fionaxuda578042017-03-10 10:16:09 -0800438 myProgressBar.setProgress(newProgress);
439 }
440 }
441
442 private void runOnUiThreadIfNotFinishing(Runnable r) {
443 if (!isFinishing()) {
444 runOnUiThread(r);
445 }
446 }
447
fionaxud60a9d02017-05-23 14:55:27 -0700448 /**
449 * This alias presents the target activity, CaptivePortalLoginActivity, as a independent
450 * entity with its own intent filter to handle URL links. This alias will be enabled/disabled
451 * dynamically to handle url links based on the network conditions.
452 */
453 public static String getAlias(Context context) {
454 try {
455 PackageInfo p = context.getPackageManager().getPackageInfo(context.getPackageName(),
456 PackageManager.GET_ACTIVITIES | PackageManager.MATCH_DISABLED_COMPONENTS);
457 for (ActivityInfo activityInfo : p.activities) {
458 String targetActivity = activityInfo.targetActivity;
459 if (CaptivePortalLoginActivity.class.getName().equals(targetActivity)) {
460 return activityInfo.name;
461 }
462 }
463 } catch (PackageManager.NameNotFoundException e) {
464 e.printStackTrace();
465 }
466 return null;
467 }
468
fionaxuda578042017-03-10 10:16:09 -0800469 private static void logd(String s) {
470 Rlog.d(TAG, s);
471 }
472
473 private static void loge(String s) {
474 Rlog.d(TAG, s);
475 }
476
477}