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