blob: 8b886d6b3cffe9a5e0e55356f8de480a0b99a8a4 [file] [log] [blame]
Paul Jensenca8f16a2014-05-09 12:47:55 -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.server.connectivity;
18
Paul Jensen49e3edf2015-05-22 10:50:39 -040019import static android.net.CaptivePortal.APP_RETURN_DISMISSED;
20import static android.net.CaptivePortal.APP_RETURN_UNWANTED;
21import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS;
22
Paul Jensen869868be2014-05-15 10:33:05 -040023import android.app.PendingIntent;
24import android.content.BroadcastReceiver;
Paul Jensenca8f16a2014-05-09 12:47:55 -040025import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040026import android.content.Intent;
27import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040028import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040029import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040030import android.net.ICaptivePortal;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +090031import android.net.Network;
Paul Jensen2c311d62014-11-17 12:34:51 -050032import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050033import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040034import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040035import android.net.Uri;
Hugo Benichicfddd682016-05-31 16:28:06 +090036import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090037import android.net.metrics.NetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090038import android.net.metrics.ValidationProbeEvent;
Hugo Benichid953bf82016-09-27 09:22:35 +090039import android.net.util.Stopwatch;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.net.wifi.WifiInfo;
41import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040042import android.os.Handler;
43import android.os.Message;
Paul Jensen306f1a42014-08-04 10:59:01 -040044import android.os.SystemClock;
Paul Jensen869868be2014-05-15 10:33:05 -040045import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040046import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040047import android.telephony.CellIdentityCdma;
48import android.telephony.CellIdentityGsm;
49import android.telephony.CellIdentityLte;
50import android.telephony.CellIdentityWcdma;
51import android.telephony.CellInfo;
52import android.telephony.CellInfoCdma;
53import android.telephony.CellInfoGsm;
54import android.telephony.CellInfoLte;
55import android.telephony.CellInfoWcdma;
56import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040057import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070058import android.util.LocalLog;
59import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050060import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040061
Paul Jensend7b6ca92015-05-13 14:05:12 -040062import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040063import com.android.internal.util.Protocol;
64import com.android.internal.util.State;
65import com.android.internal.util.StateMachine;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066
Paul Jensenca8f16a2014-05-09 12:47:55 -040067import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040069import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090070import java.net.MalformedURLException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.net.URL;
Hugo Benichid953bf82016-09-27 09:22:35 +090072import java.net.UnknownHostException;
Hugo Benichieef918a2017-04-10 17:43:08 +090073import java.util.ArrayList;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +090074import java.util.Arrays;
75import java.util.Collections;
76import java.util.LinkedHashMap;
Paul Jensen306f1a42014-08-04 10:59:01 -040077import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040078import java.util.Random;
Hugo Benichid953bf82016-09-27 09:22:35 +090079import java.util.concurrent.CountDownLatch;
80import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040081
82/**
83 * {@hide}
84 */
85public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +090086 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +090087 private static final boolean DBG = true;
88 private static final boolean VDBG = false;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090089
Hugo Benichi11ae28f2016-09-27 13:16:19 +090090 // Default configuration values for captive portal detection probes.
91 // TODO: append a random length parameter to the default HTTPS url.
92 // TODO: randomize browser version ids in the default User-Agent String.
93 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090094 private static final String DEFAULT_HTTP_URL =
95 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090096 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
Hugo Benichieef918a2017-04-10 17:43:08 +090097 private static final String DEFAULT_OTHER_FALLBACK_URLS =
98 "http://play.googleapis.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090099 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
100 + "AppleWebKit/537.36 (KHTML, like Gecko) "
Lorenzo Colittid8a06082017-06-28 23:39:40 +0900101 + "Chrome/60.0.3112.32 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900102
Paul Jensenca8f16a2014-05-09 12:47:55 -0400103 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900104 private static final int PROBE_TIMEOUT_MS = 3000;
105
Hugo Benichidd229822016-11-15 23:23:24 +0900106 static enum EvaluationResult {
107 VALIDATED(true),
108 CAPTIVE_PORTAL(false);
109 final boolean isValidated;
110 EvaluationResult(boolean isValidated) {
111 this.isValidated = isValidated;
112 }
113 }
114
115 static enum ValidationStage {
116 FIRST_VALIDATION(true),
117 REVALIDATION(false);
118 final boolean isFirstValidation;
119 ValidationStage(boolean isFirstValidation) {
120 this.isFirstValidation = isFirstValidation;
121 }
122 }
123
Paul Jensen306f1a42014-08-04 10:59:01 -0400124 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
125 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
126 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
127 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
128 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
129 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
130 public static final String EXTRA_CELL_ID = "extra_cellid";
131 public static final String EXTRA_SSID = "extra_ssid";
132 public static final String EXTRA_BSSID = "extra_bssid";
133 /** real time since boot */
134 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
135 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
136
137 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
138 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400139
Paul Jensenad50a1f2014-09-05 12:06:44 -0400140 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
141 // The network should be used as a default internet connection. It was found to be:
142 // 1. a functioning network providing internet access, or
143 // 2. a captive portal and the user decided to use it as is.
144 public static final int NETWORK_TEST_RESULT_VALID = 0;
145 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
146 // The network should not be used as a default internet connection. It was found to be:
147 // 1. a captive portal and the user is prompted to sign-in, or
148 // 2. a captive portal and the user did not want to use it, or
149 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
150 public static final int NETWORK_TEST_RESULT_INVALID = 1;
151
Paul Jensenca8f16a2014-05-09 12:47:55 -0400152 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
153
154 /**
155 * Inform NetworkMonitor that their network is connected.
156 * Initiates Network Validation.
157 */
158 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
159
160 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400161 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400162 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400163 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400164 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400165 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400166 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400167
168 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400169 * Message to self indicating it's time to evaluate a network's connectivity.
170 * arg1 = Token to ignore old messages.
171 */
Paul Jensen869868be2014-05-15 10:33:05 -0400172 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400173
174 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400175 * Inform NetworkMonitor that the network has disconnected.
176 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400177 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400178
179 /**
180 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400181 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400182 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400183 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400184
185 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400186 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400187 * arg1 = one of: APP_RETURN_DISMISSED,
188 * APP_RETURN_UNWANTED,
189 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500190 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400191 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400192 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400193
194 /**
195 * Request ConnectivityService display provisioning notification.
196 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400197 * arg2 = NetID.
198 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400199 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400200 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400201
202 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900203 * Message indicating sign-in app should be launched.
Paul Jensen25a217c2015-02-27 22:55:47 -0500204 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900205 * user touches the sign in notification, or sent by
206 * ConnectivityService when the user touches the "sign into
207 * network" button in the wifi access point detail page.
Paul Jensen869868be2014-05-15 10:33:05 -0400208 */
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900209 public static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400210
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400211 /**
212 * Retest network to see if captive portal is still in place.
213 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
214 * 0 indicates self-initiated, so nobody to blame.
215 */
216 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
217
Paul Jensend0491e9a2015-05-05 14:52:22 -0400218 // Start mReevaluateDelayMs at this value and double.
219 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
220 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
221 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
222 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400223 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400224 private static final int INVALID_UID = -1;
225 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400226 // Stop blaming UID that requested re-evaluation after this many attempts.
227 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400228 // Delay between reevaluations once a captive portal has been found.
229 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400230
Hugo Benichic894b122017-07-31 12:58:20 +0900231 private static final int NUM_VALIDATION_LOG_LINES = 20;
232
Paul Jensenca8f16a2014-05-09 12:47:55 -0400233 private final Context mContext;
234 private final Handler mConnectivityServiceHandler;
235 private final NetworkAgentInfo mNetworkAgentInfo;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900236 private final Network mNetwork;
Erik Klinea488c232016-04-15 15:49:42 +0900237 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400238 private final TelephonyManager mTelephonyManager;
239 private final WifiManager mWifiManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500240 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900241 private final IpConnectivityLog mMetricsLog;
Hugo Benichic894b122017-07-31 12:58:20 +0900242 private final NetworkMonitorSettings mSettings;
243
244 // Configuration values for captive portal detection probes.
245 private final String mCaptivePortalUserAgent;
246 private final URL mCaptivePortalHttpsUrl;
247 private final URL mCaptivePortalHttpUrl;
248 private final URL[] mCaptivePortalFallbackUrls;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249
Calvin On4bc78eb2016-10-11 15:10:46 -0700250 @VisibleForTesting
251 protected boolean mIsCaptivePortalCheckEnabled;
252
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900253 private boolean mUseHttps;
Hugo Benichidd229822016-11-15 23:23:24 +0900254 // The total number of captive portal detection attempts for this NetworkMonitor instance.
255 private int mValidations = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400256
Paul Jensenad50a1f2014-09-05 12:06:44 -0400257 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
258 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400259 // Avoids surfacing "Sign in to network" notification.
260 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400261
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700262 public boolean systemReady = false;
263
Paul Jensen71b645f2014-10-13 14:13:07 -0400264 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400265 private final State mValidatedState = new ValidatedState();
266 private final State mMaybeNotifyState = new MaybeNotifyState();
267 private final State mEvaluatingState = new EvaluatingState();
268 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400269
Paul Jensen25a217c2015-02-27 22:55:47 -0500270 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400271
Hugo Benichic894b122017-07-31 12:58:20 +0900272 private final LocalLog validationLogs = new LocalLog(NUM_VALIDATION_LOG_LINES);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700273
Erik Klinea488c232016-04-15 15:49:42 +0900274 private final Stopwatch mEvaluationTimer = new Stopwatch();
275
Hugo Benichid953bf82016-09-27 09:22:35 +0900276 // This variable is set before transitioning to the mCaptivePortalState.
277 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
278
Hugo Benichieef918a2017-04-10 17:43:08 +0900279 private int mNextFallbackUrlIndex = 0;
Hugo Benichib03272c2017-04-10 22:45:13 +0900280
Paul Jensen2c311d62014-11-17 12:34:51 -0500281 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
282 NetworkRequest defaultRequest) {
Hugo Benichic894b122017-07-31 12:58:20 +0900283 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog(),
284 NetworkMonitorSettings.DEFAULT);
Hugo Benichif9fdf872016-07-28 17:53:06 +0900285 }
286
287 @VisibleForTesting
288 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
Hugo Benichic894b122017-07-31 12:58:20 +0900289 NetworkRequest defaultRequest, IpConnectivityLog logger,
290 NetworkMonitorSettings settings) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400291 // Add suffix indicating which NetworkMonitor we're talking about.
292 super(TAG + networkAgentInfo.name());
293
294 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900295 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400296 mConnectivityServiceHandler = handler;
Hugo Benichic894b122017-07-31 12:58:20 +0900297 mSettings = settings;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 mNetworkAgentInfo = networkAgentInfo;
Hugo Benichic894b122017-07-31 12:58:20 +0900299 mNetwork = new OneAddressPerFamilyNetwork(networkAgentInfo.network());
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900300 mNetId = mNetwork.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400301 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
302 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500303 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400304
305 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400306 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400307 addState(mMaybeNotifyState, mDefaultState);
308 addState(mEvaluatingState, mMaybeNotifyState);
309 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700310 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400311
Hugo Benichic894b122017-07-31 12:58:20 +0900312 mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
313 mUseHttps = getUseHttpsValidation();
314 mCaptivePortalUserAgent = getCaptivePortalUserAgent();
315 mCaptivePortalHttpsUrl = makeURL(getCaptivePortalServerHttpsUrl());
316 mCaptivePortalHttpUrl = makeURL(getCaptivePortalServerHttpUrl(settings, context));
317 mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls();
Hugo Benichib03272c2017-04-10 22:45:13 +0900318
Paul Jensenca8f16a2014-05-09 12:47:55 -0400319 start();
320 }
321
Paul Jensen532b61432014-11-10 09:50:02 -0500322 @Override
323 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400324 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500325 }
326
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900327 private void validationLog(int probeType, Object url, String msg) {
328 String probeName = ValidationProbeEvent.getProbeName(probeType);
329 validationLog(String.format("%s %s %s", probeName, url, msg));
330 }
331
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700332 private void validationLog(String s) {
333 if (DBG) log(s);
334 validationLogs.log(s);
335 }
336
337 public ReadOnlyLocalLog getValidationLogs() {
338 return validationLogs.readOnlyLocalLog();
339 }
340
Hugo Benichidd229822016-11-15 23:23:24 +0900341 private ValidationStage validationStage() {
342 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION;
343 }
344
Paul Jensen71b645f2014-10-13 14:13:07 -0400345 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
346 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400347 private class DefaultState extends State {
348 @Override
349 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400350 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400351 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900352 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400353 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400354 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400355 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900356 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500357 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
358 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
359 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400360 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700361 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400362 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400363 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400364 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400365 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400366 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400367 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400368 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400369 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400370 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900371
372 // If the user has seen and acted on a captive portal notification, and the
373 // captive portal app is now closed, disable HTTPS probes. This avoids the
374 // following pathological situation:
375 //
376 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
377 // 2. User opens the app and logs into the captive portal.
378 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
379 // perhaps due to the network blocking HTTPS?
380 //
381 // In this case, we'll fail to validate the network even after the app is
382 // dismissed. There is now no way to use this network, because the app is now
383 // gone, so the user cannot select "Use this network as is".
384 mUseHttps = false;
385
Paul Jensen71b645f2014-10-13 14:13:07 -0400386 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400387 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400388 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500389 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400390 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400391 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500392 // TODO: Distinguish this from a network that actually validates.
393 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400394 transitionTo(mValidatedState);
395 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400396 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400397 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400398 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400399 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400400 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900401 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400402 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400403 mUidResponsibleForReeval = 0;
404 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400405 break;
406 }
407 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400408 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400409 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400410 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400411 }
412 }
413
Paul Jensen71b645f2014-10-13 14:13:07 -0400414 // Being in the ValidatedState State indicates a Network is:
415 // - Successfully validated, or
416 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400417 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400418 private class ValidatedState extends State {
419 @Override
420 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900421 maybeLogEvaluationResult(
422 networkEventType(validationStage(), EvaluationResult.VALIDATED));
Paul Jensenad50a1f2014-09-05 12:06:44 -0400423 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900424 NETWORK_TEST_RESULT_VALID, mNetId, null));
Hugo Benichidd229822016-11-15 23:23:24 +0900425 mValidations++;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400426 }
427
428 @Override
429 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400430 switch (message.what) {
431 case CMD_NETWORK_CONNECTED:
432 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400433 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400434 default:
435 return NOT_HANDLED;
436 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400437 }
438 }
439
Paul Jensen71b645f2014-10-13 14:13:07 -0400440 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
441 // is required. This State takes care to clear the notification upon exit from the State.
442 private class MaybeNotifyState extends State {
443 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500444 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500445 switch (message.what) {
446 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
447 final Intent intent = new Intent(
448 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900449 // OneAddressPerFamilyNetwork is not parcelable across processes.
450 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, new Network(mNetwork));
Paul Jensen49e3edf2015-05-22 10:50:39 -0400451 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
452 new CaptivePortal(new ICaptivePortal.Stub() {
453 @Override
454 public void appResponse(int response) {
455 if (response == APP_RETURN_WANTED_AS_IS) {
456 mContext.enforceCallingPermission(
457 android.Manifest.permission.CONNECTIVITY_INTERNAL,
458 "CaptivePortal");
459 }
460 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
461 }
462 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900463 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
464 mLastPortalProbeResult.detectUrl);
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900465 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
Hugo Benichieef918a2017-04-10 17:43:08 +0900466 mCaptivePortalUserAgent);
Paul Jensen25a217c2015-02-27 22:55:47 -0500467 intent.setFlags(
468 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
469 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
470 return HANDLED;
471 default:
472 return NOT_HANDLED;
473 }
474 }
475
476 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400477 public void exit() {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900478 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0, mNetId, null);
Paul Jensen71b645f2014-10-13 14:13:07 -0400479 mConnectivityServiceHandler.sendMessage(message);
480 }
481 }
482
Paul Jensen232437312016-04-06 09:51:26 -0400483 /**
484 * Result of calling isCaptivePortal().
485 * @hide
486 */
487 @VisibleForTesting
488 public static final class CaptivePortalProbeResult {
Hugo Benichia4158702017-04-10 17:08:06 +0900489 static final int SUCCESS_CODE = 204;
490 static final int FAILED_CODE = 599;
491
492 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(FAILED_CODE);
493 static final CaptivePortalProbeResult SUCCESS = new CaptivePortalProbeResult(SUCCESS_CODE);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900494
Hugo Benichid953bf82016-09-27 09:22:35 +0900495 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
496 final String redirectUrl; // Redirect destination returned from Internet probe.
497 final String detectUrl; // URL where a 204 response code indicates
498 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400499
Hugo Benichid953bf82016-09-27 09:22:35 +0900500 public CaptivePortalProbeResult(
501 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400502 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900503 this.redirectUrl = redirectUrl;
504 this.detectUrl = detectUrl;
505 }
506
507 public CaptivePortalProbeResult(int httpResponseCode) {
508 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400509 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900510
Hugo Benichia4158702017-04-10 17:08:06 +0900511 boolean isSuccessful() {
512 return mHttpResponseCode == SUCCESS_CODE;
513 }
514
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900515 boolean isPortal() {
Hugo Benichia4158702017-04-10 17:08:06 +0900516 return !isSuccessful() && (mHttpResponseCode >= 200) && (mHttpResponseCode <= 399);
517 }
518
519 boolean isFailed() {
520 return !isSuccessful() && !isPortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900521 }
Paul Jensen232437312016-04-06 09:51:26 -0400522 }
523
Paul Jensen71b645f2014-10-13 14:13:07 -0400524 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400525 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400526 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400527 private int mReevaluateDelayMs;
528 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400529
Paul Jensenca8f16a2014-05-09 12:47:55 -0400530 @Override
531 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900532 // If we have already started to track time spent in EvaluatingState
533 // don't reset the timer due simply to, say, commands or events that
534 // cause us to exit and re-enter EvaluatingState.
535 if (!mEvaluationTimer.isStarted()) {
536 mEvaluationTimer.start();
537 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400538 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400539 if (mUidResponsibleForReeval != INVALID_UID) {
540 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
541 mUidResponsibleForReeval = INVALID_UID;
542 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400543 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
544 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400545 }
546
547 @Override
548 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400549 switch (message.what) {
550 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400551 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400552 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500553 // Don't bother validating networks that don't satisify the default request.
554 // This includes:
555 // - VPNs which can be considered explicitly desired by the user and the
556 // user's desire trumps whether the network validates.
557 // - Networks that don't provide internet access. It's unclear how to
558 // validate such networks.
559 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
560 // such networks and the user didn't express interest in connecting to
561 // such networks (an app did) so the user may be unhappily surprised when
562 // asked to sign-in to a network they didn't want to connect to in the
563 // first place. Validation could be done to adjust the network scores
564 // however these networks are app-requested and may not be intended for
565 // general usage, in which case general validation may not be an accurate
566 // measure of the network's quality. Only the app knows how to evaluate
567 // the network so don't bother validating here. Furthermore sending HTTP
568 // packets over the network may be undesirable, for example an extremely
569 // expensive metered network, or unwanted leaking of the User Agent string.
570 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
571 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900572 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400573 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400574 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400575 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400576 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900577 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
578 // server's IP addresses could hit the DNS timeout, and attempting connections
579 // to each of the server's several IP addresses (currently one IPv4 and one
580 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
581 // will be unresponsive. isCaptivePortal() could be executed on another Thread
582 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400583 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900584 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400585 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900586 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400587 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900588 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
589 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400590 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400591 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400592 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400593 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900594 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400595 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900596 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900597 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400598 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400599 // Don't continue to blame UID forever.
600 TrafficStats.clearThreadStatsUid();
601 }
602 mReevaluateDelayMs *= 2;
603 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
604 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
605 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400606 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400607 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400608 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400609 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
610 // ignore any re-evaluation requests. After, restart the
611 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900612 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400613 default:
614 return NOT_HANDLED;
615 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400616 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400617
618 @Override
619 public void exit() {
620 TrafficStats.clearThreadStatsUid();
621 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400622 }
623
Paul Jensendcbe8352014-09-16 16:28:34 -0400624 // BroadcastReceiver that waits for a particular Intent and then posts a message.
625 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400626 private final int mToken;
627 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400628 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400629 CustomIntentReceiver(String action, int token, int what) {
630 mToken = token;
631 mWhat = what;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900632 mAction = action + "_" + mNetId + "_" + token;
Paul Jensendcbe8352014-09-16 16:28:34 -0400633 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400634 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400635 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500636 final Intent intent = new Intent(mAction);
637 intent.setPackage(mContext.getPackageName());
638 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400639 }
640 @Override
641 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400642 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400643 }
644 }
Paul Jensen869868be2014-05-15 10:33:05 -0400645
Paul Jensen71b645f2014-10-13 14:13:07 -0400646 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
647 // has been shown a notification to sign-in.
648 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500649 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
650 "android.net.netmon.launchCaptivePortalApp";
651
Paul Jensen869868be2014-05-15 10:33:05 -0400652 @Override
653 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900654 maybeLogEvaluationResult(
655 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400656 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400657 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500658 // Create a CustomIntentReceiver that sends us a
659 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
660 // touches the notification.
661 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400662 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500663 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
664 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
665 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400666 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500667 // Display the sign in notification.
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900668 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1, mNetId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500669 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400670 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400671 // Retest for captive portal occasionally.
672 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
673 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Hugo Benichidd229822016-11-15 23:23:24 +0900674 mValidations++;
Paul Jensen869868be2014-05-15 10:33:05 -0400675 }
676
677 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400678 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700679 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400680 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400681 }
682
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900683 // Limits the list of IP addresses returned by getAllByName or tried by openConnection to at
684 // most one per address family. This ensures we only wait up to 20 seconds for TCP connections
685 // to complete, regardless of how many IP addresses a host has.
686 private static class OneAddressPerFamilyNetwork extends Network {
687 public OneAddressPerFamilyNetwork(Network network) {
688 super(network);
689 }
690
691 @Override
692 public InetAddress[] getAllByName(String host) throws UnknownHostException {
693 List<InetAddress> addrs = Arrays.asList(super.getAllByName(host));
694
695 // Ensure the address family of the first address is tried first.
696 LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>();
697 addressByFamily.put(addrs.get(0).getClass(), addrs.get(0));
698 Collections.shuffle(addrs);
699
700 for (InetAddress addr : addrs) {
701 addressByFamily.put(addr.getClass(), addr);
702 }
703
704 return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]);
705 }
706 }
707
Hugo Benichic894b122017-07-31 12:58:20 +0900708 public boolean getIsCaptivePortalCheckEnabled() {
709 String symbol = Settings.Global.CAPTIVE_PORTAL_MODE;
710 int defaultValue = Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT;
711 int mode = mSettings.getSetting(mContext, symbol, defaultValue);
712 return mode != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900713 }
714
Hugo Benichic894b122017-07-31 12:58:20 +0900715 public boolean getUseHttpsValidation() {
716 return mSettings.getSetting(mContext, Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
717 }
718
719 public boolean getWifiScansAlwaysAvailableDisabled() {
720 return mSettings.getSetting(mContext, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0;
721 }
722
723 private String getCaptivePortalServerHttpsUrl() {
724 return mSettings.getSetting(mContext,
725 Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
726 }
727
728 // Static for direct access by ConnectivityService
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900729 public static String getCaptivePortalServerHttpUrl(Context context) {
Hugo Benichic894b122017-07-31 12:58:20 +0900730 return getCaptivePortalServerHttpUrl(NetworkMonitorSettings.DEFAULT, context);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900731 }
732
Hugo Benichic894b122017-07-31 12:58:20 +0900733 public static String getCaptivePortalServerHttpUrl(
734 NetworkMonitorSettings settings, Context context) {
735 return settings.getSetting(
736 context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
737 }
738
739 private URL[] makeCaptivePortalFallbackUrls() {
Hugo Benichieef918a2017-04-10 17:43:08 +0900740 String separator = ",";
Hugo Benichic894b122017-07-31 12:58:20 +0900741 String firstUrl = mSettings.getSetting(mContext,
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900742 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
Hugo Benichic894b122017-07-31 12:58:20 +0900743 String joinedUrls = firstUrl + separator + mSettings.getSetting(mContext,
Hugo Benichieef918a2017-04-10 17:43:08 +0900744 Settings.Global.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS, DEFAULT_OTHER_FALLBACK_URLS);
745 List<URL> urls = new ArrayList<>();
746 for (String s : joinedUrls.split(separator)) {
747 URL u = makeURL(s);
748 if (u == null) {
749 continue;
750 }
751 urls.add(u);
752 }
753 if (urls.isEmpty()) {
754 Log.e(TAG, String.format("could not create any url from %s", joinedUrls));
755 }
756 return urls.toArray(new URL[urls.size()]);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900757 }
758
Hugo Benichic894b122017-07-31 12:58:20 +0900759 private String getCaptivePortalUserAgent() {
760 return mSettings.getSetting(mContext,
761 Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900762 }
763
Hugo Benichieef918a2017-04-10 17:43:08 +0900764 private URL nextFallbackUrl() {
765 if (mCaptivePortalFallbackUrls.length == 0) {
766 return null;
767 }
768 int idx = Math.abs(mNextFallbackUrlIndex) % mCaptivePortalFallbackUrls.length;
769 mNextFallbackUrlIndex += new Random().nextInt(); // randomely change url without memory.
770 return mCaptivePortalFallbackUrls[idx];
771 }
772
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900773 @VisibleForTesting
774 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -0700775 if (!mIsCaptivePortalCheckEnabled) {
776 validationLog("Validation disabled.");
Hugo Benichia4158702017-04-10 17:08:06 +0900777 return CaptivePortalProbeResult.SUCCESS;
Calvin On4bc78eb2016-10-11 15:10:46 -0700778 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900779
Hugo Benichib03272c2017-04-10 22:45:13 +0900780 URL pacUrl = null;
781 URL httpsUrl = mCaptivePortalHttpsUrl;
782 URL httpUrl = mCaptivePortalHttpUrl;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900783
784 // On networks with a PAC instead of fetching a URL that should result in a 204
785 // response, we instead simply fetch the PAC script. This is done for a few reasons:
786 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
787 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
788 // Network.openConnection() will ignore network-specific PACs and instead fetch
789 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
790 // NO_PROXY is the fetch of the PAC itself.
791 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
792 // happen before the fetch can commence, namely:
793 // a) the PAC script be fetched
794 // b) a PAC script resolver service be fired up and resolve the captive portal
795 // server.
796 // Network validation could be delayed until these prerequisities are satisifed or
797 // could simply be left to race them. Neither is an optimal solution.
798 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
799 // fact block fetching of the generate_204 URL which would lead to false negative
800 // results for network validation.
801 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
802 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900803 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
804 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900805 return CaptivePortalProbeResult.FAILED;
806 }
807 }
808
Hugo Benichib03272c2017-04-10 22:45:13 +0900809 if ((pacUrl == null) && (httpUrl == null || httpsUrl == null)) {
810 return CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900811 }
812
813 long startTime = SystemClock.elapsedRealtime();
814
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900815 final CaptivePortalProbeResult result;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900816 if (pacUrl != null) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900817 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900818 } else if (mUseHttps) {
Hugo Benichieef918a2017-04-10 17:43:08 +0900819 result = sendParallelHttpProbes(proxyInfo, httpsUrl, httpUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900820 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900821 result = sendDnsAndHttpProbes(proxyInfo, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900822 }
823
824 long endTime = SystemClock.elapsedRealtime();
825
826 sendNetworkConditionsBroadcast(true /* response received */,
827 result.isPortal() /* isCaptivePortal */,
828 startTime, endTime);
829
830 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800831 }
832
Paul Jensenca8f16a2014-05-09 12:47:55 -0400833 /**
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900834 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect.
835 * @return a CaptivePortalProbeResult inferred from the HTTP response.
836 */
837 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) {
838 // Pre-resolve the captive portal server host so we can log it.
839 // Only do this if HttpURLConnection is about to, to avoid any potentially
840 // unnecessary resolution.
841 final String host = (proxy != null) ? proxy.getHost() : url.getHost();
842 sendDnsProbe(host);
843 return sendHttpProbe(url, probeType);
844 }
845
846 /** Do a DNS resolution of the given server. */
847 private void sendDnsProbe(String host) {
848 if (TextUtils.isEmpty(host)) {
849 return;
850 }
851
852 final String name = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
853 final Stopwatch watch = new Stopwatch().start();
854 int result;
855 String connectInfo;
856 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900857 InetAddress[] addresses = mNetwork.getAllByName(host);
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900858 StringBuffer buffer = new StringBuffer();
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900859 for (InetAddress address : addresses) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900860 buffer.append(',').append(address.getHostAddress());
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900861 }
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900862 result = ValidationProbeEvent.DNS_SUCCESS;
863 connectInfo = "OK " + buffer.substring(1);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900864 } catch (UnknownHostException e) {
865 result = ValidationProbeEvent.DNS_FAILURE;
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900866 connectInfo = "FAIL";
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900867 }
868 final long latency = watch.stop();
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900869 validationLog(ValidationProbeEvent.PROBE_DNS, host,
870 String.format("%dms %s", latency, connectInfo));
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900871 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result);
872 }
873
874 /**
875 * Do a URL fetch on a known web server to see if we get the data we expect.
876 * @return a CaptivePortalProbeResult inferred from the HTTP response.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400877 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400878 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900879 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400880 HttpURLConnection urlConnection = null;
Hugo Benichia4158702017-04-10 17:08:06 +0900881 int httpResponseCode = CaptivePortalProbeResult.FAILED_CODE;
Paul Jensen232437312016-04-06 09:51:26 -0400882 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900883 final Stopwatch probeTimer = new Stopwatch().start();
Jeff Sharkey619a5112017-01-19 11:55:54 -0700884 final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400885 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900886 urlConnection = (HttpURLConnection) mNetwork.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900887 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400888 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
889 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
890 urlConnection.setUseCaches(false);
Hugo Benichib03272c2017-04-10 22:45:13 +0900891 if (mCaptivePortalUserAgent != null) {
892 urlConnection.setRequestProperty("User-Agent", mCaptivePortalUserAgent);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900893 }
Hugo Benichiec88fd62017-03-07 15:10:03 +0900894 // cannot read request header after connection
895 String requestHeader = urlConnection.getRequestProperties().toString();
Paul Jensen306f1a42014-08-04 10:59:01 -0400896
897 // Time how long it takes to get a response to our request
898 long requestTimestamp = SystemClock.elapsedRealtime();
899
Pierre Imaibe12d762016-03-10 17:00:50 +0900900 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400901 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400902
903 // Time how long it takes to get a response to our request
904 long responseTimestamp = SystemClock.elapsedRealtime();
905
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900906 validationLog(probeType, url, "time=" + (responseTimestamp - requestTimestamp) + "ms" +
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900907 " ret=" + httpResponseCode +
Hugo Benichiec88fd62017-03-07 15:10:03 +0900908 " request=" + requestHeader +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700909 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400910 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
911 // portal. The only example of this seen so far was a captive portal. For
912 // the time being go with prior behavior of assuming it's not a captive
913 // portal. If it is considered a captive portal, a different sign-in URL
914 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
915 // proxy server.
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900916 if (httpResponseCode == 200) {
917 if (probeType == ValidationProbeEvent.PROBE_PAC) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900918 validationLog(
919 probeType, url, "PAC fetch 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +0900920 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900921 } else if (urlConnection.getContentLengthLong() == 0) {
922 // Consider 200 response with "Content-length=0" to not be a captive portal.
923 // There's no point in considering this a captive portal as the user cannot
924 // sign-in to an empty page. Probably the result of a broken transparent proxy.
925 // See http://b/9972012.
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900926 validationLog(probeType, url,
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900927 "200 response with Content-length=0 interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +0900928 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900929 } else if (urlConnection.getContentLengthLong() == -1) {
930 // When no Content-length (default value == -1), attempt to read a byte from the
931 // response. Do not use available() as it is unreliable. See http://b/33498325.
932 if (urlConnection.getInputStream().read() == -1) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900933 validationLog(
934 probeType, url, "Empty 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +0900935 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900936 }
937 }
Paul Jensen8fe17422015-02-02 11:03:03 -0500938 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400939 } catch (IOException e) {
Hugo Benichia4158702017-04-10 17:08:06 +0900940 validationLog(probeType, url, "Probe failed with exception " + e);
941 if (httpResponseCode == CaptivePortalProbeResult.FAILED_CODE) {
Paul Jensen869868be2014-05-15 10:33:05 -0400942 // TODO: Ping gateway and DNS server and log results.
943 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400944 } finally {
945 if (urlConnection != null) {
946 urlConnection.disconnect();
947 }
Jeff Sharkey619a5112017-01-19 11:55:54 -0700948 TrafficStats.setThreadStatsTag(oldTag);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400949 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900950 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900951 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400952 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400953
Hugo Benichid953bf82016-09-27 09:22:35 +0900954 private CaptivePortalProbeResult sendParallelHttpProbes(
Hugo Benichieef918a2017-04-10 17:43:08 +0900955 ProxyInfo proxy, URL httpsUrl, URL httpUrl) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900956 // Number of probes to wait for. If a probe completes with a conclusive answer
957 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900958 final CountDownLatch latch = new CountDownLatch(2);
959
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900960 final class ProbeThread extends Thread {
961 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900962 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900963
964 public ProbeThread(boolean isHttps) {
965 mIsHttps = isHttps;
966 }
967
Hugo Benichid953bf82016-09-27 09:22:35 +0900968 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900969 return mResult;
970 }
971
972 @Override
973 public void run() {
974 if (mIsHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900975 mResult =
976 sendDnsAndHttpProbes(proxy, httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900977 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900978 mResult = sendDnsAndHttpProbes(proxy, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900979 }
980 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900981 // Stop waiting immediately if https succeeds or if http finds a portal.
982 while (latch.getCount() > 0) {
983 latch.countDown();
984 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900985 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900986 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900987 latch.countDown();
988 }
989 }
990
Hugo Benichid953bf82016-09-27 09:22:35 +0900991 final ProbeThread httpsProbe = new ProbeThread(true);
992 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900993
994 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900995 httpsProbe.start();
996 httpProbe.start();
997 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900998 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900999 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001000 return CaptivePortalProbeResult.FAILED;
1001 }
1002
Hugo Benichid953bf82016-09-27 09:22:35 +09001003 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
1004 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001005
Hugo Benichid953bf82016-09-27 09:22:35 +09001006 // Look for a conclusive probe result first.
1007 if (httpResult.isPortal()) {
1008 return httpResult;
1009 }
1010 // httpsResult.isPortal() is not expected, but check it nonetheless.
1011 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
1012 return httpsResult;
1013 }
Hugo Benichieef918a2017-04-10 17:43:08 +09001014 // If a fallback url exists, use a fallback probe to try again portal detection.
1015 URL fallbackUrl = nextFallbackUrl();
Hugo Benichid953bf82016-09-27 09:22:35 +09001016 if (fallbackUrl != null) {
1017 CaptivePortalProbeResult result =
1018 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
1019 if (result.isPortal()) {
1020 return result;
1021 }
1022 }
Hugo Benichifc474422017-05-17 10:30:40 +09001023 // Otherwise wait until http and https probes completes and use their results.
Hugo Benichid953bf82016-09-27 09:22:35 +09001024 try {
Hugo Benichifc474422017-05-17 10:30:40 +09001025 httpProbe.join();
1026 if (httpProbe.result().isPortal()) {
1027 return httpProbe.result();
1028 }
Hugo Benichid953bf82016-09-27 09:22:35 +09001029 httpsProbe.join();
Hugo Benichifc474422017-05-17 10:30:40 +09001030 return httpsProbe.result();
Hugo Benichid953bf82016-09-27 09:22:35 +09001031 } catch (InterruptedException e) {
Hugo Benichifc474422017-05-17 10:30:40 +09001032 validationLog("Error: http or https probe wait interrupted!");
Hugo Benichid953bf82016-09-27 09:22:35 +09001033 return CaptivePortalProbeResult.FAILED;
1034 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001035 }
1036
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001037 private URL makeURL(String url) {
1038 if (url != null) {
1039 try {
1040 return new URL(url);
1041 } catch (MalformedURLException e) {
1042 validationLog("Bad URL: " + url);
1043 }
1044 }
1045 return null;
1046 }
1047
Paul Jensen306f1a42014-08-04 10:59:01 -04001048 /**
1049 * @param responseReceived - whether or not we received a valid HTTP response to our request.
1050 * If false, isCaptivePortal and responseTimestampMs are ignored
1051 * TODO: This should be moved to the transports. The latency could be passed to the transports
1052 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
1053 * perhaps this could just be added to the WiFi transport only.
1054 */
1055 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
1056 long requestTimestampMs, long responseTimestampMs) {
Hugo Benichic894b122017-07-31 12:58:20 +09001057 if (getWifiScansAlwaysAvailableDisabled()) {
Paul Jensen306f1a42014-08-04 10:59:01 -04001058 return;
1059 }
1060
Hugo Benichic894b122017-07-31 12:58:20 +09001061 if (!systemReady) {
1062 return;
1063 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001064
Paul Jensen306f1a42014-08-04 10:59:01 -04001065 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
1066 switch (mNetworkAgentInfo.networkInfo.getType()) {
1067 case ConnectivityManager.TYPE_WIFI:
1068 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
1069 if (currentWifiInfo != null) {
1070 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
1071 // surrounded by double quotation marks (thus violating the Javadoc), but this
1072 // was changed to match the Javadoc in API 17. Since clients may have started
1073 // sanitizing the output of this method since API 17 was released, we should
1074 // not change it here as it would become impossible to tell whether the SSID is
1075 // simply being surrounded by quotes due to the API, or whether those quotes
1076 // are actually part of the SSID.
1077 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
1078 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
1079 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001080 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -04001081 return;
1082 }
1083 break;
1084 case ConnectivityManager.TYPE_MOBILE:
1085 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
1086 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
1087 if (info == null) return;
1088 int numRegisteredCellInfo = 0;
1089 for (CellInfo cellInfo : info) {
1090 if (cellInfo.isRegistered()) {
1091 numRegisteredCellInfo++;
1092 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001093 if (VDBG) logw("more than one registered CellInfo." +
1094 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -04001095 return;
1096 }
1097 if (cellInfo instanceof CellInfoCdma) {
1098 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
1099 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1100 } else if (cellInfo instanceof CellInfoGsm) {
1101 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
1102 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1103 } else if (cellInfo instanceof CellInfoLte) {
1104 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
1105 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1106 } else if (cellInfo instanceof CellInfoWcdma) {
1107 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
1108 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1109 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001110 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -04001111 return;
1112 }
1113 }
1114 }
1115 break;
1116 default:
1117 return;
1118 }
1119 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
1120 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
1121 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
1122
1123 if (responseReceived) {
1124 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
1125 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
1126 }
Paul Jensen55298582014-08-20 11:01:41 -04001127 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
1128 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001129 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001130
Hugo Benichicfddd682016-05-31 16:28:06 +09001131 private void logNetworkEvent(int evtype) {
1132 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
1133 }
1134
Hugo Benichidd229822016-11-15 23:23:24 +09001135 private int networkEventType(ValidationStage s, EvaluationResult r) {
1136 if (s.isFirstValidation) {
1137 if (r.isValidated) {
1138 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS;
1139 } else {
1140 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND;
1141 }
1142 } else {
1143 if (r.isValidated) {
1144 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS;
1145 } else {
1146 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND;
1147 }
1148 }
1149 }
1150
Hugo Benichicfddd682016-05-31 16:28:06 +09001151 private void maybeLogEvaluationResult(int evtype) {
1152 if (mEvaluationTimer.isRunning()) {
1153 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
1154 mEvaluationTimer.reset();
1155 }
1156 }
1157
1158 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
Hugo Benichia365bac2017-03-22 18:29:58 +09001159 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
Hugo Benichif927f0c2017-03-17 15:42:40 +09001160 boolean isFirstValidation = validationStage().isFirstValidation;
1161 ValidationProbeEvent ev = new ValidationProbeEvent();
1162 ev.probeType = ValidationProbeEvent.makeProbeType(probeType, isFirstValidation);
1163 ev.returnCode = probeResult;
1164 ev.durationMs = durationMs;
1165 mMetricsLog.log(mNetId, transports, ev);
Hugo Benichicfddd682016-05-31 16:28:06 +09001166 }
Hugo Benichic894b122017-07-31 12:58:20 +09001167
1168 @VisibleForTesting
1169 public interface NetworkMonitorSettings {
1170 int getSetting(Context context, String symbol, int defaultValue);
1171 String getSetting(Context context, String symbol, String defaultValue);
1172
1173 static NetworkMonitorSettings DEFAULT = new DefaultNetworkMonitorSettings();
1174 }
1175
1176 @VisibleForTesting
1177 public static class DefaultNetworkMonitorSettings implements NetworkMonitorSettings {
1178 public int getSetting(Context context, String symbol, int defaultValue) {
1179 return Settings.Global.getInt(context.getContentResolver(), symbol, defaultValue);
1180 }
1181
1182 public String getSetting(Context context, String symbol, String defaultValue) {
1183 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
1184 return value != null ? value : defaultValue;
1185 }
1186 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001187}