blob: c3e38424e90b9e4a66296adadc8cb5c613718190 [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;
75import com.android.internal.util.State;
76import com.android.internal.util.StateMachine;
Erik Kline736353a2018-03-21 07:18:33 -070077import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Paul Jensenca8f16a2014-05-09 12:47:55 -040078
Paul Jensenca8f16a2014-05-09 12:47:55 -040079import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040080import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040081import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090082import java.net.MalformedURLException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040083import java.net.URL;
Hugo Benichid953bf82016-09-27 09:22:35 +090084import java.net.UnknownHostException;
Hugo Benichieef918a2017-04-10 17:43:08 +090085import java.util.ArrayList;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +090086import java.util.Arrays;
87import java.util.Collections;
88import java.util.LinkedHashMap;
Paul Jensen306f1a42014-08-04 10:59:01 -040089import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040090import java.util.Random;
Erik Kline736353a2018-03-21 07:18:33 -070091import java.util.UUID;
Hugo Benichid953bf82016-09-27 09:22:35 +090092import java.util.concurrent.CountDownLatch;
93import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040094
95/**
96 * {@hide}
97 */
98public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +090099 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900100 private static final boolean DBG = true;
101 private static final boolean VDBG = false;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900102
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900103 // Default configuration values for captive portal detection probes.
104 // TODO: append a random length parameter to the default HTTPS url.
105 // TODO: randomize browser version ids in the default User-Agent String.
106 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900107 private static final String DEFAULT_HTTP_URL =
108 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900109 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
Hugo Benichieef918a2017-04-10 17:43:08 +0900110 private static final String DEFAULT_OTHER_FALLBACK_URLS =
111 "http://play.googleapis.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +0900112 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
113 + "AppleWebKit/537.36 (KHTML, like Gecko) "
Lorenzo Colittid8a06082017-06-28 23:39:40 +0900114 + "Chrome/60.0.3112.32 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900115
Paul Jensenca8f16a2014-05-09 12:47:55 -0400116 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900117 private static final int PROBE_TIMEOUT_MS = 3000;
118
Hugo Benichidd229822016-11-15 23:23:24 +0900119 static enum EvaluationResult {
120 VALIDATED(true),
121 CAPTIVE_PORTAL(false);
122 final boolean isValidated;
123 EvaluationResult(boolean isValidated) {
124 this.isValidated = isValidated;
125 }
126 }
127
128 static enum ValidationStage {
129 FIRST_VALIDATION(true),
130 REVALIDATION(false);
131 final boolean isFirstValidation;
132 ValidationStage(boolean isFirstValidation) {
133 this.isFirstValidation = isFirstValidation;
134 }
135 }
136
Paul Jensenad50a1f2014-09-05 12:06:44 -0400137 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
138 // The network should be used as a default internet connection. It was found to be:
139 // 1. a functioning network providing internet access, or
140 // 2. a captive portal and the user decided to use it as is.
141 public static final int NETWORK_TEST_RESULT_VALID = 0;
142 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
143 // The network should not be used as a default internet connection. It was found to be:
144 // 1. a captive portal and the user is prompted to sign-in, or
145 // 2. a captive portal and the user did not want to use it, or
146 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
147 public static final int NETWORK_TEST_RESULT_INVALID = 1;
148
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
150
151 /**
152 * Inform NetworkMonitor that their network is connected.
153 * Initiates Network Validation.
154 */
155 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
156
157 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400158 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400159 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400160 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400161 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400162 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400163 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164
165 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400166 * Message to self indicating it's time to evaluate a network's connectivity.
167 * arg1 = Token to ignore old messages.
168 */
Paul Jensen869868be2014-05-15 10:33:05 -0400169 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400170
171 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400172 * Inform NetworkMonitor that the network has disconnected.
173 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400174 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400175
176 /**
177 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400178 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400179 */
Erik Kline736353a2018-03-21 07:18:33 -0700180 private static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400181
182 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400183 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400184 * arg1 = one of: APP_RETURN_DISMISSED,
185 * APP_RETURN_UNWANTED,
186 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500187 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400188 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400189 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400190
191 /**
192 * Request ConnectivityService display provisioning notification.
193 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400194 * arg2 = NetID.
195 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400196 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400197 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400198
199 /**
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900200 * Message indicating sign-in app should be launched.
Paul Jensen25a217c2015-02-27 22:55:47 -0500201 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900202 * user touches the sign in notification, or sent by
203 * ConnectivityService when the user touches the "sign into
204 * network" button in the wifi access point detail page.
Paul Jensen869868be2014-05-15 10:33:05 -0400205 */
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +0900206 public static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400207
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400208 /**
209 * Retest network to see if captive portal is still in place.
210 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
211 * 0 indicates self-initiated, so nobody to blame.
212 */
213 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
214
Erik Klinea24d4592018-01-11 21:07:29 +0900215 /**
216 * ConnectivityService notifies NetworkMonitor of settings changes to
217 * Private DNS. If a DNS resolution is required, e.g. for DNS-over-TLS in
218 * strict mode, then an event is sent back to ConnectivityService with the
219 * result of the resolution attempt.
Erik Kline736353a2018-03-21 07:18:33 -0700220 *
221 * A separate message is used to trigger (re)evaluation of the Private DNS
222 * configuration, so that the message can be handled as needed in different
223 * states, including being ignored until after an ongoing captive portal
224 * validation phase is completed.
Erik Klinea24d4592018-01-11 21:07:29 +0900225 */
226 private static final int CMD_PRIVATE_DNS_SETTINGS_CHANGED = BASE + 13;
227 public static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = BASE + 14;
Erik Kline736353a2018-03-21 07:18:33 -0700228 private static final int CMD_EVALUATE_PRIVATE_DNS = BASE + 15;
Erik Klinea24d4592018-01-11 21:07:29 +0900229
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800230 /**
231 * Message to self indicating captive portal detection is completed.
232 * obj = CaptivePortalProbeResult for detection result;
233 */
234 public static final int CMD_PROBE_COMPLETE = BASE + 16;
235
Paul Jensend0491e9a2015-05-05 14:52:22 -0400236 // Start mReevaluateDelayMs at this value and double.
237 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
238 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
239 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
240 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400241 private int mReevaluateToken = 0;
Erik Kline736353a2018-03-21 07:18:33 -0700242 private static final int NO_UID = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400243 private static final int INVALID_UID = -1;
244 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400245 // Stop blaming UID that requested re-evaluation after this many attempts.
246 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400247 // Delay between reevaluations once a captive portal has been found.
248 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249
Hugo Benichic894b122017-07-31 12:58:20 +0900250 private static final int NUM_VALIDATION_LOG_LINES = 20;
251
Erik Kline736353a2018-03-21 07:18:33 -0700252 private String mPrivateDnsProviderHostname = "";
253
Erik Klinea24d4592018-01-11 21:07:29 +0900254 public static boolean isValidationRequired(
255 NetworkCapabilities dfltNetCap, NetworkCapabilities nc) {
256 // TODO: Consider requiring validation for DUN networks.
257 return dfltNetCap.satisfiedByNetworkCapabilities(nc);
258 }
259
Paul Jensenca8f16a2014-05-09 12:47:55 -0400260 private final Context mContext;
261 private final Handler mConnectivityServiceHandler;
262 private final NetworkAgentInfo mNetworkAgentInfo;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900263 private final Network mNetwork;
Erik Klinea488c232016-04-15 15:49:42 +0900264 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400265 private final TelephonyManager mTelephonyManager;
266 private final WifiManager mWifiManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500267 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900268 private final IpConnectivityLog mMetricsLog;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900269 private final Dependencies mDependencies;
Hugo Benichic894b122017-07-31 12:58:20 +0900270
271 // Configuration values for captive portal detection probes.
272 private final String mCaptivePortalUserAgent;
273 private final URL mCaptivePortalHttpsUrl;
274 private final URL mCaptivePortalHttpUrl;
275 private final URL[] mCaptivePortalFallbackUrls;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900276 @Nullable
277 private final CaptivePortalProbeSpec[] mCaptivePortalFallbackSpecs;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400278
Calvin On4bc78eb2016-10-11 15:10:46 -0700279 @VisibleForTesting
280 protected boolean mIsCaptivePortalCheckEnabled;
281
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900282 private boolean mUseHttps;
Hugo Benichidd229822016-11-15 23:23:24 +0900283 // The total number of captive portal detection attempts for this NetworkMonitor instance.
284 private int mValidations = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400285
Paul Jensenad50a1f2014-09-05 12:06:44 -0400286 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
287 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400288 // Avoids surfacing "Sign in to network" notification.
289 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400290
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700291 public boolean systemReady = false;
292
Paul Jensen71b645f2014-10-13 14:13:07 -0400293 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400294 private final State mValidatedState = new ValidatedState();
295 private final State mMaybeNotifyState = new MaybeNotifyState();
296 private final State mEvaluatingState = new EvaluatingState();
297 private final State mCaptivePortalState = new CaptivePortalState();
Erik Kline736353a2018-03-21 07:18:33 -0700298 private final State mEvaluatingPrivateDnsState = new EvaluatingPrivateDnsState();
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800299 private final State mProbingState = new ProbingState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400300
Paul Jensen25a217c2015-02-27 22:55:47 -0500301 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400302
Hugo Benichic894b122017-07-31 12:58:20 +0900303 private final LocalLog validationLogs = new LocalLog(NUM_VALIDATION_LOG_LINES);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700304
Erik Klinea488c232016-04-15 15:49:42 +0900305 private final Stopwatch mEvaluationTimer = new Stopwatch();
306
Hugo Benichid953bf82016-09-27 09:22:35 +0900307 // This variable is set before transitioning to the mCaptivePortalState.
308 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
309
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900310 // Random generator to select fallback URL index
311 private final Random mRandom;
Hugo Benichieef918a2017-04-10 17:43:08 +0900312 private int mNextFallbackUrlIndex = 0;
Hugo Benichib03272c2017-04-10 22:45:13 +0900313
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800314 private int mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
315 private int mEvaluateAttempts = 0;
Chiachang Wang30cc3672018-11-12 10:52:25 +0800316 private volatile int mProbeToken = 0;
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800317
Paul Jensen2c311d62014-11-17 12:34:51 -0500318 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
319 NetworkRequest defaultRequest) {
Hugo Benichic894b122017-07-31 12:58:20 +0900320 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog(),
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900321 Dependencies.DEFAULT);
Hugo Benichif9fdf872016-07-28 17:53:06 +0900322 }
323
324 @VisibleForTesting
325 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900326 NetworkRequest defaultRequest, IpConnectivityLog logger, Dependencies deps) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400327 // Add suffix indicating which NetworkMonitor we're talking about.
328 super(TAG + networkAgentInfo.name());
329
Erik Kline736353a2018-03-21 07:18:33 -0700330 // Logs with a tag of the form given just above, e.g.
331 // <timestamp> 862 2402 D NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: ...
332 setDbg(VDBG);
333
Paul Jensenca8f16a2014-05-09 12:47:55 -0400334 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900335 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400336 mConnectivityServiceHandler = handler;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900337 mDependencies = deps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400338 mNetworkAgentInfo = networkAgentInfo;
Erik Klinef4fa9822018-04-27 22:48:33 +0900339 mNetwork = deps.getNetwork(networkAgentInfo).getPrivateDnsBypassingCopy();
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900340 mNetId = mNetwork.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400341 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
342 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500343 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400344
345 addState(mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400346 addState(mMaybeNotifyState, mDefaultState);
347 addState(mEvaluatingState, mMaybeNotifyState);
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800348 addState(mProbingState, mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400349 addState(mCaptivePortalState, mMaybeNotifyState);
Erik Kline736353a2018-03-21 07:18:33 -0700350 addState(mEvaluatingPrivateDnsState, mDefaultState);
351 addState(mValidatedState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700352 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400353
Hugo Benichic894b122017-07-31 12:58:20 +0900354 mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
355 mUseHttps = getUseHttpsValidation();
356 mCaptivePortalUserAgent = getCaptivePortalUserAgent();
357 mCaptivePortalHttpsUrl = makeURL(getCaptivePortalServerHttpsUrl());
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900358 mCaptivePortalHttpUrl = makeURL(getCaptivePortalServerHttpUrl(deps, context));
Hugo Benichic894b122017-07-31 12:58:20 +0900359 mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls();
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900360 mCaptivePortalFallbackSpecs = makeCaptivePortalFallbackProbeSpecs();
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900361 mRandom = deps.getRandom();
Hugo Benichib03272c2017-04-10 22:45:13 +0900362
Paul Jensenca8f16a2014-05-09 12:47:55 -0400363 start();
364 }
365
Erik Kline736353a2018-03-21 07:18:33 -0700366 public void forceReevaluation(int responsibleUid) {
367 sendMessage(CMD_FORCE_REEVALUATION, responsibleUid, 0);
368 }
369
370 public void notifyPrivateDnsSettingsChanged(PrivateDnsConfig newCfg) {
371 // Cancel any outstanding resolutions.
372 removeMessages(CMD_PRIVATE_DNS_SETTINGS_CHANGED);
373 // Send the update to the proper thread.
374 sendMessage(CMD_PRIVATE_DNS_SETTINGS_CHANGED, newCfg);
375 }
376
Paul Jensen532b61432014-11-10 09:50:02 -0500377 @Override
378 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400379 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500380 }
381
Hugo Benichid9ac87e2017-04-06 14:36:39 +0900382 private void validationLog(int probeType, Object url, String msg) {
383 String probeName = ValidationProbeEvent.getProbeName(probeType);
384 validationLog(String.format("%s %s %s", probeName, url, msg));
385 }
386
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700387 private void validationLog(String s) {
388 if (DBG) log(s);
389 validationLogs.log(s);
390 }
391
392 public ReadOnlyLocalLog getValidationLogs() {
393 return validationLogs.readOnlyLocalLog();
394 }
395
Hugo Benichidd229822016-11-15 23:23:24 +0900396 private ValidationStage validationStage() {
397 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION;
398 }
399
Erik Klinea24d4592018-01-11 21:07:29 +0900400 private boolean isValidationRequired() {
401 return isValidationRequired(
402 mDefaultRequest.networkCapabilities, mNetworkAgentInfo.networkCapabilities);
403 }
404
Erik Kline736353a2018-03-21 07:18:33 -0700405
406 private void notifyNetworkTestResultInvalid(Object obj) {
407 mConnectivityServiceHandler.sendMessage(obtainMessage(
408 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId, obj));
409 }
410
Paul Jensen71b645f2014-10-13 14:13:07 -0400411 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
412 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400413 private class DefaultState extends State {
414 @Override
415 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400416 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400417 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900418 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400419 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400420 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400421 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900422 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500423 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
424 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
425 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400426 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700427 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400428 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400429 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400430 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400431 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400432 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400433 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400434 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400435 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400436 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900437
438 // If the user has seen and acted on a captive portal notification, and the
439 // captive portal app is now closed, disable HTTPS probes. This avoids the
440 // following pathological situation:
441 //
442 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
443 // 2. User opens the app and logs into the captive portal.
444 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
445 // perhaps due to the network blocking HTTPS?
446 //
447 // In this case, we'll fail to validate the network even after the app is
448 // dismissed. There is now no way to use this network, because the app is now
449 // gone, so the user cannot select "Use this network as is".
450 mUseHttps = false;
451
Paul Jensen71b645f2014-10-13 14:13:07 -0400452 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400453 case APP_RETURN_DISMISSED:
Erik Kline736353a2018-03-21 07:18:33 -0700454 sendMessage(CMD_FORCE_REEVALUATION, NO_UID, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500455 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400456 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400457 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500458 // TODO: Distinguish this from a network that actually validates.
Erik Kline736353a2018-03-21 07:18:33 -0700459 // Displaying the "x" on the system UI icon may still be a good idea.
460 transitionTo(mEvaluatingPrivateDnsState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400461 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400462 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400463 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400464 mUserDoesNotWant = true;
Erik Kline736353a2018-03-21 07:18:33 -0700465 notifyNetworkTestResultInvalid(null);
Paul Jensen71b645f2014-10-13 14:13:07 -0400466 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400467 mUidResponsibleForReeval = 0;
468 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400469 break;
470 }
471 return HANDLED;
Erik Kline736353a2018-03-21 07:18:33 -0700472 case CMD_PRIVATE_DNS_SETTINGS_CHANGED: {
473 final PrivateDnsConfig cfg = (PrivateDnsConfig) message.obj;
474 if (!isValidationRequired() || cfg == null || !cfg.inStrictMode()) {
475 // No DNS resolution required.
476 //
477 // We don't force any validation in opportunistic mode
478 // here. Opportunistic mode nameservers are validated
479 // separately within netd.
480 //
481 // Reset Private DNS settings state.
482 mPrivateDnsProviderHostname = "";
483 break;
Erik Klinea24d4592018-01-11 21:07:29 +0900484 }
Erik Kline736353a2018-03-21 07:18:33 -0700485
486 mPrivateDnsProviderHostname = cfg.hostname;
487
488 // DNS resolutions via Private DNS strict mode block for a
489 // few seconds (~4.2) checking for any IP addresses to
490 // arrive and validate. Initiating a (re)evaluation now
491 // should not significantly alter the validation outcome.
492 //
493 // No matter what: enqueue a validation request; one of
494 // three things can happen with this request:
495 // [1] ignored (EvaluatingState or CaptivePortalState)
496 // [2] transition to EvaluatingPrivateDnsState
497 // (DefaultState and ValidatedState)
498 // [3] handled (EvaluatingPrivateDnsState)
499 //
500 // The Private DNS configuration to be evaluated will:
501 // [1] be skipped (not in strict mode), or
502 // [2] validate (huzzah), or
503 // [3] encounter some problem (invalid hostname,
504 // no resolved IP addresses, IPs unreachable,
505 // port 853 unreachable, port 853 is not running a
506 // DNS-over-TLS server, et cetera).
507 sendMessage(CMD_EVALUATE_PRIVATE_DNS);
508 break;
509 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400510 default:
Erik Kline736353a2018-03-21 07:18:33 -0700511 break;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400512 }
Erik Kline736353a2018-03-21 07:18:33 -0700513 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400514 }
515 }
516
Paul Jensen71b645f2014-10-13 14:13:07 -0400517 // Being in the ValidatedState State indicates a Network is:
518 // - Successfully validated, or
519 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400520 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400521 private class ValidatedState extends State {
522 @Override
523 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900524 maybeLogEvaluationResult(
525 networkEventType(validationStage(), EvaluationResult.VALIDATED));
Paul Jensenad50a1f2014-09-05 12:06:44 -0400526 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Kline736353a2018-03-21 07:18:33 -0700527 NETWORK_TEST_RESULT_VALID, mNetId, null));
Hugo Benichidd229822016-11-15 23:23:24 +0900528 mValidations++;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400529 }
530
531 @Override
532 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400533 switch (message.what) {
534 case CMD_NETWORK_CONNECTED:
535 transitionTo(mValidatedState);
Erik Kline736353a2018-03-21 07:18:33 -0700536 break;
537 case CMD_EVALUATE_PRIVATE_DNS:
538 transitionTo(mEvaluatingPrivateDnsState);
539 break;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400540 default:
541 return NOT_HANDLED;
542 }
Erik Kline736353a2018-03-21 07:18:33 -0700543 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400544 }
545 }
546
Paul Jensen71b645f2014-10-13 14:13:07 -0400547 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
548 // is required. This State takes care to clear the notification upon exit from the State.
549 private class MaybeNotifyState extends State {
550 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500551 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500552 switch (message.what) {
553 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
554 final Intent intent = new Intent(
555 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900556 // OneAddressPerFamilyNetwork is not parcelable across processes.
557 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, new Network(mNetwork));
Paul Jensen49e3edf2015-05-22 10:50:39 -0400558 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
559 new CaptivePortal(new ICaptivePortal.Stub() {
560 @Override
561 public void appResponse(int response) {
562 if (response == APP_RETURN_WANTED_AS_IS) {
563 mContext.enforceCallingPermission(
564 android.Manifest.permission.CONNECTIVITY_INTERNAL,
565 "CaptivePortal");
566 }
567 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
568 }
569 }));
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900570 final CaptivePortalProbeResult probeRes = mLastPortalProbeResult;
571 intent.putExtra(EXTRA_CAPTIVE_PORTAL_URL, probeRes.detectUrl);
572 if (probeRes.probeSpec != null) {
573 final String encodedSpec = probeRes.probeSpec.getEncodedSpec();
574 intent.putExtra(EXTRA_CAPTIVE_PORTAL_PROBE_SPEC, encodedSpec);
575 }
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900576 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
Hugo Benichieef918a2017-04-10 17:43:08 +0900577 mCaptivePortalUserAgent);
Paul Jensen25a217c2015-02-27 22:55:47 -0500578 intent.setFlags(
579 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
580 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
581 return HANDLED;
582 default:
583 return NOT_HANDLED;
584 }
585 }
586
587 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400588 public void exit() {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900589 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0, mNetId, null);
Paul Jensen71b645f2014-10-13 14:13:07 -0400590 mConnectivityServiceHandler.sendMessage(message);
591 }
592 }
593
594 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400595 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400596 private class EvaluatingState extends State {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400597 @Override
598 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900599 // If we have already started to track time spent in EvaluatingState
600 // don't reset the timer due simply to, say, commands or events that
601 // cause us to exit and re-enter EvaluatingState.
602 if (!mEvaluationTimer.isStarted()) {
603 mEvaluationTimer.start();
604 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400605 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400606 if (mUidResponsibleForReeval != INVALID_UID) {
607 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
608 mUidResponsibleForReeval = INVALID_UID;
609 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400610 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800611 mEvaluateAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400612 }
613
614 @Override
615 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400616 switch (message.what) {
617 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400618 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400619 return HANDLED;
Erik Kline736353a2018-03-21 07:18:33 -0700620 // Don't bother validating networks that don't satisfy the default request.
Paul Jensen2c311d62014-11-17 12:34:51 -0500621 // This includes:
622 // - VPNs which can be considered explicitly desired by the user and the
623 // user's desire trumps whether the network validates.
Erik Kline736353a2018-03-21 07:18:33 -0700624 // - Networks that don't provide Internet access. It's unclear how to
Paul Jensen2c311d62014-11-17 12:34:51 -0500625 // validate such networks.
626 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
627 // such networks and the user didn't express interest in connecting to
628 // such networks (an app did) so the user may be unhappily surprised when
629 // asked to sign-in to a network they didn't want to connect to in the
630 // first place. Validation could be done to adjust the network scores
631 // however these networks are app-requested and may not be intended for
632 // general usage, in which case general validation may not be an accurate
633 // measure of the network's quality. Only the app knows how to evaluate
634 // the network so don't bother validating here. Furthermore sending HTTP
635 // packets over the network may be undesirable, for example an extremely
636 // expensive metered network, or unwanted leaking of the User Agent string.
Erik Klinea24d4592018-01-11 21:07:29 +0900637 if (!isValidationRequired()) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900638 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400639 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400640 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400641 }
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800642 mEvaluateAttempts++;
643
644 transitionTo(mProbingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400645 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400646 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400647 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
648 // ignore any re-evaluation requests. After, restart the
649 // evaluation process via EvaluatingState#enter.
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800650 return (mEvaluateAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400651 default:
652 return NOT_HANDLED;
653 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400654 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400655
656 @Override
657 public void exit() {
658 TrafficStats.clearThreadStatsUid();
659 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400660 }
661
Paul Jensendcbe8352014-09-16 16:28:34 -0400662 // BroadcastReceiver that waits for a particular Intent and then posts a message.
663 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400664 private final int mToken;
665 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400666 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400667 CustomIntentReceiver(String action, int token, int what) {
668 mToken = token;
669 mWhat = what;
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900670 mAction = action + "_" + mNetId + "_" + token;
Paul Jensendcbe8352014-09-16 16:28:34 -0400671 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400672 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400673 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500674 final Intent intent = new Intent(mAction);
675 intent.setPackage(mContext.getPackageName());
676 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400677 }
678 @Override
679 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400680 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400681 }
682 }
Paul Jensen869868be2014-05-15 10:33:05 -0400683
Paul Jensen71b645f2014-10-13 14:13:07 -0400684 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
685 // has been shown a notification to sign-in.
686 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500687 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
688 "android.net.netmon.launchCaptivePortalApp";
689
Paul Jensen869868be2014-05-15 10:33:05 -0400690 @Override
691 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900692 maybeLogEvaluationResult(
693 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400694 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400695 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500696 // Create a CustomIntentReceiver that sends us a
697 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
698 // touches the notification.
699 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400700 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500701 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
702 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
703 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400704 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500705 // Display the sign in notification.
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900706 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1, mNetId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500707 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400708 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400709 // Retest for captive portal occasionally.
710 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
711 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Hugo Benichidd229822016-11-15 23:23:24 +0900712 mValidations++;
Paul Jensen869868be2014-05-15 10:33:05 -0400713 }
714
715 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400716 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700717 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400718 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400719 }
720
Erik Kline736353a2018-03-21 07:18:33 -0700721 private class EvaluatingPrivateDnsState extends State {
722 private int mPrivateDnsReevalDelayMs;
723 private PrivateDnsConfig mPrivateDnsConfig;
724
725 @Override
726 public void enter() {
727 mPrivateDnsReevalDelayMs = INITIAL_REEVALUATE_DELAY_MS;
728 mPrivateDnsConfig = null;
729 sendMessage(CMD_EVALUATE_PRIVATE_DNS);
730 }
731
732 @Override
733 public boolean processMessage(Message msg) {
734 switch (msg.what) {
735 case CMD_EVALUATE_PRIVATE_DNS:
736 if (inStrictMode()) {
737 if (!isStrictModeHostnameResolved()) {
738 resolveStrictModeHostname();
739
740 if (isStrictModeHostnameResolved()) {
741 notifyPrivateDnsConfigResolved();
742 } else {
743 handlePrivateDnsEvaluationFailure();
744 break;
745 }
746 }
747
748 // Look up a one-time hostname, to bypass caching.
749 //
750 // Note that this will race with ConnectivityService
751 // code programming the DNS-over-TLS server IP addresses
752 // into netd (if invoked, above). If netd doesn't know
753 // the IP addresses yet, or if the connections to the IP
754 // addresses haven't yet been validated, netd will block
755 // for up to a few seconds before failing the lookup.
756 if (!sendPrivateDnsProbe()) {
757 handlePrivateDnsEvaluationFailure();
758 break;
759 }
760 }
761
762 // All good!
763 transitionTo(mValidatedState);
764 break;
765 default:
766 return NOT_HANDLED;
767 }
768 return HANDLED;
769 }
770
771 private boolean inStrictMode() {
772 return !TextUtils.isEmpty(mPrivateDnsProviderHostname);
773 }
774
775 private boolean isStrictModeHostnameResolved() {
776 return (mPrivateDnsConfig != null) &&
777 mPrivateDnsConfig.hostname.equals(mPrivateDnsProviderHostname) &&
778 (mPrivateDnsConfig.ips.length > 0);
779 }
780
781 private void resolveStrictModeHostname() {
782 try {
783 // Do a blocking DNS resolution using the network-assigned nameservers.
Erik Klinef4fa9822018-04-27 22:48:33 +0900784 final InetAddress[] ips = mNetwork.getAllByName(mPrivateDnsProviderHostname);
Erik Kline71d90c42018-04-19 17:58:15 +0900785 mPrivateDnsConfig = new PrivateDnsConfig(mPrivateDnsProviderHostname, ips);
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900786 validationLog("Strict mode hostname resolved: " + mPrivateDnsConfig);
Erik Kline736353a2018-03-21 07:18:33 -0700787 } catch (UnknownHostException uhe) {
788 mPrivateDnsConfig = null;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900789 validationLog("Strict mode hostname resolution failed: " + uhe.getMessage());
Erik Kline736353a2018-03-21 07:18:33 -0700790 }
791 }
792
793 private void notifyPrivateDnsConfigResolved() {
794 mConnectivityServiceHandler.sendMessage(obtainMessage(
795 EVENT_PRIVATE_DNS_CONFIG_RESOLVED, 0, mNetId, mPrivateDnsConfig));
796 }
797
798 private void handlePrivateDnsEvaluationFailure() {
799 notifyNetworkTestResultInvalid(null);
800
801 // Queue up a re-evaluation with backoff.
802 //
803 // TODO: Consider abandoning this state after a few attempts and
804 // transitioning back to EvaluatingState, to perhaps give ourselves
805 // the opportunity to (re)detect a captive portal or something.
806 sendMessageDelayed(CMD_EVALUATE_PRIVATE_DNS, mPrivateDnsReevalDelayMs);
807 mPrivateDnsReevalDelayMs *= 2;
808 if (mPrivateDnsReevalDelayMs > MAX_REEVALUATE_DELAY_MS) {
809 mPrivateDnsReevalDelayMs = MAX_REEVALUATE_DELAY_MS;
810 }
811 }
812
813 private boolean sendPrivateDnsProbe() {
814 // q.v. system/netd/server/dns/DnsTlsTransport.cpp
815 final String ONE_TIME_HOSTNAME_SUFFIX = "-dnsotls-ds.metric.gstatic.com";
816 final String host = UUID.randomUUID().toString().substring(0, 8) +
817 ONE_TIME_HOSTNAME_SUFFIX;
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900818 final Stopwatch watch = new Stopwatch().start();
Erik Kline736353a2018-03-21 07:18:33 -0700819 try {
820 final InetAddress[] ips = mNetworkAgentInfo.network().getAllByName(host);
Remi NGUYEN VANdcb722f2018-07-20 18:13:24 +0900821 final long time = watch.stop();
822 final String strIps = Arrays.toString(ips);
823 final boolean success = (ips != null && ips.length > 0);
824 validationLog(PROBE_PRIVDNS, host, String.format("%dms: %s", time, strIps));
825 logValidationProbe(time, PROBE_PRIVDNS, success ? DNS_SUCCESS : DNS_FAILURE);
826 return success;
827 } catch (UnknownHostException uhe) {
828 final long time = watch.stop();
829 validationLog(PROBE_PRIVDNS, host,
830 String.format("%dms - Error: %s", time, uhe.getMessage()));
831 logValidationProbe(time, PROBE_PRIVDNS, DNS_FAILURE);
832 }
Erik Kline736353a2018-03-21 07:18:33 -0700833 return false;
834 }
835 }
836
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800837 private class ProbingState extends State {
838 private Thread mThread;
839
840 @Override
841 public void enter() {
Chiachang Wang30cc3672018-11-12 10:52:25 +0800842 final int token = ++mProbeToken;
843 mThread = new Thread(() -> sendMessage(obtainMessage(CMD_PROBE_COMPLETE, token, 0,
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800844 isCaptivePortal())));
845 mThread.start();
846 }
847
848 @Override
849 public boolean processMessage(Message message) {
850 switch (message.what) {
851 case CMD_PROBE_COMPLETE:
Chiachang Wang30cc3672018-11-12 10:52:25 +0800852 // Ensure that CMD_PROBE_COMPLETE from stale threads are ignored.
853 if (message.arg1 != mProbeToken) {
854 return HANDLED;
855 }
856
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800857 final CaptivePortalProbeResult probeResult =
858 (CaptivePortalProbeResult) message.obj;
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800859 if (probeResult.isSuccessful()) {
860 // Transit EvaluatingPrivateDnsState to get to Validated
861 // state (even if no Private DNS validation required).
862 transitionTo(mEvaluatingPrivateDnsState);
863 } else if (probeResult.isPortal()) {
864 notifyNetworkTestResultInvalid(probeResult.redirectUrl);
865 mLastPortalProbeResult = probeResult;
866 transitionTo(mCaptivePortalState);
867 } else {
868 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
869 sendMessageDelayed(msg, mReevaluateDelayMs);
870 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
871 notifyNetworkTestResultInvalid(probeResult.redirectUrl);
872 if (mEvaluateAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
873 // Don't continue to blame UID forever.
874 TrafficStats.clearThreadStatsUid();
875 }
876 mReevaluateDelayMs *= 2;
877 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
878 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
879 }
880 }
881 return HANDLED;
882 case CMD_REEVALUATE:
883 // Leave the event to EvaluatingState. Defer this message will result in reset
884 // of mReevaluateDelayMs and mEvaluateAttempts.
Chiachang Wang30cc3672018-11-12 10:52:25 +0800885 case CMD_NETWORK_DISCONNECTED:
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800886 return NOT_HANDLED;
887 default:
888 // TODO: Some events may able to handle in this state, instead of deferring to
889 // next state.
890 deferMessage(message);
891 return HANDLED;
892 }
893 }
894
895 @Override
896 public void exit() {
Chiachang Wang30cc3672018-11-12 10:52:25 +0800897 if (mThread.isAlive()) {
898 mThread.interrupt();
899 }
Chiachang Wang4d11ec92018-10-23 21:10:57 +0800900 mThread = null;
901 }
902 }
903
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900904 // Limits the list of IP addresses returned by getAllByName or tried by openConnection to at
905 // most one per address family. This ensures we only wait up to 20 seconds for TCP connections
906 // to complete, regardless of how many IP addresses a host has.
907 private static class OneAddressPerFamilyNetwork extends Network {
908 public OneAddressPerFamilyNetwork(Network network) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900909 // Always bypass Private DNS.
910 super(network.getPrivateDnsBypassingCopy());
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900911 }
912
913 @Override
914 public InetAddress[] getAllByName(String host) throws UnknownHostException {
Erik Klinef4fa9822018-04-27 22:48:33 +0900915 final List<InetAddress> addrs = Arrays.asList(super.getAllByName(host));
Lorenzo Colittid8978ac2017-06-28 23:42:41 +0900916
917 // Ensure the address family of the first address is tried first.
918 LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>();
919 addressByFamily.put(addrs.get(0).getClass(), addrs.get(0));
920 Collections.shuffle(addrs);
921
922 for (InetAddress addr : addrs) {
923 addressByFamily.put(addr.getClass(), addr);
924 }
925
926 return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]);
927 }
928 }
929
Hugo Benichic894b122017-07-31 12:58:20 +0900930 public boolean getIsCaptivePortalCheckEnabled() {
931 String symbol = Settings.Global.CAPTIVE_PORTAL_MODE;
932 int defaultValue = Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900933 int mode = mDependencies.getSetting(mContext, symbol, defaultValue);
Hugo Benichic894b122017-07-31 12:58:20 +0900934 return mode != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900935 }
936
Hugo Benichic894b122017-07-31 12:58:20 +0900937 public boolean getUseHttpsValidation() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900938 return mDependencies.getSetting(mContext, Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Hugo Benichic894b122017-07-31 12:58:20 +0900939 }
940
941 public boolean getWifiScansAlwaysAvailableDisabled() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900942 return mDependencies.getSetting(mContext, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0;
Hugo Benichic894b122017-07-31 12:58:20 +0900943 }
944
945 private String getCaptivePortalServerHttpsUrl() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900946 return mDependencies.getSetting(mContext,
Hugo Benichic894b122017-07-31 12:58:20 +0900947 Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
948 }
949
950 // Static for direct access by ConnectivityService
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900951 public static String getCaptivePortalServerHttpUrl(Context context) {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900952 return getCaptivePortalServerHttpUrl(Dependencies.DEFAULT, context);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900953 }
954
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900955 public static String getCaptivePortalServerHttpUrl(Dependencies deps, Context context) {
956 return deps.getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
Hugo Benichic894b122017-07-31 12:58:20 +0900957 }
958
959 private URL[] makeCaptivePortalFallbackUrls() {
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900960 try {
961 String separator = ",";
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900962 String firstUrl = mDependencies.getSetting(mContext,
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900963 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900964 String joinedUrls = firstUrl + separator + mDependencies.getSetting(mContext,
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900965 Settings.Global.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS,
966 DEFAULT_OTHER_FALLBACK_URLS);
967 List<URL> urls = new ArrayList<>();
968 for (String s : joinedUrls.split(separator)) {
969 URL u = makeURL(s);
970 if (u == null) {
971 continue;
972 }
973 urls.add(u);
Hugo Benichieef918a2017-04-10 17:43:08 +0900974 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900975 if (urls.isEmpty()) {
976 Log.e(TAG, String.format("could not create any url from %s", joinedUrls));
977 }
978 return urls.toArray(new URL[urls.size()]);
979 } catch (Exception e) {
980 // Don't let a misconfiguration bootloop the system.
981 Log.e(TAG, "Error parsing configured fallback URLs", e);
982 return new URL[0];
Hugo Benichieef918a2017-04-10 17:43:08 +0900983 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900984 }
985
986 private CaptivePortalProbeSpec[] makeCaptivePortalFallbackProbeSpecs() {
987 try {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +0900988 final String settingsValue = mDependencies.getSetting(
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +0900989 mContext, Settings.Global.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS, null);
990 // Probe specs only used if configured in settings
991 if (TextUtils.isEmpty(settingsValue)) {
992 return null;
993 }
994
995 return CaptivePortalProbeSpec.parseCaptivePortalProbeSpecs(settingsValue);
996 } catch (Exception e) {
997 // Don't let a misconfiguration bootloop the system.
998 Log.e(TAG, "Error parsing configured fallback probe specs", e);
999 return null;
Hugo Benichieef918a2017-04-10 17:43:08 +09001000 }
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001001 }
1002
Hugo Benichic894b122017-07-31 12:58:20 +09001003 private String getCaptivePortalUserAgent() {
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001004 return mDependencies.getSetting(mContext,
Hugo Benichic894b122017-07-31 12:58:20 +09001005 Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001006 }
1007
Hugo Benichieef918a2017-04-10 17:43:08 +09001008 private URL nextFallbackUrl() {
1009 if (mCaptivePortalFallbackUrls.length == 0) {
1010 return null;
1011 }
1012 int idx = Math.abs(mNextFallbackUrlIndex) % mCaptivePortalFallbackUrls.length;
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001013 mNextFallbackUrlIndex += mRandom.nextInt(); // randomly change url without memory.
Hugo Benichieef918a2017-04-10 17:43:08 +09001014 return mCaptivePortalFallbackUrls[idx];
1015 }
1016
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001017 private CaptivePortalProbeSpec nextFallbackSpec() {
1018 if (ArrayUtils.isEmpty(mCaptivePortalFallbackSpecs)) {
1019 return null;
1020 }
1021 // Randomly change spec without memory. Also randomize the first attempt.
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001022 final int idx = Math.abs(mRandom.nextInt()) % mCaptivePortalFallbackSpecs.length;
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001023 return mCaptivePortalFallbackSpecs[idx];
1024 }
1025
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001026 @VisibleForTesting
1027 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -07001028 if (!mIsCaptivePortalCheckEnabled) {
1029 validationLog("Validation disabled.");
Hugo Benichia4158702017-04-10 17:08:06 +09001030 return CaptivePortalProbeResult.SUCCESS;
Calvin On4bc78eb2016-10-11 15:10:46 -07001031 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001032
Hugo Benichib03272c2017-04-10 22:45:13 +09001033 URL pacUrl = null;
1034 URL httpsUrl = mCaptivePortalHttpsUrl;
1035 URL httpUrl = mCaptivePortalHttpUrl;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001036
1037 // On networks with a PAC instead of fetching a URL that should result in a 204
1038 // response, we instead simply fetch the PAC script. This is done for a few reasons:
1039 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
1040 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
1041 // Network.openConnection() will ignore network-specific PACs and instead fetch
1042 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
1043 // NO_PROXY is the fetch of the PAC itself.
1044 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
1045 // happen before the fetch can commence, namely:
1046 // a) the PAC script be fetched
1047 // b) a PAC script resolver service be fired up and resolve the captive portal
1048 // server.
1049 // Network validation could be delayed until these prerequisities are satisifed or
1050 // could simply be left to race them. Neither is an optimal solution.
1051 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
1052 // fact block fetching of the generate_204 URL which would lead to false negative
1053 // results for network validation.
1054 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
1055 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001056 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
1057 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001058 return CaptivePortalProbeResult.FAILED;
1059 }
1060 }
1061
Hugo Benichib03272c2017-04-10 22:45:13 +09001062 if ((pacUrl == null) && (httpUrl == null || httpsUrl == null)) {
1063 return CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001064 }
1065
1066 long startTime = SystemClock.elapsedRealtime();
1067
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001068 final CaptivePortalProbeResult result;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001069 if (pacUrl != null) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001070 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001071 } else if (mUseHttps) {
Hugo Benichieef918a2017-04-10 17:43:08 +09001072 result = sendParallelHttpProbes(proxyInfo, httpsUrl, httpUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001073 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001074 result = sendDnsAndHttpProbes(proxyInfo, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001075 }
1076
1077 long endTime = SystemClock.elapsedRealtime();
1078
1079 sendNetworkConditionsBroadcast(true /* response received */,
1080 result.isPortal() /* isCaptivePortal */,
1081 startTime, endTime);
1082
Chiachang Wang4d11ec92018-10-23 21:10:57 +08001083 log("isCaptivePortal: isSuccessful()=" + result.isSuccessful()
1084 + " isPortal()=" + result.isPortal()
1085 + " RedirectUrl=" + result.redirectUrl
1086 + " Time=" + (endTime - startTime) + "ms");
Yohei, Oshima5225aba2016-08-02 10:34:32 +09001087
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001088 return result;
Udam Sainib7c24872016-01-04 12:16:14 -08001089 }
1090
Paul Jensenca8f16a2014-05-09 12:47:55 -04001091 /**
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001092 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect.
1093 * @return a CaptivePortalProbeResult inferred from the HTTP response.
1094 */
1095 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) {
1096 // Pre-resolve the captive portal server host so we can log it.
1097 // Only do this if HttpURLConnection is about to, to avoid any potentially
1098 // unnecessary resolution.
1099 final String host = (proxy != null) ? proxy.getHost() : url.getHost();
1100 sendDnsProbe(host);
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001101 return sendHttpProbe(url, probeType, null);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001102 }
1103
1104 /** Do a DNS resolution of the given server. */
1105 private void sendDnsProbe(String host) {
1106 if (TextUtils.isEmpty(host)) {
1107 return;
1108 }
1109
1110 final String name = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
1111 final Stopwatch watch = new Stopwatch().start();
1112 int result;
1113 String connectInfo;
1114 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +09001115 InetAddress[] addresses = mNetwork.getAllByName(host);
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001116 StringBuffer buffer = new StringBuffer();
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001117 for (InetAddress address : addresses) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001118 buffer.append(',').append(address.getHostAddress());
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001119 }
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001120 result = ValidationProbeEvent.DNS_SUCCESS;
1121 connectInfo = "OK " + buffer.substring(1);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001122 } catch (UnknownHostException e) {
1123 result = ValidationProbeEvent.DNS_FAILURE;
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001124 connectInfo = "FAIL";
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001125 }
1126 final long latency = watch.stop();
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001127 validationLog(ValidationProbeEvent.PROBE_DNS, host,
1128 String.format("%dms %s", latency, connectInfo));
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001129 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result);
1130 }
1131
1132 /**
1133 * Do a URL fetch on a known web server to see if we get the data we expect.
1134 * @return a CaptivePortalProbeResult inferred from the HTTP response.
Paul Jensenca8f16a2014-05-09 12:47:55 -04001135 */
Paul Jensencf4c2c62015-07-01 14:16:32 -04001136 @VisibleForTesting
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001137 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType,
1138 @Nullable CaptivePortalProbeSpec probeSpec) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04001139 HttpURLConnection urlConnection = null;
Hugo Benichia4158702017-04-10 17:08:06 +09001140 int httpResponseCode = CaptivePortalProbeResult.FAILED_CODE;
Paul Jensen232437312016-04-06 09:51:26 -04001141 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +09001142 final Stopwatch probeTimer = new Stopwatch().start();
Jeff Sharkey619a5112017-01-19 11:55:54 -07001143 final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001144 try {
Lorenzo Colittid8978ac2017-06-28 23:42:41 +09001145 urlConnection = (HttpURLConnection) mNetwork.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001146 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -04001147 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
1148 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
1149 urlConnection.setUseCaches(false);
Hugo Benichib03272c2017-04-10 22:45:13 +09001150 if (mCaptivePortalUserAgent != null) {
1151 urlConnection.setRequestProperty("User-Agent", mCaptivePortalUserAgent);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001152 }
Hugo Benichiec88fd62017-03-07 15:10:03 +09001153 // cannot read request header after connection
1154 String requestHeader = urlConnection.getRequestProperties().toString();
Paul Jensen306f1a42014-08-04 10:59:01 -04001155
1156 // Time how long it takes to get a response to our request
1157 long requestTimestamp = SystemClock.elapsedRealtime();
1158
Pierre Imaibe12d762016-03-10 17:00:50 +09001159 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -04001160 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -04001161
1162 // Time how long it takes to get a response to our request
1163 long responseTimestamp = SystemClock.elapsedRealtime();
1164
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001165 validationLog(probeType, url, "time=" + (responseTimestamp - requestTimestamp) + "ms" +
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001166 " ret=" + httpResponseCode +
Hugo Benichiec88fd62017-03-07 15:10:03 +09001167 " request=" + requestHeader +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001168 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -04001169 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
1170 // portal. The only example of this seen so far was a captive portal. For
1171 // the time being go with prior behavior of assuming it's not a captive
1172 // portal. If it is considered a captive portal, a different sign-in URL
1173 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
1174 // proxy server.
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001175 if (httpResponseCode == 200) {
1176 if (probeType == ValidationProbeEvent.PROBE_PAC) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001177 validationLog(
1178 probeType, url, "PAC fetch 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001179 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001180 } else if (urlConnection.getContentLengthLong() == 0) {
1181 // Consider 200 response with "Content-length=0" to not be a captive portal.
1182 // There's no point in considering this a captive portal as the user cannot
1183 // sign-in to an empty page. Probably the result of a broken transparent proxy.
1184 // See http://b/9972012.
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001185 validationLog(probeType, url,
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001186 "200 response with Content-length=0 interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001187 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001188 } else if (urlConnection.getContentLengthLong() == -1) {
1189 // When no Content-length (default value == -1), attempt to read a byte from the
1190 // response. Do not use available() as it is unreliable. See http://b/33498325.
1191 if (urlConnection.getInputStream().read() == -1) {
Hugo Benichid9ac87e2017-04-06 14:36:39 +09001192 validationLog(
1193 probeType, url, "Empty 200 response interpreted as 204 response.");
Hugo Benichia4158702017-04-10 17:08:06 +09001194 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE;
Hugo Benichicb4aa4d2017-01-11 16:23:26 +09001195 }
1196 }
Paul Jensen8fe17422015-02-02 11:03:03 -05001197 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001198 } catch (IOException e) {
Hugo Benichia4158702017-04-10 17:08:06 +09001199 validationLog(probeType, url, "Probe failed with exception " + e);
1200 if (httpResponseCode == CaptivePortalProbeResult.FAILED_CODE) {
Paul Jensen869868be2014-05-15 10:33:05 -04001201 // TODO: Ping gateway and DNS server and log results.
1202 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001203 } finally {
1204 if (urlConnection != null) {
1205 urlConnection.disconnect();
1206 }
Jeff Sharkey619a5112017-01-19 11:55:54 -07001207 TrafficStats.setThreadStatsTag(oldTag);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001208 }
Hugo Benichicfddd682016-05-31 16:28:06 +09001209 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001210
1211 if (probeSpec == null) {
1212 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
1213 } else {
1214 return probeSpec.getResult(httpResponseCode, redirectUrl);
1215 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001216 }
Paul Jensen306f1a42014-08-04 10:59:01 -04001217
Hugo Benichid953bf82016-09-27 09:22:35 +09001218 private CaptivePortalProbeResult sendParallelHttpProbes(
Hugo Benichieef918a2017-04-10 17:43:08 +09001219 ProxyInfo proxy, URL httpsUrl, URL httpUrl) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001220 // Number of probes to wait for. If a probe completes with a conclusive answer
1221 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001222 final CountDownLatch latch = new CountDownLatch(2);
1223
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001224 final class ProbeThread extends Thread {
1225 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +09001226 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001227
1228 public ProbeThread(boolean isHttps) {
1229 mIsHttps = isHttps;
1230 }
1231
Hugo Benichid953bf82016-09-27 09:22:35 +09001232 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001233 return mResult;
1234 }
1235
1236 @Override
1237 public void run() {
1238 if (mIsHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001239 mResult =
1240 sendDnsAndHttpProbes(proxy, httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001241 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +09001242 mResult = sendDnsAndHttpProbes(proxy, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001243 }
1244 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001245 // Stop waiting immediately if https succeeds or if http finds a portal.
1246 while (latch.getCount() > 0) {
1247 latch.countDown();
1248 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001249 }
Hugo Benichid953bf82016-09-27 09:22:35 +09001250 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001251 latch.countDown();
1252 }
1253 }
1254
Hugo Benichid953bf82016-09-27 09:22:35 +09001255 final ProbeThread httpsProbe = new ProbeThread(true);
1256 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001257
1258 try {
Hugo Benichid953bf82016-09-27 09:22:35 +09001259 httpsProbe.start();
1260 httpProbe.start();
1261 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001262 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +09001263 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001264 return CaptivePortalProbeResult.FAILED;
1265 }
1266
Hugo Benichid953bf82016-09-27 09:22:35 +09001267 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
1268 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001269
Hugo Benichid953bf82016-09-27 09:22:35 +09001270 // Look for a conclusive probe result first.
1271 if (httpResult.isPortal()) {
1272 return httpResult;
1273 }
1274 // httpsResult.isPortal() is not expected, but check it nonetheless.
1275 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
1276 return httpsResult;
1277 }
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001278 // If a fallback method exists, use it to retry portal detection.
1279 // If we have new-style probe specs, use those. Otherwise, use the fallback URLs.
1280 final CaptivePortalProbeSpec probeSpec = nextFallbackSpec();
1281 final URL fallbackUrl = (probeSpec != null) ? probeSpec.getUrl() : nextFallbackUrl();
Hugo Benichid953bf82016-09-27 09:22:35 +09001282 if (fallbackUrl != null) {
Remi NGUYEN VAN13e6e212018-05-22 10:01:53 +09001283 CaptivePortalProbeResult result = sendHttpProbe(fallbackUrl, PROBE_FALLBACK, probeSpec);
Hugo Benichid953bf82016-09-27 09:22:35 +09001284 if (result.isPortal()) {
1285 return result;
1286 }
1287 }
Hugo Benichifc474422017-05-17 10:30:40 +09001288 // Otherwise wait until http and https probes completes and use their results.
Hugo Benichid953bf82016-09-27 09:22:35 +09001289 try {
Hugo Benichifc474422017-05-17 10:30:40 +09001290 httpProbe.join();
1291 if (httpProbe.result().isPortal()) {
1292 return httpProbe.result();
1293 }
Hugo Benichid953bf82016-09-27 09:22:35 +09001294 httpsProbe.join();
Hugo Benichifc474422017-05-17 10:30:40 +09001295 return httpsProbe.result();
Hugo Benichid953bf82016-09-27 09:22:35 +09001296 } catch (InterruptedException e) {
Hugo Benichifc474422017-05-17 10:30:40 +09001297 validationLog("Error: http or https probe wait interrupted!");
Hugo Benichid953bf82016-09-27 09:22:35 +09001298 return CaptivePortalProbeResult.FAILED;
1299 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +09001300 }
1301
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09001302 private URL makeURL(String url) {
1303 if (url != null) {
1304 try {
1305 return new URL(url);
1306 } catch (MalformedURLException e) {
1307 validationLog("Bad URL: " + url);
1308 }
1309 }
1310 return null;
1311 }
1312
Paul Jensen306f1a42014-08-04 10:59:01 -04001313 /**
1314 * @param responseReceived - whether or not we received a valid HTTP response to our request.
1315 * If false, isCaptivePortal and responseTimestampMs are ignored
1316 * TODO: This should be moved to the transports. The latency could be passed to the transports
1317 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
1318 * perhaps this could just be added to the WiFi transport only.
1319 */
1320 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
1321 long requestTimestampMs, long responseTimestampMs) {
Hugo Benichic894b122017-07-31 12:58:20 +09001322 if (getWifiScansAlwaysAvailableDisabled()) {
Paul Jensen306f1a42014-08-04 10:59:01 -04001323 return;
1324 }
1325
Hugo Benichic894b122017-07-31 12:58:20 +09001326 if (!systemReady) {
1327 return;
1328 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001329
Chalard Jean918a68b2018-01-19 17:00:47 +09001330 Intent latencyBroadcast =
1331 new Intent(ConnectivityConstants.ACTION_NETWORK_CONDITIONS_MEASURED);
Paul Jensen306f1a42014-08-04 10:59:01 -04001332 switch (mNetworkAgentInfo.networkInfo.getType()) {
1333 case ConnectivityManager.TYPE_WIFI:
1334 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
1335 if (currentWifiInfo != null) {
1336 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
1337 // surrounded by double quotation marks (thus violating the Javadoc), but this
1338 // was changed to match the Javadoc in API 17. Since clients may have started
1339 // sanitizing the output of this method since API 17 was released, we should
1340 // not change it here as it would become impossible to tell whether the SSID is
1341 // simply being surrounded by quotes due to the API, or whether those quotes
1342 // are actually part of the SSID.
Chalard Jean918a68b2018-01-19 17:00:47 +09001343 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_SSID,
1344 currentWifiInfo.getSSID());
1345 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_BSSID,
1346 currentWifiInfo.getBSSID());
Paul Jensen306f1a42014-08-04 10:59:01 -04001347 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001348 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -04001349 return;
1350 }
1351 break;
1352 case ConnectivityManager.TYPE_MOBILE:
Chalard Jean918a68b2018-01-19 17:00:47 +09001353 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_NETWORK_TYPE,
1354 mTelephonyManager.getNetworkType());
Paul Jensen306f1a42014-08-04 10:59:01 -04001355 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
1356 if (info == null) return;
1357 int numRegisteredCellInfo = 0;
1358 for (CellInfo cellInfo : info) {
1359 if (cellInfo.isRegistered()) {
1360 numRegisteredCellInfo++;
1361 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001362 if (VDBG) logw("more than one registered CellInfo." +
1363 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -04001364 return;
1365 }
1366 if (cellInfo instanceof CellInfoCdma) {
1367 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001368 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001369 } else if (cellInfo instanceof CellInfoGsm) {
1370 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001371 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001372 } else if (cellInfo instanceof CellInfoLte) {
1373 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001374 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001375 } else if (cellInfo instanceof CellInfoWcdma) {
1376 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
Chalard Jean918a68b2018-01-19 17:00:47 +09001377 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CELL_ID, cellId);
Paul Jensen306f1a42014-08-04 10:59:01 -04001378 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001379 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -04001380 return;
1381 }
1382 }
1383 }
1384 break;
1385 default:
1386 return;
1387 }
Chalard Jean918a68b2018-01-19 17:00:47 +09001388 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_CONNECTIVITY_TYPE,
1389 mNetworkAgentInfo.networkInfo.getType());
1390 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_RESPONSE_RECEIVED,
1391 responseReceived);
1392 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_REQUEST_TIMESTAMP_MS,
1393 requestTimestampMs);
Paul Jensen306f1a42014-08-04 10:59:01 -04001394
1395 if (responseReceived) {
Chalard Jean918a68b2018-01-19 17:00:47 +09001396 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_IS_CAPTIVE_PORTAL,
1397 isCaptivePortal);
1398 latencyBroadcast.putExtra(ConnectivityConstants.EXTRA_RESPONSE_TIMESTAMP_MS,
1399 responseTimestampMs);
Paul Jensen306f1a42014-08-04 10:59:01 -04001400 }
Paul Jensen55298582014-08-20 11:01:41 -04001401 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
Chalard Jean918a68b2018-01-19 17:00:47 +09001402 ConnectivityConstants.PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001403 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001404
Hugo Benichicfddd682016-05-31 16:28:06 +09001405 private void logNetworkEvent(int evtype) {
Hugo Benichi97bfd272017-11-11 08:06:43 +09001406 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
1407 mMetricsLog.log(mNetId, transports, new NetworkEvent(evtype));
Hugo Benichicfddd682016-05-31 16:28:06 +09001408 }
1409
Hugo Benichidd229822016-11-15 23:23:24 +09001410 private int networkEventType(ValidationStage s, EvaluationResult r) {
1411 if (s.isFirstValidation) {
1412 if (r.isValidated) {
1413 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS;
1414 } else {
1415 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND;
1416 }
1417 } else {
1418 if (r.isValidated) {
1419 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS;
1420 } else {
1421 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND;
1422 }
1423 }
1424 }
1425
Hugo Benichicfddd682016-05-31 16:28:06 +09001426 private void maybeLogEvaluationResult(int evtype) {
1427 if (mEvaluationTimer.isRunning()) {
Hugo Benichi97bfd272017-11-11 08:06:43 +09001428 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
1429 mMetricsLog.log(mNetId, transports, new NetworkEvent(evtype, mEvaluationTimer.stop()));
Hugo Benichicfddd682016-05-31 16:28:06 +09001430 mEvaluationTimer.reset();
1431 }
1432 }
1433
1434 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
Hugo Benichia365bac2017-03-22 18:29:58 +09001435 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
Hugo Benichif927f0c2017-03-17 15:42:40 +09001436 boolean isFirstValidation = validationStage().isFirstValidation;
1437 ValidationProbeEvent ev = new ValidationProbeEvent();
1438 ev.probeType = ValidationProbeEvent.makeProbeType(probeType, isFirstValidation);
1439 ev.returnCode = probeResult;
1440 ev.durationMs = durationMs;
1441 mMetricsLog.log(mNetId, transports, ev);
Hugo Benichicfddd682016-05-31 16:28:06 +09001442 }
Hugo Benichic894b122017-07-31 12:58:20 +09001443
1444 @VisibleForTesting
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001445 public static class Dependencies {
1446 public Network getNetwork(NetworkAgentInfo networkAgentInfo) {
1447 return new OneAddressPerFamilyNetwork(networkAgentInfo.network());
1448 }
Hugo Benichic894b122017-07-31 12:58:20 +09001449
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001450 public Random getRandom() {
1451 return new Random();
1452 }
Hugo Benichic894b122017-07-31 12:58:20 +09001453
Hugo Benichic894b122017-07-31 12:58:20 +09001454 public int getSetting(Context context, String symbol, int defaultValue) {
1455 return Settings.Global.getInt(context.getContentResolver(), symbol, defaultValue);
1456 }
1457
1458 public String getSetting(Context context, String symbol, String defaultValue) {
1459 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
1460 return value != null ? value : defaultValue;
1461 }
Remi NGUYEN VANd9a1cd72018-05-22 13:11:15 +09001462
1463 public static final Dependencies DEFAULT = new Dependencies();
Hugo Benichic894b122017-07-31 12:58:20 +09001464 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001465}