blob: c2f4406c615d98ba89a500eeb089bde28f401e1e [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;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +090022import static android.net.ConnectivityManager.EXTRA_CAPTIVE_PORTAL_PROBE_SPEC;
23import static android.net.ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +090024import static android.net.metrics.ValidationProbeEvent.DNS_FAILURE;
25import static android.net.metrics.ValidationProbeEvent.DNS_SUCCESS;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +090026import static android.net.metrics.ValidationProbeEvent.PROBE_FALLBACK;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +090027import static android.net.metrics.ValidationProbeEvent.PROBE_PRIVDNS;
Paul Jensen49e3edf2015-05-22 10:50:39 -040028
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +090029import android.annotation.Nullable;
Paul Jensen869868be2014-05-15 10:33:05 -040030import android.app.PendingIntent;
31import android.content.BroadcastReceiver;
Paul Jensenca8f16a2014-05-09 12:47:55 -040032import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040033import android.content.Intent;
34import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040035import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040036import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040037import android.net.ICaptivePortal;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +090038import android.net.Network;
Erik Klinea24d4592018-01-11 21:07:29 +090039import android.net.NetworkCapabilities;
Paul Jensen2c311d62014-11-17 12:34:51 -050040import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050041import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040042import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040043import android.net.Uri;
Remi NGUYEN VANd57329d2018-05-22 09:58:19 +090044import android.net.captiveportal.CaptivePortalProbeResult;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +090045import android.net.captiveportal.CaptivePortalProbeSpec;
Hugo Benichicfddd682016-05-31 16:28:06 +090046import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090047import android.net.metrics.NetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090048import android.net.metrics.ValidationProbeEvent;
Hugo Benichid953bf82016-09-27 09:22:35 +090049import android.net.util.Stopwatch;
Paul Jensen306f1a42014-08-04 10:59:01 -040050import android.net.wifi.WifiInfo;
51import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040052import android.os.Handler;
53import android.os.Message;
Paul Jensen306f1a42014-08-04 10:59:01 -040054import android.os.SystemClock;
Paul Jensen869868be2014-05-15 10:33:05 -040055import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040056import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040057import android.telephony.CellIdentityCdma;
58import android.telephony.CellIdentityGsm;
59import android.telephony.CellIdentityLte;
60import android.telephony.CellIdentityWcdma;
61import android.telephony.CellInfo;
62import android.telephony.CellInfoCdma;
63import android.telephony.CellInfoGsm;
64import android.telephony.CellInfoLte;
65import android.telephony.CellInfoWcdma;
66import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040067import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070068import android.util.LocalLog;
69import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050070import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071
Paul Jensend7b6ca92015-05-13 14:05:12 -040072import com.android.internal.annotations.VisibleForTesting;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +090073import com.android.internal.util.ArrayUtils;
Paul Jensenca8f16a2014-05-09 12:47:55 -040074import com.android.internal.util.Protocol;
Chiachang Wang7a70a7e2018-11-27 18:00:05 +080075import com.android.internal.util.RingBufferIndices;
Paul Jensenca8f16a2014-05-09 12:47:55 -040076import com.android.internal.util.State;
77import com.android.internal.util.StateMachine;
Erik Kline736353a2018-03-21 07:18:33 -070078import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Paul Jensenca8f16a2014-05-09 12:47:55 -040079
Paul Jensenca8f16a2014-05-09 12:47:55 -040080import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040081import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040082import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090083import java.net.MalformedURLException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040084import java.net.URL;
Hugo Benichid953bf82016-09-27 09:22:35 +090085import java.net.UnknownHostException;
Hugo Benichieef918a2017-04-10 17:43:08 +090086import java.util.ArrayList;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +090087import java.util.Arrays;
88import java.util.Collections;
89import java.util.LinkedHashMap;
Paul Jensen306f1a42014-08-04 10:59:01 -040090import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040091import java.util.Random;
Erik Kline736353a2018-03-21 07:18:33 -070092import java.util.UUID;
Hugo Benichid953bf82016-09-27 09:22:35 +090093import java.util.concurrent.CountDownLatch;
94import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040095
96/**
97 * {@hide}
98 */
99public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +0900100 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900101 private static final boolean DBG = true;
102 private static final boolean VDBG = false;
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800103 private static final boolean VDBG_STALL = Log.isLoggable(TAG, Log.DEBUG);
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900104 // Default configuration values for captive portal detection probes.
105 // TODO: append a random length parameter to the default HTTPS url.
106 // TODO: randomize browser version ids in the default User-Agent String.
107 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900108 private static final String DEFAULT_HTTP_URL =
109 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900110 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
Hugo Benichieef918a2017-04-10 17:43:08 +0900111 private static final String DEFAULT_OTHER_FALLBACK_URLS =
112 "http://play.googleapis.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900113 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
114 + "AppleWebKit/537.36 (KHTML, like Gecko) "
Lorenzo Colittid8a06082017-06-28 23:39:40 +0900115 + "Chrome/60.0.3112.32 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900116
Paul Jensenca8f16a2014-05-09 12:47:55 -0400117 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900118 private static final int PROBE_TIMEOUT_MS = 3000;
119
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800120 // Default configuration values for data stall detection.
121 private static final int DEFAULT_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD = 5;
122 private static final int DEFAULT_DATA_STALL_MIN_EVALUATE_TIME_MS = 60 * 1000;
123 private static final int DEFAULT_DATA_STALL_VALID_DNS_TIME_THRESHOLD_MS = 30 * 60 * 1000;
124
125 private static final int DATA_STALL_EVALUATION_TYPE_DNS = 1;
126 private static final int DEFAULT_DATA_STALL_EVALUATION_TYPES =
127 (1 << DATA_STALL_EVALUATION_TYPE_DNS);
128
Hugo Benichidd229822016-11-15 23:23:24 +0900129 static enum EvaluationResult {
130 VALIDATED(true),
131 CAPTIVE_PORTAL(false);
132 final boolean isValidated;
133 EvaluationResult(boolean isValidated) {
134 this.isValidated = isValidated;
135 }
136 }
137
138 static enum ValidationStage {
139 FIRST_VALIDATION(true),
140 REVALIDATION(false);
141 final boolean isFirstValidation;
142 ValidationStage(boolean isFirstValidation) {
143 this.isFirstValidation = isFirstValidation;
144 }
145 }
146
Paul Jensenad50a1f2014-09-05 12:06:44 -0400147 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
148 // The network should be used as a default internet connection. It was found to be:
149 // 1. a functioning network providing internet access, or
150 // 2. a captive portal and the user decided to use it as is.
151 public static final int NETWORK_TEST_RESULT_VALID = 0;
152 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
153 // The network should not be used as a default internet connection. It was found to be:
154 // 1. a captive portal and the user is prompted to sign-in, or
155 // 2. a captive portal and the user did not want to use it, or
156 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
157 public static final int NETWORK_TEST_RESULT_INVALID = 1;
158
Paul Jensenca8f16a2014-05-09 12:47:55 -0400159 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
160
161 /**
162 * Inform NetworkMonitor that their network is connected.
163 * Initiates Network Validation.
164 */
165 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
166
167 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400168 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400169 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400170 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400171 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400172 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400173 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400174
175 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400176 * Message to self indicating it's time to evaluate a network's connectivity.
177 * arg1 = Token to ignore old messages.
178 */
Paul Jensen869868be2014-05-15 10:33:05 -0400179 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400180
181 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400182 * Inform NetworkMonitor that the network has disconnected.
183 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400184 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400185
186 /**
187 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400188 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400189 */
Erik Kline736353a2018-03-21 07:18:33 -0700190 private static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400191
192 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400193 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400194 * arg1 = one of: APP_RETURN_DISMISSED,
195 * APP_RETURN_UNWANTED,
196 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500197 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400198 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400199 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400200
201 /**
202 * Request ConnectivityService display provisioning notification.
203 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400204 * arg2 = NetID.
205 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400206 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400207 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400208
209 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900210 * Message indicating sign-in app should be launched.
Paul Jensen25a217c2015-02-27 22:55:47 -0500211 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900212 * user touches the sign in notification, or sent by
213 * ConnectivityService when the user touches the "sign into
214 * network" button in the wifi access point detail page.
Paul Jensen869868be2014-05-15 10:33:05 -0400215 */
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900216 public static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400217
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400218 /**
219 * Retest network to see if captive portal is still in place.
220 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
221 * 0 indicates self-initiated, so nobody to blame.
222 */
223 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
224
Erik Klinea24d4592018-01-11 21:07:29 +0900225 /**
226 * ConnectivityService notifies NetworkMonitor of settings changes to
227 * Private DNS. If a DNS resolution is required, e.g. for DNS-over-TLS in
228 * strict mode, then an event is sent back to ConnectivityService with the
229 * result of the resolution attempt.
Erik Kline736353a2018-03-21 07:18:33 -0700230 *
231 * A separate message is used to trigger (re)evaluation of the Private DNS
232 * configuration, so that the message can be handled as needed in different
233 * states, including being ignored until after an ongoing captive portal
234 * validation phase is completed.
Erik Klinea24d4592018-01-11 21:07:29 +0900235 */
236 private static final int CMD_PRIVATE_DNS_SETTINGS_CHANGED = BASE + 13;
237 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = BASE + 14;
Erik Kline736353a2018-03-21 07:18:33 -0700238 private static final int CMD_EVALUATE_PRIVATE_DNS = BASE + 15;
Erik Klinea24d4592018-01-11 21:07:29 +0900239
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800240 /**
241 * Message to self indicating captive portal detection is completed.
242 * obj = CaptivePortalProbeResult for detection result;
243 */
244 public static final int CMD_PROBE_COMPLETE = BASE + 16;
245
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800246 /**
247 * ConnectivityService notifies NetworkMonitor of DNS query responses event.
248 * arg1 = returncode in OnDnsEvent which indicates the response code for the DNS query.
249 */
250 public static final int EVENT_DNS_NOTIFICATION = BASE + 17;
251
Paul Jensend0491e9a2015-05-05 14:52:22 -0400252 // Start mReevaluateDelayMs at this value and double.
253 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
254 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
255 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
256 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400257 private int mReevaluateToken = 0;
Erik Kline736353a2018-03-21 07:18:33 -0700258 private static final int NO_UID = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400259 private static final int INVALID_UID = -1;
260 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400261 // Stop blaming UID that requested re-evaluation after this many attempts.
262 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400263 // Delay between reevaluations once a captive portal has been found.
264 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400265
Hugo Benichic894b122017-07-31 12:58:20 +0900266 private static final int NUM_VALIDATION_LOG_LINES = 20;
267
Erik Kline736353a2018-03-21 07:18:33 -0700268 private String mPrivateDnsProviderHostname = "";
269
Erik Klinea24d4592018-01-11 21:07:29 +0900270 public static boolean isValidationRequired(
271 NetworkCapabilities dfltNetCap, NetworkCapabilities nc) {
272 // TODO: Consider requiring validation for DUN networks.
273 return dfltNetCap.satisfiedByNetworkCapabilities(nc);
274 }
275
Paul Jensenca8f16a2014-05-09 12:47:55 -0400276 private final Context mContext;
277 private final Handler mConnectivityServiceHandler;
278 private final NetworkAgentInfo mNetworkAgentInfo;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900279 private final Network mNetwork;
Erik Klinea488c232016-04-15 15:49:42 +0900280 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400281 private final TelephonyManager mTelephonyManager;
282 private final WifiManager mWifiManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500283 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900284 private final IpConnectivityLog mMetricsLog;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900285 private final Dependencies mDependencies;
Hugo Benichic894b122017-07-31 12:58:20 +0900286
287 // Configuration values for captive portal detection probes.
288 private final String mCaptivePortalUserAgent;
289 private final URL mCaptivePortalHttpsUrl;
290 private final URL mCaptivePortalHttpUrl;
291 private final URL[] mCaptivePortalFallbackUrls;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900292 @Nullable
293 private final CaptivePortalProbeSpec[] mCaptivePortalFallbackSpecs;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400294
Calvin On4bc78eb2016-10-11 15:10:46 -0700295 @VisibleForTesting
296 protected boolean mIsCaptivePortalCheckEnabled;
297
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900298 private boolean mUseHttps;
Hugo Benichidd229822016-11-15 23:23:24 +0900299 // The total number of captive portal detection attempts for this NetworkMonitor instance.
300 private int mValidations = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301
Paul Jensenad50a1f2014-09-05 12:06:44 -0400302 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
303 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400304 // Avoids surfacing "Sign in to network" notification.
305 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400306
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700307 public boolean systemReady = false;
308
Paul Jensen71b645f2014-10-13 14:13:07 -0400309 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400310 private final State mValidatedState = new ValidatedState();
311 private final State mMaybeNotifyState = new MaybeNotifyState();
312 private final State mEvaluatingState = new EvaluatingState();
313 private final State mCaptivePortalState = new CaptivePortalState();
Erik Kline736353a2018-03-21 07:18:33 -0700314 private final State mEvaluatingPrivateDnsState = new EvaluatingPrivateDnsState();
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800315 private final State mProbingState = new ProbingState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400316
Paul Jensen25a217c2015-02-27 22:55:47 -0500317 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400318
Hugo Benichic894b122017-07-31 12:58:20 +0900319 private final LocalLog validationLogs = new LocalLog(NUM_VALIDATION_LOG_LINES);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700320
Erik Klinea488c232016-04-15 15:49:42 +0900321 private final Stopwatch mEvaluationTimer = new Stopwatch();
322
Hugo Benichid953bf82016-09-27 09:22:35 +0900323 // This variable is set before transitioning to the mCaptivePortalState.
324 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
325
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900326 // Random generator to select fallback URL index
327 private final Random mRandom;
Hugo Benichieef918a2017-04-10 17:43:08 +0900328 private int mNextFallbackUrlIndex = 0;
Hugo Benichib03272c2017-04-10 22:45:13 +0900329
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800330 private int mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
331 private int mEvaluateAttempts = 0;
Chiachang Wang30cc3672018-11-12 10:52:25 +0800332 private volatile int mProbeToken = 0;
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800333 private final int mConsecutiveDnsTimeoutThreshold;
334 private final int mDataStallMinEvaluateTime;
335 private final int mDataStallValidDnsTimeThreshold;
336 private final int mDataStallEvaluationType;
337 private final DnsStallDetector mDnsStallDetector;
338 private long mLastProbeTime;
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800339
Paul Jensen2c311d62014-11-17 12:34:51 -0500340 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
341 NetworkRequest defaultRequest) {
Hugo Benichic894b122017-07-31 12:58:20 +0900342 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog(),
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900343 Dependencies.DEFAULT);
Hugo Benichif9fdf872016-07-28 17:53:06 +0900344 }
345
346 @VisibleForTesting
347 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900348 NetworkRequest defaultRequest, IpConnectivityLog logger, Dependencies deps) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400349 // Add suffix indicating which NetworkMonitor we're talking about.
350 super(TAG + networkAgentInfo.name());
351
Erik Kline736353a2018-03-21 07:18:33 -0700352 // Logs with a tag of the form given just above, e.g.
353 // <timestamp> 862 2402 D NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: ...
354 setDbg(VDBG);
355
Paul Jensenca8f16a2014-05-09 12:47:55 -0400356 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900357 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400358 mConnectivityServiceHandler = handler;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900359 mDependencies = deps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400360 mNetworkAgentInfo = networkAgentInfo;
Erik Klinef4fa9822018-04-27 22:48:33 +0900361 mNetwork = deps.getNetwork(networkAgentInfo).getPrivateDnsBypassingCopy();
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900362 mNetId = mNetwork.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400363 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
364 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500365 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400366
367 addState(mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400368 addState(mMaybeNotifyState, mDefaultState);
369 addState(mEvaluatingState, mMaybeNotifyState);
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800370 addState(mProbingState, mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400371 addState(mCaptivePortalState, mMaybeNotifyState);
Erik Kline736353a2018-03-21 07:18:33 -0700372 addState(mEvaluatingPrivateDnsState, mDefaultState);
373 addState(mValidatedState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700374 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400375
Hugo Benichic894b122017-07-31 12:58:20 +0900376 mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
377 mUseHttps = getUseHttpsValidation();
378 mCaptivePortalUserAgent = getCaptivePortalUserAgent();
379 mCaptivePortalHttpsUrl = makeURL(getCaptivePortalServerHttpsUrl());
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900380 mCaptivePortalHttpUrl = makeURL(getCaptivePortalServerHttpUrl(deps, context));
Hugo Benichic894b122017-07-31 12:58:20 +0900381 mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls();
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900382 mCaptivePortalFallbackSpecs = makeCaptivePortalFallbackProbeSpecs();
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900383 mRandom = deps.getRandom();
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800384 // TODO: Evaluate to move data stall configuration to a specific class.
385 mConsecutiveDnsTimeoutThreshold = getConsecutiveDnsTimeoutThreshold();
386 mDnsStallDetector = new DnsStallDetector(mConsecutiveDnsTimeoutThreshold);
387 mDataStallMinEvaluateTime = getDataStallMinEvaluateTime();
388 mDataStallValidDnsTimeThreshold = getDataStallValidDnsTimeThreshold();
389 mDataStallEvaluationType = getDataStallEvalutionType();
Hugo Benichib03272c2017-04-10 22:45:13 +0900390
Paul Jensenca8f16a2014-05-09 12:47:55 -0400391 start();
392 }
393
Erik Kline736353a2018-03-21 07:18:33 -0700394 public void forceReevaluation(int responsibleUid) {
395 sendMessage(CMD_FORCE_REEVALUATION, responsibleUid, 0);
396 }
397
398 public void notifyPrivateDnsSettingsChanged(PrivateDnsConfig newCfg) {
399 // Cancel any outstanding resolutions.
400 removeMessages(CMD_PRIVATE_DNS_SETTINGS_CHANGED);
401 // Send the update to the proper thread.
402 sendMessage(CMD_PRIVATE_DNS_SETTINGS_CHANGED, newCfg);
403 }
404
Paul Jensen532b61432014-11-10 09:50:02 -0500405 @Override
406 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400407 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500408 }
409
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900410 private void validationLog(int probeType, Object url, String msg) {
411 String probeName = ValidationProbeEvent.getProbeName(probeType);
412 validationLog(String.format("%s %s %s", probeName, url, msg));
413 }
414
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700415 private void validationLog(String s) {
416 if (DBG) log(s);
417 validationLogs.log(s);
418 }
419
420 public ReadOnlyLocalLog getValidationLogs() {
421 return validationLogs.readOnlyLocalLog();
422 }
423
Hugo Benichidd229822016-11-15 23:23:24 +0900424 private ValidationStage validationStage() {
425 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION;
426 }
427
Erik Klinea24d4592018-01-11 21:07:29 +0900428 private boolean isValidationRequired() {
429 return isValidationRequired(
430 mDefaultRequest.networkCapabilities, mNetworkAgentInfo.networkCapabilities);
431 }
432
Erik Kline736353a2018-03-21 07:18:33 -0700433
434 private void notifyNetworkTestResultInvalid(Object obj) {
435 mConnectivityServiceHandler.sendMessage(obtainMessage(
436 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId, obj));
437 }
438
Paul Jensen71b645f2014-10-13 14:13:07 -0400439 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
440 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400441 private class DefaultState extends State {
442 @Override
443 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400444 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400445 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900446 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400447 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400448 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400449 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900450 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500451 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
452 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
453 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400454 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700455 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400456 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400457 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400458 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400459 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400460 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400461 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400462 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400463 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400464 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900465
466 // If the user has seen and acted on a captive portal notification, and the
467 // captive portal app is now closed, disable HTTPS probes. This avoids the
468 // following pathological situation:
469 //
470 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
471 // 2. User opens the app and logs into the captive portal.
472 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
473 // perhaps due to the network blocking HTTPS?
474 //
475 // In this case, we'll fail to validate the network even after the app is
476 // dismissed. There is now no way to use this network, because the app is now
477 // gone, so the user cannot select "Use this network as is".
478 mUseHttps = false;
479
Paul Jensen71b645f2014-10-13 14:13:07 -0400480 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400481 case APP_RETURN_DISMISSED:
Erik Kline736353a2018-03-21 07:18:33 -0700482 sendMessage(CMD_FORCE_REEVALUATION, NO_UID, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500483 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400484 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400485 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500486 // TODO: Distinguish this from a network that actually validates.
Erik Kline736353a2018-03-21 07:18:33 -0700487 // Displaying the "x" on the system UI icon may still be a good idea.
488 transitionTo(mEvaluatingPrivateDnsState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400489 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400490 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400491 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400492 mUserDoesNotWant = true;
Erik Kline736353a2018-03-21 07:18:33 -0700493 notifyNetworkTestResultInvalid(null);
Paul Jensen71b645f2014-10-13 14:13:07 -0400494 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400495 mUidResponsibleForReeval = 0;
496 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400497 break;
498 }
499 return HANDLED;
Erik Kline736353a2018-03-21 07:18:33 -0700500 case CMD_PRIVATE_DNS_SETTINGS_CHANGED: {
501 final PrivateDnsConfig cfg = (PrivateDnsConfig) message.obj;
502 if (!isValidationRequired() || cfg == null || !cfg.inStrictMode()) {
503 // No DNS resolution required.
504 //
505 // We don't force any validation in opportunistic mode
506 // here. Opportunistic mode nameservers are validated
507 // separately within netd.
508 //
509 // Reset Private DNS settings state.
510 mPrivateDnsProviderHostname = "";
511 break;
Erik Klinea24d4592018-01-11 21:07:29 +0900512 }
Erik Kline736353a2018-03-21 07:18:33 -0700513
514 mPrivateDnsProviderHostname = cfg.hostname;
515
516 // DNS resolutions via Private DNS strict mode block for a
517 // few seconds (~4.2) checking for any IP addresses to
518 // arrive and validate. Initiating a (re)evaluation now
519 // should not significantly alter the validation outcome.
520 //
521 // No matter what: enqueue a validation request; one of
522 // three things can happen with this request:
523 // [1] ignored (EvaluatingState or CaptivePortalState)
524 // [2] transition to EvaluatingPrivateDnsState
525 // (DefaultState and ValidatedState)
526 // [3] handled (EvaluatingPrivateDnsState)
527 //
528 // The Private DNS configuration to be evaluated will:
529 // [1] be skipped (not in strict mode), or
530 // [2] validate (huzzah), or
531 // [3] encounter some problem (invalid hostname,
532 // no resolved IP addresses, IPs unreachable,
533 // port 853 unreachable, port 853 is not running a
534 // DNS-over-TLS server, et cetera).
535 sendMessage(CMD_EVALUATE_PRIVATE_DNS);
536 break;
537 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800538 case EVENT_DNS_NOTIFICATION:
539 mDnsStallDetector.accumulateConsecutiveDnsTimeoutCount(message.arg1);
540 break;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400541 default:
Erik Kline736353a2018-03-21 07:18:33 -0700542 break;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400543 }
Erik Kline736353a2018-03-21 07:18:33 -0700544 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400545 }
546 }
547
Paul Jensen71b645f2014-10-13 14:13:07 -0400548 // Being in the ValidatedState State indicates a Network is:
549 // - Successfully validated, or
550 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400551 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400552 private class ValidatedState extends State {
553 @Override
554 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900555 maybeLogEvaluationResult(
556 networkEventType(validationStage(), EvaluationResult.VALIDATED));
Paul Jensenad50a1f2014-09-05 12:06:44 -0400557 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Kline736353a2018-03-21 07:18:33 -0700558 NETWORK_TEST_RESULT_VALID, mNetId, null));
Hugo Benichidd229822016-11-15 23:23:24 +0900559 mValidations++;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400560 }
561
562 @Override
563 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400564 switch (message.what) {
565 case CMD_NETWORK_CONNECTED:
566 transitionTo(mValidatedState);
Erik Kline736353a2018-03-21 07:18:33 -0700567 break;
568 case CMD_EVALUATE_PRIVATE_DNS:
569 transitionTo(mEvaluatingPrivateDnsState);
570 break;
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800571 case EVENT_DNS_NOTIFICATION:
572 mDnsStallDetector.accumulateConsecutiveDnsTimeoutCount(message.arg1);
573 if (isDataStall()) {
574 validationLog("Suspecting data stall, reevaluate");
575 transitionTo(mEvaluatingState);
576 }
577 break;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400578 default:
579 return NOT_HANDLED;
580 }
Erik Kline736353a2018-03-21 07:18:33 -0700581 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400582 }
583 }
584
Paul Jensen71b645f2014-10-13 14:13:07 -0400585 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
586 // is required. This State takes care to clear the notification upon exit from the State.
587 private class MaybeNotifyState extends State {
588 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500589 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500590 switch (message.what) {
591 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
592 final Intent intent = new Intent(
593 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900594 // OneAddressPerFamilyNetwork is not parcelable across processes.
595 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, new Network(mNetwork));
Paul Jensen49e3edf2015-05-22 10:50:39 -0400596 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
597 new CaptivePortal(new ICaptivePortal.Stub() {
598 @Override
599 public void appResponse(int response) {
600 if (response == APP_RETURN_WANTED_AS_IS) {
601 mContext.enforceCallingPermission(
602 android.Manifest.permission.CONNECTIVITY_INTERNAL,
603 "CaptivePortal");
604 }
605 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
606 }
607 }));
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900608 final CaptivePortalProbeResult probeRes = mLastPortalProbeResult;
609 intent.putExtra(EXTRA_CAPTIVE_PORTAL_URL, probeRes.detectUrl);
610 if (probeRes.probeSpec != null) {
611 final String encodedSpec = probeRes.probeSpec.getEncodedSpec();
612 intent.putExtra(EXTRA_CAPTIVE_PORTAL_PROBE_SPEC, encodedSpec);
613 }
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900614 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
Hugo Benichieef918a2017-04-10 17:43:08 +0900615 mCaptivePortalUserAgent);
Paul Jensen25a217c2015-02-27 22:55:47 -0500616 intent.setFlags(
617 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
618 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
619 return HANDLED;
620 default:
621 return NOT_HANDLED;
622 }
623 }
624
625 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400626 public void exit() {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900627 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0, mNetId, null);
Paul Jensen71b645f2014-10-13 14:13:07 -0400628 mConnectivityServiceHandler.sendMessage(message);
629 }
630 }
631
632 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400633 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400634 private class EvaluatingState extends State {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400635 @Override
636 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900637 // If we have already started to track time spent in EvaluatingState
638 // don't reset the timer due simply to, say, commands or events that
639 // cause us to exit and re-enter EvaluatingState.
640 if (!mEvaluationTimer.isStarted()) {
641 mEvaluationTimer.start();
642 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400643 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400644 if (mUidResponsibleForReeval != INVALID_UID) {
645 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
646 mUidResponsibleForReeval = INVALID_UID;
647 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400648 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800649 mEvaluateAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400650 }
651
652 @Override
653 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400654 switch (message.what) {
655 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400656 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400657 return HANDLED;
Erik Kline736353a2018-03-21 07:18:33 -0700658 // Don't bother validating networks that don't satisfy the default request.
Paul Jensen2c311d62014-11-17 12:34:51 -0500659 // This includes:
660 // - VPNs which can be considered explicitly desired by the user and the
661 // user's desire trumps whether the network validates.
Erik Kline736353a2018-03-21 07:18:33 -0700662 // - Networks that don't provide Internet access. It's unclear how to
Paul Jensen2c311d62014-11-17 12:34:51 -0500663 // validate such networks.
664 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
665 // such networks and the user didn't express interest in connecting to
666 // such networks (an app did) so the user may be unhappily surprised when
667 // asked to sign-in to a network they didn't want to connect to in the
668 // first place. Validation could be done to adjust the network scores
669 // however these networks are app-requested and may not be intended for
670 // general usage, in which case general validation may not be an accurate
671 // measure of the network's quality. Only the app knows how to evaluate
672 // the network so don't bother validating here. Furthermore sending HTTP
673 // packets over the network may be undesirable, for example an extremely
674 // expensive metered network, or unwanted leaking of the User Agent string.
Erik Klinea24d4592018-01-11 21:07:29 +0900675 if (!isValidationRequired()) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900676 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400677 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400678 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400679 }
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800680 mEvaluateAttempts++;
681
682 transitionTo(mProbingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400683 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400684 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400685 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
686 // ignore any re-evaluation requests. After, restart the
687 // evaluation process via EvaluatingState#enter.
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800688 return (mEvaluateAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400689 default:
690 return NOT_HANDLED;
691 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400692 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400693
694 @Override
695 public void exit() {
696 TrafficStats.clearThreadStatsUid();
697 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400698 }
699
Paul Jensendcbe8352014-09-16 16:28:34 -0400700 // BroadcastReceiver that waits for a particular Intent and then posts a message.
701 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400702 private final int mToken;
703 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400704 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400705 CustomIntentReceiver(String action, int token, int what) {
706 mToken = token;
707 mWhat = what;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900708 mAction = action + "_" + mNetId + "_" + token;
Paul Jensendcbe8352014-09-16 16:28:34 -0400709 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400710 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400711 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500712 final Intent intent = new Intent(mAction);
713 intent.setPackage(mContext.getPackageName());
714 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400715 }
716 @Override
717 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400718 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400719 }
720 }
Paul Jensen869868be2014-05-15 10:33:05 -0400721
Paul Jensen71b645f2014-10-13 14:13:07 -0400722 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
723 // has been shown a notification to sign-in.
724 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500725 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
726 "android.net.netmon.launchCaptivePortalApp";
727
Paul Jensen869868be2014-05-15 10:33:05 -0400728 @Override
729 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900730 maybeLogEvaluationResult(
731 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400732 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400733 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500734 // Create a CustomIntentReceiver that sends us a
735 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
736 // touches the notification.
737 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400738 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500739 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
740 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
741 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400742 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500743 // Display the sign in notification.
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900744 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1, mNetId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500745 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400746 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400747 // Retest for captive portal occasionally.
748 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
749 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Hugo Benichidd229822016-11-15 23:23:24 +0900750 mValidations++;
Paul Jensen869868be2014-05-15 10:33:05 -0400751 }
752
753 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400754 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700755 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400756 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400757 }
758
Erik Kline736353a2018-03-21 07:18:33 -0700759 private class EvaluatingPrivateDnsState extends State {
760 private int mPrivateDnsReevalDelayMs;
761 private PrivateDnsConfig mPrivateDnsConfig;
762
763 @Override
764 public void enter() {
765 mPrivateDnsReevalDelayMs = INITIAL_REEVALUATE_DELAY_MS;
766 mPrivateDnsConfig = null;
767 sendMessage(CMD_EVALUATE_PRIVATE_DNS);
768 }
769
770 @Override
771 public boolean processMessage(Message msg) {
772 switch (msg.what) {
773 case CMD_EVALUATE_PRIVATE_DNS:
774 if (inStrictMode()) {
775 if (!isStrictModeHostnameResolved()) {
776 resolveStrictModeHostname();
777
778 if (isStrictModeHostnameResolved()) {
779 notifyPrivateDnsConfigResolved();
780 } else {
781 handlePrivateDnsEvaluationFailure();
782 break;
783 }
784 }
785
786 // Look up a one-time hostname, to bypass caching.
787 //
788 // Note that this will race with ConnectivityService
789 // code programming the DNS-over-TLS server IP addresses
790 // into netd (if invoked, above). If netd doesn't know
791 // the IP addresses yet, or if the connections to the IP
792 // addresses haven't yet been validated, netd will block
793 // for up to a few seconds before failing the lookup.
794 if (!sendPrivateDnsProbe()) {
795 handlePrivateDnsEvaluationFailure();
796 break;
797 }
798 }
799
800 // All good!
801 transitionTo(mValidatedState);
802 break;
803 default:
804 return NOT_HANDLED;
805 }
806 return HANDLED;
807 }
808
809 private boolean inStrictMode() {
810 return !TextUtils.isEmpty(mPrivateDnsProviderHostname);
811 }
812
813 private boolean isStrictModeHostnameResolved() {
814 return (mPrivateDnsConfig != null) &&
815 mPrivateDnsConfig.hostname.equals(mPrivateDnsProviderHostname) &&
816 (mPrivateDnsConfig.ips.length > 0);
817 }
818
819 private void resolveStrictModeHostname() {
820 try {
821 // Do a blocking DNS resolution using the network-assigned nameservers.
Erik Klinef4fa9822018-04-27 22:48:33 +0900822 final InetAddress[] ips = mNetwork.getAllByName(mPrivateDnsProviderHostname);
Erik Kline71d90c42018-04-19 17:58:15 +0900823 mPrivateDnsConfig = new PrivateDnsConfig(mPrivateDnsProviderHostname, ips);
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900824 validationLog("Strict mode hostname resolved: " + mPrivateDnsConfig);
Erik Kline736353a2018-03-21 07:18:33 -0700825 } catch (UnknownHostException uhe) {
826 mPrivateDnsConfig = null;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900827 validationLog("Strict mode hostname resolution failed: " + uhe.getMessage());
Erik Kline736353a2018-03-21 07:18:33 -0700828 }
829 }
830
831 private void notifyPrivateDnsConfigResolved() {
832 mConnectivityServiceHandler.sendMessage(obtainMessage(
833 EVENT_PRIVATE_DNS_CONFIG_RESOLVED, 0, mNetId, mPrivateDnsConfig));
834 }
835
836 private void handlePrivateDnsEvaluationFailure() {
837 notifyNetworkTestResultInvalid(null);
838
839 // Queue up a re-evaluation with backoff.
840 //
841 // TODO: Consider abandoning this state after a few attempts and
842 // transitioning back to EvaluatingState, to perhaps give ourselves
843 // the opportunity to (re)detect a captive portal or something.
844 sendMessageDelayed(CMD_EVALUATE_PRIVATE_DNS, mPrivateDnsReevalDelayMs);
845 mPrivateDnsReevalDelayMs *= 2;
846 if (mPrivateDnsReevalDelayMs > MAX_REEVALUATE_DELAY_MS) {
847 mPrivateDnsReevalDelayMs = MAX_REEVALUATE_DELAY_MS;
848 }
849 }
850
851 private boolean sendPrivateDnsProbe() {
852 // q.v. system/netd/server/dns/DnsTlsTransport.cpp
853 final String ONE_TIME_HOSTNAME_SUFFIX = "-dnsotls-ds.metric.gstatic.com";
854 final String host = UUID.randomUUID().toString().substring(0, 8) +
855 ONE_TIME_HOSTNAME_SUFFIX;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900856 final Stopwatch watch = new Stopwatch().start();
Erik Kline736353a2018-03-21 07:18:33 -0700857 try {
858 final InetAddress[] ips = mNetworkAgentInfo.network().getAllByName(host);
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900859 final long time = watch.stop();
860 final String strIps = Arrays.toString(ips);
861 final boolean success = (ips != null && ips.length > 0);
862 validationLog(PROBE_PRIVDNS, host, String.format("%dms: %s", time, strIps));
863 logValidationProbe(time, PROBE_PRIVDNS, success ? DNS_SUCCESS : DNS_FAILURE);
864 return success;
865 } catch (UnknownHostException uhe) {
866 final long time = watch.stop();
867 validationLog(PROBE_PRIVDNS, host,
868 String.format("%dms - Error: %s", time, uhe.getMessage()));
869 logValidationProbe(time, PROBE_PRIVDNS, DNS_FAILURE);
870 }
Erik Kline736353a2018-03-21 07:18:33 -0700871 return false;
872 }
873 }
874
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800875 private class ProbingState extends State {
876 private Thread mThread;
877
878 @Override
879 public void enter() {
Chiachang Wang30cc3672018-11-12 10:52:25 +0800880 final int token = ++mProbeToken;
881 mThread = new Thread(() -> sendMessage(obtainMessage(CMD_PROBE_COMPLETE, token, 0,
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800882 isCaptivePortal())));
883 mThread.start();
884 }
885
886 @Override
887 public boolean processMessage(Message message) {
888 switch (message.what) {
889 case CMD_PROBE_COMPLETE:
Chiachang Wang30cc3672018-11-12 10:52:25 +0800890 // Ensure that CMD_PROBE_COMPLETE from stale threads are ignored.
891 if (message.arg1 != mProbeToken) {
892 return HANDLED;
893 }
894
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800895 final CaptivePortalProbeResult probeResult =
896 (CaptivePortalProbeResult) message.obj;
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800897 mLastProbeTime = SystemClock.elapsedRealtime();
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800898 if (probeResult.isSuccessful()) {
899 // Transit EvaluatingPrivateDnsState to get to Validated
900 // state (even if no Private DNS validation required).
901 transitionTo(mEvaluatingPrivateDnsState);
902 } else if (probeResult.isPortal()) {
903 notifyNetworkTestResultInvalid(probeResult.redirectUrl);
904 mLastPortalProbeResult = probeResult;
905 transitionTo(mCaptivePortalState);
906 } else {
907 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
908 sendMessageDelayed(msg, mReevaluateDelayMs);
909 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
910 notifyNetworkTestResultInvalid(probeResult.redirectUrl);
911 if (mEvaluateAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
912 // Don't continue to blame UID forever.
913 TrafficStats.clearThreadStatsUid();
914 }
915 mReevaluateDelayMs *= 2;
916 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
917 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
918 }
919 }
920 return HANDLED;
921 case CMD_REEVALUATE:
922 // Leave the event to EvaluatingState. Defer this message will result in reset
923 // of mReevaluateDelayMs and mEvaluateAttempts.
Chiachang Wang30cc3672018-11-12 10:52:25 +0800924 case CMD_NETWORK_DISCONNECTED:
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800925 case EVENT_DNS_NOTIFICATION:
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800926 return NOT_HANDLED;
927 default:
928 // TODO: Some events may able to handle in this state, instead of deferring to
929 // next state.
930 deferMessage(message);
931 return HANDLED;
932 }
933 }
934
935 @Override
936 public void exit() {
Chiachang Wang30cc3672018-11-12 10:52:25 +0800937 if (mThread.isAlive()) {
938 mThread.interrupt();
939 }
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800940 mThread = null;
941 }
942 }
943
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900944 // Limits the list of IP addresses returned by getAllByName or tried by openConnection to at
945 // most one per address family. This ensures we only wait up to 20 seconds for TCP connections
946 // to complete, regardless of how many IP addresses a host has.
947 private static class OneAddressPerFamilyNetwork extends Network {
948 public OneAddressPerFamilyNetwork(Network network) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900949 // Always bypass Private DNS.
950 super(network.getPrivateDnsBypassingCopy());
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900951 }
952
953 @Override
954 public InetAddress[] getAllByName(String host) throws UnknownHostException {
Erik Klinef4fa9822018-04-27 22:48:33 +0900955 final List<InetAddress> addrs = Arrays.asList(super.getAllByName(host));
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900956
957 // Ensure the address family of the first address is tried first.
958 LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>();
959 addressByFamily.put(addrs.get(0).getClass(), addrs.get(0));
960 Collections.shuffle(addrs);
961
962 for (InetAddress addr : addrs) {
963 addressByFamily.put(addr.getClass(), addr);
964 }
965
966 return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]);
967 }
968 }
969
Hugo Benichic894b122017-07-31 12:58:20 +0900970 public boolean getIsCaptivePortalCheckEnabled() {
971 String symbol = Settings.Global.CAPTIVE_PORTAL_MODE;
972 int defaultValue = Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900973 int mode = mDependencies.getSetting(mContext, symbol, defaultValue);
Hugo Benichic894b122017-07-31 12:58:20 +0900974 return mode != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900975 }
976
Hugo Benichic894b122017-07-31 12:58:20 +0900977 public boolean getUseHttpsValidation() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900978 return mDependencies.getSetting(mContext, Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Hugo Benichic894b122017-07-31 12:58:20 +0900979 }
980
981 public boolean getWifiScansAlwaysAvailableDisabled() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900982 return mDependencies.getSetting(mContext, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0;
Hugo Benichic894b122017-07-31 12:58:20 +0900983 }
984
985 private String getCaptivePortalServerHttpsUrl() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900986 return mDependencies.getSetting(mContext,
Hugo Benichic894b122017-07-31 12:58:20 +0900987 Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
988 }
989
Chiachang Wang7a70a7e2018-11-27 18:00:05 +0800990 private int getConsecutiveDnsTimeoutThreshold() {
991 return mDependencies.getSetting(mContext,
992 Settings.Global.DATA_STALL_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD,
993 DEFAULT_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD);
994 }
995
996 private int getDataStallMinEvaluateTime() {
997 return mDependencies.getSetting(mContext,
998 Settings.Global.DATA_STALL_MIN_EVALUATE_INTERVAL,
999 DEFAULT_DATA_STALL_MIN_EVALUATE_TIME_MS);
1000 }
1001
1002 private int getDataStallValidDnsTimeThreshold() {
1003 return mDependencies.getSetting(mContext,
1004 Settings.Global.DATA_STALL_VALID_DNS_TIME_THRESHOLD,
1005 DEFAULT_DATA_STALL_VALID_DNS_TIME_THRESHOLD_MS);
1006 }
1007
1008 private int getDataStallEvalutionType() {
1009 return mDependencies.getSetting(mContext, Settings.Global.DATA_STALL_EVALUATION_TYPE,
1010 DEFAULT_DATA_STALL_EVALUATION_TYPES);
1011 }
1012
Hugo Benichic894b122017-07-31 12:58:20 +09001013 // Static for direct access by ConnectivityService
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001014 public static String getCaptivePortalServerHttpUrl(Context context) {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001015 return getCaptivePortalServerHttpUrl(Dependencies.DEFAULT, context);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001016 }
1017
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001018 public static String getCaptivePortalServerHttpUrl(Dependencies deps, Context context) {
1019 return deps.getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
Hugo Benichic894b122017-07-31 12:58:20 +09001020 }
1021
1022 private URL[] makeCaptivePortalFallbackUrls() {
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001023 try {
1024 String separator = ",";
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001025 String firstUrl = mDependencies.getSetting(mContext,
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001026 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001027 String joinedUrls = firstUrl + separator + mDependencies.getSetting(mContext,
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001028 Settings.Global.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS,
1029 DEFAULT_OTHER_FALLBACK_URLS);
1030 List<URL> urls = new ArrayList<>();
1031 for (String s : joinedUrls.split(separator)) {
1032 URL u = makeURL(s);
1033 if (u == null) {
1034 continue;
1035 }
1036 urls.add(u);
Hugo Benichieef918a2017-04-10 17:43:08 +09001037 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001038 if (urls.isEmpty()) {
1039 Log.e(TAG, String.format("could not create any url from %s", joinedUrls));
1040 }
1041 return urls.toArray(new URL[urls.size()]);
1042 } catch (Exception e) {
1043 // Don't let a misconfiguration bootloop the system.
1044 Log.e(TAG, "Error parsing configured fallback URLs", e);
1045 return new URL[0];
Hugo Benichieef918a2017-04-10 17:43:08 +09001046 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001047 }
1048
1049 private CaptivePortalProbeSpec[] makeCaptivePortalFallbackProbeSpecs() {
1050 try {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001051 final String settingsValue = mDependencies.getSetting(
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001052 mContext, Settings.Global.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS, null);
1053 // Probe specs only used if configured in settings
1054 if (TextUtils.isEmpty(settingsValue)) {
1055 return null;
1056 }
1057
1058 return CaptivePortalProbeSpec.parseCaptivePortalProbeSpecs(settingsValue);
1059 } catch (Exception e) {
1060 // Don't let a misconfiguration bootloop the system.
1061 Log.e(TAG, "Error parsing configured fallback probe specs", e);
1062 return null;
Hugo Benichieef918a2017-04-10 17:43:08 +09001063 }
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001064 }
1065
Hugo Benichic894b122017-07-31 12:58:20 +09001066 private String getCaptivePortalUserAgent() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001067 return mDependencies.getSetting(mContext,
Hugo Benichic894b122017-07-31 12:58:20 +09001068 Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001069 }
1070
Hugo Benichieef918a2017-04-10 17:43:08 +09001071 private URL nextFallbackUrl() {
1072 if (mCaptivePortalFallbackUrls.length == 0) {
1073 return null;
1074 }
1075 int idx = Math.abs(mNextFallbackUrlIndex) % mCaptivePortalFallbackUrls.length;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001076 mNextFallbackUrlIndex += mRandom.nextInt(); // randomly change url without memory.
Hugo Benichieef918a2017-04-10 17:43:08 +09001077 return mCaptivePortalFallbackUrls[idx];
1078 }
1079
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001080 private CaptivePortalProbeSpec nextFallbackSpec() {
1081 if (ArrayUtils.isEmpty(mCaptivePortalFallbackSpecs)) {
1082 return null;
1083 }
1084 // Randomly change spec without memory. Also randomize the first attempt.
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001085 final int idx = Math.abs(mRandom.nextInt()) % mCaptivePortalFallbackSpecs.length;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001086 return mCaptivePortalFallbackSpecs[idx];
1087 }
1088
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001089 @VisibleForTesting
1090 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -07001091 if (!mIsCaptivePortalCheckEnabled) {
1092 validationLog("Validation disabled.");
Hugo Benichia4158702017-04-10 17:08:06 +09001093 return CaptivePortalProbeResult.SUCCESS;
Calvin On4bc78eb2016-10-11 15:10:46 -07001094 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001095
Hugo Benichib03272c2017-04-10 22:45:13 +09001096 URL pacUrl = null;
1097 URL httpsUrl = mCaptivePortalHttpsUrl;
1098 URL httpUrl = mCaptivePortalHttpUrl;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001099
1100 // On networks with a PAC instead of fetching a URL that should result in a 204
1101 // response, we instead simply fetch the PAC script. This is done for a few reasons:
1102 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
1103 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
1104 // Network.openConnection() will ignore network-specific PACs and instead fetch
1105 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
1106 // NO_PROXY is the fetch of the PAC itself.
1107 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
1108 // happen before the fetch can commence, namely:
1109 // a) the PAC script be fetched
1110 // b) a PAC script resolver service be fired up and resolve the captive portal
1111 // server.
1112 // Network validation could be delayed until these prerequisities are satisifed or
1113 // could simply be left to race them. Neither is an optimal solution.
1114 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
1115 // fact block fetching of the generate_204 URL which would lead to false negative
1116 // results for network validation.
1117 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
1118 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001119 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
1120 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001121 return CaptivePortalProbeResult.FAILED;
1122 }
1123 }
1124
Hugo Benichib03272c2017-04-10 22:45:13 +09001125 if ((pacUrl == null) && (httpUrl == null || httpsUrl == null)) {
1126 return CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001127 }
1128
1129 long startTime = SystemClock.elapsedRealtime();
1130
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001131 final CaptivePortalProbeResult result;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001132 if (pacUrl != null) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001133 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001134 } else if (mUseHttps) {
Hugo Benichieef918a2017-04-10 17:43:08 +09001135 result = sendParallelHttpProbes(proxyInfo, httpsUrl, httpUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001136 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001137 result = sendDnsAndHttpProbes(proxyInfo, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001138 }
1139
1140 long endTime = SystemClock.elapsedRealtime();
1141
1142 sendNetworkConditionsBroadcast(true /* response received */,
1143 result.isPortal() /* isCaptivePortal */,
1144 startTime, endTime);
1145
Chiachang Wang4d11ec92018-10-23 21:10:57 +08001146 log("isCaptivePortal: isSuccessful()=" + result.isSuccessful()
1147 + " isPortal()=" + result.isPortal()
1148 + " RedirectUrl=" + result.redirectUrl
1149 + " Time=" + (endTime - startTime) + "ms");
Yohei, Oshima5225aba2016-08-02 10:34:32 +09001150
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001151 return result;
Udam Sainib7c24872016-01-04 12:16:14 -08001152 }
1153
Paul Jensenca8f16a2014-05-09 12:47:55 -04001154 /**
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001155 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect.
1156 * @return a CaptivePortalProbeResult inferred from the HTTP response.
1157 */
1158 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) {
1159 // Pre-resolve the captive portal server host so we can log it.
1160 // Only do this if HttpURLConnection is about to, to avoid any potentially
1161 // unnecessary resolution.
1162 final String host = (proxy != null) ? proxy.getHost() : url.getHost();
1163 sendDnsProbe(host);
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001164 return sendHttpProbe(url, probeType, null);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001165 }
1166
1167 /** Do a DNS resolution of the given server. */
1168 private void sendDnsProbe(String host) {
1169 if (TextUtils.isEmpty(host)) {
1170 return;
1171 }
1172
1173 final String name = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
1174 final Stopwatch watch = new Stopwatch().start();
1175 int result;
1176 String connectInfo;
1177 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +09001178 InetAddress[] addresses = mNetwork.getAllByName(host);
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001179 StringBuffer buffer = new StringBuffer();
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001180 for (InetAddress address : addresses) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001181 buffer.append(',').append(address.getHostAddress());
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001182 }
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001183 result = ValidationProbeEvent.DNS_SUCCESS;
1184 connectInfo = "OK " + buffer.substring(1);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001185 } catch (UnknownHostException e) {
1186 result = ValidationProbeEvent.DNS_FAILURE;
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001187 connectInfo = "FAIL";
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001188 }
1189 final long latency = watch.stop();
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001190 validationLog(ValidationProbeEvent.PROBE_DNS, host,
1191 String.format("%dms %s", latency, connectInfo));
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001192 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result);
1193 }
1194
1195 /**
1196 * Do a URL fetch on a known web server to see if we get the data we expect.
1197 * @return a CaptivePortalProbeResult inferred from the HTTP response.
Paul Jensenca8f16a2014-05-09 12:47:55 -04001198 */
Paul Jensencf4c2c62015-07-01 14:16:32 -04001199 @VisibleForTesting
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001200 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType,
1201 @Nullable CaptivePortalProbeSpec probeSpec) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04001202 HttpURLConnection urlConnection = null;
Hugo Benichia4158702017-04-10 17:08:06 +09001203 int httpResponseCode = CaptivePortalProbeResult.FAILED_CODE;
Paul Jensen232437312016-04-06 09:51:26 -04001204 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +09001205 final Stopwatch probeTimer = new Stopwatch().start();
Jeff Sharkey619a5112017-01-19 11:55:54 -07001206 final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001207 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +09001208 urlConnection = (HttpURLConnection) mNetwork.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001209 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -04001210 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
1211 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
1212 urlConnection.setUseCaches(false);
Hugo Benichib03272c2017-04-10 22:45:13 +09001213 if (mCaptivePortalUserAgent != null) {
1214 urlConnection.setRequestProperty("User-Agent", mCaptivePortalUserAgent);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001215 }
Hugo Benichiec88fd62017-03-07 15:10:03 +09001216 // cannot read request header after connection
1217 String requestHeader = urlConnection.getRequestProperties().toString();
Paul Jensen306f1a42014-08-04 10:59:01 -04001218
1219 // Time how long it takes to get a response to our request
1220 long requestTimestamp = SystemClock.elapsedRealtime();
1221
Pierre Imaibe12d762016-03-10 17:00:50 +09001222 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -04001223 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -04001224
1225 // Time how long it takes to get a response to our request
1226 long responseTimestamp = SystemClock.elapsedRealtime();
1227
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001228 validationLog(probeType, url, "time=" + (responseTimestamp - requestTimestamp) + "ms" +
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001229 " ret=" + httpResponseCode +
Hugo Benichiec88fd62017-03-07 15:10:03 +09001230 " request=" + requestHeader +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001231 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -04001232 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
1233 // portal. The only example of this seen so far was a captive portal. For
1234 // the time being go with prior behavior of assuming it's not a captive
1235 // portal. If it is considered a captive portal, a different sign-in URL
1236 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
1237 // proxy server.
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001238 if (httpResponseCode == 200) {
1239 if (probeType == ValidationProbeEvent.PROBE_PAC) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001240 validationLog(
1241 probeType, url, "PAC fetch 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001242 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001243 } else if (urlConnection.getContentLengthLong() == 0) {
1244 // Consider 200 response with "Content-length=0" to not be a captive portal.
1245 // There's no point in considering this a captive portal as the user cannot
1246 // sign-in to an empty page. Probably the result of a broken transparent proxy.
1247 // See http://b/9972012.
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001248 validationLog(probeType, url,
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001249 "200 response with Content-length=0 interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001250 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001251 } else if (urlConnection.getContentLengthLong() == -1) {
1252 // When no Content-length (default value == -1), attempt to read a byte from the
1253 // response. Do not use available() as it is unreliable. See http://b/33498325.
1254 if (urlConnection.getInputStream().read() == -1) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001255 validationLog(
1256 probeType, url, "Empty 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001257 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001258 }
1259 }
Paul Jensen8fe17422015-02-02 11:03:03 -05001260 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001261 } catch (IOException e) {
Hugo Benichia4158702017-04-10 17:08:06 +09001262 validationLog(probeType, url, "Probe failed with exception " + e);
1263 if (httpResponseCode == CaptivePortalProbeResult.FAILED_CODE) {
Paul Jensen869868be2014-05-15 10:33:05 -04001264 // TODO: Ping gateway and DNS server and log results.
1265 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001266 } finally {
1267 if (urlConnection != null) {
1268 urlConnection.disconnect();
1269 }
Jeff Sharkey619a5112017-01-19 11:55:54 -07001270 TrafficStats.setThreadStatsTag(oldTag);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001271 }
Hugo Benichicfddd682016-05-31 16:28:06 +09001272 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001273
1274 if (probeSpec == null) {
1275 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
1276 } else {
1277 return probeSpec.getResult(httpResponseCode, redirectUrl);
1278 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001279 }
Paul Jensen306f1a42014-08-04 10:59:01 -04001280
Hugo Benichid953bf82016-09-27 09:22:35 +09001281 private CaptivePortalProbeResult sendParallelHttpProbes(
Hugo Benichieef918a2017-04-10 17:43:08 +09001282 ProxyInfo proxy, URL httpsUrl, URL httpUrl) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001283 // Number of probes to wait for. If a probe completes with a conclusive answer
1284 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001285 final CountDownLatch latch = new CountDownLatch(2);
1286
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001287 final class ProbeThread extends Thread {
1288 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +09001289 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001290
1291 public ProbeThread(boolean isHttps) {
1292 mIsHttps = isHttps;
1293 }
1294
Hugo Benichid953bf82016-09-27 09:22:35 +09001295 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001296 return mResult;
1297 }
1298
1299 @Override
1300 public void run() {
1301 if (mIsHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001302 mResult =
1303 sendDnsAndHttpProbes(proxy, httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001304 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001305 mResult = sendDnsAndHttpProbes(proxy, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001306 }
1307 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001308 // Stop waiting immediately if https succeeds or if http finds a portal.
1309 while (latch.getCount() > 0) {
1310 latch.countDown();
1311 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001312 }
Hugo Benichid953bf82016-09-27 09:22:35 +09001313 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001314 latch.countDown();
1315 }
1316 }
1317
Hugo Benichid953bf82016-09-27 09:22:35 +09001318 final ProbeThread httpsProbe = new ProbeThread(true);
1319 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001320
1321 try {
Hugo Benichid953bf82016-09-27 09:22:35 +09001322 httpsProbe.start();
1323 httpProbe.start();
1324 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001325 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001326 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001327 return CaptivePortalProbeResult.FAILED;
1328 }
1329
Hugo Benichid953bf82016-09-27 09:22:35 +09001330 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
1331 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001332
Hugo Benichid953bf82016-09-27 09:22:35 +09001333 // Look for a conclusive probe result first.
1334 if (httpResult.isPortal()) {
1335 return httpResult;
1336 }
1337 // httpsResult.isPortal() is not expected, but check it nonetheless.
1338 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
1339 return httpsResult;
1340 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001341 // If a fallback method exists, use it to retry portal detection.
1342 // If we have new-style probe specs, use those. Otherwise, use the fallback URLs.
1343 final CaptivePortalProbeSpec probeSpec = nextFallbackSpec();
1344 final URL fallbackUrl = (probeSpec != null) ? probeSpec.getUrl() : nextFallbackUrl();
Hugo Benichid953bf82016-09-27 09:22:35 +09001345 if (fallbackUrl != null) {
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001346 CaptivePortalProbeResult result = sendHttpProbe(fallbackUrl, PROBE_FALLBACK, probeSpec);
Hugo Benichid953bf82016-09-27 09:22:35 +09001347 if (result.isPortal()) {
1348 return result;
1349 }
1350 }
Hugo Benichifc474422017-05-17 10:30:40 +09001351 // Otherwise wait until http and https probes completes and use their results.
Hugo Benichid953bf82016-09-27 09:22:35 +09001352 try {
Hugo Benichifc474422017-05-17 10:30:40 +09001353 httpProbe.join();
1354 if (httpProbe.result().isPortal()) {
1355 return httpProbe.result();
1356 }
Hugo Benichid953bf82016-09-27 09:22:35 +09001357 httpsProbe.join();
Hugo Benichifc474422017-05-17 10:30:40 +09001358 return httpsProbe.result();
Hugo Benichid953bf82016-09-27 09:22:35 +09001359 } catch (InterruptedException e) {
Hugo Benichifc474422017-05-17 10:30:40 +09001360 validationLog("Error: http or https probe wait interrupted!");
Hugo Benichid953bf82016-09-27 09:22:35 +09001361 return CaptivePortalProbeResult.FAILED;
1362 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001363 }
1364
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001365 private URL makeURL(String url) {
1366 if (url != null) {
1367 try {
1368 return new URL(url);
1369 } catch (MalformedURLException e) {
1370 validationLog("Bad URL: " + url);
1371 }
1372 }
1373 return null;
1374 }
1375
Paul Jensen306f1a42014-08-04 10:59:01 -04001376 /**
1377 * @param responseReceived - whether or not we received a valid HTTP response to our request.
1378 * If false, isCaptivePortal and responseTimestampMs are ignored
1379 * TODO: This should be moved to the transports. The latency could be passed to the transports
1380 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
1381 * perhaps this could just be added to the WiFi transport only.
1382 */
1383 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
1384 long requestTimestampMs, long responseTimestampMs) {
Hugo Benichic894b122017-07-31 12:58:20 +09001385 if (getWifiScansAlwaysAvailableDisabled()) {
Paul Jensen306f1a42014-08-04 10:59:01 -04001386 return;
1387 }
1388
Hugo Benichic894b122017-07-31 12:58:20 +09001389 if (!systemReady) {
1390 return;
1391 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001392
Chalard Jean918a68b2018-01-19 17:00:47 +09001393 Intent latencyBroadcast =
1394 new Intent(ConnectivityConstants.ACTION_NETWORK_CONDITIONS_MEASURED);
Paul Jensen306f1a42014-08-04 10:59:01 -04001395 switch (mNetworkAgentInfo.networkInfo.getType()) {
1396 case ConnectivityManager.TYPE_WIFI:
1397 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
1398 if (currentWifiInfo != null) {
1399 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
1400 // surrounded by double quotation marks (thus violating the Javadoc), but this
1401 // was changed to match the Javadoc in API 17. Since clients may have started
1402 // sanitizing the output of this method since API 17 was released, we should
1403 // not change it here as it would become impossible to tell whether the SSID is
1404 // simply being surrounded by quotes due to the API, or whether those quotes
1405 // are actually part of the SSID.
Chalard Jean918a68b2018-01-19 17:00:47 +09001406 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_SSID,
1407 currentWifiInfo.getSSID());
1408 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_BSSID,
1409 currentWifiInfo.getBSSID());
Paul Jensen306f1a42014-08-04 10:59:01 -04001410 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001411 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -04001412 return;
1413 }
1414 break;
1415 case ConnectivityManager.TYPE_MOBILE:
Chalard Jean918a68b2018-01-19 17:00:47 +09001416 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_NETWORK_TYPE,
1417 mTelephonyManager.getNetworkType());
Paul Jensen306f1a42014-08-04 10:59:01 -04001418 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
1419 if (info == null) return;
1420 int numRegisteredCellInfo = 0;
1421 for (CellInfo cellInfo : info) {
1422 if (cellInfo.isRegistered()) {
1423 numRegisteredCellInfo++;
1424 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001425 if (VDBG) logw("more than one registered CellInfo." +
1426 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -04001427 return;
1428 }
1429 if (cellInfo instanceof CellInfoCdma) {
1430 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001431 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001432 } else if (cellInfo instanceof CellInfoGsm) {
1433 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001434 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001435 } else if (cellInfo instanceof CellInfoLte) {
1436 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001437 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001438 } else if (cellInfo instanceof CellInfoWcdma) {
1439 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001440 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001441 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001442 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -04001443 return;
1444 }
1445 }
1446 }
1447 break;
1448 default:
1449 return;
1450 }
Chalard Jean918a68b2018-01-19 17:00:47 +09001451 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CONNECTIVITY_TYPE,
1452 mNetworkAgentInfo.networkInfo.getType());
1453 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_RESPONSE_RECEIVED,
1454 responseReceived);
1455 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_REQUEST_TIMESTAMP_MS,
1456 requestTimestampMs);
Paul Jensen306f1a42014-08-04 10:59:01 -04001457
1458 if (responseReceived) {
Chalard Jean918a68b2018-01-19 17:00:47 +09001459 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_IS_CAPTIVE_PORTAL,
1460 isCaptivePortal);
1461 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_RESPONSE_TIMESTAMP_MS,
1462 responseTimestampMs);
Paul Jensen306f1a42014-08-04 10:59:01 -04001463 }
Paul Jensen55298582014-08-20 11:01:41 -04001464 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
Chalard Jean918a68b2018-01-19 17:00:47 +09001465 ConnectivityConstants.PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001466 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001467
Hugo Benichicfddd682016-05-31 16:28:06 +09001468 private void logNetworkEvent(int evtype) {
Hugo Benichi97bfd272017-11-11 08:06:43 +09001469 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
1470 mMetricsLog.log(mNetId, transports, new NetworkEvent(evtype));
Hugo Benichicfddd682016-05-31 16:28:06 +09001471 }
1472
Hugo Benichidd229822016-11-15 23:23:24 +09001473 private int networkEventType(ValidationStage s, EvaluationResult r) {
1474 if (s.isFirstValidation) {
1475 if (r.isValidated) {
1476 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS;
1477 } else {
1478 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND;
1479 }
1480 } else {
1481 if (r.isValidated) {
1482 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS;
1483 } else {
1484 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND;
1485 }
1486 }
1487 }
1488
Hugo Benichicfddd682016-05-31 16:28:06 +09001489 private void maybeLogEvaluationResult(int evtype) {
1490 if (mEvaluationTimer.isRunning()) {
Hugo Benichi97bfd272017-11-11 08:06:43 +09001491 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
1492 mMetricsLog.log(mNetId, transports, new NetworkEvent(evtype, mEvaluationTimer.stop()));
Hugo Benichicfddd682016-05-31 16:28:06 +09001493 mEvaluationTimer.reset();
1494 }
1495 }
1496
1497 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
Hugo Benichia365bac2017-03-22 18:29:58 +09001498 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
Hugo Benichif927f0c2017-03-17 15:42:40 +09001499 boolean isFirstValidation = validationStage().isFirstValidation;
1500 ValidationProbeEvent ev = new ValidationProbeEvent();
1501 ev.probeType = ValidationProbeEvent.makeProbeType(probeType, isFirstValidation);
1502 ev.returnCode = probeResult;
1503 ev.durationMs = durationMs;
1504 mMetricsLog.log(mNetId, transports, ev);
Hugo Benichicfddd682016-05-31 16:28:06 +09001505 }
Hugo Benichic894b122017-07-31 12:58:20 +09001506
1507 @VisibleForTesting
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001508 public static class Dependencies {
1509 public Network getNetwork(NetworkAgentInfo networkAgentInfo) {
1510 return new OneAddressPerFamilyNetwork(networkAgentInfo.network());
1511 }
Hugo Benichic894b122017-07-31 12:58:20 +09001512
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001513 public Random getRandom() {
1514 return new Random();
1515 }
Hugo Benichic894b122017-07-31 12:58:20 +09001516
Hugo Benichic894b122017-07-31 12:58:20 +09001517 public int getSetting(Context context, String symbol, int defaultValue) {
1518 return Settings.Global.getInt(context.getContentResolver(), symbol, defaultValue);
1519 }
1520
1521 public String getSetting(Context context, String symbol, String defaultValue) {
1522 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
1523 return value != null ? value : defaultValue;
1524 }
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001525
1526 public static final Dependencies DEFAULT = new Dependencies();
Hugo Benichic894b122017-07-31 12:58:20 +09001527 }
Chiachang Wang7a70a7e2018-11-27 18:00:05 +08001528
1529 /**
1530 * Methods in this class perform no locking because all accesses are performed on the state
1531 * machine's thread. Need to consider the thread safety if it ever could be accessed outside the
1532 * state machine.
1533 */
1534 @VisibleForTesting
1535 protected class DnsStallDetector {
1536 private static final int DEFAULT_DNS_LOG_SIZE = 50;
1537 private int mConsecutiveTimeoutCount = 0;
1538 private int mSize;
1539 final DnsResult[] mDnsEvents;
1540 final RingBufferIndices mResultIndices;
1541
1542 DnsStallDetector(int size) {
1543 mSize = Math.max(DEFAULT_DNS_LOG_SIZE, size);
1544 mDnsEvents = new DnsResult[mSize];
1545 mResultIndices = new RingBufferIndices(mSize);
1546 }
1547
1548 @VisibleForTesting
1549 protected void accumulateConsecutiveDnsTimeoutCount(int code) {
1550 final DnsResult result = new DnsResult(code);
1551 mDnsEvents[mResultIndices.add()] = result;
1552 if (result.isTimeout()) {
1553 mConsecutiveTimeoutCount++;
1554 } else {
1555 // Keep the event in mDnsEvents without clearing it so that there are logs to do the
1556 // simulation and analysis.
1557 mConsecutiveTimeoutCount = 0;
1558 }
1559 }
1560
1561 private boolean isDataStallSuspected(int timeoutCountThreshold, int validTime) {
1562 if (timeoutCountThreshold <= 0) {
1563 Log.wtf(TAG, "Timeout count threshold should be larger than 0.");
1564 return false;
1565 }
1566
1567 // Check if the consecutive timeout count reach the threshold or not.
1568 if (mConsecutiveTimeoutCount < timeoutCountThreshold) {
1569 return false;
1570 }
1571
1572 // Check if the target dns event index is valid or not.
1573 final int firstConsecutiveTimeoutIndex =
1574 mResultIndices.indexOf(mResultIndices.size() - timeoutCountThreshold);
1575
1576 // If the dns timeout events happened long time ago, the events are meaningless for
1577 // data stall evaluation. Thus, check if the first consecutive timeout dns event
1578 // considered in the evaluation happened in defined threshold time.
1579 final long now = SystemClock.elapsedRealtime();
1580 final long firstTimeoutTime = now - mDnsEvents[firstConsecutiveTimeoutIndex].mTimeStamp;
1581 return (firstTimeoutTime < validTime);
1582 }
1583
1584 int getConsecutiveTimeoutCount() {
1585 return mConsecutiveTimeoutCount;
1586 }
1587 }
1588
1589 private static class DnsResult {
1590 // TODO: Need to move the DNS return code definition to a specific class once unify DNS
1591 // response code is done.
1592 private static final int RETURN_CODE_DNS_TIMEOUT = 255;
1593
1594 private final long mTimeStamp;
1595 private final int mReturnCode;
1596
1597 DnsResult(int code) {
1598 mTimeStamp = SystemClock.elapsedRealtime();
1599 mReturnCode = code;
1600 }
1601
1602 private boolean isTimeout() {
1603 return mReturnCode == RETURN_CODE_DNS_TIMEOUT;
1604 }
1605 }
1606
1607
1608 @VisibleForTesting
1609 protected DnsStallDetector getDnsStallDetector() {
1610 return mDnsStallDetector;
1611 }
1612
1613 private boolean dataStallEvaluateTypeEnabled(int type) {
1614 return (mDataStallEvaluationType & (1 << type)) != 0;
1615 }
1616
1617 @VisibleForTesting
1618 protected long getLastProbeTime() {
1619 return mLastProbeTime;
1620 }
1621
1622 @VisibleForTesting
1623 protected boolean isDataStall() {
1624 boolean result = false;
1625 // Reevaluation will generate traffic. Thus, set a minimal reevaluation timer to limit the
1626 // possible traffic cost in metered network.
1627 if (mNetworkAgentInfo.networkCapabilities.isMetered()
1628 && (SystemClock.elapsedRealtime() - getLastProbeTime()
1629 < mDataStallMinEvaluateTime)) {
1630 return false;
1631 }
1632
1633 // Check dns signal. Suspect it may be a data stall if both :
1634 // 1. The number of consecutive DNS query timeouts > mConsecutiveDnsTimeoutThreshold.
1635 // 2. Those consecutive DNS queries happened in the last mValidDataStallDnsTimeThreshold ms.
1636 if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) {
1637 if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold,
1638 mDataStallValidDnsTimeThreshold)) {
1639 result = true;
1640 logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND);
1641 }
1642 }
1643
1644 if (VDBG_STALL) {
1645 log("isDataStall: result=" + result + ", consecutive dns timeout count="
1646 + mDnsStallDetector.getConsecutiveTimeoutCount());
1647 }
1648
1649 return result;
1650 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001651}