1 /* 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 17 package com.android.server.connectivity; 18 19 import static android.net.CaptivePortal.APP_RETURN_DISMISSED; 20 import static android.net.CaptivePortal.APP_RETURN_UNWANTED; 21 import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS; 22 import static android.net.ConnectivityManager.EXTRA_CAPTIVE_PORTAL_PROBE_SPEC; 23 import static android.net.ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL; 24 import static android.net.DnsResolver.FLAG_EMPTY; 25 import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_INVALID; 26 import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY; 27 import static android.net.INetworkMonitor.NETWORK_TEST_RESULT_VALID; 28 import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_DNS; 29 import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_FALLBACK; 30 import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_HTTP; 31 import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_HTTPS; 32 import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS; 33 import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL; 34 import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID; 35 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; 36 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; 37 import static android.net.captiveportal.CaptivePortalProbeSpec.parseCaptivePortalProbeSpecs; 38 import static android.net.metrics.ValidationProbeEvent.DNS_FAILURE; 39 import static android.net.metrics.ValidationProbeEvent.DNS_SUCCESS; 40 import static android.net.metrics.ValidationProbeEvent.PROBE_FALLBACK; 41 import static android.net.metrics.ValidationProbeEvent.PROBE_PRIVDNS; 42 import static android.net.util.DataStallUtils.CONFIG_DATA_STALL_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD; 43 import static android.net.util.DataStallUtils.CONFIG_DATA_STALL_EVALUATION_TYPE; 44 import static android.net.util.DataStallUtils.CONFIG_DATA_STALL_MIN_EVALUATE_INTERVAL; 45 import static android.net.util.DataStallUtils.CONFIG_DATA_STALL_TCP_POLLING_INTERVAL; 46 import static android.net.util.DataStallUtils.CONFIG_DATA_STALL_VALID_DNS_TIME_THRESHOLD; 47 import static android.net.util.DataStallUtils.DATA_STALL_EVALUATION_TYPE_DNS; 48 import static android.net.util.DataStallUtils.DATA_STALL_EVALUATION_TYPE_NONE; 49 import static android.net.util.DataStallUtils.DATA_STALL_EVALUATION_TYPE_TCP; 50 import static android.net.util.DataStallUtils.DEFAULT_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD; 51 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_EVALUATION_TYPES; 52 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_MIN_EVALUATE_TIME_MS; 53 import static android.net.util.DataStallUtils.DEFAULT_DATA_STALL_VALID_DNS_TIME_THRESHOLD_MS; 54 import static android.net.util.DataStallUtils.DEFAULT_DNS_LOG_SIZE; 55 import static android.net.util.DataStallUtils.DEFAULT_TCP_POLLING_INTERVAL_MS; 56 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS; 57 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_FALLBACK_URL; 58 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTPS_URL; 59 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_HTTP_URL; 60 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE; 61 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_IGNORE; 62 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_MODE_PROMPT; 63 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS; 64 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTPS_URLS; 65 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_OTHER_HTTP_URLS; 66 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_USER_AGENT; 67 import static android.net.util.NetworkStackUtils.CAPTIVE_PORTAL_USE_HTTPS; 68 import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT; 69 import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS; 70 import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTPS_URLS; 71 import static android.net.util.NetworkStackUtils.DEFAULT_CAPTIVE_PORTAL_HTTP_URLS; 72 import static android.net.util.NetworkStackUtils.DISMISS_PORTAL_IN_VALIDATED_NETWORK; 73 import static android.net.util.NetworkStackUtils.DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION; 74 import static android.net.util.NetworkStackUtils.TEST_CAPTIVE_PORTAL_HTTPS_URL; 75 import static android.net.util.NetworkStackUtils.TEST_CAPTIVE_PORTAL_HTTP_URL; 76 import static android.net.util.NetworkStackUtils.TEST_URL_EXPIRATION_TIME; 77 import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY; 78 79 import static com.android.net.module.util.CollectionUtils.isEmpty; 80 import static com.android.net.module.util.ConnectivityUtils.isIPv6ULA; 81 import static com.android.net.module.util.DeviceConfigUtils.getResBooleanConfig; 82 import static com.android.networkstack.apishim.ConstantsShim.DETECTION_METHOD_DNS_EVENTS; 83 import static com.android.networkstack.apishim.ConstantsShim.DETECTION_METHOD_TCP_METRICS; 84 import static com.android.networkstack.apishim.ConstantsShim.TRANSPORT_TEST; 85 import static com.android.networkstack.util.DnsUtils.PRIVATE_DNS_PROBE_HOST_SUFFIX; 86 import static com.android.networkstack.util.DnsUtils.TYPE_ADDRCONFIG; 87 88 import android.app.PendingIntent; 89 import android.content.BroadcastReceiver; 90 import android.content.Context; 91 import android.content.Intent; 92 import android.content.IntentFilter; 93 import android.content.pm.PackageManager; 94 import android.content.res.Configuration; 95 import android.content.res.Resources; 96 import android.net.ConnectivityManager; 97 import android.net.DataStallReportParcelable; 98 import android.net.DnsResolver; 99 import android.net.INetworkMonitorCallbacks; 100 import android.net.LinkProperties; 101 import android.net.Network; 102 import android.net.NetworkCapabilities; 103 import android.net.NetworkTestResultParcelable; 104 import android.net.ProxyInfo; 105 import android.net.TrafficStats; 106 import android.net.Uri; 107 import android.net.captiveportal.CapportApiProbeResult; 108 import android.net.captiveportal.CaptivePortalProbeResult; 109 import android.net.captiveportal.CaptivePortalProbeSpec; 110 import android.net.metrics.IpConnectivityLog; 111 import android.net.metrics.NetworkEvent; 112 import android.net.metrics.ValidationProbeEvent; 113 import android.net.shared.NetworkMonitorUtils; 114 import android.net.shared.PrivateDnsConfig; 115 import android.net.util.DataStallUtils.EvaluationType; 116 import android.net.util.NetworkStackUtils; 117 import android.net.util.SharedLog; 118 import android.net.util.Stopwatch; 119 import android.net.wifi.WifiInfo; 120 import android.net.wifi.WifiManager; 121 import android.os.Build; 122 import android.os.Bundle; 123 import android.os.Message; 124 import android.os.Process; 125 import android.os.RemoteException; 126 import android.os.SystemClock; 127 import android.os.SystemProperties; 128 import android.provider.DeviceConfig; 129 import android.provider.Settings; 130 import android.stats.connectivity.ProbeResult; 131 import android.stats.connectivity.ProbeType; 132 import android.telephony.CellIdentityNr; 133 import android.telephony.CellInfo; 134 import android.telephony.CellInfoGsm; 135 import android.telephony.CellInfoLte; 136 import android.telephony.CellInfoNr; 137 import android.telephony.CellInfoTdscdma; 138 import android.telephony.CellInfoWcdma; 139 import android.telephony.CellSignalStrength; 140 import android.telephony.SignalStrength; 141 import android.telephony.TelephonyManager; 142 import android.text.TextUtils; 143 import android.util.Log; 144 import android.util.Pair; 145 import android.util.SparseArray; 146 147 import androidx.annotation.ArrayRes; 148 import androidx.annotation.IntegerRes; 149 import androidx.annotation.NonNull; 150 import androidx.annotation.Nullable; 151 import androidx.annotation.StringRes; 152 import androidx.annotation.VisibleForTesting; 153 154 import com.android.internal.annotations.GuardedBy; 155 import com.android.internal.util.RingBufferIndices; 156 import com.android.internal.util.State; 157 import com.android.internal.util.StateMachine; 158 import com.android.net.module.util.DeviceConfigUtils; 159 import com.android.net.module.util.NetworkStackConstants; 160 import com.android.networkstack.NetworkStackNotifier; 161 import com.android.networkstack.R; 162 import com.android.networkstack.apishim.CaptivePortalDataShimImpl; 163 import com.android.networkstack.apishim.NetworkInformationShimImpl; 164 import com.android.networkstack.apishim.api29.ConstantsShim; 165 import com.android.networkstack.apishim.common.CaptivePortalDataShim; 166 import com.android.networkstack.apishim.common.NetworkInformationShim; 167 import com.android.networkstack.apishim.common.ShimUtils; 168 import com.android.networkstack.apishim.common.UnsupportedApiLevelException; 169 import com.android.networkstack.metrics.DataStallDetectionStats; 170 import com.android.networkstack.metrics.DataStallStatsUtils; 171 import com.android.networkstack.metrics.NetworkValidationMetrics; 172 import com.android.networkstack.netlink.TcpSocketTracker; 173 import com.android.networkstack.util.DnsUtils; 174 import com.android.server.NetworkStackService.NetworkStackServiceManager; 175 176 import org.json.JSONException; 177 import org.json.JSONObject; 178 179 import java.io.BufferedInputStream; 180 import java.io.IOException; 181 import java.io.InputStream; 182 import java.io.InputStreamReader; 183 import java.io.InterruptedIOException; 184 import java.net.HttpURLConnection; 185 import java.net.InetAddress; 186 import java.net.MalformedURLException; 187 import java.net.URL; 188 import java.net.UnknownHostException; 189 import java.nio.charset.Charset; 190 import java.nio.charset.StandardCharsets; 191 import java.util.ArrayList; 192 import java.util.Arrays; 193 import java.util.Collections; 194 import java.util.HashMap; 195 import java.util.LinkedHashMap; 196 import java.util.List; 197 import java.util.Map; 198 import java.util.Objects; 199 import java.util.Random; 200 import java.util.StringJoiner; 201 import java.util.UUID; 202 import java.util.concurrent.CompletionService; 203 import java.util.concurrent.CountDownLatch; 204 import java.util.concurrent.ExecutionException; 205 import java.util.concurrent.ExecutorCompletionService; 206 import java.util.concurrent.ExecutorService; 207 import java.util.concurrent.Executors; 208 import java.util.concurrent.Future; 209 import java.util.concurrent.TimeUnit; 210 import java.util.concurrent.atomic.AtomicInteger; 211 import java.util.function.Function; 212 import java.util.regex.Matcher; 213 import java.util.regex.Pattern; 214 import java.util.regex.PatternSyntaxException; 215 216 /** 217 * {@hide} 218 */ 219 public class NetworkMonitor extends StateMachine { 220 private static final String TAG = NetworkMonitor.class.getSimpleName(); 221 private static final boolean DBG = true; 222 private static final boolean VDBG = false; 223 // TODO(b/185082309): For flaky test debug only, remove it after fixing. 224 private static final boolean DDBG_STALL = "cf_x86_auto-userdebug".equals( 225 SystemProperties.get("ro.build.flavor", "")); 226 private static final boolean VDBG_STALL = Log.isLoggable(TAG, Log.DEBUG); 227 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) " 228 + "AppleWebKit/537.36 (KHTML, like Gecko) " 229 + "Chrome/60.0.3112.32 Safari/537.36"; 230 231 @VisibleForTesting 232 static final String CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT = 233 "captive_portal_dns_probe_timeout"; 234 235 private static final int SOCKET_TIMEOUT_MS = 10000; 236 private static final int PROBE_TIMEOUT_MS = 3000; 237 private static final long TEST_URL_EXPIRATION_MS = TimeUnit.MINUTES.toMillis(10); 238 239 private static final int UNSET_MCC_OR_MNC = -1; 240 241 private static final int CAPPORT_API_MAX_JSON_LENGTH = 4096; 242 private static final String ACCEPT_HEADER = "Accept"; 243 private static final String CONTENT_TYPE_HEADER = "Content-Type"; 244 private static final String CAPPORT_API_CONTENT_TYPE = "application/captive+json"; 245 246 enum EvaluationResult { 247 VALIDATED(true), 248 CAPTIVE_PORTAL(false); 249 final boolean mIsValidated; EvaluationResult(boolean isValidated)250 EvaluationResult(boolean isValidated) { 251 this.mIsValidated = isValidated; 252 } 253 } 254 255 enum ValidationStage { 256 FIRST_VALIDATION(true), 257 REVALIDATION(false); 258 final boolean mIsFirstValidation; ValidationStage(boolean isFirstValidation)259 ValidationStage(boolean isFirstValidation) { 260 this.mIsFirstValidation = isFirstValidation; 261 } 262 } 263 264 @VisibleForTesting 265 protected static final class MccMncOverrideInfo { 266 public final int mcc; 267 public final int mnc; MccMncOverrideInfo(int mcc, int mnc)268 MccMncOverrideInfo(int mcc, int mnc) { 269 this.mcc = mcc; 270 this.mnc = mnc; 271 } 272 } 273 274 @VisibleForTesting 275 protected static final SparseArray<MccMncOverrideInfo> sCarrierIdToMccMnc = new SparseArray<>(); 276 277 static { 278 // CTC 279 sCarrierIdToMccMnc.put(1854, new MccMncOverrideInfo(460, 03)); 280 } 281 282 /** 283 * ConnectivityService has sent a notification to indicate that network has connected. 284 * Initiates Network Validation. 285 */ 286 private static final int CMD_NETWORK_CONNECTED = 1; 287 288 /** 289 * Message to self indicating it's time to evaluate a network's connectivity. 290 * arg1 = Token to ignore old messages. 291 */ 292 private static final int CMD_REEVALUATE = 6; 293 294 /** 295 * ConnectivityService has sent a notification to indicate that network has disconnected. 296 */ 297 private static final int CMD_NETWORK_DISCONNECTED = 7; 298 299 /** 300 * Force evaluation even if it has succeeded in the past. 301 * arg1 = UID responsible for requesting this reeval. Will be billed for data. 302 */ 303 private static final int CMD_FORCE_REEVALUATION = 8; 304 305 /** 306 * Message to self indicating captive portal app finished. 307 * arg1 = one of: APP_RETURN_DISMISSED, 308 * APP_RETURN_UNWANTED, 309 * APP_RETURN_WANTED_AS_IS 310 * obj = mCaptivePortalLoggedInResponseToken as String 311 */ 312 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = 9; 313 314 /** 315 * Message indicating sign-in app should be launched. 316 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the 317 * user touches the sign in notification, or sent by 318 * ConnectivityService when the user touches the "sign into 319 * network" button in the wifi access point detail page. 320 */ 321 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = 11; 322 323 /** 324 * Retest network to see if captive portal is still in place. 325 * arg1 = UID responsible for requesting this reeval. Will be billed for data. 326 * 0 indicates self-initiated, so nobody to blame. 327 */ 328 private static final int CMD_CAPTIVE_PORTAL_RECHECK = 12; 329 330 /** 331 * ConnectivityService notifies NetworkMonitor of settings changes to 332 * Private DNS. If a DNS resolution is required, e.g. for DNS-over-TLS in 333 * strict mode, then an event is sent back to ConnectivityService with the 334 * result of the resolution attempt. 335 * 336 * A separate message is used to trigger (re)evaluation of the Private DNS 337 * configuration, so that the message can be handled as needed in different 338 * states, including being ignored until after an ongoing captive portal 339 * validation phase is completed. 340 */ 341 private static final int CMD_PRIVATE_DNS_SETTINGS_CHANGED = 13; 342 private static final int CMD_EVALUATE_PRIVATE_DNS = 15; 343 344 /** 345 * Message to self indicating captive portal detection is completed. 346 * obj = CaptivePortalProbeResult for detection result; 347 */ 348 private static final int CMD_PROBE_COMPLETE = 16; 349 350 /** 351 * ConnectivityService notifies NetworkMonitor of DNS query responses event. 352 * arg1 = returncode in OnDnsEvent which indicates the response code for the DNS query. 353 */ 354 private static final int EVENT_DNS_NOTIFICATION = 17; 355 356 /** 357 * ConnectivityService notifies NetworkMonitor that the user accepts partial connectivity and 358 * NetworkMonitor should ignore the https probe. 359 */ 360 private static final int EVENT_ACCEPT_PARTIAL_CONNECTIVITY = 18; 361 362 /** 363 * ConnectivityService notifies NetworkMonitor of changed LinkProperties. 364 * obj = new LinkProperties. 365 */ 366 private static final int EVENT_LINK_PROPERTIES_CHANGED = 19; 367 368 /** 369 * ConnectivityService notifies NetworkMonitor of changed NetworkCapabilities. 370 * obj = new NetworkCapabilities. 371 */ 372 private static final int EVENT_NETWORK_CAPABILITIES_CHANGED = 20; 373 374 /** 375 * Message to self to poll current tcp status from kernel. 376 */ 377 private static final int EVENT_POLL_TCPINFO = 21; 378 379 /** 380 * Message to self to do the bandwidth check in EvaluatingBandwidthState. 381 */ 382 private static final int CMD_EVALUATE_BANDWIDTH = 22; 383 384 /** 385 * Message to self to know the bandwidth check is completed. 386 */ 387 private static final int CMD_BANDWIDTH_CHECK_COMPLETE = 23; 388 389 /** 390 * Message to self to know the bandwidth check is timeouted. 391 */ 392 private static final int CMD_BANDWIDTH_CHECK_TIMEOUT = 24; 393 394 // Start mReevaluateDelayMs at this value and double. 395 @VisibleForTesting 396 static final int INITIAL_REEVALUATE_DELAY_MS = 1000; 397 private static final int MAX_REEVALUATE_DELAY_MS = 10 * 60 * 1000; 398 // Default timeout of evaluating network bandwidth. 399 private static final int DEFAULT_EVALUATING_BANDWIDTH_TIMEOUT_MS = 10_000; 400 // Before network has been evaluated this many times, ignore repeated reevaluate requests. 401 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5; 402 private int mReevaluateToken = 0; 403 private static final int NO_UID = 0; 404 private static final int INVALID_UID = -1; 405 private int mUidResponsibleForReeval = INVALID_UID; 406 // Stop blaming UID that requested re-evaluation after this many attempts. 407 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5; 408 // Delay between reevaluations once a captive portal has been found. 409 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10 * 60 * 1000; 410 private static final int NETWORK_VALIDATION_RESULT_INVALID = 0; 411 // Max thread pool size for parallel probing. Fixed thread pool size to control the thread 412 // number used for either HTTP or HTTPS probing. 413 @VisibleForTesting 414 static final int MAX_PROBE_THREAD_POOL_SIZE = 5; 415 private String mPrivateDnsProviderHostname = ""; 416 417 private final Context mContext; 418 private final Context mCustomizedContext; 419 private final INetworkMonitorCallbacks mCallback; 420 private final int mCallbackVersion; 421 private final Network mCleartextDnsNetwork; 422 private final Network mNetwork; 423 private final TelephonyManager mTelephonyManager; 424 private final WifiManager mWifiManager; 425 private final ConnectivityManager mCm; 426 @Nullable 427 private final NetworkStackNotifier mNotifier; 428 private final IpConnectivityLog mMetricsLog; 429 private final Dependencies mDependencies; 430 private final TcpSocketTracker mTcpTracker; 431 // Configuration values for captive portal detection probes. 432 private final String mCaptivePortalUserAgent; 433 private final URL[] mCaptivePortalFallbackUrls; 434 @NonNull 435 private final URL[] mCaptivePortalHttpUrls; 436 @NonNull 437 private final URL[] mCaptivePortalHttpsUrls; 438 @Nullable 439 private final CaptivePortalProbeSpec[] mCaptivePortalFallbackSpecs; 440 // Configuration values for network bandwidth check. 441 @Nullable 442 private final String mEvaluatingBandwidthUrl; 443 private final int mMaxRetryTimerMs; 444 private final int mEvaluatingBandwidthTimeoutMs; 445 private final AtomicInteger mNextEvaluatingBandwidthThreadId = new AtomicInteger(1); 446 447 private NetworkCapabilities mNetworkCapabilities; 448 private LinkProperties mLinkProperties; 449 450 @VisibleForTesting 451 protected boolean mIsCaptivePortalCheckEnabled; 452 453 private boolean mUseHttps; 454 /** 455 * The total number of completed validation attempts (network validated or a captive portal was 456 * detected) for this NetworkMonitor instance. 457 * This does not include attempts that were interrupted, retried or finished with a result that 458 * is not success or portal. See {@code mValidationIndex} in {@link NetworkValidationMetrics} 459 * for a count of all attempts. 460 * TODO: remove when removing legacy metrics. 461 */ 462 private int mValidations = 0; 463 464 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app. 465 private boolean mUserDoesNotWant = false; 466 // Avoids surfacing "Sign in to network" notification. 467 private boolean mDontDisplaySigninNotification = false; 468 // Set to true once the evaluating network bandwidth is passed or the captive portal respond 469 // APP_RETURN_WANTED_AS_IS which means the user wants to use this network anyway. 470 @VisibleForTesting 471 protected boolean mIsBandwidthCheckPassedOrIgnored = false; 472 473 private final State mDefaultState = new DefaultState(); 474 private final State mValidatedState = new ValidatedState(); 475 private final State mMaybeNotifyState = new MaybeNotifyState(); 476 private final State mEvaluatingState = new EvaluatingState(); 477 private final State mCaptivePortalState = new CaptivePortalState(); 478 private final State mEvaluatingPrivateDnsState = new EvaluatingPrivateDnsState(); 479 private final State mProbingState = new ProbingState(); 480 private final State mWaitingForNextProbeState = new WaitingForNextProbeState(); 481 private final State mEvaluatingBandwidthState = new EvaluatingBandwidthState(); 482 483 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null; 484 485 private final SharedLog mValidationLogs; 486 487 private final Stopwatch mEvaluationTimer = new Stopwatch(); 488 489 // This variable is set before transitioning to the mCaptivePortalState. 490 private CaptivePortalProbeResult mLastPortalProbeResult = 491 CaptivePortalProbeResult.failed(CaptivePortalProbeResult.PROBE_UNKNOWN); 492 493 // Random generator to select fallback URL index 494 private final Random mRandom; 495 private int mNextFallbackUrlIndex = 0; 496 497 498 private int mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS; 499 private int mEvaluateAttempts = 0; 500 private volatile int mProbeToken = 0; 501 private final int mConsecutiveDnsTimeoutThreshold; 502 private final int mDataStallMinEvaluateTime; 503 private final int mDataStallValidDnsTimeThreshold; 504 private final int mDataStallEvaluationType; 505 @Nullable 506 private final DnsStallDetector mDnsStallDetector; 507 private long mLastProbeTime; 508 // A bitmask of signals causing a data stall to be suspected. Reset to 509 // {@link DataStallUtils#DATA_STALL_EVALUATION_TYPE_NONE} after metrics are sent to statsd. 510 private @EvaluationType int mDataStallTypeToCollect; 511 private boolean mAcceptPartialConnectivity = false; 512 private final EvaluationState mEvaluationState = new EvaluationState(); 513 514 private final boolean mPrivateIpNoInternetEnabled; 515 516 private final boolean mMetricsEnabled; 517 @NonNull 518 private final NetworkInformationShim mInfoShim = NetworkInformationShimImpl.newInstance(); 519 520 // The validation metrics are accessed by individual probe threads, and by the StateMachine 521 // thread. All accesses must be synchronized to make sure the StateMachine thread can see 522 // reports from all probes. 523 // TODO: as that most usage is in the StateMachine thread and probes only add their probe 524 // events, consider having probes return their stats to the StateMachine, and only access this 525 // member on the StateMachine thread without synchronization. 526 @GuardedBy("mNetworkValidationMetrics") 527 private final NetworkValidationMetrics mNetworkValidationMetrics = 528 new NetworkValidationMetrics(); 529 getCallbackVersion(INetworkMonitorCallbacks cb)530 private int getCallbackVersion(INetworkMonitorCallbacks cb) { 531 int version; 532 try { 533 version = cb.getInterfaceVersion(); 534 } catch (RemoteException e) { 535 version = 0; 536 } 537 // The AIDL was freezed from Q beta 5 but it's unfreezing from R before releasing. In order 538 // to distinguish the behavior between R and Q beta 5 and before Q beta 5, add SDK and 539 // CODENAME check here. Basically, it's only expected to return 0 for Q beta 4 and below 540 // because the test result has changed. 541 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q 542 && Build.VERSION.CODENAME.equals("REL") 543 && version == Build.VERSION_CODES.CUR_DEVELOPMENT) version = 0; 544 return version; 545 } 546 NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network, SharedLog validationLog, @NonNull NetworkStackServiceManager serviceManager)547 public NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network, 548 SharedLog validationLog, @NonNull NetworkStackServiceManager serviceManager) { 549 this(context, cb, network, new IpConnectivityLog(), validationLog, serviceManager, 550 Dependencies.DEFAULT, getTcpSocketTrackerOrNull(context, network)); 551 } 552 553 @VisibleForTesting NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network, IpConnectivityLog logger, SharedLog validationLogs, @NonNull NetworkStackServiceManager serviceManager, Dependencies deps, @Nullable TcpSocketTracker tst)554 public NetworkMonitor(Context context, INetworkMonitorCallbacks cb, Network network, 555 IpConnectivityLog logger, SharedLog validationLogs, 556 @NonNull NetworkStackServiceManager serviceManager, Dependencies deps, 557 @Nullable TcpSocketTracker tst) { 558 // Add suffix indicating which NetworkMonitor we're talking about. 559 super(TAG + "/" + network.toString()); 560 561 // Logs with a tag of the form given just above, e.g. 562 // <timestamp> 862 2402 D NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: ... 563 setDbg(VDBG); 564 565 mContext = context; 566 mMetricsLog = logger; 567 mValidationLogs = validationLogs; 568 mCallback = cb; 569 mCallbackVersion = getCallbackVersion(cb); 570 mDependencies = deps; 571 mNetwork = network; 572 mCleartextDnsNetwork = deps.getPrivateDnsBypassNetwork(network); 573 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 574 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 575 mCm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 576 mNotifier = serviceManager.getNotifier(); 577 mCustomizedContext = getCustomizedContextOrDefault(); 578 579 // CHECKSTYLE:OFF IndentationCheck 580 addState(mDefaultState); 581 addState(mMaybeNotifyState, mDefaultState); 582 addState(mEvaluatingState, mMaybeNotifyState); 583 addState(mProbingState, mEvaluatingState); 584 addState(mWaitingForNextProbeState, mEvaluatingState); 585 addState(mCaptivePortalState, mMaybeNotifyState); 586 addState(mEvaluatingPrivateDnsState, mDefaultState); 587 addState(mEvaluatingBandwidthState, mDefaultState); 588 addState(mValidatedState, mDefaultState); 589 setInitialState(mDefaultState); 590 // CHECKSTYLE:ON IndentationCheck 591 592 mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled(); 593 mPrivateIpNoInternetEnabled = getIsPrivateIpNoInternetEnabled(); 594 mMetricsEnabled = deps.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, 595 NetworkStackUtils.VALIDATION_METRICS_VERSION, true /* defaultEnabled */); 596 mUseHttps = getUseHttpsValidation(); 597 mCaptivePortalUserAgent = getCaptivePortalUserAgent(); 598 mCaptivePortalHttpsUrls = makeCaptivePortalHttpsUrls(); 599 mCaptivePortalHttpUrls = makeCaptivePortalHttpUrls(); 600 mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls(); 601 mCaptivePortalFallbackSpecs = makeCaptivePortalFallbackProbeSpecs(); 602 mRandom = deps.getRandom(); 603 // TODO: Evaluate to move data stall configuration to a specific class. 604 mConsecutiveDnsTimeoutThreshold = getConsecutiveDnsTimeoutThreshold(); 605 mDataStallMinEvaluateTime = getDataStallMinEvaluateTime(); 606 mDataStallValidDnsTimeThreshold = getDataStallValidDnsTimeThreshold(); 607 mDataStallEvaluationType = getDataStallEvaluationType(); 608 mDnsStallDetector = initDnsStallDetectorIfRequired(mDataStallEvaluationType, 609 mConsecutiveDnsTimeoutThreshold); 610 mTcpTracker = tst; 611 // Read the configurations of evaluating network bandwidth. 612 mEvaluatingBandwidthUrl = getResStringConfig(mContext, 613 R.string.config_evaluating_bandwidth_url, null); 614 mMaxRetryTimerMs = getResIntConfig(mContext, 615 R.integer.config_evaluating_bandwidth_max_retry_timer_ms, 616 MAX_REEVALUATE_DELAY_MS); 617 mEvaluatingBandwidthTimeoutMs = getResIntConfig(mContext, 618 R.integer.config_evaluating_bandwidth_timeout_ms, 619 DEFAULT_EVALUATING_BANDWIDTH_TIMEOUT_MS); 620 621 // Provide empty LinkProperties and NetworkCapabilities to make sure they are never null, 622 // even before notifyNetworkConnected. 623 mLinkProperties = new LinkProperties(); 624 mNetworkCapabilities = new NetworkCapabilities(null); 625 } 626 627 /** 628 * ConnectivityService notifies NetworkMonitor that the user already accepted partial 629 * connectivity previously, so NetworkMonitor can validate the network even if it has partial 630 * connectivity. 631 */ setAcceptPartialConnectivity()632 public void setAcceptPartialConnectivity() { 633 sendMessage(EVENT_ACCEPT_PARTIAL_CONNECTIVITY); 634 } 635 636 /** 637 * Request the NetworkMonitor to reevaluate the network. 638 */ forceReevaluation(int responsibleUid)639 public void forceReevaluation(int responsibleUid) { 640 sendMessage(CMD_FORCE_REEVALUATION, responsibleUid, 0); 641 } 642 643 /** 644 * Send a notification to NetworkMonitor indicating that there was a DNS query response event. 645 * @param returnCode the DNS return code of the response. 646 */ notifyDnsResponse(int returnCode)647 public void notifyDnsResponse(int returnCode) { 648 sendMessage(EVENT_DNS_NOTIFICATION, returnCode); 649 } 650 651 /** 652 * Send a notification to NetworkMonitor indicating that private DNS settings have changed. 653 * @param newCfg The new private DNS configuration. 654 */ notifyPrivateDnsSettingsChanged(PrivateDnsConfig newCfg)655 public void notifyPrivateDnsSettingsChanged(PrivateDnsConfig newCfg) { 656 // Cancel any outstanding resolutions. 657 removeMessages(CMD_PRIVATE_DNS_SETTINGS_CHANGED); 658 // Send the update to the proper thread. 659 sendMessage(CMD_PRIVATE_DNS_SETTINGS_CHANGED, newCfg); 660 } 661 662 /** 663 * Send a notification to NetworkMonitor indicating that the network is now connected. 664 */ notifyNetworkConnected(LinkProperties lp, NetworkCapabilities nc)665 public void notifyNetworkConnected(LinkProperties lp, NetworkCapabilities nc) { 666 sendMessage(CMD_NETWORK_CONNECTED, new Pair<>( 667 new LinkProperties(lp), new NetworkCapabilities(nc))); 668 } 669 updateConnectedNetworkAttributes(Message connectedMsg)670 private void updateConnectedNetworkAttributes(Message connectedMsg) { 671 final Pair<LinkProperties, NetworkCapabilities> attrs = 672 (Pair<LinkProperties, NetworkCapabilities>) connectedMsg.obj; 673 mLinkProperties = attrs.first; 674 mNetworkCapabilities = attrs.second; 675 suppressNotificationIfNetworkRestricted(); 676 } 677 678 /** 679 * Send a notification to NetworkMonitor indicating that the network is now disconnected. 680 */ notifyNetworkDisconnected()681 public void notifyNetworkDisconnected() { 682 sendMessage(CMD_NETWORK_DISCONNECTED); 683 } 684 685 /** 686 * Send a notification to NetworkMonitor indicating that link properties have changed. 687 */ notifyLinkPropertiesChanged(final LinkProperties lp)688 public void notifyLinkPropertiesChanged(final LinkProperties lp) { 689 sendMessage(EVENT_LINK_PROPERTIES_CHANGED, new LinkProperties(lp)); 690 } 691 692 /** 693 * Send a notification to NetworkMonitor indicating that network capabilities have changed. 694 */ notifyNetworkCapabilitiesChanged(final NetworkCapabilities nc)695 public void notifyNetworkCapabilitiesChanged(final NetworkCapabilities nc) { 696 sendMessage(EVENT_NETWORK_CAPABILITIES_CHANGED, new NetworkCapabilities(nc)); 697 } 698 699 /** 700 * Request the captive portal application to be launched. 701 */ launchCaptivePortalApp()702 public void launchCaptivePortalApp() { 703 sendMessage(CMD_LAUNCH_CAPTIVE_PORTAL_APP); 704 } 705 706 /** 707 * Notify that the captive portal app was closed with the provided response code. 708 */ notifyCaptivePortalAppFinished(int response)709 public void notifyCaptivePortalAppFinished(int response) { 710 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response); 711 } 712 713 @Override log(String s)714 protected void log(String s) { 715 if (DBG) Log.d(TAG + "/" + mCleartextDnsNetwork.toString(), s); 716 } 717 validationLog(int probeType, Object url, String msg)718 private void validationLog(int probeType, Object url, String msg) { 719 String probeName = ValidationProbeEvent.getProbeName(probeType); 720 validationLog(String.format("%s %s %s", probeName, url, msg)); 721 } 722 validationLog(String s)723 private void validationLog(String s) { 724 if (DBG) log(s); 725 mValidationLogs.log(s); 726 } 727 validationStage()728 private ValidationStage validationStage() { 729 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION; 730 } 731 isValidationRequired()732 private boolean isValidationRequired() { 733 return NetworkMonitorUtils.isValidationRequired(mNetworkCapabilities); 734 } 735 isPrivateDnsValidationRequired()736 private boolean isPrivateDnsValidationRequired() { 737 return NetworkMonitorUtils.isPrivateDnsValidationRequired(mNetworkCapabilities); 738 } 739 suppressNotificationIfNetworkRestricted()740 private void suppressNotificationIfNetworkRestricted() { 741 if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { 742 mDontDisplaySigninNotification = true; 743 } 744 } 745 notifyNetworkTested(NetworkTestResultParcelable result)746 private void notifyNetworkTested(NetworkTestResultParcelable result) { 747 try { 748 if (mCallbackVersion <= 5) { 749 mCallback.notifyNetworkTested( 750 getLegacyTestResult(result.result, result.probesSucceeded), 751 result.redirectUrl); 752 } else { 753 mCallback.notifyNetworkTestedWithExtras(result); 754 } 755 } catch (RemoteException e) { 756 Log.e(TAG, "Error sending network test result", e); 757 } 758 } 759 760 /** 761 * Get the test result that was used as an int up to interface version 5. 762 * 763 * <p>For callback version < 3 (only used in Q beta preview builds), the int represented one of 764 * the NETWORK_TEST_RESULT_* constants. 765 * 766 * <p>Q released with version 3, which used a single int for both the evaluation result bitmask, 767 * and the probesSucceeded bitmask. 768 */ getLegacyTestResult(int evaluationResult, int probesSucceeded)769 protected int getLegacyTestResult(int evaluationResult, int probesSucceeded) { 770 if (mCallbackVersion < 3) { 771 if ((evaluationResult & NETWORK_VALIDATION_RESULT_VALID) != 0) { 772 return NETWORK_TEST_RESULT_VALID; 773 } 774 if ((evaluationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0) { 775 return NETWORK_TEST_RESULT_PARTIAL_CONNECTIVITY; 776 } 777 return NETWORK_TEST_RESULT_INVALID; 778 } 779 780 return evaluationResult | probesSucceeded; 781 } 782 notifyProbeStatusChanged(int probesCompleted, int probesSucceeded)783 private void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) { 784 try { 785 mCallback.notifyProbeStatusChanged(probesCompleted, probesSucceeded); 786 } catch (RemoteException e) { 787 Log.e(TAG, "Error sending probe status", e); 788 } 789 } 790 showProvisioningNotification(String action)791 private void showProvisioningNotification(String action) { 792 try { 793 mCallback.showProvisioningNotification(action, mContext.getPackageName()); 794 } catch (RemoteException e) { 795 Log.e(TAG, "Error showing provisioning notification", e); 796 } 797 } 798 hideProvisioningNotification()799 private void hideProvisioningNotification() { 800 try { 801 mCallback.hideProvisioningNotification(); 802 } catch (RemoteException e) { 803 Log.e(TAG, "Error hiding provisioning notification", e); 804 } 805 } 806 notifyDataStallSuspected(@onNull DataStallReportParcelable p)807 private void notifyDataStallSuspected(@NonNull DataStallReportParcelable p) { 808 try { 809 mCallback.notifyDataStallSuspected(p); 810 } catch (RemoteException e) { 811 Log.e(TAG, "Error sending notification for suspected data stall", e); 812 } 813 } 814 startMetricsCollection()815 private void startMetricsCollection() { 816 if (!mMetricsEnabled) return; 817 try { 818 synchronized (mNetworkValidationMetrics) { 819 mNetworkValidationMetrics.startCollection(mNetworkCapabilities); 820 } 821 } catch (Exception e) { 822 Log.wtf(TAG, "Error resetting validation metrics", e); 823 } 824 } 825 recordProbeEventMetrics(ProbeType type, long latencyMicros, ProbeResult result, CaptivePortalDataShim capportData)826 private void recordProbeEventMetrics(ProbeType type, long latencyMicros, ProbeResult result, 827 CaptivePortalDataShim capportData) { 828 if (!mMetricsEnabled) return; 829 try { 830 synchronized (mNetworkValidationMetrics) { 831 mNetworkValidationMetrics.addProbeEvent(type, latencyMicros, result, capportData); 832 } 833 } catch (Exception e) { 834 Log.wtf(TAG, "Error recording probe event", e); 835 } 836 } 837 recordValidationResult(int result, String redirectUrl)838 private void recordValidationResult(int result, String redirectUrl) { 839 if (!mMetricsEnabled) return; 840 try { 841 synchronized (mNetworkValidationMetrics) { 842 mNetworkValidationMetrics.setValidationResult(result, redirectUrl); 843 } 844 } catch (Exception e) { 845 Log.wtf(TAG, "Error recording validation result", e); 846 } 847 } 848 maybeStopCollectionAndSendMetrics()849 private void maybeStopCollectionAndSendMetrics() { 850 if (!mMetricsEnabled) return; 851 try { 852 synchronized (mNetworkValidationMetrics) { 853 mNetworkValidationMetrics.maybeStopCollectionAndSend(); 854 } 855 } catch (Exception e) { 856 Log.wtf(TAG, "Error sending validation stats", e); 857 } 858 } 859 860 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but 861 // does not entail any real state (hence no enter() or exit() routines). 862 private class DefaultState extends State { 863 @Override processMessage(Message message)864 public boolean processMessage(Message message) { 865 switch (message.what) { 866 case CMD_NETWORK_CONNECTED: 867 updateConnectedNetworkAttributes(message); 868 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED); 869 transitionTo(mEvaluatingState); 870 return HANDLED; 871 case CMD_NETWORK_DISCONNECTED: 872 maybeStopCollectionAndSendMetrics(); 873 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED); 874 quit(); 875 return HANDLED; 876 case CMD_FORCE_REEVALUATION: 877 case CMD_CAPTIVE_PORTAL_RECHECK: 878 if (getCurrentState() == mDefaultState) { 879 // Before receiving CMD_NETWORK_CONNECTED (when still in mDefaultState), 880 // requests to reevaluate are not valid: drop them. 881 return HANDLED; 882 } 883 String msg = "Forcing reevaluation for UID " + message.arg1; 884 final DnsStallDetector dsd = getDnsStallDetector(); 885 if (dsd != null) { 886 msg += ". Dns signal count: " + dsd.getConsecutiveTimeoutCount(); 887 } 888 validationLog(msg); 889 mUidResponsibleForReeval = message.arg1; 890 transitionTo(mEvaluatingState); 891 return HANDLED; 892 case CMD_CAPTIVE_PORTAL_APP_FINISHED: 893 log("CaptivePortal App responded with " + message.arg1); 894 895 // If the user has seen and acted on a captive portal notification, and the 896 // captive portal app is now closed, disable HTTPS probes. This avoids the 897 // following pathological situation: 898 // 899 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out. 900 // 2. User opens the app and logs into the captive portal. 901 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason - 902 // perhaps due to the network blocking HTTPS? 903 // 904 // In this case, we'll fail to validate the network even after the app is 905 // dismissed. There is now no way to use this network, because the app is now 906 // gone, so the user cannot select "Use this network as is". 907 mUseHttps = false; 908 909 switch (message.arg1) { 910 case APP_RETURN_DISMISSED: 911 sendMessage(CMD_FORCE_REEVALUATION, NO_UID, 0); 912 break; 913 case APP_RETURN_WANTED_AS_IS: 914 mDontDisplaySigninNotification = true; 915 // If the user wants to use this network anyway, there is no need to 916 // perform the bandwidth check even if configured. 917 mIsBandwidthCheckPassedOrIgnored = true; 918 // TODO: Distinguish this from a network that actually validates. 919 // Displaying the "x" on the system UI icon may still be a good idea. 920 transitionTo(mEvaluatingPrivateDnsState); 921 break; 922 case APP_RETURN_UNWANTED: 923 mDontDisplaySigninNotification = true; 924 mUserDoesNotWant = true; 925 mEvaluationState.reportEvaluationResult( 926 NETWORK_VALIDATION_RESULT_INVALID, null); 927 // TODO: Should teardown network. 928 mUidResponsibleForReeval = 0; 929 transitionTo(mEvaluatingState); 930 break; 931 } 932 return HANDLED; 933 case CMD_PRIVATE_DNS_SETTINGS_CHANGED: { 934 final PrivateDnsConfig cfg = (PrivateDnsConfig) message.obj; 935 if (!isPrivateDnsValidationRequired() || cfg == null || !cfg.inStrictMode()) { 936 // No DNS resolution required. 937 // 938 // We don't force any validation in opportunistic mode 939 // here. Opportunistic mode nameservers are validated 940 // separately within netd. 941 // 942 // Reset Private DNS settings state. 943 mPrivateDnsProviderHostname = ""; 944 break; 945 } 946 947 mPrivateDnsProviderHostname = cfg.hostname; 948 949 // DNS resolutions via Private DNS strict mode block for a 950 // few seconds (~4.2) checking for any IP addresses to 951 // arrive and validate. Initiating a (re)evaluation now 952 // should not significantly alter the validation outcome. 953 // 954 // No matter what: enqueue a validation request; one of 955 // three things can happen with this request: 956 // [1] ignored (EvaluatingState or CaptivePortalState) 957 // [2] transition to EvaluatingPrivateDnsState 958 // (DefaultState and ValidatedState) 959 // [3] handled (EvaluatingPrivateDnsState) 960 // 961 // The Private DNS configuration to be evaluated will: 962 // [1] be skipped (not in strict mode), or 963 // [2] validate (huzzah), or 964 // [3] encounter some problem (invalid hostname, 965 // no resolved IP addresses, IPs unreachable, 966 // port 853 unreachable, port 853 is not running a 967 // DNS-over-TLS server, et cetera). 968 // Cancel any outstanding CMD_EVALUATE_PRIVATE_DNS. 969 removeMessages(CMD_EVALUATE_PRIVATE_DNS); 970 sendMessage(CMD_EVALUATE_PRIVATE_DNS); 971 break; 972 } 973 case EVENT_DNS_NOTIFICATION: 974 final DnsStallDetector detector = getDnsStallDetector(); 975 if (detector != null) { 976 detector.accumulateConsecutiveDnsTimeoutCount(message.arg1); 977 } 978 break; 979 // Set mAcceptPartialConnectivity to true and if network start evaluating or 980 // re-evaluating and get the result of partial connectivity, ProbingState will 981 // disable HTTPS probe and transition to EvaluatingPrivateDnsState. 982 case EVENT_ACCEPT_PARTIAL_CONNECTIVITY: 983 maybeDisableHttpsProbing(true /* acceptPartial */); 984 break; 985 case EVENT_LINK_PROPERTIES_CHANGED: 986 final Uri oldCapportUrl = getCaptivePortalApiUrl(mLinkProperties); 987 mLinkProperties = (LinkProperties) message.obj; 988 final Uri newCapportUrl = getCaptivePortalApiUrl(mLinkProperties); 989 if (!Objects.equals(oldCapportUrl, newCapportUrl)) { 990 sendMessage(CMD_FORCE_REEVALUATION, NO_UID, 0); 991 } 992 break; 993 case EVENT_NETWORK_CAPABILITIES_CHANGED: 994 mNetworkCapabilities = (NetworkCapabilities) message.obj; 995 suppressNotificationIfNetworkRestricted(); 996 break; 997 default: 998 break; 999 } 1000 return HANDLED; 1001 } 1002 } 1003 1004 // Being in the ValidatedState State indicates a Network is: 1005 // - Successfully validated, or 1006 // - Wanted "as is" by the user, or 1007 // - Does not satisfy the default NetworkRequest and so validation has been skipped. 1008 private class ValidatedState extends State { 1009 @Override enter()1010 public void enter() { 1011 maybeLogEvaluationResult( 1012 networkEventType(validationStage(), EvaluationResult.VALIDATED)); 1013 // If the user has accepted partial connectivity and HTTPS probing is disabled, then 1014 // mark the network as validated and partial so that settings can keep informing the 1015 // user that the connection is limited. 1016 int result = NETWORK_VALIDATION_RESULT_VALID; 1017 if (!mUseHttps && mAcceptPartialConnectivity) { 1018 result |= NETWORK_VALIDATION_RESULT_PARTIAL; 1019 } 1020 mEvaluationState.reportEvaluationResult(result, null /* redirectUrl */); 1021 mValidations++; 1022 initSocketTrackingIfRequired(); 1023 // start periodical polling. 1024 sendTcpPollingEvent(); 1025 maybeStopCollectionAndSendMetrics(); 1026 } 1027 initSocketTrackingIfRequired()1028 private void initSocketTrackingIfRequired() { 1029 if (!isValidationRequired()) return; 1030 1031 final TcpSocketTracker tst = getTcpSocketTracker(); 1032 if (tst != null) { 1033 tst.pollSocketsInfo(); 1034 } 1035 } 1036 1037 @Override processMessage(Message message)1038 public boolean processMessage(Message message) { 1039 switch (message.what) { 1040 case CMD_NETWORK_CONNECTED: 1041 updateConnectedNetworkAttributes(message); 1042 transitionTo(mValidatedState); 1043 break; 1044 case CMD_EVALUATE_PRIVATE_DNS: 1045 // TODO: this causes reevaluation of a single probe that is not counted in 1046 // metrics. Add support for such reevaluation probes in metrics, and log them 1047 // separately. 1048 transitionTo(mEvaluatingPrivateDnsState); 1049 break; 1050 case EVENT_DNS_NOTIFICATION: 1051 final DnsStallDetector dsd = getDnsStallDetector(); 1052 if (dsd == null) break; 1053 1054 dsd.accumulateConsecutiveDnsTimeoutCount(message.arg1); 1055 if (evaluateDataStall()) { 1056 transitionTo(mEvaluatingState); 1057 } 1058 break; 1059 case EVENT_POLL_TCPINFO: 1060 final TcpSocketTracker tst = getTcpSocketTracker(); 1061 if (tst == null) break; 1062 // Transit if retrieve socket info is succeeded and suspected as a stall. 1063 if (tst.pollSocketsInfo() && evaluateDataStall()) { 1064 transitionTo(mEvaluatingState); 1065 } else { 1066 sendTcpPollingEvent(); 1067 } 1068 break; 1069 default: 1070 return NOT_HANDLED; 1071 } 1072 return HANDLED; 1073 } 1074 evaluateDataStall()1075 boolean evaluateDataStall() { 1076 if (isDataStall()) { 1077 validationLog("Suspecting data stall, reevaluate"); 1078 return true; 1079 } 1080 return false; 1081 } 1082 1083 @Override exit()1084 public void exit() { 1085 // Not useful for non-ValidatedState. 1086 removeMessages(EVENT_POLL_TCPINFO); 1087 } 1088 } 1089 1090 @VisibleForTesting sendTcpPollingEvent()1091 void sendTcpPollingEvent() { 1092 if (isValidationRequired()) { 1093 sendMessageDelayed(EVENT_POLL_TCPINFO, getTcpPollingInterval()); 1094 } 1095 } 1096 maybeWriteDataStallStats(@onNull final CaptivePortalProbeResult result)1097 private void maybeWriteDataStallStats(@NonNull final CaptivePortalProbeResult result) { 1098 if (mDataStallTypeToCollect == DATA_STALL_EVALUATION_TYPE_NONE) return; 1099 /* 1100 * Collect data stall detection level information for each transport type. Collect type 1101 * specific information for cellular and wifi only currently. Generate 1102 * DataStallDetectionStats for each transport type. E.g., if a network supports both 1103 * TRANSPORT_WIFI and TRANSPORT_VPN, two DataStallDetectionStats will be generated. 1104 */ 1105 final int[] transports = mNetworkCapabilities.getTransportTypes(); 1106 for (int i = 0; i < transports.length; i++) { 1107 final DataStallDetectionStats stats = 1108 buildDataStallDetectionStats(transports[i], mDataStallTypeToCollect); 1109 mDependencies.writeDataStallDetectionStats(stats, result); 1110 } 1111 mDataStallTypeToCollect = DATA_STALL_EVALUATION_TYPE_NONE; 1112 } 1113 1114 @VisibleForTesting buildDataStallDetectionStats(int transport, @EvaluationType int evaluationType)1115 protected DataStallDetectionStats buildDataStallDetectionStats(int transport, 1116 @EvaluationType int evaluationType) { 1117 final DataStallDetectionStats.Builder stats = new DataStallDetectionStats.Builder(); 1118 if (VDBG_STALL) { 1119 log("collectDataStallMetrics: type=" + transport + ", evaluation=" + evaluationType); 1120 } 1121 stats.setEvaluationType(evaluationType); 1122 stats.setNetworkType(transport); 1123 switch (transport) { 1124 case NetworkCapabilities.TRANSPORT_WIFI: 1125 // TODO: Update it if status query in dual wifi is supported. 1126 final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); 1127 stats.setWiFiData(wifiInfo); 1128 break; 1129 case NetworkCapabilities.TRANSPORT_CELLULAR: 1130 final boolean isRoaming = !mNetworkCapabilities.hasCapability( 1131 NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING); 1132 final SignalStrength ss = mTelephonyManager.getSignalStrength(); 1133 // TODO(b/120452078): Support multi-sim. 1134 stats.setCellData( 1135 mTelephonyManager.getDataNetworkType(), 1136 isRoaming, 1137 mTelephonyManager.getNetworkOperator(), 1138 mTelephonyManager.getSimOperator(), 1139 (ss != null) 1140 ? ss.getLevel() : CellSignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN); 1141 break; 1142 default: 1143 // No transport type specific information for the other types. 1144 break; 1145 } 1146 1147 addDnsEvents(stats); 1148 addTcpStats(stats); 1149 1150 return stats.build(); 1151 } 1152 addTcpStats(@onNull final DataStallDetectionStats.Builder stats)1153 private void addTcpStats(@NonNull final DataStallDetectionStats.Builder stats) { 1154 final TcpSocketTracker tst = getTcpSocketTracker(); 1155 if (tst == null) return; 1156 1157 stats.setTcpSentSinceLastRecv(tst.getSentSinceLastRecv()); 1158 stats.setTcpFailRate(tst.getLatestPacketFailPercentage()); 1159 } 1160 1161 @VisibleForTesting addDnsEvents(@onNull final DataStallDetectionStats.Builder stats)1162 protected void addDnsEvents(@NonNull final DataStallDetectionStats.Builder stats) { 1163 final DnsStallDetector dsd = getDnsStallDetector(); 1164 if (dsd == null) return; 1165 1166 final int size = dsd.mResultIndices.size(); 1167 for (int i = 1; i <= DEFAULT_DNS_LOG_SIZE && i <= size; i++) { 1168 final int index = dsd.mResultIndices.indexOf(size - i); 1169 stats.addDnsEvent(dsd.mDnsEvents[index].mReturnCode, dsd.mDnsEvents[index].mTimeStamp); 1170 } 1171 } 1172 1173 1174 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in 1175 // is required. This State takes care to clear the notification upon exit from the State. 1176 private class MaybeNotifyState extends State { 1177 @Override processMessage(Message message)1178 public boolean processMessage(Message message) { 1179 switch (message.what) { 1180 case CMD_LAUNCH_CAPTIVE_PORTAL_APP: 1181 final Bundle appExtras = new Bundle(); 1182 // OneAddressPerFamilyNetwork is not parcelable across processes. 1183 final Network network = new Network(mCleartextDnsNetwork); 1184 appExtras.putParcelable(ConnectivityManager.EXTRA_NETWORK, network); 1185 final CaptivePortalProbeResult probeRes = mLastPortalProbeResult; 1186 // Use redirect URL from AP if exists. 1187 final String portalUrl = 1188 (useRedirectUrlForPortal() && makeURL(probeRes.redirectUrl) != null) 1189 ? probeRes.redirectUrl : probeRes.detectUrl; 1190 appExtras.putString(EXTRA_CAPTIVE_PORTAL_URL, portalUrl); 1191 if (probeRes.probeSpec != null) { 1192 final String encodedSpec = probeRes.probeSpec.getEncodedSpec(); 1193 appExtras.putString(EXTRA_CAPTIVE_PORTAL_PROBE_SPEC, encodedSpec); 1194 } 1195 appExtras.putString(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT, 1196 mCaptivePortalUserAgent); 1197 if (mNotifier != null) { 1198 mNotifier.notifyCaptivePortalValidationPending(network); 1199 } 1200 mCm.startCaptivePortalApp(network, appExtras); 1201 return HANDLED; 1202 default: 1203 return NOT_HANDLED; 1204 } 1205 } 1206 useRedirectUrlForPortal()1207 private boolean useRedirectUrlForPortal() { 1208 // It must match the conditions in CaptivePortalLogin in which the redirect URL is not 1209 // used to validate that the portal is gone. 1210 final boolean aboveQ = 1211 ShimUtils.isReleaseOrDevelopmentApiAbove(Build.VERSION_CODES.Q); 1212 return aboveQ && mDependencies.isFeatureEnabled(mContext, NAMESPACE_CONNECTIVITY, 1213 DISMISS_PORTAL_IN_VALIDATED_NETWORK, aboveQ /* defaultEnabled */); 1214 } 1215 1216 @Override exit()1217 public void exit() { 1218 if (mLaunchCaptivePortalAppBroadcastReceiver != null) { 1219 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver); 1220 mLaunchCaptivePortalAppBroadcastReceiver = null; 1221 } 1222 hideProvisioningNotification(); 1223 } 1224 } 1225 1226 // Being in the EvaluatingState State indicates the Network is being evaluated for internet 1227 // connectivity, or that the user has indicated that this network is unwanted. 1228 private class EvaluatingState extends State { 1229 private Uri mEvaluatingCapportUrl; 1230 1231 @Override enter()1232 public void enter() { 1233 // If we have already started to track time spent in EvaluatingState 1234 // don't reset the timer due simply to, say, commands or events that 1235 // cause us to exit and re-enter EvaluatingState. 1236 if (!mEvaluationTimer.isStarted()) { 1237 mEvaluationTimer.start(); 1238 } 1239 1240 // Check if the network is captive with Terms & Conditions page. The first network 1241 // evaluation for captive networks with T&Cs returns early but NetworkMonitor will then 1242 // keep checking for connectivity to determine when the T&Cs are cleared. 1243 if (isTermsAndConditionsCaptive(mInfoShim.getCaptivePortalData(mLinkProperties)) 1244 && mValidations == 0) { 1245 mLastPortalProbeResult = new CaptivePortalProbeResult( 1246 CaptivePortalProbeResult.PORTAL_CODE, 1247 mLinkProperties.getCaptivePortalData().getUserPortalUrl() 1248 .toString(), null, 1249 CaptivePortalProbeResult.PROBE_UNKNOWN); 1250 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_INVALID, 1251 mLastPortalProbeResult.redirectUrl); 1252 transitionTo(mCaptivePortalState); 1253 return; 1254 } 1255 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0); 1256 if (mUidResponsibleForReeval != INVALID_UID) { 1257 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval); 1258 mUidResponsibleForReeval = INVALID_UID; 1259 } 1260 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS; 1261 mEvaluateAttempts = 0; 1262 mEvaluatingCapportUrl = getCaptivePortalApiUrl(mLinkProperties); 1263 // Reset all current probe results to zero, but retain current validation state until 1264 // validation succeeds or fails. 1265 mEvaluationState.clearProbeResults(); 1266 } 1267 1268 @Override processMessage(Message message)1269 public boolean processMessage(Message message) { 1270 switch (message.what) { 1271 case CMD_REEVALUATE: 1272 if (message.arg1 != mReevaluateToken || mUserDoesNotWant) { 1273 return HANDLED; 1274 } 1275 // Don't bother validating networks that don't satisfy the default request. 1276 // This includes: 1277 // - VPNs which can be considered explicitly desired by the user and the 1278 // user's desire trumps whether the network validates. 1279 // - Networks that don't provide Internet access. It's unclear how to 1280 // validate such networks. 1281 // - Untrusted networks. It's unsafe to prompt the user to sign-in to 1282 // such networks and the user didn't express interest in connecting to 1283 // such networks (an app did) so the user may be unhappily surprised when 1284 // asked to sign-in to a network they didn't want to connect to in the 1285 // first place. Validation could be done to adjust the network scores 1286 // however these networks are app-requested and may not be intended for 1287 // general usage, in which case general validation may not be an accurate 1288 // measure of the network's quality. Only the app knows how to evaluate 1289 // the network so don't bother validating here. Furthermore sending HTTP 1290 // packets over the network may be undesirable, for example an extremely 1291 // expensive metered network, or unwanted leaking of the User Agent string. 1292 // 1293 // On networks that need to support private DNS in strict mode (e.g., VPNs, but 1294 // not networks that don't provide Internet access), we still need to perform 1295 // private DNS server resolution. 1296 if (!isValidationRequired()) { 1297 if (isPrivateDnsValidationRequired()) { 1298 validationLog("Network would not satisfy default request, " 1299 + "resolving private DNS"); 1300 transitionTo(mEvaluatingPrivateDnsState); 1301 } else { 1302 validationLog("Network would not satisfy default request, " 1303 + "not validating"); 1304 transitionTo(mValidatedState); 1305 } 1306 return HANDLED; 1307 } 1308 mEvaluateAttempts++; 1309 1310 transitionTo(mProbingState); 1311 return HANDLED; 1312 case CMD_FORCE_REEVALUATION: 1313 // The evaluation process restarts via EvaluatingState#enter. 1314 return shouldAcceptForceRevalidation() ? NOT_HANDLED : HANDLED; 1315 // Disable HTTPS probe and transition to EvaluatingPrivateDnsState because: 1316 // 1. Network is connected and finish the network validation. 1317 // 2. NetworkMonitor detects network is partial connectivity and user accepts it. 1318 case EVENT_ACCEPT_PARTIAL_CONNECTIVITY: 1319 maybeDisableHttpsProbing(true /* acceptPartial */); 1320 transitionTo(mEvaluatingPrivateDnsState); 1321 return HANDLED; 1322 default: 1323 return NOT_HANDLED; 1324 } 1325 } 1326 shouldAcceptForceRevalidation()1327 private boolean shouldAcceptForceRevalidation() { 1328 // If the captive portal URL has changed since the last evaluation attempt, always 1329 // revalidate. Otherwise, ignore any re-evaluation requests before 1330 // IGNORE_REEVALUATE_ATTEMPTS are made. 1331 return mEvaluateAttempts >= IGNORE_REEVALUATE_ATTEMPTS 1332 || !Objects.equals( 1333 mEvaluatingCapportUrl, getCaptivePortalApiUrl(mLinkProperties)); 1334 } 1335 1336 @Override exit()1337 public void exit() { 1338 TrafficStats.clearThreadStatsUid(); 1339 } 1340 } 1341 1342 // BroadcastReceiver that waits for a particular Intent and then posts a message. 1343 private class CustomIntentReceiver extends BroadcastReceiver { 1344 private final int mToken; 1345 private final int mWhat; 1346 private final String mAction; CustomIntentReceiver(String action, int token, int what)1347 CustomIntentReceiver(String action, int token, int what) { 1348 mToken = token; 1349 mWhat = what; 1350 mAction = action + "_" + mCleartextDnsNetwork.getNetworkHandle() + "_" + token; 1351 mContext.registerReceiver(this, new IntentFilter(mAction)); 1352 } getPendingIntent()1353 public PendingIntent getPendingIntent() { 1354 final Intent intent = new Intent(mAction); 1355 intent.setPackage(mContext.getPackageName()); 1356 return PendingIntent.getBroadcast(mContext, 0, intent, 0); 1357 } 1358 @Override onReceive(Context context, Intent intent)1359 public void onReceive(Context context, Intent intent) { 1360 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken)); 1361 } 1362 } 1363 1364 // Being in the CaptivePortalState State indicates a captive portal was detected and the user 1365 // has been shown a notification to sign-in. 1366 private class CaptivePortalState extends State { 1367 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP = 1368 "android.net.netmon.launchCaptivePortalApp"; 1369 1370 @Override enter()1371 public void enter() { 1372 maybeLogEvaluationResult( 1373 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL)); 1374 // Don't annoy user with sign-in notifications. 1375 if (mDontDisplaySigninNotification) return; 1376 // Create a CustomIntentReceiver that sends us a 1377 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user 1378 // touches the notification. 1379 if (mLaunchCaptivePortalAppBroadcastReceiver == null) { 1380 // Wait for result. 1381 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver( 1382 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(), 1383 CMD_LAUNCH_CAPTIVE_PORTAL_APP); 1384 // Display the sign in notification. 1385 // Only do this once for every time we enter MaybeNotifyState. b/122164725 1386 showProvisioningNotification(mLaunchCaptivePortalAppBroadcastReceiver.mAction); 1387 } 1388 // Retest for captive portal occasionally. 1389 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */, 1390 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS); 1391 mValidations++; 1392 maybeStopCollectionAndSendMetrics(); 1393 } 1394 1395 @Override exit()1396 public void exit() { 1397 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK); 1398 } 1399 } 1400 1401 private class EvaluatingPrivateDnsState extends State { 1402 private int mPrivateDnsReevalDelayMs; 1403 private PrivateDnsConfig mPrivateDnsConfig; 1404 1405 @Override enter()1406 public void enter() { 1407 mPrivateDnsReevalDelayMs = INITIAL_REEVALUATE_DELAY_MS; 1408 mPrivateDnsConfig = null; 1409 sendMessage(CMD_EVALUATE_PRIVATE_DNS); 1410 } 1411 1412 @Override processMessage(Message msg)1413 public boolean processMessage(Message msg) { 1414 switch (msg.what) { 1415 case CMD_EVALUATE_PRIVATE_DNS: 1416 if (inStrictMode()) { 1417 if (!isStrictModeHostnameResolved()) { 1418 resolveStrictModeHostname(); 1419 1420 if (isStrictModeHostnameResolved()) { 1421 notifyPrivateDnsConfigResolved(); 1422 } else { 1423 handlePrivateDnsEvaluationFailure(); 1424 // The private DNS probe fails-fast if the server hostname cannot 1425 // be resolved. Record it as a failure with zero latency. 1426 // TODO: refactor this together with the probe recorded in 1427 // sendPrivateDnsProbe, so logging is symmetric / easier to follow. 1428 recordProbeEventMetrics(ProbeType.PT_PRIVDNS, 0 /* latency */, 1429 ProbeResult.PR_FAILURE, null /* capportData */); 1430 break; 1431 } 1432 } 1433 1434 // Look up a one-time hostname, to bypass caching. 1435 // 1436 // Note that this will race with ConnectivityService 1437 // code programming the DNS-over-TLS server IP addresses 1438 // into netd (if invoked, above). If netd doesn't know 1439 // the IP addresses yet, or if the connections to the IP 1440 // addresses haven't yet been validated, netd will block 1441 // for up to a few seconds before failing the lookup. 1442 if (!sendPrivateDnsProbe()) { 1443 handlePrivateDnsEvaluationFailure(); 1444 break; 1445 } 1446 handlePrivateDnsEvaluationSuccess(); 1447 } else { 1448 mEvaluationState.removeProbeResult(NETWORK_VALIDATION_PROBE_PRIVDNS); 1449 } 1450 1451 if (needEvaluatingBandwidth()) { 1452 transitionTo(mEvaluatingBandwidthState); 1453 } else { 1454 // All good! 1455 transitionTo(mValidatedState); 1456 } 1457 break; 1458 case CMD_PRIVATE_DNS_SETTINGS_CHANGED: 1459 // When settings change the reevaluation timer must be reset. 1460 mPrivateDnsReevalDelayMs = INITIAL_REEVALUATE_DELAY_MS; 1461 // Let the message bubble up and be handled by parent states as usual. 1462 return NOT_HANDLED; 1463 default: 1464 return NOT_HANDLED; 1465 } 1466 return HANDLED; 1467 } 1468 inStrictMode()1469 private boolean inStrictMode() { 1470 return !TextUtils.isEmpty(mPrivateDnsProviderHostname); 1471 } 1472 isStrictModeHostnameResolved()1473 private boolean isStrictModeHostnameResolved() { 1474 return (mPrivateDnsConfig != null) 1475 && mPrivateDnsConfig.hostname.equals(mPrivateDnsProviderHostname) 1476 && (mPrivateDnsConfig.ips.length > 0); 1477 } 1478 resolveStrictModeHostname()1479 private void resolveStrictModeHostname() { 1480 try { 1481 // Do a blocking DNS resolution using the network-assigned nameservers. 1482 final InetAddress[] ips = DnsUtils.getAllByName(mDependencies.getDnsResolver(), 1483 mCleartextDnsNetwork, mPrivateDnsProviderHostname, getDnsProbeTimeout(), 1484 str -> validationLog("Strict mode hostname resolution " + str)); 1485 mPrivateDnsConfig = new PrivateDnsConfig(mPrivateDnsProviderHostname, ips); 1486 } catch (UnknownHostException uhe) { 1487 mPrivateDnsConfig = null; 1488 } 1489 } 1490 notifyPrivateDnsConfigResolved()1491 private void notifyPrivateDnsConfigResolved() { 1492 try { 1493 mCallback.notifyPrivateDnsConfigResolved(mPrivateDnsConfig.toParcel()); 1494 } catch (RemoteException e) { 1495 Log.e(TAG, "Error sending private DNS config resolved notification", e); 1496 } 1497 } 1498 handlePrivateDnsEvaluationSuccess()1499 private void handlePrivateDnsEvaluationSuccess() { 1500 mEvaluationState.noteProbeResult(NETWORK_VALIDATION_PROBE_PRIVDNS, 1501 true /* succeeded */); 1502 } 1503 handlePrivateDnsEvaluationFailure()1504 private void handlePrivateDnsEvaluationFailure() { 1505 mEvaluationState.noteProbeResult(NETWORK_VALIDATION_PROBE_PRIVDNS, 1506 false /* succeeded */); 1507 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_INVALID, 1508 null /* redirectUrl */); 1509 // Queue up a re-evaluation with backoff. 1510 // 1511 // TODO: Consider abandoning this state after a few attempts and 1512 // transitioning back to EvaluatingState, to perhaps give ourselves 1513 // the opportunity to (re)detect a captive portal or something. 1514 // 1515 sendMessageDelayed(CMD_EVALUATE_PRIVATE_DNS, mPrivateDnsReevalDelayMs); 1516 mPrivateDnsReevalDelayMs *= 2; 1517 if (mPrivateDnsReevalDelayMs > MAX_REEVALUATE_DELAY_MS) { 1518 mPrivateDnsReevalDelayMs = MAX_REEVALUATE_DELAY_MS; 1519 } 1520 } 1521 sendPrivateDnsProbe()1522 private boolean sendPrivateDnsProbe() { 1523 final String host = UUID.randomUUID().toString().substring(0, 8) 1524 + PRIVATE_DNS_PROBE_HOST_SUFFIX; 1525 final Stopwatch watch = new Stopwatch().start(); 1526 boolean success = false; 1527 long time; 1528 try { 1529 final InetAddress[] ips = mNetwork.getAllByName(host); 1530 time = watch.stop(); 1531 final String strIps = Arrays.toString(ips); 1532 success = (ips != null && ips.length > 0); 1533 validationLog(PROBE_PRIVDNS, host, String.format("%dus: %s", time, strIps)); 1534 } catch (UnknownHostException uhe) { 1535 time = watch.stop(); 1536 validationLog(PROBE_PRIVDNS, host, 1537 String.format("%dus - Error: %s", time, uhe.getMessage())); 1538 } 1539 recordProbeEventMetrics(ProbeType.PT_PRIVDNS, time, success ? ProbeResult.PR_SUCCESS : 1540 ProbeResult.PR_FAILURE, null /* capportData */); 1541 logValidationProbe(time, PROBE_PRIVDNS, success ? DNS_SUCCESS : DNS_FAILURE); 1542 return success; 1543 } 1544 } 1545 1546 private class ProbingState extends State { 1547 private Thread mThread; 1548 1549 @Override enter()1550 public void enter() { 1551 // When starting a full probe cycle here, record any pending stats (for example if 1552 // CMD_FORCE_REEVALUATE was called before evaluation finished, as can happen in 1553 // EvaluatingPrivateDnsState). 1554 maybeStopCollectionAndSendMetrics(); 1555 // Restart the metrics collection timers. Metrics will be stopped and sent when the 1556 // validation attempt finishes (as success, failure or portal), or if it is interrupted 1557 // (by being restarted or if NetworkMonitor stops). 1558 startMetricsCollection(); 1559 if (mEvaluateAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) { 1560 //Don't continue to blame UID forever. 1561 TrafficStats.clearThreadStatsUid(); 1562 } 1563 1564 final int token = ++mProbeToken; 1565 final ValidationProperties deps = new ValidationProperties(mNetworkCapabilities); 1566 mThread = new Thread(() -> sendMessage(obtainMessage(CMD_PROBE_COMPLETE, token, 0, 1567 isCaptivePortal(deps)))); 1568 mThread.start(); 1569 } 1570 1571 @Override processMessage(Message message)1572 public boolean processMessage(Message message) { 1573 switch (message.what) { 1574 case CMD_PROBE_COMPLETE: 1575 // Ensure that CMD_PROBE_COMPLETE from stale threads are ignored. 1576 if (message.arg1 != mProbeToken) { 1577 return HANDLED; 1578 } 1579 1580 final CaptivePortalProbeResult probeResult = 1581 (CaptivePortalProbeResult) message.obj; 1582 mLastProbeTime = SystemClock.elapsedRealtime(); 1583 1584 maybeWriteDataStallStats(probeResult); 1585 1586 if (probeResult.isSuccessful()) { 1587 // Transit EvaluatingPrivateDnsState to get to Validated 1588 // state (even if no Private DNS validation required). 1589 transitionTo(mEvaluatingPrivateDnsState); 1590 } else if (isTermsAndConditionsCaptive( 1591 mInfoShim.getCaptivePortalData(mLinkProperties))) { 1592 mLastPortalProbeResult = new CaptivePortalProbeResult( 1593 CaptivePortalProbeResult.PORTAL_CODE, 1594 mLinkProperties.getCaptivePortalData().getUserPortalUrl() 1595 .toString(), null, 1596 CaptivePortalProbeResult.PROBE_UNKNOWN); 1597 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_INVALID, 1598 mLastPortalProbeResult.redirectUrl); 1599 transitionTo(mCaptivePortalState); 1600 } else if (probeResult.isPortal()) { 1601 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_INVALID, 1602 probeResult.redirectUrl); 1603 mLastPortalProbeResult = probeResult; 1604 transitionTo(mCaptivePortalState); 1605 } else if (probeResult.isPartialConnectivity()) { 1606 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_PARTIAL, 1607 null /* redirectUrl */); 1608 maybeDisableHttpsProbing(mAcceptPartialConnectivity); 1609 if (mAcceptPartialConnectivity) { 1610 transitionTo(mEvaluatingPrivateDnsState); 1611 } else { 1612 transitionTo(mWaitingForNextProbeState); 1613 } 1614 } else { 1615 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED); 1616 mEvaluationState.reportEvaluationResult(NETWORK_VALIDATION_RESULT_INVALID, 1617 null /* redirectUrl */); 1618 transitionTo(mWaitingForNextProbeState); 1619 } 1620 return HANDLED; 1621 case EVENT_DNS_NOTIFICATION: 1622 case EVENT_ACCEPT_PARTIAL_CONNECTIVITY: 1623 // Leave the event to DefaultState. 1624 return NOT_HANDLED; 1625 default: 1626 // Wait for probe result and defer events to next state by default. 1627 deferMessage(message); 1628 return HANDLED; 1629 } 1630 } 1631 1632 @Override exit()1633 public void exit() { 1634 if (mThread.isAlive()) { 1635 mThread.interrupt(); 1636 } 1637 mThread = null; 1638 } 1639 } 1640 1641 // Being in the WaitingForNextProbeState indicates that evaluating probes failed and state is 1642 // transited from ProbingState. This ensures that the state machine is only in ProbingState 1643 // while a probe is in progress, not while waiting to perform the next probe. That allows 1644 // ProbingState to defer most messages until the probe is complete, which keeps the code simple 1645 // and matches the pre-Q behaviour where probes were a blocking operation performed on the state 1646 // machine thread. 1647 private class WaitingForNextProbeState extends State { 1648 @Override enter()1649 public void enter() { 1650 // Send metrics for this evaluation attempt. Metrics collection (and its timers) will be 1651 // restarted when the next probe starts. 1652 maybeStopCollectionAndSendMetrics(); 1653 scheduleNextProbe(); 1654 } 1655 scheduleNextProbe()1656 private void scheduleNextProbe() { 1657 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0); 1658 sendMessageDelayed(msg, mReevaluateDelayMs); 1659 mReevaluateDelayMs *= 2; 1660 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) { 1661 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS; 1662 } 1663 } 1664 1665 @Override processMessage(Message message)1666 public boolean processMessage(Message message) { 1667 return NOT_HANDLED; 1668 } 1669 } 1670 1671 private final class EvaluatingBandwidthThread extends Thread { 1672 final int mThreadId; 1673 EvaluatingBandwidthThread(int id)1674 EvaluatingBandwidthThread(int id) { 1675 mThreadId = id; 1676 } 1677 1678 @Override run()1679 public void run() { 1680 HttpURLConnection urlConnection = null; 1681 try { 1682 final URL url = makeURL(mEvaluatingBandwidthUrl); 1683 urlConnection = makeProbeConnection(url, true /* followRedirects */); 1684 // In order to exclude the time of DNS lookup, send the delay message of timeout 1685 // here. 1686 sendMessageDelayed(CMD_BANDWIDTH_CHECK_TIMEOUT, mEvaluatingBandwidthTimeoutMs); 1687 readContentFromDownloadUrl(urlConnection); 1688 } catch (InterruptedIOException e) { 1689 // There is a timing issue that someone triggers the forcing reevaluation when 1690 // executing the getInputStream(). The InterruptedIOException is thrown by 1691 // Timeout#throwIfReached, it will reset the interrupt flag of Thread. So just 1692 // return and wait for the bandwidth reevaluation, otherwise the 1693 // CMD_BANDWIDTH_CHECK_COMPLETE will be sent. 1694 validationLog("The thread is interrupted when executing the getInputStream()," 1695 + " return and wait for the bandwidth reevaluation"); 1696 return; 1697 } catch (IOException e) { 1698 validationLog("Evaluating bandwidth failed: " + e + ", if the thread is not" 1699 + " interrupted, transition to validated state directly to make sure user" 1700 + " can use wifi normally."); 1701 } finally { 1702 if (urlConnection != null) { 1703 urlConnection.disconnect(); 1704 } 1705 } 1706 // Don't send CMD_BANDWIDTH_CHECK_COMPLETE if the IO is interrupted or timeout. 1707 // Only send CMD_BANDWIDTH_CHECK_COMPLETE when the download is finished normally. 1708 // Add a serial number for CMD_BANDWIDTH_CHECK_COMPLETE to prevent handling the obsolete 1709 // CMD_BANDWIDTH_CHECK_COMPLETE. 1710 if (!isInterrupted()) sendMessage(CMD_BANDWIDTH_CHECK_COMPLETE, mThreadId); 1711 } 1712 readContentFromDownloadUrl(@onNull final HttpURLConnection conn)1713 private void readContentFromDownloadUrl(@NonNull final HttpURLConnection conn) 1714 throws IOException { 1715 final byte[] buffer = new byte[1000]; 1716 final InputStream is = conn.getInputStream(); 1717 while (!isInterrupted() && is.read(buffer) > 0) { /* read again */ } 1718 } 1719 } 1720 1721 private class EvaluatingBandwidthState extends State { 1722 private EvaluatingBandwidthThread mEvaluatingBandwidthThread; 1723 private int mRetryBandwidthDelayMs; 1724 private int mCurrentThreadId; 1725 1726 @Override enter()1727 public void enter() { 1728 mRetryBandwidthDelayMs = getResIntConfig(mContext, 1729 R.integer.config_evaluating_bandwidth_min_retry_timer_ms, 1730 INITIAL_REEVALUATE_DELAY_MS); 1731 sendMessage(CMD_EVALUATE_BANDWIDTH); 1732 } 1733 1734 @Override processMessage(Message msg)1735 public boolean processMessage(Message msg) { 1736 switch (msg.what) { 1737 case CMD_EVALUATE_BANDWIDTH: 1738 mCurrentThreadId = mNextEvaluatingBandwidthThreadId.getAndIncrement(); 1739 mEvaluatingBandwidthThread = new EvaluatingBandwidthThread(mCurrentThreadId); 1740 mEvaluatingBandwidthThread.start(); 1741 break; 1742 case CMD_BANDWIDTH_CHECK_COMPLETE: 1743 // Only handle the CMD_BANDWIDTH_CHECK_COMPLETE which is sent by the newest 1744 // EvaluatingBandwidthThread. 1745 if (mCurrentThreadId == msg.arg1) { 1746 mIsBandwidthCheckPassedOrIgnored = true; 1747 transitionTo(mValidatedState); 1748 } 1749 break; 1750 case CMD_BANDWIDTH_CHECK_TIMEOUT: 1751 validationLog("Evaluating bandwidth timeout!"); 1752 mEvaluatingBandwidthThread.interrupt(); 1753 scheduleReevaluatingBandwidth(); 1754 break; 1755 default: 1756 return NOT_HANDLED; 1757 } 1758 return HANDLED; 1759 } 1760 scheduleReevaluatingBandwidth()1761 private void scheduleReevaluatingBandwidth() { 1762 sendMessageDelayed(obtainMessage(CMD_EVALUATE_BANDWIDTH), mRetryBandwidthDelayMs); 1763 mRetryBandwidthDelayMs *= 2; 1764 if (mRetryBandwidthDelayMs > mMaxRetryTimerMs) { 1765 mRetryBandwidthDelayMs = mMaxRetryTimerMs; 1766 } 1767 } 1768 1769 @Override exit()1770 public void exit() { 1771 mEvaluatingBandwidthThread.interrupt(); 1772 removeMessages(CMD_EVALUATE_BANDWIDTH); 1773 removeMessages(CMD_BANDWIDTH_CHECK_TIMEOUT); 1774 } 1775 } 1776 1777 // Limits the list of IP addresses returned by getAllByName or tried by openConnection to at 1778 // most one per address family. This ensures we only wait up to 20 seconds for TCP connections 1779 // to complete, regardless of how many IP addresses a host has. 1780 private static class OneAddressPerFamilyNetwork extends Network { OneAddressPerFamilyNetwork(Network network)1781 OneAddressPerFamilyNetwork(Network network) { 1782 // Always bypass Private DNS. 1783 super(network.getPrivateDnsBypassingCopy()); 1784 } 1785 1786 @Override getAllByName(String host)1787 public InetAddress[] getAllByName(String host) throws UnknownHostException { 1788 final List<InetAddress> addrs = Arrays.asList(super.getAllByName(host)); 1789 1790 // Ensure the address family of the first address is tried first. 1791 LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>(); 1792 addressByFamily.put(addrs.get(0).getClass(), addrs.get(0)); 1793 Collections.shuffle(addrs); 1794 1795 for (InetAddress addr : addrs) { 1796 addressByFamily.put(addr.getClass(), addr); 1797 } 1798 1799 return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]); 1800 } 1801 } 1802 1803 @VisibleForTesting onlyWifiTransport()1804 boolean onlyWifiTransport() { 1805 int[] transportTypes = mNetworkCapabilities.getTransportTypes(); 1806 return transportTypes.length == 1 1807 && transportTypes[0] == NetworkCapabilities.TRANSPORT_WIFI; 1808 } 1809 1810 @VisibleForTesting needEvaluatingBandwidth()1811 boolean needEvaluatingBandwidth() { 1812 if (mIsBandwidthCheckPassedOrIgnored 1813 || TextUtils.isEmpty(mEvaluatingBandwidthUrl) 1814 || !mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) 1815 || !onlyWifiTransport()) { 1816 return false; 1817 } 1818 1819 return true; 1820 } 1821 getIsCaptivePortalCheckEnabled()1822 private boolean getIsCaptivePortalCheckEnabled() { 1823 String symbol = CAPTIVE_PORTAL_MODE; 1824 int defaultValue = CAPTIVE_PORTAL_MODE_PROMPT; 1825 int mode = mDependencies.getSetting(mContext, symbol, defaultValue); 1826 return mode != CAPTIVE_PORTAL_MODE_IGNORE; 1827 } 1828 getIsPrivateIpNoInternetEnabled()1829 private boolean getIsPrivateIpNoInternetEnabled() { 1830 return mDependencies.isFeatureEnabled(mContext, DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION) 1831 || mContext.getResources().getBoolean( 1832 R.bool.config_force_dns_probe_private_ip_no_internet); 1833 } 1834 getUseHttpsValidation()1835 private boolean getUseHttpsValidation() { 1836 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 1837 CAPTIVE_PORTAL_USE_HTTPS, 1) == 1; 1838 } 1839 1840 @Nullable getMccFromCellInfo(final CellInfo cell)1841 private String getMccFromCellInfo(final CellInfo cell) { 1842 if (cell instanceof CellInfoGsm) { 1843 return ((CellInfoGsm) cell).getCellIdentity().getMccString(); 1844 } else if (cell instanceof CellInfoLte) { 1845 return ((CellInfoLte) cell).getCellIdentity().getMccString(); 1846 } else if (cell instanceof CellInfoWcdma) { 1847 return ((CellInfoWcdma) cell).getCellIdentity().getMccString(); 1848 } else if (cell instanceof CellInfoTdscdma) { 1849 return ((CellInfoTdscdma) cell).getCellIdentity().getMccString(); 1850 } else if (cell instanceof CellInfoNr) { 1851 return ((CellIdentityNr) ((CellInfoNr) cell).getCellIdentity()).getMccString(); 1852 } else { 1853 return null; 1854 } 1855 } 1856 1857 /** 1858 * Return location mcc. 1859 */ 1860 @VisibleForTesting 1861 @Nullable getLocationMcc()1862 protected String getLocationMcc() { 1863 // Adding this check is because the new permission won't be granted by mainline update, 1864 // the new permission only be granted by OTA for current design. Tracking: b/145774617. 1865 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, 1866 Process.myPid(), Process.myUid()) 1867 == PackageManager.PERMISSION_DENIED) { 1868 log("getLocationMcc : NetworkStack does not hold ACCESS_FINE_LOCATION"); 1869 return null; 1870 } 1871 try { 1872 final List<CellInfo> cells = mTelephonyManager.getAllCellInfo(); 1873 if (cells == null) { 1874 log("CellInfo is null"); 1875 return null; 1876 } 1877 final Map<String, Integer> countryCodeMap = new HashMap<>(); 1878 int maxCount = 0; 1879 for (final CellInfo cell : cells) { 1880 final String mcc = getMccFromCellInfo(cell); 1881 if (mcc != null) { 1882 final int count = countryCodeMap.getOrDefault(mcc, 0) + 1; 1883 countryCodeMap.put(mcc, count); 1884 } 1885 } 1886 // Return the MCC which occurs most. 1887 if (countryCodeMap.size() <= 0) return null; 1888 return Collections.max(countryCodeMap.entrySet(), 1889 (e1, e2) -> e1.getValue().compareTo(e2.getValue())).getKey(); 1890 } catch (SecurityException e) { 1891 log("Permission is not granted:" + e); 1892 return null; 1893 } 1894 } 1895 1896 /** 1897 * Return a matched MccMncOverrideInfo if carrier id and sim mccmnc are matching a record in 1898 * sCarrierIdToMccMnc. 1899 */ 1900 @VisibleForTesting 1901 @Nullable getMccMncOverrideInfo()1902 MccMncOverrideInfo getMccMncOverrideInfo() { 1903 final int carrierId = mTelephonyManager.getSimCarrierId(); 1904 return sCarrierIdToMccMnc.get(carrierId); 1905 } 1906 getContextByMccMnc(final int mcc, final int mnc)1907 private Context getContextByMccMnc(final int mcc, final int mnc) { 1908 final Configuration config = mContext.getResources().getConfiguration(); 1909 if (mcc != UNSET_MCC_OR_MNC) config.mcc = mcc; 1910 if (mnc != UNSET_MCC_OR_MNC) config.mnc = mnc; 1911 return mContext.createConfigurationContext(config); 1912 } 1913 1914 @VisibleForTesting getCustomizedContextOrDefault()1915 protected Context getCustomizedContextOrDefault() { 1916 // Return customized context if carrier id can match a record in sCarrierIdToMccMnc. 1917 final MccMncOverrideInfo overrideInfo = getMccMncOverrideInfo(); 1918 if (overrideInfo != null) { 1919 log("Return customized context by MccMncOverrideInfo."); 1920 return getContextByMccMnc(overrideInfo.mcc, overrideInfo.mnc); 1921 } 1922 1923 // Use neighbor mcc feature only works when the config_no_sim_card_uses_neighbor_mcc is 1924 // true and there is no sim card inserted. 1925 final boolean useNeighborResource = 1926 getResBooleanConfig(mContext, R.bool.config_no_sim_card_uses_neighbor_mcc, false); 1927 if (!useNeighborResource 1928 || TelephonyManager.SIM_STATE_READY == mTelephonyManager.getSimState()) { 1929 if (useNeighborResource) log("Sim state is ready, return original context."); 1930 return mContext; 1931 } 1932 1933 final String mcc = getLocationMcc(); 1934 if (TextUtils.isEmpty(mcc)) { 1935 log("Return original context due to getting mcc failed."); 1936 return mContext; 1937 } 1938 1939 return getContextByMccMnc(Integer.parseInt(mcc), UNSET_MCC_OR_MNC); 1940 } 1941 1942 @Nullable getTestUrl(@onNull String key)1943 private URL getTestUrl(@NonNull String key) { 1944 final String strExpiration = mDependencies.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY, 1945 TEST_URL_EXPIRATION_TIME, null); 1946 if (strExpiration == null) return null; 1947 1948 final long expTime; 1949 try { 1950 expTime = Long.parseUnsignedLong(strExpiration); 1951 } catch (NumberFormatException e) { 1952 loge("Invalid test URL expiration time format", e); 1953 return null; 1954 } 1955 1956 final long now = System.currentTimeMillis(); 1957 if (expTime < now || (expTime - now) > TEST_URL_EXPIRATION_MS) return null; 1958 1959 final String strUrl = mDependencies.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY, 1960 key, null /* defaultValue */); 1961 if (!isValidTestUrl(strUrl)) return null; 1962 return makeURL(strUrl); 1963 } 1964 getCaptivePortalServerHttpsUrl()1965 private String getCaptivePortalServerHttpsUrl() { 1966 return getSettingFromResource(mCustomizedContext, 1967 R.string.config_captive_portal_https_url, CAPTIVE_PORTAL_HTTPS_URL, 1968 mCustomizedContext.getResources().getString( 1969 R.string.default_captive_portal_https_url)); 1970 } 1971 isValidTestUrl(@ullable String url)1972 private static boolean isValidTestUrl(@Nullable String url) { 1973 if (TextUtils.isEmpty(url)) return false; 1974 1975 try { 1976 // Only accept test URLs on localhost 1977 return Uri.parse(url).getHost().equals("localhost"); 1978 } catch (Throwable e) { 1979 Log.wtf(TAG, "Error parsing test URL", e); 1980 return false; 1981 } 1982 } 1983 getDnsProbeTimeout()1984 private int getDnsProbeTimeout() { 1985 return getIntSetting(mContext, R.integer.config_captive_portal_dns_probe_timeout, 1986 CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT, DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT); 1987 } 1988 1989 /** 1990 * Gets an integer setting from resources or device config 1991 * 1992 * configResource is used if set, followed by device config if set, followed by defaultValue. 1993 * If none of these are set then an exception is thrown. 1994 * 1995 * TODO: move to a common location such as a ConfigUtils class. 1996 * TODO(b/130324939): test that the resources can be overlayed by an RRO package. 1997 */ 1998 @VisibleForTesting getIntSetting(@onNull final Context context, @StringRes int configResource, @NonNull String symbol, int defaultValue)1999 int getIntSetting(@NonNull final Context context, @StringRes int configResource, 2000 @NonNull String symbol, int defaultValue) { 2001 final Resources res = context.getResources(); 2002 try { 2003 return res.getInteger(configResource); 2004 } catch (Resources.NotFoundException e) { 2005 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2006 symbol, defaultValue); 2007 } 2008 } 2009 2010 /** 2011 * Gets integer config from resources. 2012 */ 2013 @VisibleForTesting getResIntConfig(@onNull final Context context, @IntegerRes final int configResource, final int defaultValue)2014 int getResIntConfig(@NonNull final Context context, 2015 @IntegerRes final int configResource, final int defaultValue) { 2016 final Resources res = context.getResources(); 2017 try { 2018 return res.getInteger(configResource); 2019 } catch (Resources.NotFoundException e) { 2020 return defaultValue; 2021 } 2022 } 2023 2024 /** 2025 * Gets string config from resources. 2026 */ 2027 @VisibleForTesting getResStringConfig(@onNull final Context context, @StringRes final int configResource, @Nullable final String defaultValue)2028 String getResStringConfig(@NonNull final Context context, 2029 @StringRes final int configResource, @Nullable final String defaultValue) { 2030 final Resources res = context.getResources(); 2031 try { 2032 return res.getString(configResource); 2033 } catch (Resources.NotFoundException e) { 2034 return defaultValue; 2035 } 2036 } 2037 2038 /** 2039 * Get the captive portal server HTTP URL that is configured on the device. 2040 * 2041 * NetworkMonitor does not use {@link ConnectivityManager#getCaptivePortalServerUrl()} as 2042 * it has its own updatable strategies to detect captive portals. The framework only advises 2043 * on one URL that can be used, while NetworkMonitor may implement more complex logic. 2044 */ getCaptivePortalServerHttpUrl()2045 public String getCaptivePortalServerHttpUrl() { 2046 return getSettingFromResource(mCustomizedContext, 2047 R.string.config_captive_portal_http_url, CAPTIVE_PORTAL_HTTP_URL, 2048 mCustomizedContext.getResources().getString( 2049 R.string.default_captive_portal_http_url)); 2050 } 2051 getConsecutiveDnsTimeoutThreshold()2052 private int getConsecutiveDnsTimeoutThreshold() { 2053 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2054 CONFIG_DATA_STALL_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD, 2055 DEFAULT_CONSECUTIVE_DNS_TIMEOUT_THRESHOLD); 2056 } 2057 getDataStallMinEvaluateTime()2058 private int getDataStallMinEvaluateTime() { 2059 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2060 CONFIG_DATA_STALL_MIN_EVALUATE_INTERVAL, 2061 DEFAULT_DATA_STALL_MIN_EVALUATE_TIME_MS); 2062 } 2063 getDataStallValidDnsTimeThreshold()2064 private int getDataStallValidDnsTimeThreshold() { 2065 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2066 CONFIG_DATA_STALL_VALID_DNS_TIME_THRESHOLD, 2067 DEFAULT_DATA_STALL_VALID_DNS_TIME_THRESHOLD_MS); 2068 } 2069 2070 @VisibleForTesting getDataStallEvaluationType()2071 int getDataStallEvaluationType() { 2072 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2073 CONFIG_DATA_STALL_EVALUATION_TYPE, 2074 DEFAULT_DATA_STALL_EVALUATION_TYPES); 2075 } 2076 getTcpPollingInterval()2077 private int getTcpPollingInterval() { 2078 return mDependencies.getDeviceConfigPropertyInt(NAMESPACE_CONNECTIVITY, 2079 CONFIG_DATA_STALL_TCP_POLLING_INTERVAL, 2080 DEFAULT_TCP_POLLING_INTERVAL_MS); 2081 } 2082 2083 @VisibleForTesting makeCaptivePortalFallbackUrls()2084 URL[] makeCaptivePortalFallbackUrls() { 2085 try { 2086 final String firstUrl = mDependencies.getSetting(mContext, CAPTIVE_PORTAL_FALLBACK_URL, 2087 null); 2088 final URL[] settingProviderUrls = 2089 combineCaptivePortalUrls(firstUrl, CAPTIVE_PORTAL_OTHER_FALLBACK_URLS); 2090 return getProbeUrlArrayConfig(settingProviderUrls, 2091 R.array.config_captive_portal_fallback_urls, 2092 R.array.default_captive_portal_fallback_urls, 2093 this::makeURL); 2094 } catch (Exception e) { 2095 // Don't let a misconfiguration bootloop the system. 2096 Log.e(TAG, "Error parsing configured fallback URLs", e); 2097 return new URL[0]; 2098 } 2099 } 2100 makeCaptivePortalFallbackProbeSpecs()2101 private CaptivePortalProbeSpec[] makeCaptivePortalFallbackProbeSpecs() { 2102 try { 2103 final String settingsValue = mDependencies.getDeviceConfigProperty( 2104 NAMESPACE_CONNECTIVITY, CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS, null); 2105 2106 final CaptivePortalProbeSpec[] emptySpecs = new CaptivePortalProbeSpec[0]; 2107 final CaptivePortalProbeSpec[] providerValue = TextUtils.isEmpty(settingsValue) 2108 ? emptySpecs 2109 : parseCaptivePortalProbeSpecs(settingsValue).toArray(emptySpecs); 2110 2111 return getProbeUrlArrayConfig(providerValue, 2112 R.array.config_captive_portal_fallback_probe_specs, 2113 DEFAULT_CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS, 2114 CaptivePortalProbeSpec::parseSpecOrNull); 2115 } catch (Exception e) { 2116 // Don't let a misconfiguration bootloop the system. 2117 Log.e(TAG, "Error parsing configured fallback probe specs", e); 2118 return null; 2119 } 2120 } 2121 makeCaptivePortalHttpsUrls()2122 private URL[] makeCaptivePortalHttpsUrls() { 2123 final URL testUrl = getTestUrl(TEST_CAPTIVE_PORTAL_HTTPS_URL); 2124 if (testUrl != null) return new URL[] { testUrl }; 2125 2126 final String firstUrl = getCaptivePortalServerHttpsUrl(); 2127 try { 2128 final URL[] settingProviderUrls = 2129 combineCaptivePortalUrls(firstUrl, CAPTIVE_PORTAL_OTHER_HTTPS_URLS); 2130 // firstUrl will at least be default configuration, so default value in 2131 // getProbeUrlArrayConfig is actually never used. 2132 return getProbeUrlArrayConfig(settingProviderUrls, 2133 R.array.config_captive_portal_https_urls, 2134 DEFAULT_CAPTIVE_PORTAL_HTTPS_URLS, this::makeURL); 2135 } catch (Exception e) { 2136 // Don't let a misconfiguration bootloop the system. 2137 Log.e(TAG, "Error parsing configured https URLs", e); 2138 // Ensure URL aligned with legacy configuration. 2139 return new URL[]{makeURL(firstUrl)}; 2140 } 2141 } 2142 makeCaptivePortalHttpUrls()2143 private URL[] makeCaptivePortalHttpUrls() { 2144 final URL testUrl = getTestUrl(TEST_CAPTIVE_PORTAL_HTTP_URL); 2145 if (testUrl != null) return new URL[] { testUrl }; 2146 2147 final String firstUrl = getCaptivePortalServerHttpUrl(); 2148 try { 2149 final URL[] settingProviderUrls = 2150 combineCaptivePortalUrls(firstUrl, CAPTIVE_PORTAL_OTHER_HTTP_URLS); 2151 // firstUrl will at least be default configuration, so default value in 2152 // getProbeUrlArrayConfig is actually never used. 2153 return getProbeUrlArrayConfig(settingProviderUrls, 2154 R.array.config_captive_portal_http_urls, 2155 DEFAULT_CAPTIVE_PORTAL_HTTP_URLS, this::makeURL); 2156 } catch (Exception e) { 2157 // Don't let a misconfiguration bootloop the system. 2158 Log.e(TAG, "Error parsing configured http URLs", e); 2159 // Ensure URL aligned with legacy configuration. 2160 return new URL[]{makeURL(firstUrl)}; 2161 } 2162 } 2163 combineCaptivePortalUrls(final String firstUrl, final String propertyName)2164 private URL[] combineCaptivePortalUrls(final String firstUrl, final String propertyName) { 2165 if (TextUtils.isEmpty(firstUrl)) return new URL[0]; 2166 2167 final String otherUrls = mDependencies.getDeviceConfigProperty( 2168 NAMESPACE_CONNECTIVITY, propertyName, ""); 2169 // otherUrls may be empty, but .split() ignores trailing empty strings 2170 final String separator = ","; 2171 final String[] urls = (firstUrl + separator + otherUrls).split(separator); 2172 return convertStrings(urls, this::makeURL, new URL[0]); 2173 } 2174 2175 /** 2176 * Read a setting from a resource or the settings provider. 2177 * 2178 * <p>The configuration resource is prioritized, then the provider value. 2179 * @param context The context 2180 * @param configResource The resource id for the configuration parameter 2181 * @param symbol The symbol in the settings provider 2182 * @param defaultValue The default value 2183 * @return The best available value 2184 */ 2185 @Nullable getSettingFromResource(@onNull final Context context, @StringRes int configResource, @NonNull String symbol, @NonNull String defaultValue)2186 private String getSettingFromResource(@NonNull final Context context, 2187 @StringRes int configResource, @NonNull String symbol, @NonNull String defaultValue) { 2188 final Resources res = context.getResources(); 2189 String setting = res.getString(configResource); 2190 2191 if (!TextUtils.isEmpty(setting)) return setting; 2192 2193 setting = mDependencies.getSetting(context, symbol, null); 2194 2195 if (!TextUtils.isEmpty(setting)) return setting; 2196 2197 return defaultValue; 2198 } 2199 2200 /** 2201 * Get an array configuration from resources or the settings provider. 2202 * 2203 * <p>The configuration resource is prioritized, then the provider values, then the default 2204 * resource values. 2205 * @param providerValue Values obtained from the setting provider. 2206 * @param configResId ID of the configuration resource. 2207 * @param defaultResId ID of the default resource. 2208 * @param resourceConverter Converter from the resource strings to stored setting class. Null 2209 * return values are ignored. 2210 */ getProbeUrlArrayConfig(@onNull T[] providerValue, @ArrayRes int configResId, @ArrayRes int defaultResId, @NonNull Function<String, T> resourceConverter)2211 private <T> T[] getProbeUrlArrayConfig(@NonNull T[] providerValue, @ArrayRes int configResId, 2212 @ArrayRes int defaultResId, @NonNull Function<String, T> resourceConverter) { 2213 final Resources res = mCustomizedContext.getResources(); 2214 return getProbeUrlArrayConfig(providerValue, configResId, res.getStringArray(defaultResId), 2215 resourceConverter); 2216 } 2217 2218 /** 2219 * Get an array configuration from resources or the settings provider. 2220 * 2221 * <p>The configuration resource is prioritized, then the provider values, then the default 2222 * resource values. 2223 * @param providerValue Values obtained from the setting provider. 2224 * @param configResId ID of the configuration resource. 2225 * @param defaultConfig Values of default configuration. 2226 * @param resourceConverter Converter from the resource strings to stored setting class. Null 2227 * return values are ignored. 2228 */ getProbeUrlArrayConfig(@onNull T[] providerValue, @ArrayRes int configResId, String[] defaultConfig, @NonNull Function<String, T> resourceConverter)2229 private <T> T[] getProbeUrlArrayConfig(@NonNull T[] providerValue, @ArrayRes int configResId, 2230 String[] defaultConfig, @NonNull Function<String, T> resourceConverter) { 2231 final Resources res = mCustomizedContext.getResources(); 2232 String[] configValue = res.getStringArray(configResId); 2233 2234 if (configValue.length == 0) { 2235 if (providerValue.length > 0) { 2236 return providerValue; 2237 } 2238 2239 configValue = defaultConfig; 2240 } 2241 2242 return convertStrings(configValue, resourceConverter, Arrays.copyOf(providerValue, 0)); 2243 } 2244 2245 /** 2246 * Convert a String array to an array of some other type using the specified converter. 2247 * 2248 * <p>Any null value, or value for which the converter throws a {@link RuntimeException}, will 2249 * not be added to the output array, so the output array may be smaller than the input. 2250 */ convertStrings( @onNull String[] strings, Function<String, T> converter, T[] emptyArray)2251 private <T> T[] convertStrings( 2252 @NonNull String[] strings, Function<String, T> converter, T[] emptyArray) { 2253 final ArrayList<T> convertedValues = new ArrayList<>(strings.length); 2254 for (String configString : strings) { 2255 T convertedValue = null; 2256 try { 2257 convertedValue = converter.apply(configString); 2258 } catch (Exception e) { 2259 Log.e(TAG, "Error parsing configuration", e); 2260 // Fall through 2261 } 2262 if (convertedValue != null) { 2263 convertedValues.add(convertedValue); 2264 } 2265 } 2266 return convertedValues.toArray(emptyArray); 2267 } 2268 getCaptivePortalUserAgent()2269 private String getCaptivePortalUserAgent() { 2270 return mDependencies.getDeviceConfigProperty(NAMESPACE_CONNECTIVITY, 2271 CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT); 2272 } 2273 nextFallbackUrl()2274 private URL nextFallbackUrl() { 2275 if (mCaptivePortalFallbackUrls.length == 0) { 2276 return null; 2277 } 2278 int idx = Math.abs(mNextFallbackUrlIndex) % mCaptivePortalFallbackUrls.length; 2279 mNextFallbackUrlIndex += mRandom.nextInt(); // randomly change url without memory. 2280 return mCaptivePortalFallbackUrls[idx]; 2281 } 2282 nextFallbackSpec()2283 private CaptivePortalProbeSpec nextFallbackSpec() { 2284 if (isEmpty(mCaptivePortalFallbackSpecs)) { 2285 return null; 2286 } 2287 // Randomly change spec without memory. Also randomize the first attempt. 2288 final int idx = Math.abs(mRandom.nextInt()) % mCaptivePortalFallbackSpecs.length; 2289 return mCaptivePortalFallbackSpecs[idx]; 2290 } 2291 2292 /** 2293 * Validation properties that can be accessed by the evaluation thread in a thread-safe way. 2294 * 2295 * Parameters such as LinkProperties and NetworkCapabilities cannot be accessed by the 2296 * evaluation thread directly, as they are managed in the state machine thread and not 2297 * synchronized. This class provides a copy of the required data that is not modified and can be 2298 * used safely by the evaluation thread. 2299 */ 2300 private static class ValidationProperties { 2301 // TODO: add other properties that are needed for evaluation and currently extracted in a 2302 // non-thread-safe way from LinkProperties, NetworkCapabilities, etc. 2303 private final boolean mIsTestNetwork; 2304 ValidationProperties(NetworkCapabilities nc)2305 ValidationProperties(NetworkCapabilities nc) { 2306 this.mIsTestNetwork = nc.hasTransport(TRANSPORT_TEST); 2307 } 2308 } 2309 isCaptivePortal(ValidationProperties properties)2310 private CaptivePortalProbeResult isCaptivePortal(ValidationProperties properties) { 2311 if (!mIsCaptivePortalCheckEnabled) { 2312 validationLog("Validation disabled."); 2313 return CaptivePortalProbeResult.success(CaptivePortalProbeResult.PROBE_UNKNOWN); 2314 } 2315 2316 URL pacUrl = null; 2317 final URL[] httpsUrls = mCaptivePortalHttpsUrls; 2318 final URL[] httpUrls = mCaptivePortalHttpUrls; 2319 2320 // On networks with a PAC instead of fetching a URL that should result in a 204 2321 // response, we instead simply fetch the PAC script. This is done for a few reasons: 2322 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks 2323 // until something like https://android-review.googlesource.com/#/c/115180/ lands. 2324 // Network.openConnection() will ignore network-specific PACs and instead fetch 2325 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with 2326 // NO_PROXY is the fetch of the PAC itself. 2327 // 2. To proxy the generate_204 fetch through a PAC would require a number of things 2328 // happen before the fetch can commence, namely: 2329 // a) the PAC script be fetched 2330 // b) a PAC script resolver service be fired up and resolve the captive portal 2331 // server. 2332 // Network validation could be delayed until these prerequisities are satisifed or 2333 // could simply be left to race them. Neither is an optimal solution. 2334 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in 2335 // fact block fetching of the generate_204 URL which would lead to false negative 2336 // results for network validation. 2337 final ProxyInfo proxyInfo = mLinkProperties.getHttpProxy(); 2338 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) { 2339 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString()); 2340 if (pacUrl == null) { 2341 return CaptivePortalProbeResult.failed(CaptivePortalProbeResult.PROBE_UNKNOWN); 2342 } 2343 } 2344 2345 if ((pacUrl == null) && (httpUrls.length == 0 || httpsUrls.length == 0 2346 || httpUrls[0] == null || httpsUrls[0] == null)) { 2347 return CaptivePortalProbeResult.failed(CaptivePortalProbeResult.PROBE_UNKNOWN); 2348 } 2349 2350 long startTime = SystemClock.elapsedRealtime(); 2351 2352 final CaptivePortalProbeResult result; 2353 if (pacUrl != null) { 2354 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC); 2355 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_HTTP, result); 2356 } else if (mUseHttps && httpsUrls.length == 1 && httpUrls.length == 1) { 2357 // Probe results are reported inside sendHttpAndHttpsParallelWithFallbackProbes. 2358 result = sendHttpAndHttpsParallelWithFallbackProbes(properties, proxyInfo, 2359 httpsUrls[0], httpUrls[0]); 2360 } else if (mUseHttps) { 2361 // Support result aggregation from multiple Urls. 2362 result = sendMultiParallelHttpAndHttpsProbes(properties, proxyInfo, httpsUrls, 2363 httpUrls); 2364 } else { 2365 result = sendDnsAndHttpProbes(proxyInfo, httpUrls[0], ValidationProbeEvent.PROBE_HTTP); 2366 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_HTTP, result); 2367 } 2368 2369 long endTime = SystemClock.elapsedRealtime(); 2370 2371 log("isCaptivePortal: isSuccessful()=" + result.isSuccessful() 2372 + " isPortal()=" + result.isPortal() 2373 + " RedirectUrl=" + result.redirectUrl 2374 + " isPartialConnectivity()=" + result.isPartialConnectivity() 2375 + " Time=" + (endTime - startTime) + "ms"); 2376 2377 return result; 2378 } 2379 2380 /** 2381 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect. 2382 * @return a CaptivePortalProbeResult inferred from the HTTP response. 2383 */ sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType)2384 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) { 2385 // Pre-resolve the captive portal server host so we can log it. 2386 // Only do this if HttpURLConnection is about to, to avoid any potentially 2387 // unnecessary resolution. 2388 final String host = (proxy != null) ? proxy.getHost() : url.getHost(); 2389 // This method cannot safely report probe results because it might not be running on the 2390 // state machine thread. Reporting results here would cause races and potentially send 2391 // information to callers that does not make sense because the state machine has already 2392 // changed state. 2393 final InetAddress[] resolvedAddr = sendDnsProbe(host); 2394 // The private IP logic only applies to captive portal detection (the HTTP probe), not 2395 // network validation (the HTTPS probe, which would likely fail anyway) or the PAC probe. 2396 if (mPrivateIpNoInternetEnabled && probeType == ValidationProbeEvent.PROBE_HTTP 2397 && (proxy == null) && hasPrivateIpAddress(resolvedAddr)) { 2398 recordProbeEventMetrics(NetworkValidationMetrics.probeTypeToEnum(probeType), 2399 0 /* latency */, ProbeResult.PR_PRIVATE_IP_DNS, null /* capportData */); 2400 return CaptivePortalProbeResult.PRIVATE_IP; 2401 } 2402 return sendHttpProbe(url, probeType, null); 2403 } 2404 2405 /** Do a DNS lookup for the given server, or throw UnknownHostException after timeoutMs */ 2406 @VisibleForTesting sendDnsProbeWithTimeout(String host, int timeoutMs)2407 protected InetAddress[] sendDnsProbeWithTimeout(String host, int timeoutMs) 2408 throws UnknownHostException { 2409 return DnsUtils.getAllByName(mDependencies.getDnsResolver(), mCleartextDnsNetwork, host, 2410 TYPE_ADDRCONFIG, FLAG_EMPTY, timeoutMs, 2411 str -> validationLog(ValidationProbeEvent.PROBE_DNS, host, str)); 2412 } 2413 2414 /** Do a DNS resolution of the given server. */ sendDnsProbe(String host)2415 private InetAddress[] sendDnsProbe(String host) { 2416 if (TextUtils.isEmpty(host)) { 2417 return null; 2418 } 2419 2420 final Stopwatch watch = new Stopwatch().start(); 2421 int result; 2422 InetAddress[] addresses; 2423 try { 2424 addresses = sendDnsProbeWithTimeout(host, getDnsProbeTimeout()); 2425 result = ValidationProbeEvent.DNS_SUCCESS; 2426 } catch (UnknownHostException e) { 2427 addresses = null; 2428 result = ValidationProbeEvent.DNS_FAILURE; 2429 } 2430 final long latency = watch.stop(); 2431 recordProbeEventMetrics(ProbeType.PT_DNS, latency, 2432 (result == ValidationProbeEvent.DNS_SUCCESS) ? ProbeResult.PR_SUCCESS : 2433 ProbeResult.PR_FAILURE, null /* capportData */); 2434 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result); 2435 return addresses; 2436 } 2437 2438 /** 2439 * Check if any of the provided IP addresses include a private IP. 2440 * @return true if an IP address is private. 2441 */ hasPrivateIpAddress(@ullable InetAddress[] addresses)2442 private static boolean hasPrivateIpAddress(@Nullable InetAddress[] addresses) { 2443 if (addresses == null) { 2444 return false; 2445 } 2446 for (InetAddress address : addresses) { 2447 if (address.isLinkLocalAddress() || address.isSiteLocalAddress() 2448 || isIPv6ULA(address)) { 2449 return true; 2450 } 2451 } 2452 return false; 2453 } 2454 2455 /** 2456 * Do a URL fetch on a known web server to see if we get the data we expect. 2457 * @return a CaptivePortalProbeResult inferred from the HTTP response. 2458 */ 2459 @VisibleForTesting sendHttpProbe(URL url, int probeType, @Nullable CaptivePortalProbeSpec probeSpec)2460 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType, 2461 @Nullable CaptivePortalProbeSpec probeSpec) { 2462 HttpURLConnection urlConnection = null; 2463 int httpResponseCode = CaptivePortalProbeResult.FAILED_CODE; 2464 String redirectUrl = null; 2465 final Stopwatch probeTimer = new Stopwatch().start(); 2466 final int oldTag = TrafficStats.getAndSetThreadStatsTag( 2467 NetworkStackConstants.TAG_SYSTEM_PROBE); 2468 try { 2469 // Follow redirects for PAC probes as such probes verify connectivity by fetching the 2470 // PAC proxy file, which may be configured behind a redirect. 2471 final boolean followRedirect = probeType == ValidationProbeEvent.PROBE_PAC; 2472 urlConnection = makeProbeConnection(url, followRedirect); 2473 // cannot read request header after connection 2474 String requestHeader = urlConnection.getRequestProperties().toString(); 2475 2476 // Time how long it takes to get a response to our request 2477 long requestTimestamp = SystemClock.elapsedRealtime(); 2478 2479 httpResponseCode = urlConnection.getResponseCode(); 2480 redirectUrl = urlConnection.getHeaderField("location"); 2481 2482 // Time how long it takes to get a response to our request 2483 long responseTimestamp = SystemClock.elapsedRealtime(); 2484 2485 validationLog(probeType, url, "time=" + (responseTimestamp - requestTimestamp) + "ms" 2486 + " ret=" + httpResponseCode 2487 + " request=" + requestHeader 2488 + " headers=" + urlConnection.getHeaderFields()); 2489 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive 2490 // portal. The only example of this seen so far was a captive portal. For 2491 // the time being go with prior behavior of assuming it's not a captive 2492 // portal. If it is considered a captive portal, a different sign-in URL 2493 // is needed (i.e. can't browse a 204). This could be the result of an HTTP 2494 // proxy server. 2495 if (httpResponseCode == 200) { 2496 long contentLength = urlConnection.getContentLengthLong(); 2497 if (probeType == ValidationProbeEvent.PROBE_PAC) { 2498 validationLog( 2499 probeType, url, "PAC fetch 200 response interpreted as 204 response."); 2500 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE; 2501 } else if (contentLength == -1) { 2502 // When no Content-length (default value == -1), attempt to read a byte 2503 // from the response. Do not use available() as it is unreliable. 2504 // See http://b/33498325. 2505 if (urlConnection.getInputStream().read() == -1) { 2506 validationLog(probeType, url, 2507 "Empty 200 response interpreted as failed response."); 2508 httpResponseCode = CaptivePortalProbeResult.FAILED_CODE; 2509 } 2510 } else if (matchesHttpContentLength(contentLength)) { 2511 final InputStream is = new BufferedInputStream(urlConnection.getInputStream()); 2512 final String content = readAsString(is, (int) contentLength, 2513 extractCharset(urlConnection.getContentType())); 2514 if (matchesHttpContent(content, 2515 R.string.config_network_validation_failed_content_regexp)) { 2516 httpResponseCode = CaptivePortalProbeResult.FAILED_CODE; 2517 } else if (matchesHttpContent(content, 2518 R.string.config_network_validation_success_content_regexp)) { 2519 httpResponseCode = CaptivePortalProbeResult.SUCCESS_CODE; 2520 } 2521 2522 if (httpResponseCode != 200) { 2523 validationLog(probeType, url, "200 response with Content-length =" 2524 + contentLength + ", content matches custom regexp, interpreted" 2525 + " as " + httpResponseCode 2526 + " response."); 2527 } 2528 } else if (contentLength <= 4) { 2529 // Consider 200 response with "Content-length <= 4" to not be a captive 2530 // portal. There's no point in considering this a captive portal as the 2531 // user cannot sign-in to an empty page. Probably the result of a broken 2532 // transparent proxy. See http://b/9972012 and http://b/122999481. 2533 validationLog(probeType, url, "200 response with Content-length <= 4" 2534 + " interpreted as failed response."); 2535 httpResponseCode = CaptivePortalProbeResult.FAILED_CODE; 2536 } 2537 } 2538 } catch (IOException e) { 2539 validationLog(probeType, url, "Probe failed with exception " + e); 2540 if (httpResponseCode == CaptivePortalProbeResult.FAILED_CODE) { 2541 // TODO: Ping gateway and DNS server and log results. 2542 } 2543 } finally { 2544 if (urlConnection != null) { 2545 urlConnection.disconnect(); 2546 } 2547 TrafficStats.setThreadStatsTag(oldTag); 2548 } 2549 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode); 2550 2551 final CaptivePortalProbeResult probeResult; 2552 if (probeSpec == null) { 2553 if (CaptivePortalProbeResult.isPortalCode(httpResponseCode) 2554 && TextUtils.isEmpty(redirectUrl) 2555 && ShimUtils.isAtLeastS()) { 2556 // If a portal is a non-redirect portal (often portals that return HTTP 200 with a 2557 // login page for all HTTP requests), report the probe URL as the login URL starting 2558 // from S (b/172048052). This avoids breaking assumptions that 2559 // [is a portal] is equivalent to [there is a login URL]. 2560 redirectUrl = url.toString(); 2561 } 2562 probeResult = new CaptivePortalProbeResult(httpResponseCode, redirectUrl, 2563 url.toString(), 1 << probeType); 2564 } else { 2565 probeResult = probeSpec.getResult(httpResponseCode, redirectUrl); 2566 } 2567 recordProbeEventMetrics(NetworkValidationMetrics.probeTypeToEnum(probeType), 2568 probeTimer.stop(), NetworkValidationMetrics.httpProbeResultToEnum(probeResult), 2569 null /* capportData */); 2570 return probeResult; 2571 } 2572 2573 @VisibleForTesting matchesHttpContent(final String content, @StringRes final int configResource)2574 boolean matchesHttpContent(final String content, @StringRes final int configResource) { 2575 final String resString = getResStringConfig(mContext, configResource, ""); 2576 try { 2577 return content.matches(resString); 2578 } catch (PatternSyntaxException e) { 2579 Log.e(TAG, "Pattern syntax exception occurs when matching the resource=" + resString, 2580 e); 2581 return false; 2582 } 2583 } 2584 2585 @VisibleForTesting matchesHttpContentLength(final long contentLength)2586 boolean matchesHttpContentLength(final long contentLength) { 2587 // Consider that the Resources#getInteger() is returning an integer, so if the contentLength 2588 // is lower or equal to 0 or higher than Integer.MAX_VALUE, then it's an invalid value. 2589 if (contentLength <= 0) return false; 2590 if (contentLength > Integer.MAX_VALUE) { 2591 logw("matchesHttpContentLength : Get invalid contentLength = " + contentLength); 2592 return false; 2593 } 2594 return (contentLength > getResIntConfig(mContext, 2595 R.integer.config_min_matches_http_content_length, Integer.MAX_VALUE) 2596 && 2597 contentLength < getResIntConfig(mContext, 2598 R.integer.config_max_matches_http_content_length, 0)); 2599 } 2600 makeProbeConnection(URL url, boolean followRedirects)2601 private HttpURLConnection makeProbeConnection(URL url, boolean followRedirects) 2602 throws IOException { 2603 final HttpURLConnection conn = (HttpURLConnection) mCleartextDnsNetwork.openConnection(url); 2604 conn.setInstanceFollowRedirects(followRedirects); 2605 conn.setConnectTimeout(SOCKET_TIMEOUT_MS); 2606 conn.setReadTimeout(SOCKET_TIMEOUT_MS); 2607 conn.setRequestProperty("Connection", "close"); 2608 conn.setUseCaches(false); 2609 if (mCaptivePortalUserAgent != null) { 2610 conn.setRequestProperty("User-Agent", mCaptivePortalUserAgent); 2611 } 2612 return conn; 2613 } 2614 2615 @VisibleForTesting 2616 @NonNull readAsString(InputStream is, int maxLength, Charset charset)2617 protected static String readAsString(InputStream is, int maxLength, Charset charset) 2618 throws IOException { 2619 final InputStreamReader reader = new InputStreamReader(is, charset); 2620 final char[] buffer = new char[1000]; 2621 final StringBuilder builder = new StringBuilder(); 2622 int totalReadLength = 0; 2623 while (totalReadLength < maxLength) { 2624 final int availableLength = Math.min(maxLength - totalReadLength, buffer.length); 2625 final int currentLength = reader.read(buffer, 0, availableLength); 2626 if (currentLength < 0) break; // EOF 2627 2628 totalReadLength += currentLength; 2629 builder.append(buffer, 0, currentLength); 2630 } 2631 return builder.toString(); 2632 } 2633 2634 /** 2635 * Attempt to extract the {@link Charset} of the response from its Content-Type header. 2636 * 2637 * <p>If the {@link Charset} cannot be extracted, UTF-8 is returned by default. 2638 */ 2639 @VisibleForTesting 2640 @NonNull extractCharset(@ullable String contentTypeHeader)2641 protected static Charset extractCharset(@Nullable String contentTypeHeader) { 2642 if (contentTypeHeader == null) return StandardCharsets.UTF_8; 2643 // See format in https://tools.ietf.org/html/rfc7231#section-3.1.1.1 2644 final Pattern charsetPattern = Pattern.compile("; *charset=\"?([^ ;\"]+)\"?", 2645 Pattern.CASE_INSENSITIVE); 2646 final Matcher matcher = charsetPattern.matcher(contentTypeHeader); 2647 if (!matcher.find()) return StandardCharsets.UTF_8; 2648 2649 try { 2650 return Charset.forName(matcher.group(1)); 2651 } catch (IllegalArgumentException e) { 2652 return StandardCharsets.UTF_8; 2653 } 2654 } 2655 2656 private class ProbeThread extends Thread { 2657 private final CountDownLatch mLatch; 2658 private final Probe mProbe; 2659 ProbeThread(CountDownLatch latch, ValidationProperties properties, ProxyInfo proxy, URL url, int probeType, Uri captivePortalApiUrl)2660 ProbeThread(CountDownLatch latch, ValidationProperties properties, ProxyInfo proxy, URL url, 2661 int probeType, Uri captivePortalApiUrl) { 2662 mLatch = latch; 2663 mProbe = (probeType == ValidationProbeEvent.PROBE_HTTPS) 2664 ? new HttpsProbe(properties, proxy, url, captivePortalApiUrl) 2665 : new HttpProbe(properties, proxy, url, captivePortalApiUrl); 2666 mResult = CaptivePortalProbeResult.failed(probeType); 2667 } 2668 2669 private volatile CaptivePortalProbeResult mResult; 2670 result()2671 public CaptivePortalProbeResult result() { 2672 return mResult; 2673 } 2674 2675 @Override run()2676 public void run() { 2677 mResult = mProbe.sendProbe(); 2678 if (isConclusiveResult(mResult, mProbe.mCaptivePortalApiUrl)) { 2679 // Stop waiting immediately if any probe is conclusive. 2680 while (mLatch.getCount() > 0) { 2681 mLatch.countDown(); 2682 } 2683 } 2684 // Signal this probe has completed. 2685 mLatch.countDown(); 2686 } 2687 } 2688 2689 private abstract static class Probe { 2690 protected final ValidationProperties mProperties; 2691 protected final ProxyInfo mProxy; 2692 protected final URL mUrl; 2693 protected final Uri mCaptivePortalApiUrl; 2694 Probe(ValidationProperties properties, ProxyInfo proxy, URL url, Uri captivePortalApiUrl)2695 protected Probe(ValidationProperties properties, ProxyInfo proxy, URL url, 2696 Uri captivePortalApiUrl) { 2697 mProperties = properties; 2698 mProxy = proxy; 2699 mUrl = url; 2700 mCaptivePortalApiUrl = captivePortalApiUrl; 2701 } 2702 // sendProbe() is synchronous and blocks until it has the result. sendProbe()2703 protected abstract CaptivePortalProbeResult sendProbe(); 2704 } 2705 2706 final class HttpsProbe extends Probe { HttpsProbe(ValidationProperties properties, ProxyInfo proxy, URL url, Uri captivePortalApiUrl)2707 HttpsProbe(ValidationProperties properties, ProxyInfo proxy, URL url, 2708 Uri captivePortalApiUrl) { 2709 super(properties, proxy, url, captivePortalApiUrl); 2710 } 2711 2712 @Override sendProbe()2713 protected CaptivePortalProbeResult sendProbe() { 2714 return sendDnsAndHttpProbes(mProxy, mUrl, ValidationProbeEvent.PROBE_HTTPS); 2715 } 2716 } 2717 2718 final class HttpProbe extends Probe { HttpProbe(ValidationProperties properties, ProxyInfo proxy, URL url, Uri captivePortalApiUrl)2719 HttpProbe(ValidationProperties properties, ProxyInfo proxy, URL url, 2720 Uri captivePortalApiUrl) { 2721 super(properties, proxy, url, captivePortalApiUrl); 2722 } 2723 sendCapportApiProbe()2724 private CaptivePortalDataShim sendCapportApiProbe() { 2725 // TODO: consider adding metrics counters for each case returning null in this method 2726 // (cases where the API is not implemented properly). 2727 validationLog("Fetching captive portal data from " + mCaptivePortalApiUrl); 2728 2729 final String apiContent; 2730 try { 2731 final URL url = new URL(mCaptivePortalApiUrl.toString()); 2732 // Protocol must be HTTPS 2733 // (as per https://www.ietf.org/id/draft-ietf-capport-api-07.txt, #4). 2734 // Only allow HTTP on localhost, for testing. 2735 final boolean isTestLocalhostHttp = mProperties.mIsTestNetwork 2736 && "localhost".equals(url.getHost()) && "http".equals(url.getProtocol()); 2737 if (!"https".equals(url.getProtocol()) && !isTestLocalhostHttp) { 2738 validationLog("Invalid captive portal API protocol: " + url.getProtocol()); 2739 return null; 2740 } 2741 2742 final HttpURLConnection conn = makeProbeConnection( 2743 url, true /* followRedirects */); 2744 conn.setRequestProperty(ACCEPT_HEADER, CAPPORT_API_CONTENT_TYPE); 2745 final int responseCode = conn.getResponseCode(); 2746 if (responseCode != 200) { 2747 validationLog("Non-200 API response code: " + conn.getResponseCode()); 2748 return null; 2749 } 2750 final Charset charset = extractCharset(conn.getHeaderField(CONTENT_TYPE_HEADER)); 2751 if (charset != StandardCharsets.UTF_8) { 2752 validationLog("Invalid charset for capport API: " + charset); 2753 return null; 2754 } 2755 2756 apiContent = readAsString(conn.getInputStream(), 2757 CAPPORT_API_MAX_JSON_LENGTH, charset); 2758 } catch (IOException e) { 2759 validationLog("I/O error reading capport data: " + e.getMessage()); 2760 return null; 2761 } 2762 2763 try { 2764 final JSONObject info = new JSONObject(apiContent); 2765 final CaptivePortalDataShim capportData = CaptivePortalDataShimImpl.fromJson(info); 2766 if (capportData != null && capportData.isCaptive() 2767 && capportData.getUserPortalUrl() == null) { 2768 validationLog("Missing user-portal-url from capport response"); 2769 return null; 2770 } 2771 return capportData; 2772 } catch (JSONException e) { 2773 validationLog("Could not parse capport API JSON: " + e.getMessage()); 2774 return null; 2775 } catch (UnsupportedApiLevelException e) { 2776 // This should never happen because LinkProperties would not have a capport URL 2777 // before R. 2778 validationLog("Platform API too low to support capport API"); 2779 return null; 2780 } 2781 } 2782 tryCapportApiProbe()2783 private CaptivePortalDataShim tryCapportApiProbe() { 2784 if (mCaptivePortalApiUrl == null) return null; 2785 final Stopwatch capportApiWatch = new Stopwatch().start(); 2786 final CaptivePortalDataShim capportData = sendCapportApiProbe(); 2787 recordProbeEventMetrics(ProbeType.PT_CAPPORT_API, capportApiWatch.stop(), 2788 capportData == null ? ProbeResult.PR_FAILURE : ProbeResult.PR_SUCCESS, 2789 capportData); 2790 return capportData; 2791 } 2792 2793 @Override sendProbe()2794 protected CaptivePortalProbeResult sendProbe() { 2795 final CaptivePortalDataShim capportData = tryCapportApiProbe(); 2796 if (capportData != null && capportData.isCaptive()) { 2797 final String loginUrlString = capportData.getUserPortalUrl().toString(); 2798 // Starting from R (where CaptivePortalData was introduced), the captive portal app 2799 // delegates to NetworkMonitor for verifying when the network validates instead of 2800 // probing the detectUrl. So pass the detectUrl to have the portal open on that, 2801 // page; CaptivePortalLogin will not use it for probing. 2802 return new CapportApiProbeResult( 2803 CaptivePortalProbeResult.PORTAL_CODE, 2804 loginUrlString /* redirectUrl */, 2805 loginUrlString /* detectUrl */, 2806 capportData, 2807 1 << ValidationProbeEvent.PROBE_HTTP); 2808 } 2809 2810 // If the API says it's not captive, still check for HTTP connectivity. This helps 2811 // with partial connectivity detection, and a broken API saying that there is no 2812 // redirect when there is one. 2813 final CaptivePortalProbeResult res = 2814 sendDnsAndHttpProbes(mProxy, mUrl, ValidationProbeEvent.PROBE_HTTP); 2815 return mCaptivePortalApiUrl == null ? res : new CapportApiProbeResult(res, capportData); 2816 } 2817 } 2818 isConclusiveResult(@onNull CaptivePortalProbeResult result, @Nullable Uri captivePortalApiUrl)2819 private static boolean isConclusiveResult(@NonNull CaptivePortalProbeResult result, 2820 @Nullable Uri captivePortalApiUrl) { 2821 // isPortal() is not expected on the HTTPS probe, but treat the network as portal would make 2822 // sense if the probe reports portal. In case the capport API is available, the API is 2823 // authoritative on whether there is a portal, so the HTTPS probe is not enough to conclude 2824 // there is connectivity, and a determination will be made once the capport API probe 2825 // returns. Note that the API can only force the system to detect a portal even if the HTTPS 2826 // probe succeeds. It cannot force the system to detect no portal if the HTTPS probe fails. 2827 return result.isPortal() 2828 || (result.isConcludedFromHttps() && result.isSuccessful() 2829 && captivePortalApiUrl == null); 2830 } 2831 sendMultiParallelHttpAndHttpsProbes( @onNull ValidationProperties properties, @Nullable ProxyInfo proxy, @NonNull URL[] httpsUrls, @NonNull URL[] httpUrls)2832 private CaptivePortalProbeResult sendMultiParallelHttpAndHttpsProbes( 2833 @NonNull ValidationProperties properties, @Nullable ProxyInfo proxy, 2834 @NonNull URL[] httpsUrls, @NonNull URL[] httpUrls) { 2835 // If multiple URLs are required to ensure the correctness of validation, send parallel 2836 // probes to explore the result in separate probe threads and aggregate those results into 2837 // one as the final result for either HTTP or HTTPS. 2838 2839 // Number of probes to wait for. 2840 final int num = httpsUrls.length + httpUrls.length; 2841 // Fixed pool to prevent configuring too many urls to exhaust system resource. 2842 final ExecutorService executor = Executors.newFixedThreadPool( 2843 Math.min(num, MAX_PROBE_THREAD_POOL_SIZE)); 2844 final CompletionService<CaptivePortalProbeResult> ecs = 2845 new ExecutorCompletionService<CaptivePortalProbeResult>(executor); 2846 final Uri capportApiUrl = getCaptivePortalApiUrl(mLinkProperties); 2847 final List<Future<CaptivePortalProbeResult>> futures = new ArrayList<>(); 2848 2849 try { 2850 // Queue https and http probe. 2851 2852 // Each of these HTTP probes will start with probing capport API if present. So if 2853 // multiple HTTP URLs are configured, AP will send multiple identical accesses to the 2854 // capport URL. Thus, send capport API probing with one of the HTTP probe is enough. 2855 // Probe capport API with the first HTTP probe. 2856 // TODO: Have the capport probe as a different probe for cleanliness. 2857 final URL urlMaybeWithCapport = httpUrls[0]; 2858 for (final URL url : httpUrls) { 2859 futures.add(ecs.submit(() -> new HttpProbe(properties, proxy, url, 2860 url.equals(urlMaybeWithCapport) ? capportApiUrl : null).sendProbe())); 2861 } 2862 2863 for (final URL url : httpsUrls) { 2864 futures.add(ecs.submit(() -> new HttpsProbe(properties, proxy, url, capportApiUrl) 2865 .sendProbe())); 2866 } 2867 2868 final ArrayList<CaptivePortalProbeResult> completedProbes = new ArrayList<>(); 2869 for (int i = 0; i < num; i++) { 2870 completedProbes.add(ecs.take().get()); 2871 final CaptivePortalProbeResult res = evaluateCapportResult( 2872 completedProbes, httpsUrls.length, capportApiUrl != null /* hasCapport */); 2873 if (res != null) { 2874 reportProbeResult(res); 2875 return res; 2876 } 2877 } 2878 } catch (ExecutionException e) { 2879 Log.e(TAG, "Error sending probes.", e); 2880 } catch (InterruptedException e) { 2881 // Ignore interrupted probe result because result is not important to conclude the 2882 // result. 2883 } finally { 2884 // Interrupt ongoing probes since we have already gotten result from one of them. 2885 futures.forEach(future -> future.cancel(true)); 2886 executor.shutdownNow(); 2887 } 2888 2889 return CaptivePortalProbeResult.failed(ValidationProbeEvent.PROBE_HTTPS); 2890 } 2891 2892 @Nullable evaluateCapportResult( List<CaptivePortalProbeResult> probes, int numHttps, boolean hasCapport)2893 private CaptivePortalProbeResult evaluateCapportResult( 2894 List<CaptivePortalProbeResult> probes, int numHttps, boolean hasCapport) { 2895 CaptivePortalProbeResult capportResult = null; 2896 CaptivePortalProbeResult httpPortalResult = null; 2897 int httpSuccesses = 0; 2898 int httpsSuccesses = 0; 2899 int httpsFailures = 0; 2900 2901 for (CaptivePortalProbeResult probe : probes) { 2902 if (probe instanceof CapportApiProbeResult) { 2903 capportResult = probe; 2904 } else if (probe.isConcludedFromHttps()) { 2905 if (probe.isSuccessful()) httpsSuccesses++; 2906 else httpsFailures++; 2907 } else { // http probes 2908 if (probe.isPortal()) { 2909 // Unlike https probe, http probe may have redirect url information kept in the 2910 // probe result. Thus, the result can not be newly created with response code 2911 // only. If the captive portal behavior will be varied because of different 2912 // probe URLs, this means that if the portal returns different redirect URLs for 2913 // different probes and has a different behavior depending on the URL, then the 2914 // behavior of the login page may differ depending on the order in which the 2915 // probes terminate. However, NetworkMonitor does have to choose one of the 2916 // redirect URLs and right now there is no clue at all which of the probe has 2917 // the better redirect URL, so there is no telling which is best to use. 2918 // Therefore the current code just uses whichever happens to be the last one to 2919 // complete. 2920 httpPortalResult = probe; 2921 } else if (probe.isSuccessful()) { 2922 httpSuccesses++; 2923 } 2924 } 2925 } 2926 // If there is Capport url configured but the result is not available yet, wait for it. 2927 if (hasCapport && capportResult == null) return null; 2928 // Capport API saying it's a portal is authoritative. 2929 if (capportResult != null && capportResult.isPortal()) return capportResult; 2930 // Any HTTP probes saying probe portal is conclusive. 2931 if (httpPortalResult != null) return httpPortalResult; 2932 // Any HTTPS probes works then the network validates. 2933 if (httpsSuccesses > 0) { 2934 return CaptivePortalProbeResult.success(1 << ValidationProbeEvent.PROBE_HTTPS); 2935 } 2936 // All HTTPS failed and at least one HTTP succeeded, then it's partial. 2937 if (httpsFailures == numHttps && httpSuccesses > 0) { 2938 return CaptivePortalProbeResult.PARTIAL; 2939 } 2940 // Otherwise, the result is unknown yet. 2941 return null; 2942 } 2943 reportProbeResult(@onNull CaptivePortalProbeResult res)2944 private void reportProbeResult(@NonNull CaptivePortalProbeResult res) { 2945 if (res instanceof CapportApiProbeResult) { 2946 maybeReportCaptivePortalData(((CapportApiProbeResult) res).getCaptivePortalData()); 2947 } 2948 2949 // This is not a if-else case since partial connectivity will concluded from both HTTP and 2950 // HTTPS probe. Both HTTP and HTTPS result should be reported. 2951 if (res.isConcludedFromHttps()) { 2952 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_HTTPS, res); 2953 } 2954 2955 if (res.isConcludedFromHttp()) { 2956 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_HTTP, res); 2957 } 2958 } 2959 sendHttpAndHttpsParallelWithFallbackProbes( ValidationProperties properties, ProxyInfo proxy, URL httpsUrl, URL httpUrl)2960 private CaptivePortalProbeResult sendHttpAndHttpsParallelWithFallbackProbes( 2961 ValidationProperties properties, ProxyInfo proxy, URL httpsUrl, URL httpUrl) { 2962 // Number of probes to wait for. If a probe completes with a conclusive answer 2963 // it shortcuts the latch immediately by forcing the count to 0. 2964 final CountDownLatch latch = new CountDownLatch(2); 2965 2966 final Uri capportApiUrl = getCaptivePortalApiUrl(mLinkProperties); 2967 final ProbeThread httpsProbe = new ProbeThread(latch, properties, proxy, httpsUrl, 2968 ValidationProbeEvent.PROBE_HTTPS, capportApiUrl); 2969 final ProbeThread httpProbe = new ProbeThread(latch, properties, proxy, httpUrl, 2970 ValidationProbeEvent.PROBE_HTTP, capportApiUrl); 2971 2972 try { 2973 httpsProbe.start(); 2974 httpProbe.start(); 2975 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS); 2976 } catch (InterruptedException e) { 2977 validationLog("Error: probes wait interrupted!"); 2978 return CaptivePortalProbeResult.failed(CaptivePortalProbeResult.PROBE_UNKNOWN); 2979 } 2980 2981 final CaptivePortalProbeResult httpsResult = httpsProbe.result(); 2982 final CaptivePortalProbeResult httpResult = httpProbe.result(); 2983 2984 // Look for a conclusive probe result first. 2985 if (isConclusiveResult(httpResult, capportApiUrl)) { 2986 reportProbeResult(httpProbe.result()); 2987 return httpResult; 2988 } 2989 2990 if (isConclusiveResult(httpsResult, capportApiUrl)) { 2991 reportProbeResult(httpsProbe.result()); 2992 return httpsResult; 2993 } 2994 // Consider a DNS response with a private IP address on the HTTP probe as an indication that 2995 // the network is not connected to the Internet, and have the whole evaluation fail in that 2996 // case, instead of potentially detecting a captive portal. This logic only affects portal 2997 // detection, not network validation. 2998 // This only applies if the DNS probe completed within PROBE_TIMEOUT_MS, as the fallback 2999 // probe should not be delayed by this check. 3000 if (mPrivateIpNoInternetEnabled && (httpResult.isDnsPrivateIpResponse())) { 3001 validationLog("DNS response to the URL is private IP"); 3002 return CaptivePortalProbeResult.failed(1 << ValidationProbeEvent.PROBE_HTTP); 3003 } 3004 // If a fallback method exists, use it to retry portal detection. 3005 // If we have new-style probe specs, use those. Otherwise, use the fallback URLs. 3006 final CaptivePortalProbeSpec probeSpec = nextFallbackSpec(); 3007 final URL fallbackUrl = (probeSpec != null) ? probeSpec.getUrl() : nextFallbackUrl(); 3008 CaptivePortalProbeResult fallbackProbeResult = null; 3009 if (fallbackUrl != null) { 3010 fallbackProbeResult = sendHttpProbe(fallbackUrl, PROBE_FALLBACK, probeSpec); 3011 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_FALLBACK, fallbackProbeResult); 3012 if (fallbackProbeResult.isPortal()) { 3013 return fallbackProbeResult; 3014 } 3015 } 3016 // Otherwise wait until http and https probes completes and use their results. 3017 try { 3018 httpProbe.join(); 3019 reportProbeResult(httpProbe.result()); 3020 3021 if (httpProbe.result().isPortal()) { 3022 return httpProbe.result(); 3023 } 3024 3025 httpsProbe.join(); 3026 reportHttpProbeResult(NETWORK_VALIDATION_PROBE_HTTPS, httpsProbe.result()); 3027 3028 if (httpsProbe.result().isFailed() && httpProbe.result().isSuccessful()) { 3029 return CaptivePortalProbeResult.PARTIAL; 3030 } 3031 return httpsProbe.result(); 3032 } catch (InterruptedException e) { 3033 validationLog("Error: http or https probe wait interrupted!"); 3034 return CaptivePortalProbeResult.failed(CaptivePortalProbeResult.PROBE_UNKNOWN); 3035 } 3036 } 3037 makeURL(String url)3038 private URL makeURL(String url) { 3039 if (url != null) { 3040 try { 3041 return new URL(url); 3042 } catch (MalformedURLException e) { 3043 validationLog("Bad URL: " + url); 3044 } 3045 } 3046 return null; 3047 } 3048 logNetworkEvent(int evtype)3049 private void logNetworkEvent(int evtype) { 3050 int[] transports = mNetworkCapabilities.getTransportTypes(); 3051 mMetricsLog.log(mCleartextDnsNetwork, transports, new NetworkEvent(evtype)); 3052 } 3053 networkEventType(ValidationStage s, EvaluationResult r)3054 private int networkEventType(ValidationStage s, EvaluationResult r) { 3055 if (s.mIsFirstValidation) { 3056 if (r.mIsValidated) { 3057 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS; 3058 } else { 3059 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND; 3060 } 3061 } else { 3062 if (r.mIsValidated) { 3063 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS; 3064 } else { 3065 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND; 3066 } 3067 } 3068 } 3069 maybeLogEvaluationResult(int evtype)3070 private void maybeLogEvaluationResult(int evtype) { 3071 if (mEvaluationTimer.isRunning()) { 3072 int[] transports = mNetworkCapabilities.getTransportTypes(); 3073 mMetricsLog.log(mCleartextDnsNetwork, transports, 3074 new NetworkEvent(evtype, mEvaluationTimer.stop() / 1000)); 3075 mEvaluationTimer.reset(); 3076 } 3077 } 3078 logValidationProbe(long durationUs, int probeType, int probeResult)3079 private void logValidationProbe(long durationUs, int probeType, int probeResult) { 3080 int[] transports = mNetworkCapabilities.getTransportTypes(); 3081 boolean isFirstValidation = validationStage().mIsFirstValidation; 3082 ValidationProbeEvent ev = new ValidationProbeEvent.Builder() 3083 .setProbeType(probeType, isFirstValidation) 3084 .setReturnCode(probeResult) 3085 .setDurationMs(durationUs / 1000) 3086 .build(); 3087 mMetricsLog.log(mCleartextDnsNetwork, transports, ev); 3088 } 3089 3090 @VisibleForTesting 3091 public static class Dependencies { getPrivateDnsBypassNetwork(Network network)3092 public Network getPrivateDnsBypassNetwork(Network network) { 3093 return new OneAddressPerFamilyNetwork(network); 3094 } 3095 getDnsResolver()3096 public DnsResolver getDnsResolver() { 3097 return DnsResolver.getInstance(); 3098 } 3099 getRandom()3100 public Random getRandom() { 3101 return new Random(); 3102 } 3103 3104 /** 3105 * Get the value of a global integer setting. 3106 * @param symbol Name of the setting 3107 * @param defaultValue Value to return if the setting is not defined. 3108 */ getSetting(Context context, String symbol, int defaultValue)3109 public int getSetting(Context context, String symbol, int defaultValue) { 3110 return Settings.Global.getInt(context.getContentResolver(), symbol, defaultValue); 3111 } 3112 3113 /** 3114 * Get the value of a global String setting. 3115 * @param symbol Name of the setting 3116 * @param defaultValue Value to return if the setting is not defined. 3117 */ getSetting(Context context, String symbol, String defaultValue)3118 public String getSetting(Context context, String symbol, String defaultValue) { 3119 final String value = Settings.Global.getString(context.getContentResolver(), symbol); 3120 return value != null ? value : defaultValue; 3121 } 3122 3123 /** 3124 * Look up the value of a property in DeviceConfig. 3125 * @param namespace The namespace containing the property to look up. 3126 * @param name The name of the property to look up. 3127 * @param defaultValue The value to return if the property does not exist or has no non-null 3128 * value. 3129 * @return the corresponding value, or defaultValue if none exists. 3130 */ 3131 @Nullable getDeviceConfigProperty(@onNull String namespace, @NonNull String name, @Nullable String defaultValue)3132 public String getDeviceConfigProperty(@NonNull String namespace, @NonNull String name, 3133 @Nullable String defaultValue) { 3134 return DeviceConfigUtils.getDeviceConfigProperty(namespace, name, defaultValue); 3135 } 3136 3137 /** 3138 * Look up the value of a property in DeviceConfig. 3139 * @param namespace The namespace containing the property to look up. 3140 * @param name The name of the property to look up. 3141 * @param defaultValue The value to return if the property does not exist or has no non-null 3142 * value. 3143 * @return the corresponding value, or defaultValue if none exists. 3144 */ getDeviceConfigPropertyInt(@onNull String namespace, @NonNull String name, int defaultValue)3145 public int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name, 3146 int defaultValue) { 3147 return DeviceConfigUtils.getDeviceConfigPropertyInt(namespace, name, defaultValue); 3148 } 3149 3150 /** 3151 * Check whether or not one experimental feature in the connectivity namespace is 3152 * enabled. 3153 * @param name Flag name of the experiment in the connectivity namespace. 3154 * @see DeviceConfigUtils#isFeatureEnabled(Context, String, String) 3155 */ isFeatureEnabled(@onNull Context context, @NonNull String name)3156 public boolean isFeatureEnabled(@NonNull Context context, @NonNull String name) { 3157 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name); 3158 } 3159 3160 /** 3161 * Check whether or not one specific experimental feature for a particular namespace from 3162 * {@link DeviceConfig} is enabled by comparing NetworkStack module version 3163 * {@link NetworkStack} with current version of property. If this property version is valid, 3164 * the corresponding experimental feature would be enabled, otherwise disabled. 3165 * @param context The global context information about an app environment. 3166 * @param namespace The namespace containing the property to look up. 3167 * @param name The name of the property to look up. 3168 * @param defaultEnabled The value to return if the property does not exist or its value is 3169 * null. 3170 * @return true if this feature is enabled, or false if disabled. 3171 */ isFeatureEnabled(@onNull Context context, @NonNull String namespace, @NonNull String name, boolean defaultEnabled)3172 public boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace, 3173 @NonNull String name, boolean defaultEnabled) { 3174 return DeviceConfigUtils.isFeatureEnabled(context, namespace, name, defaultEnabled); 3175 } 3176 3177 /** 3178 * Collect data stall detection level information for each transport type. Write metrics 3179 * data to statsd pipeline. 3180 * @param stats a {@link DataStallDetectionStats} that contains the detection level 3181 * information. 3182 * @para result the network reevaluation result. 3183 */ writeDataStallDetectionStats(@onNull final DataStallDetectionStats stats, @NonNull final CaptivePortalProbeResult result)3184 public void writeDataStallDetectionStats(@NonNull final DataStallDetectionStats stats, 3185 @NonNull final CaptivePortalProbeResult result) { 3186 DataStallStatsUtils.write(stats, result); 3187 } 3188 3189 public static final Dependencies DEFAULT = new Dependencies(); 3190 } 3191 3192 /** 3193 * Methods in this class perform no locking because all accesses are performed on the state 3194 * machine's thread. Need to consider the thread safety if it ever could be accessed outside the 3195 * state machine. 3196 */ 3197 @VisibleForTesting 3198 protected class DnsStallDetector { 3199 private int mConsecutiveTimeoutCount = 0; 3200 private int mSize; 3201 final DnsResult[] mDnsEvents; 3202 final RingBufferIndices mResultIndices; 3203 DnsStallDetector(int size)3204 DnsStallDetector(int size) { 3205 mSize = Math.max(DEFAULT_DNS_LOG_SIZE, size); 3206 mDnsEvents = new DnsResult[mSize]; 3207 mResultIndices = new RingBufferIndices(mSize); 3208 } 3209 3210 @VisibleForTesting accumulateConsecutiveDnsTimeoutCount(int code)3211 protected void accumulateConsecutiveDnsTimeoutCount(int code) { 3212 final DnsResult result = new DnsResult(code); 3213 mDnsEvents[mResultIndices.add()] = result; 3214 if (result.isTimeout()) { 3215 mConsecutiveTimeoutCount++; 3216 } else { 3217 // Keep the event in mDnsEvents without clearing it so that there are logs to do the 3218 // simulation and analysis. 3219 mConsecutiveTimeoutCount = 0; 3220 } 3221 } 3222 isDataStallSuspected(int timeoutCountThreshold, int validTime)3223 private boolean isDataStallSuspected(int timeoutCountThreshold, int validTime) { 3224 if (timeoutCountThreshold <= 0) { 3225 Log.wtf(TAG, "Timeout count threshold should be larger than 0."); 3226 return false; 3227 } 3228 3229 // Check if the consecutive timeout count reach the threshold or not. 3230 if (mConsecutiveTimeoutCount < timeoutCountThreshold) { 3231 return false; 3232 } 3233 3234 // Check if the target dns event index is valid or not. 3235 final int firstConsecutiveTimeoutIndex = 3236 mResultIndices.indexOf(mResultIndices.size() - timeoutCountThreshold); 3237 3238 // If the dns timeout events happened long time ago, the events are meaningless for 3239 // data stall evaluation. Thus, check if the first consecutive timeout dns event 3240 // considered in the evaluation happened in defined threshold time. 3241 final long now = SystemClock.elapsedRealtime(); 3242 final long firstTimeoutTime = now - mDnsEvents[firstConsecutiveTimeoutIndex].mTimeStamp; 3243 if (DDBG_STALL) { 3244 Log.d(TAG, "DSD.isDataStallSuspected, first=" 3245 + firstTimeoutTime + ", valid=" + validTime); 3246 } 3247 return (firstTimeoutTime < validTime); 3248 } 3249 getConsecutiveTimeoutCount()3250 int getConsecutiveTimeoutCount() { 3251 return mConsecutiveTimeoutCount; 3252 } 3253 } 3254 3255 private static class DnsResult { 3256 // TODO: Need to move the DNS return code definition to a specific class once unify DNS 3257 // response code is done. 3258 private static final int RETURN_CODE_DNS_TIMEOUT = 255; 3259 3260 private final long mTimeStamp; 3261 private final int mReturnCode; 3262 DnsResult(int code)3263 DnsResult(int code) { 3264 mTimeStamp = SystemClock.elapsedRealtime(); 3265 mReturnCode = code; 3266 } 3267 isTimeout()3268 private boolean isTimeout() { 3269 return mReturnCode == RETURN_CODE_DNS_TIMEOUT; 3270 } 3271 } 3272 3273 @VisibleForTesting 3274 @Nullable getDnsStallDetector()3275 protected DnsStallDetector getDnsStallDetector() { 3276 return mDnsStallDetector; 3277 } 3278 3279 @Nullable getTcpSocketTracker()3280 private TcpSocketTracker getTcpSocketTracker() { 3281 return mTcpTracker; 3282 } 3283 dataStallEvaluateTypeEnabled(int type)3284 private boolean dataStallEvaluateTypeEnabled(int type) { 3285 return (mDataStallEvaluationType & type) != 0; 3286 } 3287 3288 @VisibleForTesting getLastProbeTime()3289 protected long getLastProbeTime() { 3290 return mLastProbeTime; 3291 } 3292 3293 @VisibleForTesting isDataStall()3294 protected boolean isDataStall() { 3295 if (!isValidationRequired()) { 3296 return false; 3297 } 3298 3299 int typeToCollect = 0; 3300 final int notStall = -1; 3301 final StringJoiner msg = (DBG || VDBG_STALL || DDBG_STALL) ? new StringJoiner(", ") : null; 3302 // Reevaluation will generate traffic. Thus, set a minimal reevaluation timer to limit the 3303 // possible traffic cost in metered network. 3304 final long currentTime = SystemClock.elapsedRealtime(); 3305 if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) 3306 && (currentTime - getLastProbeTime() < mDataStallMinEvaluateTime)) { 3307 if (DDBG_STALL) { 3308 Log.d(TAG, "isDataStall: false, currentTime=" + currentTime 3309 + ", lastProbeTime=" + getLastProbeTime() 3310 + ", MinEvaluateTime=" + mDataStallMinEvaluateTime); 3311 } 3312 return false; 3313 } 3314 // Check TCP signal. Suspect it may be a data stall if : 3315 // 1. TCP connection fail rate(lost+retrans) is higher than threshold. 3316 // 2. Accumulate enough packets count. 3317 final TcpSocketTracker tst = getTcpSocketTracker(); 3318 if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP) && tst != null) { 3319 if (tst.getLatestReceivedCount() > 0) { 3320 typeToCollect = notStall; 3321 } else if (tst.isDataStallSuspected()) { 3322 typeToCollect |= DATA_STALL_EVALUATION_TYPE_TCP; 3323 } 3324 if (DBG || VDBG_STALL || DDBG_STALL) { 3325 msg.add("tcp packets received=" + tst.getLatestReceivedCount()) 3326 .add("latest tcp fail rate=" + tst.getLatestPacketFailPercentage()); 3327 } 3328 } 3329 3330 // Check dns signal. Suspect it may be a data stall if both : 3331 // 1. The number of consecutive DNS query timeouts >= mConsecutiveDnsTimeoutThreshold. 3332 // 2. Those consecutive DNS queries happened in the last mValidDataStallDnsTimeThreshold ms. 3333 final DnsStallDetector dsd = getDnsStallDetector(); 3334 if ((typeToCollect != notStall) && (dsd != null) 3335 && dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { 3336 if (dsd.isDataStallSuspected( 3337 mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { 3338 typeToCollect |= DATA_STALL_EVALUATION_TYPE_DNS; 3339 logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); 3340 } 3341 if (DBG || VDBG_STALL || DDBG_STALL) { 3342 msg.add("consecutive dns timeout count=" + dsd.getConsecutiveTimeoutCount()); 3343 } 3344 } 3345 3346 if (typeToCollect > 0) { 3347 mDataStallTypeToCollect = typeToCollect; 3348 final DataStallReportParcelable p = new DataStallReportParcelable(); 3349 int detectionMethod = 0; 3350 p.timestampMillis = SystemClock.elapsedRealtime(); 3351 if (isDataStallTypeDetected(typeToCollect, DATA_STALL_EVALUATION_TYPE_DNS)) { 3352 detectionMethod |= DETECTION_METHOD_DNS_EVENTS; 3353 p.dnsConsecutiveTimeouts = mDnsStallDetector.getConsecutiveTimeoutCount(); 3354 } 3355 3356 if (isDataStallTypeDetected(typeToCollect, DATA_STALL_EVALUATION_TYPE_TCP)) { 3357 detectionMethod |= DETECTION_METHOD_TCP_METRICS; 3358 p.tcpPacketFailRate = tst.getLatestPacketFailPercentage(); 3359 p.tcpMetricsCollectionPeriodMillis = getTcpPollingInterval(); 3360 } 3361 p.detectionMethod = detectionMethod; 3362 notifyDataStallSuspected(p); 3363 } 3364 3365 // log only data stall suspected. 3366 if ((DBG && (typeToCollect > 0)) || VDBG_STALL || DDBG_STALL) { 3367 log("isDataStall: result=" + typeToCollect + ", " + msg); 3368 } 3369 3370 return typeToCollect > 0; 3371 } 3372 isDataStallTypeDetected(int typeToCollect, int evaluationType)3373 private static boolean isDataStallTypeDetected(int typeToCollect, int evaluationType) { 3374 return (typeToCollect & evaluationType) != 0; 3375 } 3376 // Class to keep state of evaluation results and probe results. 3377 // 3378 // The main purpose was to ensure NetworkMonitor can notify ConnectivityService of probe results 3379 // as soon as they happen, without triggering any other changes. This requires keeping state on 3380 // the most recent evaluation result. Calling noteProbeResult will ensure that the results 3381 // reported to ConnectivityService contain the previous evaluation result, and thus won't 3382 // trigger a validation or partial connectivity state change. 3383 // 3384 // Note that this class is not currently being used for this purpose. The reason is that some 3385 // of the system behaviour triggered by reporting network validation - notably, NetworkAgent 3386 // behaviour - depends not only on the value passed by notifyNetworkTested, but also on the 3387 // fact that notifyNetworkTested was called. For example, telephony triggers network recovery 3388 // any time it is told that validation failed, i.e., if the result does not contain 3389 // NETWORK_VALIDATION_RESULT_VALID. But with this scheme, the first two or three validation 3390 // reports are all failures, because they are "HTTP succeeded but validation not yet passed", 3391 // "HTTP and HTTPS succeeded but validation not yet passed", etc. 3392 @VisibleForTesting 3393 protected class EvaluationState { 3394 // The latest validation result for this network. This is a bitmask of 3395 // INetworkMonitor.NETWORK_VALIDATION_RESULT_* constants. 3396 private int mEvaluationResult = NETWORK_VALIDATION_RESULT_INVALID; 3397 // Indicates which probes have succeeded since clearProbeResults was called. 3398 // This is a bitmask of INetworkMonitor.NETWORK_VALIDATION_PROBE_* constants. 3399 private int mProbeResults = 0; 3400 // A bitmask to record which probes are completed. 3401 private int mProbeCompleted = 0; 3402 // The latest redirect URL. 3403 private String mRedirectUrl; 3404 clearProbeResults()3405 protected void clearProbeResults() { 3406 mProbeResults = 0; 3407 mProbeCompleted = 0; 3408 } 3409 maybeNotifyProbeResults(@onNull final Runnable modif)3410 private void maybeNotifyProbeResults(@NonNull final Runnable modif) { 3411 final int oldCompleted = mProbeCompleted; 3412 final int oldResults = mProbeResults; 3413 modif.run(); 3414 if (oldCompleted != mProbeCompleted || oldResults != mProbeResults) { 3415 notifyProbeStatusChanged(mProbeCompleted, mProbeResults); 3416 } 3417 } 3418 removeProbeResult(final int probeResult)3419 protected void removeProbeResult(final int probeResult) { 3420 maybeNotifyProbeResults(() -> { 3421 mProbeCompleted &= ~probeResult; 3422 mProbeResults &= ~probeResult; 3423 }); 3424 } 3425 noteProbeResult(final int probeResult, final boolean succeeded)3426 protected void noteProbeResult(final int probeResult, final boolean succeeded) { 3427 maybeNotifyProbeResults(() -> { 3428 mProbeCompleted |= probeResult; 3429 if (succeeded) { 3430 mProbeResults |= probeResult; 3431 } else { 3432 mProbeResults &= ~probeResult; 3433 } 3434 }); 3435 } 3436 reportEvaluationResult(int result, @Nullable String redirectUrl)3437 protected void reportEvaluationResult(int result, @Nullable String redirectUrl) { 3438 mEvaluationResult = result; 3439 mRedirectUrl = redirectUrl; 3440 final NetworkTestResultParcelable p = new NetworkTestResultParcelable(); 3441 p.result = result; 3442 p.probesSucceeded = mProbeResults; 3443 p.probesAttempted = mProbeCompleted; 3444 p.redirectUrl = redirectUrl; 3445 p.timestampMillis = SystemClock.elapsedRealtime(); 3446 notifyNetworkTested(p); 3447 recordValidationResult(result, redirectUrl); 3448 } 3449 3450 @VisibleForTesting getEvaluationResult()3451 protected int getEvaluationResult() { 3452 return mEvaluationResult; 3453 } 3454 3455 @VisibleForTesting getProbeResults()3456 protected int getProbeResults() { 3457 return mProbeResults; 3458 } 3459 3460 @VisibleForTesting getProbeCompletedResult()3461 protected int getProbeCompletedResult() { 3462 return mProbeCompleted; 3463 } 3464 } 3465 3466 @VisibleForTesting getEvaluationState()3467 protected EvaluationState getEvaluationState() { 3468 return mEvaluationState; 3469 } 3470 maybeDisableHttpsProbing(boolean acceptPartial)3471 private void maybeDisableHttpsProbing(boolean acceptPartial) { 3472 mAcceptPartialConnectivity = acceptPartial; 3473 // Ignore https probe in next validation if user accept partial connectivity on a partial 3474 // connectivity network. 3475 if (((mEvaluationState.getEvaluationResult() & NETWORK_VALIDATION_RESULT_PARTIAL) != 0) 3476 && mAcceptPartialConnectivity) { 3477 mUseHttps = false; 3478 } 3479 } 3480 3481 // Report HTTP, HTTP or FALLBACK probe result. 3482 @VisibleForTesting reportHttpProbeResult(int probeResult, @NonNull final CaptivePortalProbeResult result)3483 protected void reportHttpProbeResult(int probeResult, 3484 @NonNull final CaptivePortalProbeResult result) { 3485 boolean succeeded = result.isSuccessful(); 3486 // The success of a HTTP probe does not tell us whether the DNS probe succeeded. 3487 // The DNS and HTTP probes run one after the other in sendDnsAndHttpProbes, and that 3488 // method cannot report the result of the DNS probe because that it could be running 3489 // on a different thread which is racing with the main state machine thread. So, if 3490 // an HTTP or HTTPS probe succeeded, assume that the DNS probe succeeded. But if an 3491 // HTTP or HTTPS probe failed, don't assume that DNS is not working. 3492 // TODO: fix this. 3493 if (succeeded) { 3494 probeResult |= NETWORK_VALIDATION_PROBE_DNS; 3495 } 3496 mEvaluationState.noteProbeResult(probeResult, succeeded); 3497 } 3498 maybeReportCaptivePortalData(@ullable CaptivePortalDataShim data)3499 private void maybeReportCaptivePortalData(@Nullable CaptivePortalDataShim data) { 3500 // Do not clear data even if it is null: access points should not stop serving the API, so 3501 // if the API disappears this is treated as a temporary failure, and previous data should 3502 // remain valid. 3503 if (data == null) return; 3504 try { 3505 data.notifyChanged(mCallback); 3506 } catch (RemoteException e) { 3507 Log.e(TAG, "Error notifying ConnectivityService of new capport data", e); 3508 } 3509 } 3510 3511 /** 3512 * Interface for logging dns results. 3513 */ 3514 public interface DnsLogFunc { 3515 /** 3516 * Log function. 3517 */ log(String s)3518 void log(String s); 3519 } 3520 3521 @Nullable getTcpSocketTrackerOrNull(Context context, Network network)3522 private static TcpSocketTracker getTcpSocketTrackerOrNull(Context context, Network network) { 3523 return ((Dependencies.DEFAULT.getDeviceConfigPropertyInt( 3524 NAMESPACE_CONNECTIVITY, 3525 CONFIG_DATA_STALL_EVALUATION_TYPE, 3526 DEFAULT_DATA_STALL_EVALUATION_TYPES) 3527 & DATA_STALL_EVALUATION_TYPE_TCP) != 0) 3528 ? new TcpSocketTracker(new TcpSocketTracker.Dependencies(context), network) 3529 : null; 3530 } 3531 3532 @Nullable initDnsStallDetectorIfRequired(int type, int threshold)3533 private DnsStallDetector initDnsStallDetectorIfRequired(int type, int threshold) { 3534 return ((type & DATA_STALL_EVALUATION_TYPE_DNS) != 0) 3535 ? new DnsStallDetector(threshold) : null; 3536 } 3537 getCaptivePortalApiUrl(LinkProperties lp)3538 private static Uri getCaptivePortalApiUrl(LinkProperties lp) { 3539 return NetworkInformationShimImpl.newInstance().getCaptivePortalApiUrl(lp); 3540 } 3541 3542 /** 3543 * Check if the network is captive with terms and conditions page 3544 * @return true if network is captive with T&C page, false otherwise 3545 */ isTermsAndConditionsCaptive(CaptivePortalDataShim captivePortalDataShim)3546 private boolean isTermsAndConditionsCaptive(CaptivePortalDataShim captivePortalDataShim) { 3547 return captivePortalDataShim != null 3548 && captivePortalDataShim.getUserPortalUrl() != null 3549 && !TextUtils.isEmpty(captivePortalDataShim.getUserPortalUrl().toString()) 3550 && captivePortalDataShim.isCaptive() 3551 && captivePortalDataShim.getUserPortalUrlSource() 3552 == ConstantsShim.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT; 3553 } 3554 } 3555