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