blob: b655ed6e6adb48ed63e240aa14ce17cbf2ced987 [file] [log] [blame]
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
25import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
33import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
35import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
36import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
37import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
38import static android.net.ConnectivityManager.TYPE_ETHERNET;
39import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
49import static android.net.ConnectivityManager.TYPE_NONE;
50import static android.net.ConnectivityManager.TYPE_PROXY;
51import static android.net.ConnectivityManager.TYPE_VPN;
52import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
54import static android.net.ConnectivityManager.getNetworkTypeName;
55import static android.net.ConnectivityManager.isNetworkTypeValid;
56import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
57import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
58import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
59import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
60import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
61import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
62import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
63import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
64import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
65import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
66import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
68import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
69import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
75import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
76import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
77import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
78import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
79import static android.net.NetworkCapabilities.TRANSPORT_TEST;
80import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Treehugger Robot27b68882021-06-07 19:42:39 +000081import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000082import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
James Mattisb7ca0342021-06-16 01:30:05 +000083import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
84import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000085import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
86import static android.os.Process.INVALID_UID;
87import static android.os.Process.VPN_UID;
88import static android.system.OsConstants.IPPROTO_TCP;
89import static android.system.OsConstants.IPPROTO_UDP;
90
91import static java.util.Map.Entry;
92
93import android.Manifest;
94import android.annotation.NonNull;
95import android.annotation.Nullable;
96import android.app.AppOpsManager;
97import android.app.BroadcastOptions;
98import android.app.PendingIntent;
99import android.app.usage.NetworkStatsManager;
100import android.content.BroadcastReceiver;
101import android.content.ComponentName;
102import android.content.ContentResolver;
103import android.content.Context;
104import android.content.Intent;
105import android.content.IntentFilter;
106import android.content.pm.PackageManager;
107import android.database.ContentObserver;
108import android.net.CaptivePortal;
109import android.net.CaptivePortalData;
110import android.net.ConnectionInfo;
111import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
112import android.net.ConnectivityDiagnosticsManager.DataStallReport;
113import android.net.ConnectivityManager;
114import android.net.ConnectivityManager.BlockedReason;
115import android.net.ConnectivityManager.NetworkCallback;
Aaron Huangcff22942021-05-27 16:31:26 +0800116import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000117import android.net.ConnectivityResources;
118import android.net.ConnectivitySettingsManager;
119import android.net.DataStallReportParcelable;
120import android.net.DnsResolverServiceManager;
121import android.net.ICaptivePortal;
122import android.net.IConnectivityDiagnosticsCallback;
123import android.net.IConnectivityManager;
124import android.net.IDnsResolver;
125import android.net.INetd;
126import android.net.INetworkActivityListener;
127import android.net.INetworkAgent;
128import android.net.INetworkMonitor;
129import android.net.INetworkMonitorCallbacks;
130import android.net.INetworkOfferCallback;
131import android.net.IOnCompleteListener;
132import android.net.IQosCallback;
133import android.net.ISocketKeepaliveCallback;
134import android.net.InetAddresses;
135import android.net.IpMemoryStore;
136import android.net.IpPrefix;
137import android.net.LinkProperties;
138import android.net.MatchAllNetworkSpecifier;
139import android.net.NativeNetworkConfig;
140import android.net.NativeNetworkType;
141import android.net.NattSocketKeepalive;
142import android.net.Network;
143import android.net.NetworkAgent;
144import android.net.NetworkAgentConfig;
145import android.net.NetworkCapabilities;
146import android.net.NetworkInfo;
147import android.net.NetworkInfo.DetailedState;
148import android.net.NetworkMonitorManager;
149import android.net.NetworkPolicyManager;
150import android.net.NetworkPolicyManager.NetworkPolicyCallback;
151import android.net.NetworkProvider;
152import android.net.NetworkRequest;
153import android.net.NetworkScore;
154import android.net.NetworkSpecifier;
155import android.net.NetworkStack;
156import android.net.NetworkState;
157import android.net.NetworkStateSnapshot;
158import android.net.NetworkTestResultParcelable;
159import android.net.NetworkUtils;
160import android.net.NetworkWatchlistManager;
161import android.net.OemNetworkPreferences;
162import android.net.PrivateDnsConfigParcel;
163import android.net.ProxyInfo;
164import android.net.QosCallbackException;
165import android.net.QosFilter;
166import android.net.QosSocketFilter;
167import android.net.QosSocketInfo;
168import android.net.RouteInfo;
169import android.net.RouteInfoParcel;
170import android.net.SocketKeepalive;
171import android.net.TetheringManager;
172import android.net.TransportInfo;
173import android.net.UidRange;
174import android.net.UidRangeParcel;
175import android.net.UnderlyingNetworkInfo;
176import android.net.Uri;
177import android.net.VpnManager;
178import android.net.VpnTransportInfo;
179import android.net.metrics.IpConnectivityLog;
180import android.net.metrics.NetworkEvent;
paulhude2a2392021-06-09 16:11:35 +0800181import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000182import android.net.netlink.InetDiagMessage;
183import android.net.networkstack.ModuleNetworkStackClient;
184import android.net.networkstack.NetworkStackClientBase;
185import android.net.resolv.aidl.DnsHealthEventParcel;
186import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
187import android.net.resolv.aidl.Nat64PrefixEventParcel;
188import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
189import android.net.shared.PrivateDnsConfig;
190import android.net.util.MultinetworkPolicyTracker;
191import android.os.BatteryStatsManager;
192import android.os.Binder;
193import android.os.Build;
194import android.os.Bundle;
195import android.os.Handler;
196import android.os.HandlerThread;
197import android.os.IBinder;
198import android.os.Looper;
199import android.os.Message;
200import android.os.Messenger;
201import android.os.ParcelFileDescriptor;
202import android.os.Parcelable;
203import android.os.PersistableBundle;
204import android.os.PowerManager;
205import android.os.Process;
206import android.os.RemoteCallbackList;
207import android.os.RemoteException;
208import android.os.ServiceSpecificException;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.provider.Settings;
214import android.sysprop.NetworkProperties;
215import android.telephony.TelephonyManager;
216import android.text.TextUtils;
217import android.util.ArrayMap;
218import android.util.ArraySet;
219import android.util.LocalLog;
220import android.util.Log;
221import android.util.Pair;
222import android.util.SparseArray;
223import android.util.SparseIntArray;
224
225import com.android.connectivity.resources.R;
226import com.android.internal.annotations.GuardedBy;
227import com.android.internal.annotations.VisibleForTesting;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.MessageUtils;
230import com.android.modules.utils.BasicShellCommandHandler;
231import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
232import com.android.net.module.util.CollectionUtils;
233import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
234import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
235import com.android.net.module.util.LocationPermissionChecker;
236import com.android.net.module.util.NetworkCapabilitiesUtils;
237import com.android.net.module.util.PermissionUtils;
238import com.android.server.connectivity.AutodestructReference;
239import com.android.server.connectivity.DnsManager;
240import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
241import com.android.server.connectivity.FullScore;
242import com.android.server.connectivity.KeepaliveTracker;
243import com.android.server.connectivity.LingerMonitor;
244import com.android.server.connectivity.MockableSystemProperties;
245import com.android.server.connectivity.NetworkAgentInfo;
246import com.android.server.connectivity.NetworkDiagnostics;
247import com.android.server.connectivity.NetworkNotificationManager;
248import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
249import com.android.server.connectivity.NetworkOffer;
250import com.android.server.connectivity.NetworkRanker;
251import com.android.server.connectivity.PermissionMonitor;
252import com.android.server.connectivity.ProfileNetworkPreferences;
253import com.android.server.connectivity.ProxyTracker;
254import com.android.server.connectivity.QosCallbackTracker;
255
256import libcore.io.IoUtils;
257
258import java.io.FileDescriptor;
259import java.io.PrintWriter;
260import java.net.Inet4Address;
261import java.net.InetAddress;
262import java.net.InetSocketAddress;
263import java.net.UnknownHostException;
264import java.util.ArrayList;
265import java.util.Arrays;
266import java.util.Collection;
267import java.util.Collections;
268import java.util.Comparator;
269import java.util.ConcurrentModificationException;
270import java.util.HashMap;
271import java.util.HashSet;
272import java.util.List;
273import java.util.Map;
274import java.util.Objects;
275import java.util.Set;
276import java.util.SortedSet;
277import java.util.StringJoiner;
278import java.util.TreeSet;
279import java.util.concurrent.atomic.AtomicInteger;
280
281/**
282 * @hide
283 */
284public class ConnectivityService extends IConnectivityManager.Stub
285 implements PendingIntent.OnFinished {
286 private static final String TAG = ConnectivityService.class.getSimpleName();
287
288 private static final String DIAG_ARG = "--diag";
289 public static final String SHORT_ARG = "--short";
290 private static final String NETWORK_ARG = "networks";
291 private static final String REQUEST_ARG = "requests";
292
293 private static final boolean DBG = true;
294 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
295 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
296
297 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
298
299 /**
300 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
301 * by OEMs for configuration purposes, as this value is overridden by
302 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
303 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
304 * (preferably via runtime resource overlays).
305 */
306 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
307 "http://connectivitycheck.gstatic.com/generate_204";
308
309 // TODO: create better separation between radio types and network types
310
311 // how long to wait before switching back to a radio's default network
312 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
313 // system property that can override the above value
314 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
315 "android.telephony.apn-restore";
316
317 // How long to wait before putting up a "This network doesn't have an Internet connection,
318 // connect anyway?" dialog after the user selects a network that doesn't validate.
319 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
320
321 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
322 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
323 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
324 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
325
326 // The maximum number of network request allowed per uid before an exception is thrown.
327 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
328
329 // The maximum number of network request allowed for system UIDs before an exception is thrown.
330 @VisibleForTesting
331 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
332
333 @VisibleForTesting
334 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
335 @VisibleForTesting
336 protected int mNascentDelayMs;
337
338 // How long to delay to removal of a pending intent based request.
339 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
340 private final int mReleasePendingIntentDelayMs;
341
342 private MockableSystemProperties mSystemProperties;
343
344 @VisibleForTesting
345 protected final PermissionMonitor mPermissionMonitor;
346
347 private final PerUidCounter mNetworkRequestCounter;
348 @VisibleForTesting
349 final PerUidCounter mSystemNetworkRequestCounter;
350
351 private volatile boolean mLockdownEnabled;
352
353 /**
354 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
355 * internal handler thread, they don't need a lock.
356 */
357 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
358
359 private final Context mContext;
360 private final ConnectivityResources mResources;
361 // The Context is created for UserHandle.ALL.
362 private final Context mUserAllContext;
363 private final Dependencies mDeps;
364 // 0 is full bad, 100 is full good
365 private int mDefaultInetConditionPublished = 0;
366
367 @VisibleForTesting
368 protected IDnsResolver mDnsResolver;
369 @VisibleForTesting
370 protected INetd mNetd;
371 private NetworkStatsManager mStatsManager;
372 private NetworkPolicyManager mPolicyManager;
373 private final NetdCallback mNetdCallback;
374
375 /**
376 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
377 * instances.
378 */
379 @GuardedBy("mTNSLock")
380 private TestNetworkService mTNS;
381
382 private final Object mTNSLock = new Object();
383
384 private String mCurrentTcpBufferSizes;
385
386 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
387 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
388
389 private enum ReapUnvalidatedNetworks {
390 // Tear down networks that have no chance (e.g. even if validated) of becoming
391 // the highest scoring network satisfying a NetworkRequest. This should be passed when
392 // all networks have been rematched against all NetworkRequests.
393 REAP,
394 // Don't reap networks. This should be passed when some networks have not yet been
395 // rematched against all NetworkRequests.
396 DONT_REAP
397 }
398
399 private enum UnneededFor {
400 LINGER, // Determine whether this network is unneeded and should be lingered.
401 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
402 }
403
404 /**
paulhude5efb92021-05-26 21:56:03 +0800405 * For per-app preferences, requests contain an int to signify which request
406 * should have priority. The priority is passed to netd which will use it
407 * together with UID ranges to generate the corresponding IP rule. This serves
408 * to direct device-originated data traffic of the specific UIDs to the correct
409 * default network for each app.
410 * Priorities passed to netd must be in the 0~999 range. Larger values code for
411 * a lower priority, {@see NativeUidRangeConfig}
paulhuc2198772021-05-26 15:19:20 +0800412 *
paulhude5efb92021-05-26 21:56:03 +0800413 * Requests that don't code for a per-app preference use PREFERENCE_PRIORITY_INVALID.
414 * The default request uses PREFERENCE_PRIORITY_DEFAULT.
paulhuc2198772021-05-26 15:19:20 +0800415 */
paulhude5efb92021-05-26 21:56:03 +0800416 // Bound for the lowest valid priority.
417 static final int PREFERENCE_PRIORITY_LOWEST = 999;
418 // Used when sending to netd to code for "no priority".
419 static final int PREFERENCE_PRIORITY_NONE = 0;
420 // Priority for requests that don't code for a per-app preference. As it is
421 // out of the valid range, the corresponding priority should be
422 // PREFERENCE_PRIORITY_NONE when sending to netd.
paulhuc2198772021-05-26 15:19:20 +0800423 @VisibleForTesting
paulhude5efb92021-05-26 21:56:03 +0800424 static final int PREFERENCE_PRIORITY_INVALID = Integer.MAX_VALUE;
425 // Priority for the default internet request. Since this must always have the
426 // lowest priority, its value is larger than the largest acceptable value. As
427 // it is out of the valid range, the corresponding priority should be
428 // PREFERENCE_PRIORITY_NONE when sending to netd.
429 static final int PREFERENCE_PRIORITY_DEFAULT = 1000;
430 // As a security feature, VPNs have the top priority.
431 static final int PREFERENCE_PRIORITY_VPN = 1;
432 // Priority of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhuc2198772021-05-26 15:19:20 +0800433 @VisibleForTesting
paulhude5efb92021-05-26 21:56:03 +0800434 static final int PREFERENCE_PRIORITY_OEM = 10;
435 // Priority of per-profile preference, such as used by enterprise networks.
paulhuc2198772021-05-26 15:19:20 +0800436 // See {@link #setProfileNetworkPreference}.
437 @VisibleForTesting
paulhude5efb92021-05-26 21:56:03 +0800438 static final int PREFERENCE_PRIORITY_PROFILE = 20;
439 // Priority of user setting to prefer mobile data even when networks with
440 // better scores are connected.
441 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhuc2198772021-05-26 15:19:20 +0800442 @VisibleForTesting
paulhude5efb92021-05-26 21:56:03 +0800443 static final int PREFERENCE_PRIORITY_MOBILE_DATA_PREFERERRED = 30;
paulhuc2198772021-05-26 15:19:20 +0800444
445 /**
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000446 * used internally to clear a wakelock when transitioning
447 * from one net to another. Clear happens when we get a new
448 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
449 * after a timeout if no network is found (typically 1 min).
450 */
451 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
452
453 /**
454 * used internally to reload global proxy settings
455 */
456 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
457
458 /**
459 * PAC manager has received new port.
460 */
461 private static final int EVENT_PROXY_HAS_CHANGED = 16;
462
463 /**
464 * used internally when registering NetworkProviders
465 * obj = NetworkProviderInfo
466 */
467 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
468
469 /**
470 * used internally when registering NetworkAgents
471 * obj = Messenger
472 */
473 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
474
475 /**
476 * used to add a network request
477 * includes a NetworkRequestInfo
478 */
479 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
480
481 /**
482 * indicates a timeout period is over - check if we had a network yet or not
483 * and if not, call the timeout callback (but leave the request live until they
484 * cancel it.
485 * includes a NetworkRequestInfo
486 */
487 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
488
489 /**
490 * used to add a network listener - no request
491 * includes a NetworkRequestInfo
492 */
493 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
494
495 /**
496 * used to remove a network request, either a listener or a real request
497 * arg1 = UID of caller
498 * obj = NetworkRequest
499 */
500 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
501
502 /**
503 * used internally when registering NetworkProviders
504 * obj = Messenger
505 */
506 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
507
508 /**
509 * used internally to expire a wakelock when transitioning
510 * from one net to another. Expire happens when we fail to find
511 * a new network (typically after 1 minute) -
512 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
513 * a replacement network.
514 */
515 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
516
517 /**
518 * used to add a network request with a pending intent
519 * obj = NetworkRequestInfo
520 */
521 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
522
523 /**
524 * used to remove a pending intent and its associated network request.
525 * arg1 = UID of caller
526 * obj = PendingIntent
527 */
528 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
529
530 /**
531 * used to specify whether a network should be used even if unvalidated.
532 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
533 * arg2 = whether to remember this choice in the future (1 or 0)
534 * obj = network
535 */
536 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
537
538 /**
539 * used to ask the user to confirm a connection to an unvalidated network.
540 * obj = network
541 */
542 private static final int EVENT_PROMPT_UNVALIDATED = 29;
543
544 /**
545 * used internally to (re)configure always-on networks.
546 */
547 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
548
549 /**
550 * used to add a network listener with a pending intent
551 * obj = NetworkRequestInfo
552 */
553 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
554
555 /**
556 * used to specify whether a network should not be penalized when it becomes unvalidated.
557 */
558 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
559
560 /**
561 * used to trigger revalidation of a network.
562 */
563 private static final int EVENT_REVALIDATE_NETWORK = 36;
564
565 // Handle changes in Private DNS settings.
566 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
567
568 // Handle private DNS validation status updates.
569 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
570
571 /**
572 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
573 * been tested.
574 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
575 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
576 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
577 */
578 private static final int EVENT_NETWORK_TESTED = 41;
579
580 /**
581 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
582 * config was resolved.
583 * obj = PrivateDnsConfig
584 * arg2 = netid
585 */
586 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
587
588 /**
589 * Request ConnectivityService display provisioning notification.
590 * arg1 = Whether to make the notification visible.
591 * arg2 = NetID.
592 * obj = Intent to be launched when notification selected by user, null if !arg1.
593 */
594 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
595
596 /**
597 * Used to specify whether a network should be used even if connectivity is partial.
598 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
599 * false)
600 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
601 * obj = network
602 */
603 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
604
605 /**
606 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
607 * Both of the arguments are bitmasks, and the value of bits come from
608 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
609 * arg1 = A bitmask to describe which probes are completed.
610 * arg2 = A bitmask to describe which probes are successful.
611 */
612 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
613
614 /**
615 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
616 * arg1 = unused
617 * arg2 = netId
618 * obj = captive portal data
619 */
620 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
621
622 /**
623 * Used by setRequireVpnForUids.
624 * arg1 = whether the specified UID ranges are required to use a VPN.
625 * obj = Array of UidRange objects.
626 */
627 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
628
629 /**
630 * Used internally when setting the default networks for OemNetworkPreferences.
631 * obj = Pair<OemNetworkPreferences, listener>
632 */
633 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
634
635 /**
636 * Used to indicate the system default network becomes active.
637 */
638 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
639
640 /**
641 * Used internally when setting a network preference for a user profile.
642 * obj = Pair<ProfileNetworkPreference, Listener>
643 */
644 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
645
646 /**
647 * Event to specify that reasons for why an uid is blocked changed.
648 * arg1 = uid
649 * arg2 = blockedReasons
650 */
651 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
652
653 /**
654 * Event to register a new network offer
655 * obj = NetworkOffer
656 */
657 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
658
659 /**
660 * Event to unregister an existing network offer
661 * obj = INetworkOfferCallback
662 */
663 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
664
665 /**
paulhu71ad4f12021-05-25 14:56:27 +0800666 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
667 */
668 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
669
670 /**
Chiachang Wangfad30e32021-06-23 02:08:44 +0000671 * Event to set temporary allow bad wifi within a limited time to override
672 * {@code config_networkAvoidBadWifi}.
673 */
674 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
675
676 /**
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000677 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
678 * should be shown.
679 */
680 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
681
682 /**
683 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
684 * should be hidden.
685 */
686 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
687
Chiachang Wangfad30e32021-06-23 02:08:44 +0000688 /**
689 * The maximum alive time to allow bad wifi configuration for testing.
690 */
691 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
692
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000693 private static String eventName(int what) {
694 return sMagicDecoderRing.get(what, Integer.toString(what));
695 }
696
697 private static IDnsResolver getDnsResolver(Context context) {
698 final DnsResolverServiceManager dsm = context.getSystemService(
699 DnsResolverServiceManager.class);
700 return IDnsResolver.Stub.asInterface(dsm.getService());
701 }
702
703 /** Handler thread used for all of the handlers below. */
704 @VisibleForTesting
705 protected final HandlerThread mHandlerThread;
706 /** Handler used for internal events. */
707 final private InternalHandler mHandler;
708 /** Handler used for incoming {@link NetworkStateTracker} events. */
709 final private NetworkStateTrackerHandler mTrackerHandler;
710 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
711 @VisibleForTesting
712 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
713
714 private final DnsManager mDnsManager;
715 private final NetworkRanker mNetworkRanker;
716
717 private boolean mSystemReady;
718 private Intent mInitialBroadcast;
719
720 private PowerManager.WakeLock mNetTransitionWakeLock;
721 private final PowerManager.WakeLock mPendingIntentWakeLock;
722
723 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
724 // the world when it changes.
725 @VisibleForTesting
726 protected final ProxyTracker mProxyTracker;
727
728 final private SettingsObserver mSettingsObserver;
729
730 private UserManager mUserManager;
731
732 // the set of network types that can only be enabled by system/sig apps
733 private List<Integer> mProtectedNetworks;
734
735 private Set<String> mWolSupportedInterfaces;
736
737 private final TelephonyManager mTelephonyManager;
738 private final AppOpsManager mAppOpsManager;
739
740 private final LocationPermissionChecker mLocationPermissionChecker;
741
742 private KeepaliveTracker mKeepaliveTracker;
743 private QosCallbackTracker mQosCallbackTracker;
744 private NetworkNotificationManager mNotifier;
745 private LingerMonitor mLingerMonitor;
746
747 // sequence number of NetworkRequests
748 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
749
750 // Sequence number for NetworkProvider IDs.
751 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
752 NetworkProvider.FIRST_PROVIDER_ID);
753
754 // NetworkRequest activity String log entries.
755 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
756 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
757
758 // NetworkInfo blocked and unblocked String log entries
759 private static final int MAX_NETWORK_INFO_LOGS = 40;
760 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
761
762 private static final int MAX_WAKELOCK_LOGS = 20;
763 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
764 private int mTotalWakelockAcquisitions = 0;
765 private int mTotalWakelockReleases = 0;
766 private long mTotalWakelockDurationMs = 0;
767 private long mMaxWakelockDurationMs = 0;
768 private long mLastWakeLockAcquireTimestamp = 0;
769
770 private final IpConnectivityLog mMetricsLog;
771
772 @GuardedBy("mBandwidthRequests")
773 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
774
775 @VisibleForTesting
776 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
777
778 @VisibleForTesting
779 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
780 new HashMap<>();
781
782 /**
783 * Implements support for the legacy "one network per network type" model.
784 *
785 * We used to have a static array of NetworkStateTrackers, one for each
786 * network type, but that doesn't work any more now that we can have,
787 * for example, more that one wifi network. This class stores all the
788 * NetworkAgentInfo objects that support a given type, but the legacy
789 * API will only see the first one.
790 *
791 * It serves two main purposes:
792 *
793 * 1. Provide information about "the network for a given type" (since this
794 * API only supports one).
795 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
796 * the first network for a given type changes, or if the default network
797 * changes.
798 */
799 @VisibleForTesting
800 static class LegacyTypeTracker {
801
802 private static final boolean DBG = true;
803 private static final boolean VDBG = false;
804
805 /**
806 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
807 * Each list holds references to all NetworkAgentInfos that are used to
808 * satisfy requests for that network type.
809 *
810 * This array is built out at startup such that an unsupported network
811 * doesn't get an ArrayList instance, making this a tristate:
812 * unsupported, supported but not active and active.
813 *
814 * The actual lists are populated when we scan the network types that
815 * are supported on this device.
816 *
817 * Threading model:
818 * - addSupportedType() is only called in the constructor
819 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
820 * They are therefore not thread-safe with respect to each other.
821 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
822 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
823 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
824 * - dump is thread-safe with respect to concurrent add and remove calls.
825 */
826 private final ArrayList<NetworkAgentInfo> mTypeLists[];
827 @NonNull
828 private final ConnectivityService mService;
829
830 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
831 // an entry have no timer (equivalent to -1). Lazily loaded.
832 @NonNull
833 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
834
835 LegacyTypeTracker(@NonNull ConnectivityService service) {
836 mService = service;
837 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
838 }
839
840 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
841 final PackageManager pm = ctx.getPackageManager();
842 if (pm.hasSystemFeature(FEATURE_WIFI)) {
843 addSupportedType(TYPE_WIFI);
844 }
845 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
846 addSupportedType(TYPE_WIFI_P2P);
847 }
848 if (tm.isDataCapable()) {
849 // Telephony does not have granular support for these types: they are either all
850 // supported, or none is supported
851 addSupportedType(TYPE_MOBILE);
852 addSupportedType(TYPE_MOBILE_MMS);
853 addSupportedType(TYPE_MOBILE_SUPL);
854 addSupportedType(TYPE_MOBILE_DUN);
855 addSupportedType(TYPE_MOBILE_HIPRI);
856 addSupportedType(TYPE_MOBILE_FOTA);
857 addSupportedType(TYPE_MOBILE_IMS);
858 addSupportedType(TYPE_MOBILE_CBS);
859 addSupportedType(TYPE_MOBILE_IA);
860 addSupportedType(TYPE_MOBILE_EMERGENCY);
861 }
862 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
863 addSupportedType(TYPE_BLUETOOTH);
864 }
865 if (pm.hasSystemFeature(FEATURE_WATCH)) {
866 // TYPE_PROXY is only used on Wear
867 addSupportedType(TYPE_PROXY);
868 }
869 // Ethernet is often not specified in the configs, although many devices can use it via
870 // USB host adapters. Add it as long as the ethernet service is here.
871 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
872 addSupportedType(TYPE_ETHERNET);
873 }
874
875 // Always add TYPE_VPN as a supported type
876 addSupportedType(TYPE_VPN);
877 }
878
879 private void addSupportedType(int type) {
880 if (mTypeLists[type] != null) {
881 throw new IllegalStateException(
882 "legacy list for type " + type + "already initialized");
883 }
884 mTypeLists[type] = new ArrayList<>();
885 }
886
887 public boolean isTypeSupported(int type) {
888 return isNetworkTypeValid(type) && mTypeLists[type] != null;
889 }
890
891 public NetworkAgentInfo getNetworkForType(int type) {
892 synchronized (mTypeLists) {
893 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
894 return mTypeLists[type].get(0);
895 }
896 }
897 return null;
898 }
899
900 public int getRestoreTimerForType(int type) {
901 synchronized (mTypeLists) {
902 if (mRestoreTimers == null) {
903 mRestoreTimers = loadRestoreTimers();
904 }
905 return mRestoreTimers.getOrDefault(type, -1);
906 }
907 }
908
909 private ArrayMap<Integer, Integer> loadRestoreTimers() {
910 final String[] configs = mService.mResources.get().getStringArray(
911 R.array.config_legacy_networktype_restore_timers);
912 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
913 for (final String config : configs) {
914 final String[] splits = TextUtils.split(config, ",");
915 if (splits.length != 2) {
916 logwtf("Invalid restore timer token count: " + config);
917 continue;
918 }
919 try {
920 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
921 } catch (NumberFormatException e) {
922 logwtf("Invalid restore timer number format: " + config, e);
923 }
924 }
925 return ret;
926 }
927
928 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
929 boolean isDefaultNetwork) {
930 if (DBG) {
931 log("Sending " + state
932 + " broadcast for type " + type + " " + nai.toShortString()
933 + " isDefaultNetwork=" + isDefaultNetwork);
934 }
935 }
936
937 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
938 // network type, to preserve previous behaviour.
939 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
940 if (vpnNai != mService.getLegacyLockdownNai()) return;
941
942 if (vpnNai.declaredUnderlyingNetworks == null
943 || vpnNai.declaredUnderlyingNetworks.length != 1) {
944 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
945 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
946 return;
947 }
948 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
949 vpnNai.declaredUnderlyingNetworks[0]);
950 if (underlyingNai == null) return;
951
952 final int type = underlyingNai.networkInfo.getType();
953 final DetailedState state = DetailedState.CONNECTED;
954 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
955 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
956 }
957
958 /** Adds the given network to the specified legacy type list. */
959 public void add(int type, NetworkAgentInfo nai) {
960 if (!isTypeSupported(type)) {
961 return; // Invalid network type.
962 }
963 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
964
965 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
966 if (list.contains(nai)) {
967 return;
968 }
969 synchronized (mTypeLists) {
970 list.add(nai);
971 }
972
973 // Send a broadcast if this is the first network of its type or if it's the default.
974 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
975
976 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
977 // to preserve previous behaviour.
978 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
979 if ((list.size() == 1) || isDefaultNetwork) {
980 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
981 mService.sendLegacyNetworkBroadcast(nai, state, type);
982 }
983
984 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
985 maybeSendLegacyLockdownBroadcast(nai);
986 }
987 }
988
989 /** Removes the given network from the specified legacy type list. */
990 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
991 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
992 if (list == null || list.isEmpty()) {
993 return;
994 }
995 final boolean wasFirstNetwork = list.get(0).equals(nai);
996
997 synchronized (mTypeLists) {
998 if (!list.remove(nai)) {
999 return;
1000 }
1001 }
1002
1003 if (wasFirstNetwork || wasDefault) {
1004 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1005 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
1006 }
1007
1008 if (!list.isEmpty() && wasFirstNetwork) {
1009 if (DBG) log("Other network available for type " + type +
1010 ", sending connected broadcast");
1011 final NetworkAgentInfo replacement = list.get(0);
1012 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
1013 mService.isDefaultNetwork(replacement));
1014 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
1015 }
1016 }
1017
1018 /** Removes the given network from all legacy type lists. */
1019 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1020 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
1021 for (int type = 0; type < mTypeLists.length; type++) {
1022 remove(type, nai, wasDefault);
1023 }
1024 }
1025
1026 // send out another legacy broadcast - currently only used for suspend/unsuspend
1027 // toggle
1028 public void update(NetworkAgentInfo nai) {
1029 final boolean isDefault = mService.isDefaultNetwork(nai);
1030 final DetailedState state = nai.networkInfo.getDetailedState();
1031 for (int type = 0; type < mTypeLists.length; type++) {
1032 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1033 final boolean contains = (list != null && list.contains(nai));
1034 final boolean isFirst = contains && (nai == list.get(0));
1035 if (isFirst || contains && isDefault) {
1036 maybeLogBroadcast(nai, state, type, isDefault);
1037 mService.sendLegacyNetworkBroadcast(nai, state, type);
1038 }
1039 }
1040 }
1041
1042 public void dump(IndentingPrintWriter pw) {
1043 pw.println("mLegacyTypeTracker:");
1044 pw.increaseIndent();
1045 pw.print("Supported types:");
1046 for (int type = 0; type < mTypeLists.length; type++) {
1047 if (mTypeLists[type] != null) pw.print(" " + type);
1048 }
1049 pw.println();
1050 pw.println("Current state:");
1051 pw.increaseIndent();
1052 synchronized (mTypeLists) {
1053 for (int type = 0; type < mTypeLists.length; type++) {
1054 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1055 for (NetworkAgentInfo nai : mTypeLists[type]) {
1056 pw.println(type + " " + nai.toShortString());
1057 }
1058 }
1059 }
1060 pw.decreaseIndent();
1061 pw.decreaseIndent();
1062 pw.println();
1063 }
1064 }
1065 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
1066
1067 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
1068 /**
1069 * Helper class which parses out priority arguments and dumps sections according to their
1070 * priority. If priority arguments are omitted, function calls the legacy dump command.
1071 */
1072 private class LocalPriorityDump {
1073 private static final String PRIORITY_ARG = "--dump-priority";
1074 private static final String PRIORITY_ARG_HIGH = "HIGH";
1075 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1076
1077 LocalPriorityDump() {}
1078
1079 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1080 doDump(fd, pw, new String[] {DIAG_ARG});
1081 doDump(fd, pw, new String[] {SHORT_ARG});
1082 }
1083
1084 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1085 doDump(fd, pw, args);
1086 }
1087
1088 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1089 if (args == null) {
1090 dumpNormal(fd, pw, args);
1091 return;
1092 }
1093
1094 String priority = null;
1095 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1096 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1097 argIndex++;
1098 priority = args[argIndex];
1099 }
1100 }
1101
1102 if (PRIORITY_ARG_HIGH.equals(priority)) {
1103 dumpHigh(fd, pw);
1104 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1105 dumpNormal(fd, pw, args);
1106 } else {
1107 // ConnectivityService publishes binder service using publishBinderService() with
1108 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang12d32a62021-05-17 16:57:15 +08001109 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1110 // legacy output for dumpsys connectivity.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001111 // TODO: Integrate into signal dump.
1112 dumpNormal(fd, pw, args);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001113 }
1114 }
1115 }
1116
1117 /**
1118 * Keeps track of the number of requests made under different uids.
1119 */
1120 public static class PerUidCounter {
1121 private final int mMaxCountPerUid;
1122
1123 // Map from UID to number of NetworkRequests that UID has filed.
1124 @VisibleForTesting
1125 @GuardedBy("mUidToNetworkRequestCount")
1126 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
1127
1128 /**
1129 * Constructor
1130 *
1131 * @param maxCountPerUid the maximum count per uid allowed
1132 */
1133 public PerUidCounter(final int maxCountPerUid) {
1134 mMaxCountPerUid = maxCountPerUid;
1135 }
1136
1137 /**
1138 * Increments the request count of the given uid. Throws an exception if the number
1139 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1140 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1141 *
1142 * @throws ServiceSpecificException with
1143 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1144 * the uid exceed the allowed number.
1145 *
1146 * @param uid the uid that the request was made under
1147 */
1148 public void incrementCountOrThrow(final int uid) {
1149 synchronized (mUidToNetworkRequestCount) {
1150 incrementCountOrThrow(uid, 1 /* numToIncrement */);
1151 }
1152 }
1153
1154 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1155 final int newRequestCount =
1156 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1157 if (newRequestCount >= mMaxCountPerUid) {
1158 throw new ServiceSpecificException(
1159 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1160 }
1161 mUidToNetworkRequestCount.put(uid, newRequestCount);
1162 }
1163
1164 /**
1165 * Decrements the request count of the given uid.
1166 *
1167 * @param uid the uid that the request was made under
1168 */
1169 public void decrementCount(final int uid) {
1170 synchronized (mUidToNetworkRequestCount) {
1171 decrementCount(uid, 1 /* numToDecrement */);
1172 }
1173 }
1174
1175 private void decrementCount(final int uid, final int numToDecrement) {
1176 final int newRequestCount =
1177 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1178 if (newRequestCount < 0) {
1179 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1180 } else if (newRequestCount == 0) {
1181 mUidToNetworkRequestCount.delete(uid);
1182 } else {
1183 mUidToNetworkRequestCount.put(uid, newRequestCount);
1184 }
1185 }
1186
1187 /**
1188 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1189 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1190 * are used to create the new nris upon set. Therefore the request count limit can be
1191 * artificially hit. This method is used as a workaround for this particular case so that
1192 * the request counts are accounted for correctly.
1193 * @param uid the uid to adjust counts for
1194 * @param numOfNewRequests the new request count to account for
1195 * @param r the runnable to execute
1196 */
1197 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1198 // This should only be used on the handler thread as per all current and foreseen
1199 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1200 // no ref to the outer ConnectivityService.
1201 synchronized (mUidToNetworkRequestCount) {
1202 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1203 decrementCount(uid, reqCountOverage);
1204 r.run();
1205 incrementCountOrThrow(uid, reqCountOverage);
1206 }
1207 }
1208
1209 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1210 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1211 + numOfNewRequests;
1212 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1213 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1214 }
1215 }
1216
1217 /**
1218 * Dependencies of ConnectivityService, for injection in tests.
1219 */
1220 @VisibleForTesting
1221 public static class Dependencies {
1222 public int getCallingUid() {
1223 return Binder.getCallingUid();
1224 }
1225
1226 /**
1227 * Get system properties to use in ConnectivityService.
1228 */
1229 public MockableSystemProperties getSystemProperties() {
1230 return new MockableSystemProperties();
1231 }
1232
1233 /**
1234 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1235 */
1236 public ConnectivityResources getResources(@NonNull Context ctx) {
1237 return new ConnectivityResources(ctx);
1238 }
1239
1240 /**
1241 * Create a HandlerThread to use in ConnectivityService.
1242 */
1243 public HandlerThread makeHandlerThread() {
1244 return new HandlerThread("ConnectivityServiceThread");
1245 }
1246
1247 /**
1248 * Get a reference to the ModuleNetworkStackClient.
1249 */
1250 public NetworkStackClientBase getNetworkStack() {
1251 return ModuleNetworkStackClient.getInstance(null);
1252 }
1253
1254 /**
1255 * @see ProxyTracker
1256 */
1257 public ProxyTracker makeProxyTracker(@NonNull Context context,
1258 @NonNull Handler connServiceHandler) {
1259 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1260 }
1261
1262 /**
1263 * @see NetIdManager
1264 */
1265 public NetIdManager makeNetIdManager() {
1266 return new NetIdManager();
1267 }
1268
1269 /**
1270 * @see NetworkUtils#queryUserAccess(int, int)
1271 */
1272 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1273 return cs.queryUserAccess(uid, network);
1274 }
1275
1276 /**
1277 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1278 * requires CAP_NET_ADMIN, which the unit tests do not have.
1279 */
1280 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1281 InetSocketAddress remote) {
1282 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1283 }
1284
1285 /**
1286 * @see MultinetworkPolicyTracker
1287 */
1288 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1289 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1290 return new MultinetworkPolicyTracker(c, h, r);
1291 }
1292
1293 /**
1294 * @see BatteryStatsManager
1295 */
1296 public void reportNetworkInterfaceForTransports(Context context, String iface,
1297 int[] transportTypes) {
1298 final BatteryStatsManager batteryStats =
1299 context.getSystemService(BatteryStatsManager.class);
1300 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1301 }
1302
1303 public boolean getCellular464XlatEnabled() {
1304 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1305 }
Remi NGUYEN VANff55aeb2021-06-16 11:37:53 +00001306
1307 /**
1308 * @see PendingIntent#intentFilterEquals
1309 */
1310 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1311 return a.intentFilterEquals(b);
1312 }
1313
1314 /**
1315 * @see LocationPermissionChecker
1316 */
1317 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1318 return new LocationPermissionChecker(context);
1319 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001320 }
1321
1322 public ConnectivityService(Context context) {
1323 this(context, getDnsResolver(context), new IpConnectivityLog(),
1324 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1325 new Dependencies());
1326 }
1327
1328 @VisibleForTesting
1329 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1330 IpConnectivityLog logger, INetd netd, Dependencies deps) {
1331 if (DBG) log("ConnectivityService starting up");
1332
1333 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
1334 mSystemProperties = mDeps.getSystemProperties();
1335 mNetIdManager = mDeps.makeNetIdManager();
1336 mContext = Objects.requireNonNull(context, "missing Context");
1337 mResources = deps.getResources(mContext);
1338 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
1339 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
1340
1341 mMetricsLog = logger;
1342 mNetworkRanker = new NetworkRanker();
1343 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1344 mDefaultRequest = new NetworkRequestInfo(
1345 Process.myUid(), defaultInternetRequest, null,
1346 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1347 null /* attributionTags */);
1348 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1349 mDefaultNetworkRequests.add(mDefaultRequest);
1350 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
1351
1352 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
1353 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
1354
1355 // The default WiFi request is a background request so that apps using WiFi are
1356 // migrated to a better network (typically ethernet) when one comes up, instead
1357 // of staying on WiFi forever.
1358 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1359 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1360
1361 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1362 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1363 NetworkRequest.Type.BACKGROUND_REQUEST);
1364
1365 mHandlerThread = mDeps.makeHandlerThread();
1366 mHandlerThread.start();
1367 mHandler = new InternalHandler(mHandlerThread.getLooper());
1368 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
1369 mConnectivityDiagnosticsHandler =
1370 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
1371
1372 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
1373 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
1374
1375 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1376 // TODO: Consider making the timer customizable.
1377 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1378
1379 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
1380 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
1381 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
1382 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
1383
1384 mNetd = netd;
1385 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
1386 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VANff55aeb2021-06-16 11:37:53 +00001387 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001388
1389 // To ensure uid state is synchronized with Network Policy, register for
1390 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1391 // reading existing policy from disk.
1392 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
1393
1394 final PowerManager powerManager = (PowerManager) context.getSystemService(
1395 Context.POWER_SERVICE);
1396 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1397 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1398
1399 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1400 mProtectedNetworks = new ArrayList<>();
1401 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
1402 for (int p : protectedNetworks) {
1403 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
1404 mProtectedNetworks.add(p);
1405 } else {
1406 if (DBG) loge("Ignoring protectedNetwork " + p);
1407 }
1408 }
1409
1410 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1411
1412 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
1413
1414 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
1415 // Listen for user add/removes to inform PermissionMonitor.
1416 // Should run on mHandler to avoid any races.
1417 final IntentFilter userIntentFilter = new IntentFilter();
1418 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1419 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1420 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1421 null /* broadcastPermission */, mHandler);
1422
1423 // Listen to package add/removes for netd
1424 final IntentFilter packageIntentFilter = new IntentFilter();
1425 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1426 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1427 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1428 packageIntentFilter.addDataScheme("package");
1429 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
1430 null /* broadcastPermission */, mHandler);
1431
1432 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
1433
1434 mNetdCallback = new NetdCallback();
1435 try {
1436 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1437 } catch (RemoteException | ServiceSpecificException e) {
1438 loge("Error registering event listener :" + e);
1439 }
1440
1441 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1442 registerSettingsCallbacks();
1443
1444 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
1445 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
1446 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
1447
1448 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1449 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1450 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1451 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1452 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1453 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1454 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
1455
1456 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
1457 mContext, mHandler, () -> updateAvoidBadWifi());
1458 mMultinetworkPolicyTracker.start();
1459
1460 mDnsManager = new DnsManager(mContext, mDnsResolver);
1461 registerPrivateDnsSettingsCallbacks();
1462
1463 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1464 // request that doesn't allow fallback to the default network. It should never be visible
1465 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1466 // arguments like the handler or the DnsResolver.
1467 // TODO : remove this ; it is probably better handled with a sentinel request.
1468 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen4f612fa2021-05-14 14:30:43 +08001469 new Network(INetd.UNREACHABLE_NET_ID),
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001470 new NetworkInfo(TYPE_NONE, 0, "", ""),
1471 new LinkProperties(), new NetworkCapabilities(),
1472 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1473 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1474 mLingerDelayMs, mQosCallbackTracker, mDeps);
1475 }
1476
1477 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1478 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1479 }
1480
1481 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1482 @NonNull final UidRange uids) {
1483 final NetworkCapabilities netCap = new NetworkCapabilities();
1484 netCap.addCapability(NET_CAPABILITY_INTERNET);
1485 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1486 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1487 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
1488 return netCap;
1489 }
1490
1491 private NetworkRequest createDefaultRequest() {
1492 return createDefaultInternetRequestForTransport(
1493 TYPE_NONE, NetworkRequest.Type.REQUEST);
1494 }
1495
1496 private NetworkRequest createDefaultInternetRequestForTransport(
1497 int transportType, NetworkRequest.Type type) {
1498 final NetworkCapabilities netCap = new NetworkCapabilities();
1499 netCap.addCapability(NET_CAPABILITY_INTERNET);
1500 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1501 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1502 if (transportType > TYPE_NONE) {
1503 netCap.addTransportType(transportType);
1504 }
1505 return createNetworkRequest(type, netCap);
1506 }
1507
1508 private NetworkRequest createNetworkRequest(
1509 NetworkRequest.Type type, NetworkCapabilities netCap) {
1510 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1511 }
1512
1513 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1514 NetworkRequest.Type type) {
1515 final NetworkCapabilities netCap = new NetworkCapabilities();
1516 netCap.clearAll();
1517 netCap.addCapability(capability);
1518 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1519 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1520 }
1521
1522 // Used only for testing.
1523 // TODO: Delete this and either:
1524 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
1525 // changing ContentResolver to make registerContentObserver non-final).
1526 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1527 // by subclassing SettingsObserver.
1528 @VisibleForTesting
1529 void updateAlwaysOnNetworks() {
1530 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1531 }
1532
1533 // See FakeSettingsProvider comment above.
1534 @VisibleForTesting
1535 void updatePrivateDnsSettings() {
1536 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1537 }
1538
paulhu71ad4f12021-05-25 14:56:27 +08001539 @VisibleForTesting
1540 void updateMobileDataPreferredUids() {
1541 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1542 }
1543
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001544 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
1545 final boolean enable = mContext.getResources().getBoolean(id);
1546 handleAlwaysOnNetworkRequest(networkRequest, enable);
1547 }
1548
1549 private void handleAlwaysOnNetworkRequest(
1550 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
1551 final boolean enable = toBool(Settings.Global.getInt(
1552 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1553 handleAlwaysOnNetworkRequest(networkRequest, enable);
1554 }
1555
1556 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
1557 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
1558 if (enable == isEnabled) {
1559 return; // Nothing to do.
1560 }
1561
1562 if (enable) {
1563 handleRegisterNetworkRequest(new NetworkRequestInfo(
1564 Process.myUid(), networkRequest, null, new Binder(),
1565 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1566 null /* attributionTags */));
1567 } else {
1568 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1569 /* callOnUnavailable */ false);
1570 }
1571 }
1572
1573 private void handleConfigureAlwaysOnNetworks() {
1574 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1575 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1576 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1577 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
1578 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1579 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001580 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001581 }
1582
paulhu71ad4f12021-05-25 14:56:27 +08001583 // Note that registering observer for setting do not get initial callback when registering,
paulhu7ed70a92021-05-26 12:22:38 +08001584 // callers must fetch the initial value of the setting themselves if needed.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001585 private void registerSettingsCallbacks() {
1586 // Watch for global HTTP proxy changes.
1587 mSettingsObserver.observe(
1588 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1589 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1590
1591 // Watch for whether or not to keep mobile data always on.
1592 mSettingsObserver.observe(
1593 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
1594 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1595
1596 // Watch for whether or not to keep wifi always on.
1597 mSettingsObserver.observe(
1598 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
1599 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu71ad4f12021-05-25 14:56:27 +08001600
1601 // Watch for mobile data preferred uids changes.
1602 mSettingsObserver.observe(
1603 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1604 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001605 }
1606
1607 private void registerPrivateDnsSettingsCallbacks() {
1608 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1609 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1610 }
1611 }
1612
1613 private synchronized int nextNetworkRequestId() {
1614 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1615 // doing that.
1616 return mNextNetworkRequestId++;
1617 }
1618
1619 @VisibleForTesting
1620 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1621 if (network == null) {
1622 return null;
1623 }
1624 return getNetworkAgentInfoForNetId(network.getNetId());
1625 }
1626
1627 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
1628 synchronized (mNetworkForNetId) {
1629 return mNetworkForNetId.get(netId);
1630 }
1631 }
1632
1633 // TODO: determine what to do when more than one VPN applies to |uid|.
1634 private NetworkAgentInfo getVpnForUid(int uid) {
1635 synchronized (mNetworkForNetId) {
1636 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1637 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1638 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1639 return nai;
1640 }
1641 }
1642 }
1643 return null;
1644 }
1645
1646 private Network[] getVpnUnderlyingNetworks(int uid) {
1647 if (mLockdownEnabled) return null;
1648 final NetworkAgentInfo nai = getVpnForUid(uid);
1649 if (nai != null) return nai.declaredUnderlyingNetworks;
1650 return null;
1651 }
1652
1653 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
1654 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1655
1656 final Network[] networks = getVpnUnderlyingNetworks(uid);
1657 if (networks != null) {
1658 // getUnderlyingNetworks() returns:
1659 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1660 // empty array => the VPN explicitly said "no default network".
1661 // non-empty array => the VPN specified one or more default networks; we use the
1662 // first one.
1663 if (networks.length > 0) {
1664 nai = getNetworkAgentInfoForNetwork(networks[0]);
1665 } else {
1666 nai = null;
1667 }
1668 }
1669 return nai;
1670 }
1671
1672 /**
1673 * Check if UID should be blocked from using the specified network.
1674 */
1675 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1676 final int uid, final boolean ignoreBlocked) {
1677 // Networks aren't blocked when ignoring blocked status
1678 if (ignoreBlocked) {
1679 return false;
1680 }
1681 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
1682 final long ident = Binder.clearCallingIdentity();
1683 try {
1684 final boolean metered = nc == null ? true : nc.isMetered();
1685 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1686 } finally {
1687 Binder.restoreCallingIdentity(ident);
1688 }
1689 }
1690
1691 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
1692 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1693 return;
1694 }
1695 final boolean blocked;
1696 synchronized (mBlockedAppUids) {
1697 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1698 blocked = true;
1699 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1700 blocked = false;
1701 } else {
1702 return;
1703 }
1704 }
1705 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1706 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1707 mNetworkInfoBlockingLogs.log(action + " " + uid);
1708 }
1709
1710 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
1711 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1712 return;
1713 }
1714 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
1715 final int requestId = nri.getActiveRequest() != null
1716 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
1717 mNetworkInfoBlockingLogs.log(String.format(
1718 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
1719 Integer.toHexString(blocked)));
1720 }
1721
1722 /**
1723 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
1724 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1725 * on {@link #isNetworkWithCapabilitiesBlocked}.
1726 */
1727 @NonNull
1728 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1729 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
1730 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1731 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1732 // but only exists if an app asks about them or requests them. Ensure the requesting app
1733 // gets the type it asks for.
1734 filtered.setType(type);
1735 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1736 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1737 null /* extraInfo */);
1738 }
1739 filterForLegacyLockdown(filtered);
1740 return filtered;
1741 }
1742
1743 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1744 boolean ignoreBlocked) {
1745 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1746 nai.networkCapabilities, uid, ignoreBlocked);
1747 }
1748
1749 /**
1750 * Return NetworkInfo for the active (i.e., connected) network interface.
1751 * It is assumed that at most one network is active at a time. If more
1752 * than one is active, it is indeterminate which will be returned.
1753 * @return the info for the active network, or {@code null} if none is
1754 * active
1755 */
1756 @Override
1757 public NetworkInfo getActiveNetworkInfo() {
1758 enforceAccessPermission();
1759 final int uid = mDeps.getCallingUid();
1760 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1761 if (nai == null) return null;
1762 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1763 maybeLogBlockedNetworkInfo(networkInfo, uid);
1764 return networkInfo;
1765 }
1766
1767 @Override
1768 public Network getActiveNetwork() {
1769 enforceAccessPermission();
1770 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
1771 }
1772
1773 @Override
1774 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1775 PermissionUtils.enforceNetworkStackPermission(mContext);
1776 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1777 }
1778
1779 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1780 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1781 if (vpnNai != null) {
1782 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1783 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1784 return vpnNai.network;
1785 }
1786 }
1787
1788 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1789 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1790 ignoreBlocked)) {
1791 return null;
1792 }
1793 return nai.network;
1794 }
1795
1796 @Override
1797 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1798 PermissionUtils.enforceNetworkStackPermission(mContext);
1799 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1800 if (nai == null) return null;
1801 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1802 }
1803
1804 /** Returns a NetworkInfo object for a network that doesn't exist. */
1805 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1806 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1807 getNetworkTypeName(networkType), "" /* subtypeName */);
1808 info.setIsAvailable(true);
1809 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1810 // background data is restricted.
1811 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1812 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1813 ? DetailedState.BLOCKED
1814 : DetailedState.DISCONNECTED;
1815 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1816 filterForLegacyLockdown(info);
1817 return info;
1818 }
1819
1820 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
1821 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1822 return null;
1823 }
1824 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1825 if (nai == null) {
1826 return makeFakeNetworkInfo(networkType, uid);
1827 }
1828 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1829 false);
1830 }
1831
1832 @Override
1833 public NetworkInfo getNetworkInfo(int networkType) {
1834 enforceAccessPermission();
1835 final int uid = mDeps.getCallingUid();
1836 if (getVpnUnderlyingNetworks(uid) != null) {
1837 // A VPN is active, so we may need to return one of its underlying networks. This
1838 // information is not available in LegacyTypeTracker, so we have to get it from
1839 // getNetworkAgentInfoForUid.
1840 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1841 if (nai == null) return null;
1842 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1843 if (networkInfo.getType() == networkType) {
1844 return networkInfo;
1845 }
1846 }
1847 return getFilteredNetworkInfoForType(networkType, uid);
1848 }
1849
1850 @Override
1851 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1852 enforceAccessPermission();
1853 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1854 if (nai == null) return null;
1855 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1856 }
1857
1858 @Override
1859 public NetworkInfo[] getAllNetworkInfo() {
1860 enforceAccessPermission();
1861 final ArrayList<NetworkInfo> result = new ArrayList<>();
1862 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1863 networkType++) {
1864 NetworkInfo info = getNetworkInfo(networkType);
1865 if (info != null) {
1866 result.add(info);
1867 }
1868 }
1869 return result.toArray(new NetworkInfo[result.size()]);
1870 }
1871
1872 @Override
1873 public Network getNetworkForType(int networkType) {
1874 enforceAccessPermission();
1875 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1876 return null;
1877 }
1878 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1879 if (nai == null) {
1880 return null;
1881 }
1882 final int uid = mDeps.getCallingUid();
1883 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1884 return null;
1885 }
1886 return nai.network;
1887 }
1888
1889 @Override
1890 public Network[] getAllNetworks() {
1891 enforceAccessPermission();
1892 synchronized (mNetworkForNetId) {
1893 final Network[] result = new Network[mNetworkForNetId.size()];
1894 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1895 result[i] = mNetworkForNetId.valueAt(i).network;
1896 }
1897 return result;
1898 }
1899 }
1900
1901 @Override
1902 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
1903 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
1904 // The basic principle is: if an app's traffic could possibly go over a
1905 // network, without the app doing anything multinetwork-specific,
1906 // (hence, by "default"), then include that network's capabilities in
1907 // the array.
1908 //
1909 // In the normal case, app traffic only goes over the system's default
1910 // network connection, so that's the only network returned.
1911 //
1912 // With a VPN in force, some app traffic may go into the VPN, and thus
1913 // over whatever underlying networks the VPN specifies, while other app
1914 // traffic may go over the system default network (e.g.: a split-tunnel
1915 // VPN, or an app disallowed by the VPN), so the set of networks
1916 // returned includes the VPN's underlying networks and the system
1917 // default.
1918 enforceAccessPermission();
1919
1920 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
1921
1922 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1923 if (!nri.isBeingSatisfied()) {
1924 continue;
1925 }
1926 final NetworkAgentInfo nai = nri.getSatisfier();
1927 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1928 if (null != nc
1929 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1930 && !result.containsKey(nai.network)) {
1931 result.put(
1932 nai.network,
1933 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1934 nc, false /* includeLocationSensitiveInfo */,
1935 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1936 callingAttributionTag));
1937 }
1938 }
1939
1940 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
1941 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
1942 if (null != networks) {
1943 for (final Network network : networks) {
1944 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1945 if (null != nc) {
1946 result.put(
1947 network,
1948 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1949 nc,
1950 false /* includeLocationSensitiveInfo */,
1951 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1952 callingAttributionTag));
1953 }
1954 }
1955 }
1956
1957 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1958 out = result.values().toArray(out);
1959 return out;
1960 }
1961
1962 @Override
1963 public boolean isNetworkSupported(int networkType) {
1964 enforceAccessPermission();
1965 return mLegacyTypeTracker.isTypeSupported(networkType);
1966 }
1967
1968 /**
1969 * Return LinkProperties for the active (i.e., connected) default
1970 * network interface for the calling uid.
1971 * @return the ip properties for the active network, or {@code null} if
1972 * none is active
1973 */
1974 @Override
1975 public LinkProperties getActiveLinkProperties() {
1976 enforceAccessPermission();
1977 final int uid = mDeps.getCallingUid();
1978 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1979 if (nai == null) return null;
1980 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
1981 Binder.getCallingPid(), uid);
1982 }
1983
1984 @Override
1985 public LinkProperties getLinkPropertiesForType(int networkType) {
1986 enforceAccessPermission();
1987 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1988 final LinkProperties lp = getLinkProperties(nai);
1989 if (lp == null) return null;
1990 return linkPropertiesRestrictedForCallerPermissions(
1991 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1992 }
1993
1994 // TODO - this should be ALL networks
1995 @Override
1996 public LinkProperties getLinkProperties(Network network) {
1997 enforceAccessPermission();
1998 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1999 if (lp == null) return null;
2000 return linkPropertiesRestrictedForCallerPermissions(
2001 lp, Binder.getCallingPid(), mDeps.getCallingUid());
2002 }
2003
2004 @Nullable
2005 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
2006 if (nai == null) {
2007 return null;
2008 }
2009 synchronized (nai) {
2010 return nai.linkProperties;
2011 }
2012 }
2013
2014 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2015 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2016 }
2017
2018 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
2019 if (nai == null) return null;
2020 synchronized (nai) {
2021 return networkCapabilitiesRestrictedForCallerPermissions(
2022 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
2023 }
2024 }
2025
2026 @Override
2027 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2028 @Nullable String callingAttributionTag) {
2029 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
2030 enforceAccessPermission();
2031 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2032 getNetworkCapabilitiesInternal(network),
2033 false /* includeLocationSensitiveInfo */,
2034 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
2035 }
2036
2037 @VisibleForTesting
2038 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
2039 NetworkCapabilities nc, int callerPid, int callerUid) {
2040 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
2041 if (!checkSettingsPermission(callerPid, callerUid)) {
2042 newNc.setUids(null);
2043 newNc.setSSID(null);
2044 }
2045 if (newNc.getNetworkSpecifier() != null) {
2046 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2047 }
2048 newNc.setAdministratorUids(new int[0]);
2049 if (!checkAnyPermissionOf(
2050 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
2051 newNc.setSubscriptionIds(Collections.emptySet());
2052 }
2053
2054 return newNc;
2055 }
2056
2057 /**
2058 * Wrapper used to cache the permission check results performed for the corresponding
2059 * app. This avoid performing multiple permission checks for different fields in
2060 * NetworkCapabilities.
2061 * Note: This wrapper does not support any sort of invalidation and thus must not be
2062 * persistent or long-lived. It may only be used for the time necessary to
2063 * compute the redactions required by one particular NetworkCallback or
2064 * synchronous call.
2065 */
2066 private class RedactionPermissionChecker {
2067 private final int mCallingPid;
2068 private final int mCallingUid;
2069 @NonNull private final String mCallingPackageName;
2070 @Nullable private final String mCallingAttributionTag;
2071
2072 private Boolean mHasLocationPermission = null;
2073 private Boolean mHasLocalMacAddressPermission = null;
2074 private Boolean mHasSettingsPermission = null;
2075
2076 RedactionPermissionChecker(int callingPid, int callingUid,
2077 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2078 mCallingPid = callingPid;
2079 mCallingUid = callingUid;
2080 mCallingPackageName = callingPackageName;
2081 mCallingAttributionTag = callingAttributionTag;
2082 }
2083
2084 private boolean hasLocationPermissionInternal() {
2085 final long token = Binder.clearCallingIdentity();
2086 try {
2087 return mLocationPermissionChecker.checkLocationPermission(
2088 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2089 null /* message */);
2090 } finally {
2091 Binder.restoreCallingIdentity(token);
2092 }
2093 }
2094
2095 /**
2096 * Returns whether the app holds location permission or not (might return cached result
2097 * if the permission was already checked before).
2098 */
2099 public boolean hasLocationPermission() {
2100 if (mHasLocationPermission == null) {
2101 // If there is no cached result, perform the check now.
2102 mHasLocationPermission = hasLocationPermissionInternal();
2103 }
2104 return mHasLocationPermission;
2105 }
2106
2107 /**
2108 * Returns whether the app holds local mac address permission or not (might return cached
2109 * result if the permission was already checked before).
2110 */
2111 public boolean hasLocalMacAddressPermission() {
2112 if (mHasLocalMacAddressPermission == null) {
2113 // If there is no cached result, perform the check now.
2114 mHasLocalMacAddressPermission =
2115 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2116 }
2117 return mHasLocalMacAddressPermission;
2118 }
2119
2120 /**
2121 * Returns whether the app holds settings permission or not (might return cached
2122 * result if the permission was already checked before).
2123 */
2124 public boolean hasSettingsPermission() {
2125 if (mHasSettingsPermission == null) {
2126 // If there is no cached result, perform the check now.
2127 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2128 }
2129 return mHasSettingsPermission;
2130 }
2131 }
2132
2133 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2134 @NetworkCapabilities.NetCapability long redaction) {
2135 return (redactions & redaction) != 0;
2136 }
2137
2138 /**
2139 * Use the provided |applicableRedactions| to check the receiving app's
2140 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2141 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2142 * before being sent to the corresponding app.
2143 */
2144 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2145 @NetworkCapabilities.RedactionType long applicableRedactions,
2146 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2147 boolean includeLocationSensitiveInfo) {
2148 long redactions = applicableRedactions;
2149 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2150 if (includeLocationSensitiveInfo
2151 && redactionPermissionChecker.hasLocationPermission()) {
2152 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2153 }
2154 }
2155 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2156 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2157 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2158 }
2159 }
2160 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2161 if (redactionPermissionChecker.hasSettingsPermission()) {
2162 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2163 }
2164 }
2165 return redactions;
2166 }
2167
2168 @VisibleForTesting
2169 @Nullable
2170 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2171 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
2172 int callingPid, int callingUid, @NonNull String callingPkgName,
2173 @Nullable String callingAttributionTag) {
2174 if (nc == null) {
2175 return null;
2176 }
2177 // Avoid doing location permission check if the transport info has no location sensitive
2178 // data.
2179 final RedactionPermissionChecker redactionPermissionChecker =
2180 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2181 callingAttributionTag);
2182 final long redactions = retrieveRequiredRedactions(
2183 nc.getApplicableRedactions(), redactionPermissionChecker,
2184 includeLocationSensitiveInfo);
2185 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
2186 // Reset owner uid if not destined for the owner app.
2187 if (callingUid != nc.getOwnerUid()) {
2188 newNc.setOwnerUid(INVALID_UID);
2189 return newNc;
2190 }
2191 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2192 if (nc.hasTransport(TRANSPORT_VPN)) {
2193 // Owner UIDs already checked above. No need to re-check.
2194 return newNc;
2195 }
2196 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2197 // Else include the owner UID iff the calling has location permission to provide backwards
2198 // compatibility for older apps.
2199 if (!includeLocationSensitiveInfo
2200 && isTargetSdkAtleast(
2201 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
2202 newNc.setOwnerUid(INVALID_UID);
2203 return newNc;
2204 }
2205 // Reset owner uid if the app has no location permission.
2206 if (!redactionPermissionChecker.hasLocationPermission()) {
2207 newNc.setOwnerUid(INVALID_UID);
2208 }
2209 return newNc;
2210 }
2211
2212 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2213 LinkProperties lp, int callerPid, int callerUid) {
2214 if (lp == null) return new LinkProperties();
2215
2216 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2217 final boolean needsSanitization =
2218 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2219 if (!needsSanitization) {
2220 return new LinkProperties(lp);
2221 }
2222
2223 if (checkSettingsPermission(callerPid, callerUid)) {
2224 return new LinkProperties(lp, true /* parcelSensitiveFields */);
2225 }
2226
2227 final LinkProperties newLp = new LinkProperties(lp);
2228 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2229 // object gets parceled.
2230 newLp.setCaptivePortalApiUrl(null);
2231 newLp.setCaptivePortalData(null);
2232 return newLp;
2233 }
2234
2235 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2236 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002237 // There is no need to track the effective UID of the request here. If the caller
2238 // lacks the settings permission, the effective UID is the same as the calling ID.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002239 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002240 // Unprivileged apps can only pass in null or their own UID.
2241 if (nc.getUids() == null) {
2242 // If the caller passes in null, the callback will also match networks that do not
2243 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2244 // In this case, redact everything in the request immediately. This ensures that the
2245 // app is not able to get any redacted information by filing an unredacted request
2246 // and observing whether the request matches something.
2247 if (nc.getNetworkSpecifier() != null) {
2248 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2249 }
2250 } else {
2251 nc.setSingleUid(callerUid);
2252 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002253 }
2254 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
2255 nc.setAdministratorUids(new int[0]);
2256
2257 // Clear owner UID; this can never come from an app.
2258 nc.setOwnerUid(INVALID_UID);
2259 }
2260
2261 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
2262 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
2263 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2264 }
2265 }
2266
2267 @Override
2268 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2269 enforceAccessPermission();
2270 final int callerUid = Binder.getCallingUid();
2271 final long token = Binder.clearCallingIdentity();
2272 try {
2273 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2274 } finally {
2275 Binder.restoreCallingIdentity(token);
2276 }
2277 }
2278
2279 // TODO: Consider delete this function or turn it into a no-op method.
2280 @Override
2281 public NetworkState[] getAllNetworkState() {
2282 // This contains IMSI details, so make sure the caller is privileged.
2283 PermissionUtils.enforceNetworkStackPermission(mContext);
2284
2285 final ArrayList<NetworkState> result = new ArrayList<>();
2286 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
2287 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2288 // NetworkAgentInfo.
2289 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
2290 if (nai != null && nai.networkInfo.isConnected()) {
2291 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
2292 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2293 snapshot.getNetwork(), snapshot.getSubscriberId()));
2294 }
2295 }
2296 return result.toArray(new NetworkState[result.size()]);
2297 }
2298
2299 @Override
2300 @NonNull
2301 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
2302 // This contains IMSI details, so make sure the caller is privileged.
junyulai7968fba2021-05-14 18:04:29 +08002303 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002304
2305 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2306 for (Network network : getAllNetworks()) {
2307 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2308 // TODO: Consider include SUSPENDED networks, which should be considered as
2309 // temporary shortage of connectivity of a connected network.
2310 if (nai != null && nai.networkInfo.isConnected()) {
2311 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2312 // NetworkCapabilities, which may contain UIDs of apps to which the
2313 // network applies. Should the UIDs be cleared so as not to leak or
2314 // interfere ?
2315 result.add(nai.getNetworkStateSnapshot());
2316 }
2317 }
2318 return result;
2319 }
2320
2321 @Override
2322 public boolean isActiveNetworkMetered() {
2323 enforceAccessPermission();
2324
2325 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
2326 if (caps != null) {
2327 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2328 } else {
2329 // Always return the most conservative value
2330 return true;
2331 }
2332 }
2333
2334 /**
2335 * Ensures that the system cannot call a particular method.
2336 */
2337 private boolean disallowedBecauseSystemCaller() {
2338 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
2339 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2340 // for devices launched with Q and above. However, existing devices upgrading to Q and
2341 // above must continued to be supported for few more releases.
2342 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
2343 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
2344 log("This method exists only for app backwards compatibility"
2345 + " and must not be called by system services.");
2346 return true;
2347 }
2348 return false;
2349 }
2350
2351 /**
2352 * Ensure that a network route exists to deliver traffic to the specified
2353 * host via the specified network interface.
2354 * @param networkType the type of the network over which traffic to the
2355 * specified host is to be routed
2356 * @param hostAddress the IP address of the host to which the route is
2357 * desired
2358 * @return {@code true} on success, {@code false} on failure
2359 */
2360 @Override
2361 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2362 String callingPackageName, String callingAttributionTag) {
2363 if (disallowedBecauseSystemCaller()) {
2364 return false;
2365 }
2366 enforceChangePermission(callingPackageName, callingAttributionTag);
2367 if (mProtectedNetworks.contains(networkType)) {
2368 enforceConnectivityRestrictedNetworksPermission();
2369 }
2370
2371 InetAddress addr;
2372 try {
2373 addr = InetAddress.getByAddress(hostAddress);
2374 } catch (UnknownHostException e) {
2375 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2376 return false;
2377 }
2378
2379 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
2380 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
2381 return false;
2382 }
2383
2384 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2385 if (nai == null) {
2386 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2387 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2388 } else {
2389 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2390 }
2391 return false;
2392 }
2393
2394 DetailedState netState;
2395 synchronized (nai) {
2396 netState = nai.networkInfo.getDetailedState();
2397 }
2398
2399 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
2400 if (VDBG) {
2401 log("requestRouteToHostAddress on down network "
2402 + "(" + networkType + ") - dropped"
2403 + " netState=" + netState);
2404 }
2405 return false;
2406 }
2407
2408 final int uid = mDeps.getCallingUid();
2409 final long token = Binder.clearCallingIdentity();
2410 try {
2411 LinkProperties lp;
2412 int netId;
2413 synchronized (nai) {
2414 lp = nai.linkProperties;
2415 netId = nai.network.getNetId();
2416 }
2417 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
2418 if (DBG) {
2419 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2420 }
2421 return ok;
2422 } finally {
2423 Binder.restoreCallingIdentity(token);
2424 }
2425 }
2426
2427 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
2428 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
2429 if (bestRoute == null) {
2430 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
2431 } else {
2432 String iface = bestRoute.getInterface();
2433 if (bestRoute.getGateway().equals(addr)) {
2434 // if there is no better route, add the implied hostroute for our gateway
2435 bestRoute = RouteInfo.makeHostRoute(addr, iface);
2436 } else {
2437 // if we will connect to this through another route, add a direct route
2438 // to it's gateway
2439 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
2440 }
2441 }
2442 if (DBG) log("Adding legacy route " + bestRoute +
2443 " for UID/PID " + uid + "/" + Binder.getCallingPid());
2444
2445 final String dst = bestRoute.getDestinationLinkAddress().toString();
2446 final String nextHop = bestRoute.hasGateway()
2447 ? bestRoute.getGateway().getHostAddress() : "";
2448 try {
2449 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2450 } catch (RemoteException | ServiceSpecificException e) {
2451 if (DBG) loge("Exception trying to add a route: " + e);
2452 return false;
2453 }
2454 return true;
2455 }
2456
2457 class DnsResolverUnsolicitedEventCallback extends
2458 IDnsResolverUnsolicitedEventListener.Stub {
2459 @Override
2460 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
2461 try {
2462 mHandler.sendMessage(mHandler.obtainMessage(
2463 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
2464 new PrivateDnsValidationUpdate(event.netId,
2465 InetAddresses.parseNumericAddress(event.ipAddress),
2466 event.hostname, event.validation)));
2467 } catch (IllegalArgumentException e) {
2468 loge("Error parsing ip address in validation event");
2469 }
2470 }
2471
2472 @Override
2473 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2474 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
2475 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2476 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2477 // event callback for certain nai. e.g. cellular. Register here to pass to
2478 // NetworkMonitor instead.
2479 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2480 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2481 // multiple NetworkMonitor registrants.
2482 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
2483 nai.networkMonitor().notifyDnsResponse(event.healthResult);
2484 }
2485 }
2486
2487 @Override
2488 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2489 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2490 event.prefixAddress, event.prefixLength));
2491 }
2492
2493 @Override
2494 public int getInterfaceVersion() {
2495 return this.VERSION;
2496 }
2497
2498 @Override
2499 public String getInterfaceHash() {
2500 return this.HASH;
2501 }
2502 }
2503
2504 @VisibleForTesting
2505 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2506 new DnsResolverUnsolicitedEventCallback();
2507
2508 private void registerDnsResolverUnsolicitedEventListener() {
2509 try {
2510 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
2511 } catch (Exception e) {
2512 loge("Error registering DnsResolver unsolicited event callback: " + e);
2513 }
2514 }
2515
2516 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
2517 @Override
2518 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2520 uid, blockedReasons));
2521 }
2522 };
2523
2524 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2525 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
2526 setUidBlockedReasons(uid, blockedReasons);
2527 }
2528
2529 private boolean checkAnyPermissionOf(String... permissions) {
2530 for (String permission : permissions) {
2531 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
2532 return true;
2533 }
2534 }
2535 return false;
2536 }
2537
2538 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2539 for (String permission : permissions) {
2540 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2541 return true;
2542 }
2543 }
2544 return false;
2545 }
2546
2547 private void enforceAnyPermissionOf(String... permissions) {
2548 if (!checkAnyPermissionOf(permissions)) {
2549 throw new SecurityException("Requires one of the following permissions: "
2550 + String.join(", ", permissions) + ".");
2551 }
2552 }
2553
2554 private void enforceInternetPermission() {
2555 mContext.enforceCallingOrSelfPermission(
2556 android.Manifest.permission.INTERNET,
2557 "ConnectivityService");
2558 }
2559
2560 private void enforceAccessPermission() {
2561 mContext.enforceCallingOrSelfPermission(
2562 android.Manifest.permission.ACCESS_NETWORK_STATE,
2563 "ConnectivityService");
2564 }
2565
2566 /**
2567 * Performs a strict and comprehensive check of whether a calling package is allowed to
2568 * change the state of network, as the condition differs for pre-M, M+, and
2569 * privileged/preinstalled apps. The caller is expected to have either the
2570 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2571 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2572 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2573 * permission and cannot be revoked. See http://b/23597341
2574 *
2575 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2576 * of this app will be updated to the current time.
2577 */
2578 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
2579 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2580 == PackageManager.PERMISSION_GRANTED) {
2581 return;
2582 }
2583
2584 if (callingPkg == null) {
2585 throw new SecurityException("Calling package name is null.");
2586 }
2587
2588 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2589 final int uid = mDeps.getCallingUid();
2590 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2591 callingPkg, callingAttributionTag, null /* message */);
2592
2593 if (mode == AppOpsManager.MODE_ALLOWED) {
2594 return;
2595 }
2596
2597 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2598 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2599 return;
2600 }
2601
2602 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2603 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2604 + android.Manifest.permission.WRITE_SETTINGS + ".");
2605 }
2606
2607 private void enforceSettingsPermission() {
2608 enforceAnyPermissionOf(
2609 android.Manifest.permission.NETWORK_SETTINGS,
2610 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2611 }
2612
2613 private void enforceNetworkFactoryPermission() {
2614 enforceAnyPermissionOf(
2615 android.Manifest.permission.NETWORK_FACTORY,
2616 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2617 }
2618
2619 private void enforceNetworkFactoryOrSettingsPermission() {
2620 enforceAnyPermissionOf(
2621 android.Manifest.permission.NETWORK_SETTINGS,
2622 android.Manifest.permission.NETWORK_FACTORY,
2623 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2624 }
2625
2626 private void enforceNetworkFactoryOrTestNetworksPermission() {
2627 enforceAnyPermissionOf(
2628 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2629 android.Manifest.permission.NETWORK_FACTORY,
2630 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2631 }
2632
2633 private boolean checkSettingsPermission() {
2634 return checkAnyPermissionOf(
2635 android.Manifest.permission.NETWORK_SETTINGS,
2636 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2637 }
2638
2639 private boolean checkSettingsPermission(int pid, int uid) {
2640 return PERMISSION_GRANTED == mContext.checkPermission(
2641 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2642 || PERMISSION_GRANTED == mContext.checkPermission(
2643 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
2644 }
2645
2646 private void enforceNetworkStackOrSettingsPermission() {
2647 enforceAnyPermissionOf(
2648 android.Manifest.permission.NETWORK_SETTINGS,
2649 android.Manifest.permission.NETWORK_STACK,
2650 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2651 }
2652
2653 private void enforceNetworkStackSettingsOrSetup() {
2654 enforceAnyPermissionOf(
2655 android.Manifest.permission.NETWORK_SETTINGS,
2656 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2657 android.Manifest.permission.NETWORK_STACK,
2658 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2659 }
2660
2661 private void enforceAirplaneModePermission() {
2662 enforceAnyPermissionOf(
2663 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2664 android.Manifest.permission.NETWORK_SETTINGS,
2665 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2666 android.Manifest.permission.NETWORK_STACK,
2667 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2668 }
2669
2670 private void enforceOemNetworkPreferencesPermission() {
2671 mContext.enforceCallingOrSelfPermission(
2672 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2673 "ConnectivityService");
2674 }
2675
James Mattisb7ca0342021-06-16 01:30:05 +00002676 private void enforceManageTestNetworksPermission() {
2677 mContext.enforceCallingOrSelfPermission(
2678 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2679 "ConnectivityService");
2680 }
2681
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002682 private boolean checkNetworkStackPermission() {
2683 return checkAnyPermissionOf(
2684 android.Manifest.permission.NETWORK_STACK,
2685 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2686 }
2687
2688 private boolean checkNetworkStackPermission(int pid, int uid) {
2689 return checkAnyPermissionOf(pid, uid,
2690 android.Manifest.permission.NETWORK_STACK,
2691 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2692 }
2693
2694 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2695 return checkAnyPermissionOf(pid, uid,
2696 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
2697 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2698 android.Manifest.permission.NETWORK_SETTINGS);
2699 }
2700
2701 private void enforceConnectivityRestrictedNetworksPermission() {
2702 try {
2703 mContext.enforceCallingOrSelfPermission(
2704 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2705 "ConnectivityService");
2706 return;
2707 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2708 // TODO: Remove this fallback check after all apps have declared
2709 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2710 mContext.enforceCallingOrSelfPermission(
2711 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2712 "ConnectivityService");
2713 }
2714
2715 private void enforceKeepalivePermission() {
2716 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
2717 }
2718
2719 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2720 return PERMISSION_GRANTED == mContext.checkPermission(
2721 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2722 }
2723
2724 private void sendConnectedBroadcast(NetworkInfo info) {
2725 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2726 }
2727
2728 private void sendInetConditionBroadcast(NetworkInfo info) {
2729 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2730 }
2731
2732 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2733 Intent intent = new Intent(bcastType);
2734 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2735 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2736 if (info.isFailover()) {
2737 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2738 info.setFailover(false);
2739 }
2740 if (info.getReason() != null) {
2741 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2742 }
2743 if (info.getExtraInfo() != null) {
2744 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2745 info.getExtraInfo());
2746 }
2747 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2748 return intent;
2749 }
2750
2751 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2752 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2753 }
2754
2755 private void sendStickyBroadcast(Intent intent) {
2756 synchronized (this) {
2757 if (!mSystemReady
2758 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
2759 mInitialBroadcast = new Intent(intent);
2760 }
2761 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2762 if (VDBG) {
2763 log("sendStickyBroadcast: action=" + intent.getAction());
2764 }
2765
2766 Bundle options = null;
2767 final long ident = Binder.clearCallingIdentity();
2768 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
2769 final NetworkInfo ni = intent.getParcelableExtra(
2770 ConnectivityManager.EXTRA_NETWORK_INFO);
2771 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2772 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2773 options = opts.toBundle();
2774 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
2775 }
2776 try {
2777 mUserAllContext.sendStickyBroadcast(intent, options);
2778 } finally {
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782 }
2783
2784 /**
2785 * Called by SystemServer through ConnectivityManager when the system is ready.
2786 */
2787 @Override
2788 public void systemReady() {
2789 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
2790 throw new SecurityException("Calling Uid is not system uid.");
2791 }
2792 systemReadyInternal();
2793 }
2794
2795 /**
2796 * Called when ConnectivityService can initialize remaining components.
2797 */
2798 @VisibleForTesting
2799 public void systemReadyInternal() {
2800 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2801 // listening network request which is sent by MultipathPolicyTracker won't be added
2802 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2803 // be called after PermissionMonitor#startMonitoring().
2804 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2805 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2806 // to ensure the tracking will be initialized correctly.
2807 mPermissionMonitor.startMonitoring();
2808 mProxyTracker.loadGlobalProxy();
2809 registerDnsResolverUnsolicitedEventListener();
2810
2811 synchronized (this) {
2812 mSystemReady = true;
2813 if (mInitialBroadcast != null) {
2814 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2815 mInitialBroadcast = null;
2816 }
2817 }
2818
2819 // Create network requests for always-on networks.
2820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu71ad4f12021-05-25 14:56:27 +08002821
2822 // Update mobile data preference if necessary.
2823 // Note that empty uid list can be skip here only because no uid rules applied before system
2824 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2825 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2826 updateMobileDataPreferredUids();
2827 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002828 }
2829
2830 /**
2831 * Start listening for default data network activity state changes.
2832 */
2833 @Override
2834 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
2835 mNetworkActivityTracker.registerNetworkActivityListener(l);
2836 }
2837
2838 /**
2839 * Stop listening for default data network activity state changes.
2840 */
2841 @Override
2842 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
2843 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
2844 }
2845
2846 /**
2847 * Check whether the default network radio is currently active.
2848 */
2849 @Override
2850 public boolean isDefaultNetworkActive() {
2851 return mNetworkActivityTracker.isDefaultNetworkActive();
2852 }
2853
2854 /**
2855 * Reads the network specific MTU size from resources.
2856 * and set it on it's iface.
2857 */
2858 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2859 final String iface = newLp.getInterfaceName();
2860 final int mtu = newLp.getMtu();
2861 if (oldLp == null && mtu == 0) {
2862 // Silently ignore unset MTU value.
2863 return;
2864 }
2865 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2866 if (VDBG) log("identical MTU - not setting");
2867 return;
2868 }
2869 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
2870 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
2871 return;
2872 }
2873
2874 // Cannot set MTU without interface name
2875 if (TextUtils.isEmpty(iface)) {
2876 loge("Setting MTU size with null iface.");
2877 return;
2878 }
2879
2880 try {
2881 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
2882 mNetd.interfaceSetMtu(iface, mtu);
2883 } catch (RemoteException | ServiceSpecificException e) {
2884 loge("exception in interfaceSetMtu()" + e);
2885 }
2886 }
2887
2888 @VisibleForTesting
2889 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
2890
2891 private void updateTcpBufferSizes(String tcpBufferSizes) {
2892 String[] values = null;
2893 if (tcpBufferSizes != null) {
2894 values = tcpBufferSizes.split(",");
2895 }
2896
2897 if (values == null || values.length != 6) {
2898 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
2899 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2900 values = tcpBufferSizes.split(",");
2901 }
2902
2903 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2904
2905 try {
2906 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
2907
2908 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2909 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2910 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
2911 mCurrentTcpBufferSizes = tcpBufferSizes;
2912 } catch (RemoteException | ServiceSpecificException e) {
2913 loge("Can't set TCP buffer sizes:" + e);
2914 }
2915 }
2916
2917 @Override
2918 public int getRestoreDefaultNetworkDelay(int networkType) {
2919 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
2920 NETWORK_RESTORE_DELAY_PROP_NAME);
2921 if(restoreDefaultNetworkDelayStr != null &&
2922 restoreDefaultNetworkDelayStr.length() != 0) {
2923 try {
2924 return Integer.parseInt(restoreDefaultNetworkDelayStr);
2925 } catch (NumberFormatException e) {
2926 }
2927 }
2928 // if the system property isn't set, use the value for the apn type
2929 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2930
2931 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2932 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
2933 }
2934 return ret;
2935 }
2936
2937 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2938 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2939 final long DIAG_TIME_MS = 5000;
2940 for (NetworkAgentInfo nai : networksSortedById()) {
2941 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
2942 // Start gathering diagnostic information.
2943 netDiags.add(new NetworkDiagnostics(
2944 nai.network,
2945 new LinkProperties(nai.linkProperties), // Must be a copy.
2946 privateDnsCfg,
2947 DIAG_TIME_MS));
2948 }
2949
2950 for (NetworkDiagnostics netDiag : netDiags) {
2951 pw.println();
2952 netDiag.waitForMeasurements();
2953 netDiag.dump(pw);
2954 }
2955 }
2956
2957 @Override
2958 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2959 @Nullable String[] args) {
2960 if (!checkDumpPermission(mContext, TAG, writer)) return;
2961
2962 mPriorityDumper.dump(fd, writer, args);
2963 }
2964
2965 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2966 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2967 != PackageManager.PERMISSION_GRANTED) {
2968 pw.println("Permission Denial: can't dump " + tag + " from from pid="
2969 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
2970 + " due to missing android.permission.DUMP permission");
2971 return false;
2972 } else {
2973 return true;
2974 }
2975 }
2976
2977 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
2978 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2979
2980 if (CollectionUtils.contains(args, DIAG_ARG)) {
2981 dumpNetworkDiagnostics(pw);
2982 return;
2983 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
2984 dumpNetworks(pw);
2985 return;
2986 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
2987 dumpNetworkRequests(pw);
2988 return;
2989 }
2990
2991 pw.print("NetworkProviders for:");
2992 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2993 pw.print(" " + npi.name);
2994 }
2995 pw.println();
2996 pw.println();
2997
2998 final NetworkAgentInfo defaultNai = getDefaultNetwork();
2999 pw.print("Active default network: ");
3000 if (defaultNai == null) {
3001 pw.println("none");
3002 } else {
3003 pw.println(defaultNai.network.getNetId());
3004 }
3005 pw.println();
3006
3007 pw.print("Current per-app default networks: ");
3008 pw.increaseIndent();
3009 dumpPerAppNetworkPreferences(pw);
3010 pw.decreaseIndent();
3011 pw.println();
3012
3013 pw.println("Current Networks:");
3014 pw.increaseIndent();
3015 dumpNetworks(pw);
3016 pw.decreaseIndent();
3017 pw.println();
3018
3019 pw.println("Status for known UIDs:");
3020 pw.increaseIndent();
3021 final int size = mUidBlockedReasons.size();
3022 for (int i = 0; i < size; i++) {
3023 // Don't crash if the array is modified while dumping in bugreports.
3024 try {
3025 final int uid = mUidBlockedReasons.keyAt(i);
3026 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3027 pw.println("UID=" + uid + " blockedReasons="
3028 + Integer.toHexString(blockedReasons));
3029 } catch (ArrayIndexOutOfBoundsException e) {
3030 pw.println(" ArrayIndexOutOfBoundsException");
3031 } catch (ConcurrentModificationException e) {
3032 pw.println(" ConcurrentModificationException");
3033 }
3034 }
3035 pw.println();
3036 pw.decreaseIndent();
3037
3038 pw.println("Network Requests:");
3039 pw.increaseIndent();
3040 dumpNetworkRequests(pw);
3041 pw.decreaseIndent();
3042 pw.println();
3043
3044 mLegacyTypeTracker.dump(pw);
3045
3046 pw.println();
3047 mKeepaliveTracker.dump(pw);
3048
3049 pw.println();
3050 dumpAvoidBadWifiSettings(pw);
3051
3052 pw.println();
3053
3054 if (!CollectionUtils.contains(args, SHORT_ARG)) {
3055 pw.println();
3056 pw.println("mNetworkRequestInfoLogs (most recent first):");
3057 pw.increaseIndent();
3058 mNetworkRequestInfoLogs.reverseDump(pw);
3059 pw.decreaseIndent();
3060
3061 pw.println();
3062 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3063 pw.increaseIndent();
3064 mNetworkInfoBlockingLogs.reverseDump(pw);
3065 pw.decreaseIndent();
3066
3067 pw.println();
3068 pw.println("NetTransition WakeLock activity (most recent first):");
3069 pw.increaseIndent();
3070 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3071 pw.println("total releases: " + mTotalWakelockReleases);
3072 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3073 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3074 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3075 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3076 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3077 }
3078 mWakelockLogs.reverseDump(pw);
3079
3080 pw.println();
3081 pw.println("bandwidth update requests (by uid):");
3082 pw.increaseIndent();
3083 synchronized (mBandwidthRequests) {
3084 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3085 pw.println("[" + mBandwidthRequests.keyAt(i)
3086 + "]: " + mBandwidthRequests.valueAt(i));
3087 }
3088 }
3089 pw.decreaseIndent();
3090 pw.decreaseIndent();
3091
3092 pw.println();
3093 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3094 pw.increaseIndent();
3095 mOemNetworkPreferencesLogs.reverseDump(pw);
3096 pw.decreaseIndent();
3097 }
3098
3099 pw.println();
3100
3101 pw.println();
3102 pw.println("Permission Monitor:");
3103 pw.increaseIndent();
3104 mPermissionMonitor.dump(pw);
3105 pw.decreaseIndent();
3106
3107 pw.println();
3108 pw.println("Legacy network activity:");
3109 pw.increaseIndent();
3110 mNetworkActivityTracker.dump(pw);
3111 pw.decreaseIndent();
3112 }
3113
3114 private void dumpNetworks(IndentingPrintWriter pw) {
3115 for (NetworkAgentInfo nai : networksSortedById()) {
3116 pw.println(nai.toString());
3117 pw.increaseIndent();
3118 pw.println(String.format(
3119 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3120 nai.numForegroundNetworkRequests(),
3121 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3122 nai.numBackgroundNetworkRequests(),
3123 nai.numNetworkRequests()));
3124 pw.increaseIndent();
3125 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3126 pw.println(nai.requestAt(i).toString());
3127 }
3128 pw.decreaseIndent();
3129 pw.println("Inactivity Timers:");
3130 pw.increaseIndent();
3131 nai.dumpInactivityTimers(pw);
3132 pw.decreaseIndent();
3133 pw.decreaseIndent();
3134 }
3135 }
3136
3137 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3138 pw.println("Per-App Network Preference:");
3139 pw.increaseIndent();
3140 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3141 pw.println("none");
3142 } else {
3143 pw.println(mOemNetworkPreferences.toString());
3144 }
3145 pw.decreaseIndent();
3146
3147 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3148 if (mDefaultRequest == defaultRequest) {
3149 continue;
3150 }
3151
3152 final boolean isActive = null != defaultRequest.getSatisfier();
3153 pw.println("Is per-app network active:");
3154 pw.increaseIndent();
3155 pw.println(isActive);
3156 if (isActive) {
3157 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3158 }
3159 pw.println("Tracked UIDs:");
3160 pw.increaseIndent();
3161 if (0 == defaultRequest.mRequests.size()) {
3162 pw.println("none, this should never occur.");
3163 } else {
3164 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
3165 }
3166 pw.decreaseIndent();
3167 pw.decreaseIndent();
3168 }
3169 }
3170
3171 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3172 for (NetworkRequestInfo nri : requestsSortedById()) {
3173 pw.println(nri.toString());
3174 }
3175 }
3176
3177 /**
3178 * Return an array of all current NetworkAgentInfos sorted by network id.
3179 */
3180 private NetworkAgentInfo[] networksSortedById() {
3181 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
3182 networks = mNetworkAgentInfos.toArray(networks);
3183 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
3184 return networks;
3185 }
3186
3187 /**
3188 * Return an array of all current NetworkRequest sorted by request id.
3189 */
3190 @VisibleForTesting
3191 NetworkRequestInfo[] requestsSortedById() {
3192 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
3193 requests = getNrisFromGlobalRequests().toArray(requests);
3194 // Sort the array based off the NRI containing the min requestId in its requests.
3195 Arrays.sort(requests,
3196 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3197 Comparator.comparingInt(req -> req.requestId)).requestId
3198 )
3199 );
3200 return requests;
3201 }
3202
3203 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
3204 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
3205 if (officialNai != null && officialNai.equals(nai)) return true;
3206 if (officialNai != null || VDBG) {
3207 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
3208 " - " + nai);
3209 }
3210 return false;
3211 }
3212
3213 // must be stateless - things change under us.
3214 private class NetworkStateTrackerHandler extends Handler {
3215 public NetworkStateTrackerHandler(Looper looper) {
3216 super(looper);
3217 }
3218
3219 private void maybeHandleNetworkAgentMessage(Message msg) {
3220 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3221 final NetworkAgentInfo nai = arg.first;
3222 if (!mNetworkAgentInfos.contains(nai)) {
3223 if (VDBG) {
3224 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
3225 }
3226 return;
3227 }
3228
3229 switch (msg.what) {
3230 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3231 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
3232 if (networkCapabilities.hasConnectivityManagedCapability()) {
3233 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
3234 }
3235 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3236 // Make sure the original object is not mutated. NetworkAgent normally
3237 // makes a copy of the capabilities when sending the message through
3238 // the Messenger, but if this ever changes, not making a defensive copy
3239 // here will give attack vectors to clients using this code path.
3240 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3241 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
3242 }
3243 processCapabilitiesFromAgent(nai, networkCapabilities);
3244 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
3245 break;
3246 }
3247 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3248 LinkProperties newLp = (LinkProperties) arg.second;
3249 processLinkPropertiesFromAgent(nai, newLp);
3250 handleUpdateLinkProperties(nai, newLp);
3251 break;
3252 }
3253 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3254 NetworkInfo info = (NetworkInfo) arg.second;
3255 updateNetworkInfo(nai, info);
3256 break;
3257 }
3258 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3259 updateNetworkScore(nai, (NetworkScore) arg.second);
3260 break;
3261 }
3262 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
3263 if (nai.everConnected) {
3264 loge("ERROR: cannot call explicitlySelected on already-connected network");
3265 // Note that if the NAI had been connected, this would affect the
3266 // score, and therefore would require re-mixing the score and performing
3267 // a rematch.
3268 }
3269 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3270 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
3271 // Mark the network as temporarily accepting partial connectivity so that it
3272 // will be validated (and possibly become default) even if it only provides
3273 // partial internet access. Note that if user connects to partial connectivity
3274 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3275 // out of wifi coverage) and if the same wifi is available again, the device
3276 // will auto connect to this wifi even though the wifi has "no internet".
3277 // TODO: Evaluate using a separate setting in IpMemoryStore.
3278 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
3279 break;
3280 }
3281 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
3282 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
3283 break;
3284 }
3285 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
3286 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003287 final List<Network> underlying = (List<Network>) arg.second;
3288
3289 if (isLegacyLockdownNai(nai)
3290 && (underlying == null || underlying.size() != 1)) {
3291 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3292 + " must have exactly one underlying network: " + underlying);
3293 }
3294
3295 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3296 nai.declaredUnderlyingNetworks = (underlying != null)
3297 ? underlying.toArray(new Network[0]) : null;
3298
3299 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3300 if (DBG) {
3301 log(nai.toShortString() + " changed underlying networks to "
3302 + Arrays.toString(nai.declaredUnderlyingNetworks));
3303 }
3304 updateCapabilitiesForNetwork(nai);
3305 notifyIfacesChangedForNetworkStats();
3306 }
3307 break;
3308 }
3309 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3310 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3311 nai.teardownDelayMs = msg.arg1;
3312 } else {
3313 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3314 }
3315 break;
3316 }
3317 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3318 nai.setLingerDuration((int) arg.second);
3319 break;
3320 }
3321 }
3322 }
3323
3324 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3325 switch (msg.what) {
3326 default:
3327 return false;
3328 case EVENT_PROBE_STATUS_CHANGED: {
3329 final Integer netId = (Integer) msg.obj;
3330 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3331 if (nai == null) {
3332 break;
3333 }
3334 final boolean probePrivateDnsCompleted =
3335 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3336 final boolean privateDnsBroken =
3337 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3338 if (probePrivateDnsCompleted) {
3339 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3340 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3341 updateCapabilitiesForNetwork(nai);
3342 }
3343 // Only show the notification when the private DNS is broken and the
3344 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3345 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3346 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3347 }
3348 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3349 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3350 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3351 // private DNS is broken, it means this network is being reevaluated.
3352 // Either probing private DNS is not necessary any more or it hasn't been
3353 // done yet. In either case, the networkCapabilities should be updated to
3354 // reflect the new status.
3355 nai.networkCapabilities.setPrivateDnsBroken(false);
3356 updateCapabilitiesForNetwork(nai);
3357 nai.networkAgentConfig.hasShownBroken = false;
3358 }
3359 break;
3360 }
3361 case EVENT_NETWORK_TESTED: {
3362 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3363
3364 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3365 if (nai == null) break;
3366
3367 handleNetworkTested(nai, results.mTestResult,
3368 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3369 break;
3370 }
3371 case EVENT_PROVISIONING_NOTIFICATION: {
3372 final int netId = msg.arg2;
3373 final boolean visible = toBool(msg.arg1);
3374 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3375 // If captive portal status has changed, update capabilities or disconnect.
3376 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3377 nai.lastCaptivePortalDetected = visible;
3378 nai.everCaptivePortalDetected |= visible;
3379 if (nai.lastCaptivePortalDetected &&
3380 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3381 == getCaptivePortalMode()) {
3382 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3383 nai.onPreventAutomaticReconnect();
3384 teardownUnneededNetwork(nai);
3385 break;
3386 }
3387 updateCapabilitiesForNetwork(nai);
3388 }
3389 if (!visible) {
3390 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3391 // notifications belong to the same network may be cleared unexpectedly.
3392 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3393 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3394 } else {
3395 if (nai == null) {
3396 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3397 break;
3398 }
3399 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3400 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3401 (PendingIntent) msg.obj,
3402 nai.networkAgentConfig.explicitlySelected);
3403 }
3404 }
3405 break;
3406 }
3407 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3408 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3409 if (nai == null) break;
3410
3411 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3412 break;
3413 }
3414 case EVENT_CAPPORT_DATA_CHANGED: {
3415 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3416 if (nai == null) break;
3417 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3418 break;
3419 }
3420 }
3421 return true;
3422 }
3423
3424 private void handleNetworkTested(
3425 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3426 final boolean wasPartial = nai.partialConnectivity;
3427 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3428 final boolean partialConnectivityChanged =
3429 (wasPartial != nai.partialConnectivity);
3430
3431 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3432 final boolean wasValidated = nai.lastValidated;
3433 final boolean wasDefault = isDefaultNetwork(nai);
3434
3435 if (DBG) {
3436 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3437 ? " with redirect to " + redirectUrl
3438 : "";
3439 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3440 }
3441 if (valid != nai.lastValidated) {
3442 final int oldScore = nai.getCurrentScore();
3443 nai.lastValidated = valid;
3444 nai.everValidated |= valid;
3445 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3446 if (valid) {
3447 handleFreshlyValidatedNetwork(nai);
3448 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3449 // LOST_INTERNET notifications if network becomes valid.
3450 mNotifier.clearNotification(nai.network.getNetId(),
3451 NotificationType.NO_INTERNET);
3452 mNotifier.clearNotification(nai.network.getNetId(),
3453 NotificationType.LOST_INTERNET);
3454 mNotifier.clearNotification(nai.network.getNetId(),
3455 NotificationType.PARTIAL_CONNECTIVITY);
3456 mNotifier.clearNotification(nai.network.getNetId(),
3457 NotificationType.PRIVATE_DNS_BROKEN);
3458 // If network becomes valid, the hasShownBroken should be reset for
3459 // that network so that the notification will be fired when the private
3460 // DNS is broken again.
3461 nai.networkAgentConfig.hasShownBroken = false;
3462 }
3463 } else if (partialConnectivityChanged) {
3464 updateCapabilitiesForNetwork(nai);
3465 }
3466 updateInetCondition(nai);
3467 // Let the NetworkAgent know the state of its network
3468 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3469 nai.onValidationStatusChanged(
3470 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3471 redirectUrl);
3472
3473 // If NetworkMonitor detects partial connectivity before
3474 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3475 // immediately. Re-notify partial connectivity silently if no internet
3476 // notification already there.
3477 if (!wasPartial && nai.partialConnectivity) {
3478 // Remove delayed message if there is a pending message.
3479 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3480 handlePromptUnvalidated(nai.network);
3481 }
3482
3483 if (wasValidated && !nai.lastValidated) {
3484 handleNetworkUnvalidated(nai);
3485 }
3486 }
3487
3488 private int getCaptivePortalMode() {
3489 return Settings.Global.getInt(mContext.getContentResolver(),
3490 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3491 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3492 }
3493
3494 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3495 switch (msg.what) {
3496 default:
3497 return false;
3498 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3499 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3500 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3501 handleLingerComplete(nai);
3502 }
3503 break;
3504 }
3505 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3506 handleNetworkAgentRegistered(msg);
3507 break;
3508 }
3509 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3510 handleNetworkAgentDisconnected(msg);
3511 break;
3512 }
3513 }
3514 return true;
3515 }
3516
3517 @Override
3518 public void handleMessage(Message msg) {
3519 if (!maybeHandleNetworkMonitorMessage(msg)
3520 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3521 maybeHandleNetworkAgentMessage(msg);
3522 }
3523 }
3524 }
3525
3526 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3527 private final int mNetId;
3528 private final AutodestructReference<NetworkAgentInfo> mNai;
3529
3530 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3531 mNetId = nai.network.getNetId();
3532 mNai = new AutodestructReference<>(nai);
3533 }
3534
3535 @Override
3536 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3537 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3538 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3539 }
3540
3541 @Override
3542 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3543 // Legacy version of notifyNetworkTestedWithExtras.
3544 // Would only be called if the system has a NetworkStack module older than the
3545 // framework, which does not happen in practice.
3546 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3547 }
3548
3549 @Override
3550 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3551 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3552 // the same looper so messages will be processed in sequence.
3553 final Message msg = mTrackerHandler.obtainMessage(
3554 EVENT_NETWORK_TESTED,
3555 new NetworkTestedResults(
3556 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3557 mTrackerHandler.sendMessage(msg);
3558
3559 // Invoke ConnectivityReport generation for this Network test event.
3560 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3561 if (nai == null) return;
3562
3563 final PersistableBundle extras = new PersistableBundle();
3564 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3565 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3566 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3567
3568 ConnectivityReportEvent reportEvent =
3569 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3570 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3571 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3572 mConnectivityDiagnosticsHandler.sendMessage(m);
3573 }
3574
3575 @Override
3576 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3577 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3578 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3579 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3580 }
3581
3582 @Override
3583 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3584 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3585 EVENT_PROBE_STATUS_CHANGED,
3586 probesCompleted, probesSucceeded, new Integer(mNetId)));
3587 }
3588
3589 @Override
3590 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3591 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3592 EVENT_CAPPORT_DATA_CHANGED,
3593 0, mNetId, data));
3594 }
3595
3596 @Override
3597 public void showProvisioningNotification(String action, String packageName) {
3598 final Intent intent = new Intent(action);
3599 intent.setPackage(packageName);
3600
3601 final PendingIntent pendingIntent;
3602 // Only the system server can register notifications with package "android"
3603 final long token = Binder.clearCallingIdentity();
3604 try {
3605 pendingIntent = PendingIntent.getBroadcast(
3606 mContext,
3607 0 /* requestCode */,
3608 intent,
3609 PendingIntent.FLAG_IMMUTABLE);
3610 } finally {
3611 Binder.restoreCallingIdentity(token);
3612 }
3613 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3614 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3615 mNetId, pendingIntent));
3616 }
3617
3618 @Override
3619 public void hideProvisioningNotification() {
3620 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3621 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3622 }
3623
3624 @Override
3625 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3626 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3627 }
3628
3629 @Override
3630 public int getInterfaceVersion() {
3631 return this.VERSION;
3632 }
3633
3634 @Override
3635 public String getInterfaceHash() {
3636 return this.HASH;
3637 }
3638 }
3639
3640 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3641 log("Data stall detected with methods: " + p.detectionMethod);
3642
3643 final PersistableBundle extras = new PersistableBundle();
3644 int detectionMethod = 0;
3645 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3646 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3647 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3648 }
3649 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3650 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3651 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3652 p.tcpMetricsCollectionPeriodMillis);
3653 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3654 }
3655
3656 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3657 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3658 new Pair<>(p.timestampMillis, extras));
3659
3660 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3661 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3662 // the cost of going through two handlers.
3663 mConnectivityDiagnosticsHandler.sendMessage(msg);
3664 }
3665
3666 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3667 return (p.detectionMethod & detectionMethod) != 0;
3668 }
3669
3670 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3671 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3672 }
3673
3674 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3675 if (nai == null) return;
3676 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3677 // in order to restart a validation pass from within netd.
3678 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3679 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3680 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3681 }
3682 }
3683
3684 private void handlePrivateDnsSettingsChanged() {
3685 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3686
3687 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3688 handlePerNetworkPrivateDnsConfig(nai, cfg);
3689 if (networkRequiresPrivateDnsValidation(nai)) {
3690 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3691 }
3692 }
3693 }
3694
3695 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3696 // Private DNS only ever applies to networks that might provide
3697 // Internet access and therefore also require validation.
3698 if (!networkRequiresPrivateDnsValidation(nai)) return;
3699
3700 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3701 // schedule DNS resolutions. If a DNS resolution is required the
3702 // result will be sent back to us.
3703 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3704
3705 // With Private DNS bypass support, we can proceed to update the
3706 // Private DNS config immediately, even if we're in strict mode
3707 // and have not yet resolved the provider name into a set of IPs.
3708 updatePrivateDns(nai, cfg);
3709 }
3710
3711 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3712 mDnsManager.updatePrivateDns(nai.network, newCfg);
3713 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3714 }
3715
3716 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3717 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3718 if (nai == null) {
3719 return;
3720 }
3721 mDnsManager.updatePrivateDnsValidation(update);
3722 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3723 }
3724
3725 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3726 int prefixLength) {
3727 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3728 if (nai == null) return;
3729
3730 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3731 netId, operation, prefixAddress, prefixLength));
3732
3733 IpPrefix prefix = null;
3734 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3735 try {
3736 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3737 prefixLength);
3738 } catch (IllegalArgumentException e) {
3739 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3740 return;
3741 }
3742 }
3743
3744 nai.clatd.setNat64PrefixFromDns(prefix);
3745 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3746 }
3747
3748 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3749 @Nullable final CaptivePortalData data) {
3750 nai.capportApiData = data;
3751 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3752 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3753 }
3754
3755 /**
3756 * Updates the inactivity state from the network requests inside the NAI.
3757 * @param nai the agent info to update
3758 * @param now the timestamp of the event causing this update
3759 * @return whether the network was inactive as a result of this update
3760 */
3761 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3762 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3763 // 2. If the network was inactive and there are now requests, unset inactive.
3764 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3765 // one lingered request, set inactive.
3766 nai.updateInactivityTimer();
3767 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3768 if (DBG) log("Unsetting inactive " + nai.toShortString());
3769 nai.unsetInactive();
3770 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3771 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3772 if (DBG) {
3773 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3774 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3775 }
3776 nai.setInactive();
3777 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3778 return true;
3779 }
3780 return false;
3781 }
3782
3783 private void handleNetworkAgentRegistered(Message msg) {
3784 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3785 if (!mNetworkAgentInfos.contains(nai)) {
3786 return;
3787 }
3788
3789 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3790 if (VDBG) log("NetworkAgent registered");
3791 } else {
3792 loge("Error connecting NetworkAgent");
3793 mNetworkAgentInfos.remove(nai);
3794 if (nai != null) {
3795 final boolean wasDefault = isDefaultNetwork(nai);
3796 synchronized (mNetworkForNetId) {
3797 mNetworkForNetId.remove(nai.network.getNetId());
3798 }
3799 mNetIdManager.releaseNetId(nai.network.getNetId());
3800 // Just in case.
3801 mLegacyTypeTracker.remove(nai, wasDefault);
3802 }
3803 }
3804 }
3805
3806 private void handleNetworkAgentDisconnected(Message msg) {
3807 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3808 if (mNetworkAgentInfos.contains(nai)) {
3809 disconnectAndDestroyNetwork(nai);
3810 }
3811 }
3812
3813 // Destroys a network, remove references to it from the internal state managed by
3814 // ConnectivityService, free its interfaces and clean up.
3815 // Must be called on the Handler thread.
3816 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3817 ensureRunningOnConnectivityServiceThread();
3818 if (DBG) {
3819 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3820 }
3821 // Clear all notifications of this network.
3822 mNotifier.clearNotification(nai.network.getNetId());
3823 // A network agent has disconnected.
3824 // TODO - if we move the logic to the network agent (have them disconnect
3825 // because they lost all their requests or because their score isn't good)
3826 // then they would disconnect organically, report their new state and then
3827 // disconnect the channel.
3828 if (nai.networkInfo.isConnected()) {
3829 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3830 null, null);
3831 }
3832 final boolean wasDefault = isDefaultNetwork(nai);
3833 if (wasDefault) {
3834 mDefaultInetConditionPublished = 0;
3835 }
3836 notifyIfacesChangedForNetworkStats();
3837 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3838 // by other networks that are already connected. Perhaps that can be done by
3839 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3840 // of rematchAllNetworksAndRequests
3841 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3842 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3843
3844 mQosCallbackTracker.handleNetworkReleased(nai.network);
3845 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3846 // Disable wakeup packet monitoring for each interface.
3847 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3848 }
3849 nai.networkMonitor().notifyNetworkDisconnected();
3850 mNetworkAgentInfos.remove(nai);
3851 nai.clatd.update();
3852 synchronized (mNetworkForNetId) {
3853 // Remove the NetworkAgent, but don't mark the netId as
3854 // available until we've told netd to delete it below.
3855 mNetworkForNetId.remove(nai.network.getNetId());
3856 }
3857 propagateUnderlyingNetworkCapabilities(nai.network);
3858 // Remove all previously satisfied requests.
3859 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3860 final NetworkRequest request = nai.requestAt(i);
3861 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3862 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3863 if (currentNetwork != null
3864 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3865 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3866 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3867 // rematch not to keep disconnected agents instead of setting it here ; this
3868 // will also allow removing updating the offers below.
3869 nri.setSatisfier(null, null);
3870 for (final NetworkOfferInfo noi : mNetworkOffers) {
3871 informOffer(nri, noi.offer, mNetworkRanker);
3872 }
3873
3874 if (mDefaultRequest == nri) {
3875 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3876 // active at the same time. For now keep calling this with the default
3877 // network, because while incorrect this is the closest to the old (also
3878 // incorrect) behavior.
3879 mNetworkActivityTracker.updateDataActivityTracking(
3880 null /* newNetwork */, nai);
3881 ensureNetworkTransitionWakelock(nai.toShortString());
3882 }
3883 }
3884 }
3885 nai.clearInactivityState();
3886 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3887 // Currently, deleting it breaks tests that check for the default network disconnecting.
3888 // Find out why, fix the rematch code, and delete this.
3889 mLegacyTypeTracker.remove(nai, wasDefault);
3890 rematchAllNetworksAndRequests();
3891 mLingerMonitor.noteDisconnect(nai);
3892
3893 // Immediate teardown.
3894 if (nai.teardownDelayMs == 0) {
3895 destroyNetwork(nai);
3896 return;
3897 }
3898
3899 // Delayed teardown.
3900 try {
3901 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3902 } catch (RemoteException e) {
3903 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3904 }
3905 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3906 }
3907
3908 private void destroyNetwork(NetworkAgentInfo nai) {
3909 if (nai.created) {
3910 // Tell netd to clean up the configuration for this network
3911 // (routing rules, DNS, etc).
3912 // This may be slow as it requires a lot of netd shelling out to ip and
3913 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3914 // after we've rematched networks with requests (which might change the default
3915 // network or service a new request from an app), so network traffic isn't interrupted
3916 // for an unnecessarily long time.
3917 destroyNativeNetwork(nai);
3918 mDnsManager.removeNetwork(nai.network);
3919 }
3920 mNetIdManager.releaseNetId(nai.network.getNetId());
3921 nai.onNetworkDestroyed();
3922 }
3923
3924 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3925 try {
3926 // This should never fail. Specifying an already in use NetID will cause failure.
3927 final NativeNetworkConfig config;
3928 if (nai.isVPN()) {
3929 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3930 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3931 return false;
3932 }
3933 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3934 INetd.PERMISSION_NONE,
3935 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3936 getVpnType(nai));
3937 } else {
3938 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3939 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3940 VpnManager.TYPE_VPN_NONE);
3941 }
3942 mNetd.networkCreate(config);
3943 mDnsResolver.createNetworkCache(nai.network.getNetId());
3944 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3945 nai.networkCapabilities.getTransportTypes());
3946 return true;
3947 } catch (RemoteException | ServiceSpecificException e) {
3948 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3949 return false;
3950 }
3951 }
3952
3953 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3954 try {
3955 mNetd.networkDestroy(nai.network.getNetId());
3956 } catch (RemoteException | ServiceSpecificException e) {
3957 loge("Exception destroying network(networkDestroy): " + e);
3958 }
3959 try {
3960 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3961 } catch (RemoteException | ServiceSpecificException e) {
3962 loge("Exception destroying network: " + e);
3963 }
3964 }
3965
3966 // If this method proves to be too slow then we can maintain a separate
3967 // pendingIntent => NetworkRequestInfo map.
3968 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3969 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3970 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3971 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3972 if (existingPendingIntent != null &&
Remi NGUYEN VANff55aeb2021-06-16 11:37:53 +00003973 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00003974 return entry.getValue();
3975 }
3976 }
3977 return null;
3978 }
3979
3980 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
3981 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3982 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3983 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3984 final NetworkRequestInfo existingRequest =
3985 findExistingNetworkRequestInfo(nri.mPendingIntent);
3986 if (existingRequest != null) { // remove the existing request.
3987 if (DBG) {
3988 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3989 + nri.mRequests.get(0) + " because their intents matched.");
3990 }
3991 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
3992 /* callOnUnavailable */ false);
3993 }
3994 handleRegisterNetworkRequest(nri);
3995 }
3996
3997 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
3998 handleRegisterNetworkRequests(Collections.singleton(nri));
3999 }
4000
4001 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4002 ensureRunningOnConnectivityServiceThread();
4003 for (final NetworkRequestInfo nri : nris) {
4004 mNetworkRequestInfoLogs.log("REGISTER " + nri);
4005 for (final NetworkRequest req : nri.mRequests) {
4006 mNetworkRequests.put(req, nri);
4007 // TODO: Consider update signal strength for other types.
4008 if (req.isListen()) {
4009 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4010 if (req.networkCapabilities.hasSignalStrength()
4011 && network.satisfiesImmutableCapabilitiesOf(req)) {
4012 updateSignalStrengthThresholds(network, "REGISTER", req);
4013 }
4014 }
4015 }
4016 }
4017 // If this NRI has a satisfier already, it is replacing an older request that
4018 // has been removed. Track it.
4019 final NetworkRequest activeRequest = nri.getActiveRequest();
4020 if (null != activeRequest) {
4021 // If there is an active request, then for sure there is a satisfier.
4022 nri.getSatisfier().addRequest(activeRequest);
4023 }
4024 }
4025
4026 rematchAllNetworksAndRequests();
4027
4028 // Requests that have not been matched to a network will not have been sent to the
4029 // providers, because the old satisfier and the new satisfier are the same (null in this
4030 // case). Send these requests to the providers.
4031 for (final NetworkRequestInfo nri : nris) {
4032 for (final NetworkOfferInfo noi : mNetworkOffers) {
4033 informOffer(nri, noi.offer, mNetworkRanker);
4034 }
4035 }
4036 }
4037
4038 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4039 final int callingUid) {
4040 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
4041 if (nri != null) {
4042 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4043 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4044 handleReleaseNetworkRequest(
4045 nri.mRequests.get(0),
4046 callingUid,
4047 /* callOnUnavailable */ false);
4048 }
4049 }
4050
4051 // Determines whether the network is the best (or could become the best, if it validated), for
4052 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4053 // on the value of reason:
4054 //
4055 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4056 // then it should be torn down.
4057 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4058 // then it should be lingered.
4059 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
4060 ensureRunningOnConnectivityServiceThread();
4061
4062 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4063 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4064 return false;
4065 }
4066
4067 final int numRequests;
4068 switch (reason) {
4069 case TEARDOWN:
4070 numRequests = nai.numRequestNetworkRequests();
4071 break;
4072 case LINGER:
4073 numRequests = nai.numForegroundNetworkRequests();
4074 break;
4075 default:
4076 Log.wtf(TAG, "Invalid reason. Cannot happen.");
4077 return true;
4078 }
4079
4080 if (numRequests > 0) return false;
4081
4082 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4083 if (reason == UnneededFor.LINGER
4084 && !nri.isMultilayerRequest()
4085 && nri.mRequests.get(0).isBackgroundRequest()) {
4086 // Background requests don't affect lingering.
4087 continue;
4088 }
4089
4090 if (isNetworkPotentialSatisfier(nai, nri)) {
4091 return false;
4092 }
4093 }
4094 return true;
4095 }
4096
4097 private boolean isNetworkPotentialSatisfier(
4098 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4099 // listen requests won't keep up a network satisfying it. If this is not a multilayer
4100 // request, return immediately. For multilayer requests, check to see if any of the
4101 // multilayer requests may have a potential satisfier.
4102 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4103 || nri.mRequests.get(0).isListenForBest())) {
4104 return false;
4105 }
4106 for (final NetworkRequest req : nri.mRequests) {
4107 // This multilayer listen request is satisfied therefore no further requests need to be
4108 // evaluated deeming this network not a potential satisfier.
4109 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4110 return false;
4111 }
4112 // As non-multilayer listen requests have already returned, the below would only happen
4113 // for a multilayer request therefore continue to the next request if available.
4114 if (req.isListen() || req.isListenForBest()) {
4115 continue;
4116 }
4117 // If this Network is already the highest scoring Network for a request, or if
4118 // there is hope for it to become one if it validated, then it is needed.
4119 if (candidate.satisfies(req)) {
4120 // As soon as a network is found that satisfies a request, return. Specifically for
4121 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4122 // is important so as to not evaluate lower priority requests further in
4123 // nri.mRequests.
4124 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4125 ? nri.getSatisfier() : null;
4126 // Note that this catches two important cases:
4127 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4128 // is currently satisfying the request. This is desirable when
4129 // cellular ends up validating but WiFi does not.
4130 // 2. Unvalidated WiFi will not be reaped when validated cellular
4131 // is currently satisfying the request. This is desirable when
4132 // WiFi ends up validating and out scoring cellular.
4133 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4134 }
4135 }
4136
4137 return false;
4138 }
4139
4140 private NetworkRequestInfo getNriForAppRequest(
4141 NetworkRequest request, int callingUid, String requestedOperation) {
4142 // Looking up the app passed param request in mRequests isn't possible since it may return
4143 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4144 // do the lookup since that will also find per-app default managed requests.
4145 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4146 // to avoid potential race conditions when validating a package->uid mapping when sending
4147 // the callback on the very low-chance that an application shuts down prior to the callback
4148 // being sent.
4149 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4150 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4151
4152 if (nri != null) {
4153 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4154 log(String.format("UID %d attempted to %s for unowned request %s",
4155 callingUid, requestedOperation, nri));
4156 return null;
4157 }
4158 }
4159
4160 return nri;
4161 }
4162
4163 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4164 final String callingMethod) {
4165 if (nri.isMultilayerRequest()) {
4166 throw new IllegalStateException(
4167 callingMethod + " does not support multilayer requests.");
4168 }
4169 }
4170
4171 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4172 ensureRunningOnConnectivityServiceThread();
4173 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4174 // single NetworkRequest and thus does not apply to multilayer requests.
4175 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4176 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4177 return;
4178 }
4179 if (nri.isBeingSatisfied()) {
4180 return;
4181 }
4182 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4183 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4184 }
4185 handleRemoveNetworkRequest(nri);
4186 callCallbackForRequest(
4187 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4188 }
4189
4190 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4191 final int callingUid,
4192 final boolean callOnUnavailable) {
4193 final NetworkRequestInfo nri =
4194 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4195 if (nri == null) {
4196 return;
4197 }
4198 if (VDBG || (DBG && request.isRequest())) {
4199 log("releasing " + request + " (release request)");
4200 }
4201 handleRemoveNetworkRequest(nri);
4202 if (callOnUnavailable) {
4203 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4204 }
4205 }
4206
4207 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4208 ensureRunningOnConnectivityServiceThread();
4209 nri.unlinkDeathRecipient();
4210 for (final NetworkRequest req : nri.mRequests) {
4211 mNetworkRequests.remove(req);
4212 if (req.isListen()) {
4213 removeListenRequestFromNetworks(req);
4214 }
4215 }
4216 if (mDefaultNetworkRequests.remove(nri)) {
4217 // If this request was one of the defaults, then the UID rules need to be updated
4218 // WARNING : if the app(s) for which this network request is the default are doing
4219 // traffic, this will kill their connected sockets, even if an equivalent request
4220 // is going to be reinstated right away ; unconnected traffic will go on the default
4221 // until the new default is set, which will happen very soon.
4222 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4223 // remove ranges for those requests that won't have a replacement
4224 final NetworkAgentInfo satisfier = nri.getSatisfier();
4225 if (null != satisfier) {
4226 try {
paulhude2a2392021-06-09 16:11:35 +08004227 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4228 satisfier.network.getNetId(),
4229 toUidRangeStableParcels(nri.getUids()),
paulhude5efb92021-05-26 21:56:03 +08004230 nri.getPriorityForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004231 } catch (RemoteException e) {
4232 loge("Exception setting network preference default network", e);
4233 }
4234 }
4235 }
4236 nri.decrementRequestCount();
4237 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4238
4239 if (null != nri.getActiveRequest()) {
4240 if (!nri.getActiveRequest().isListen()) {
4241 removeSatisfiedNetworkRequestFromNetwork(nri);
4242 } else {
4243 nri.setSatisfier(null, null);
4244 }
4245 }
4246
4247 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4248 // needed for this offer.
4249 for (final NetworkOfferInfo noi : mNetworkOffers) {
4250 for (final NetworkRequest req : nri.mRequests) {
4251 if (req.isRequest() && noi.offer.neededFor(req)) {
4252 noi.offer.onNetworkUnneeded(req);
4253 }
4254 }
4255 }
4256 }
4257
4258 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4259 for (final NetworkRequestInfo nri : nris) {
4260 if (mDefaultRequest == nri) {
4261 // Make sure we never remove the default request.
4262 continue;
4263 }
4264 handleRemoveNetworkRequest(nri);
4265 }
4266 }
4267
4268 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4269 // listens don't have a singular affected Network. Check all networks to see
4270 // if this listen request applies and remove it.
4271 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4272 nai.removeRequest(req.requestId);
4273 if (req.networkCapabilities.hasSignalStrength()
4274 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4275 updateSignalStrengthThresholds(nai, "RELEASE", req);
4276 }
4277 }
4278 }
4279
4280 /**
4281 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4282 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4283 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4284 */
4285 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4286 boolean wasKept = false;
4287 final NetworkAgentInfo nai = nri.getSatisfier();
4288 if (nai != null) {
4289 final int requestLegacyType = nri.getActiveRequest().legacyType;
4290 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4291 nai.removeRequest(nri.getActiveRequest().requestId);
4292 if (VDBG || DDBG) {
4293 log(" Removing from current network " + nai.toShortString()
4294 + ", leaving " + nai.numNetworkRequests() + " requests.");
4295 }
4296 // If there are still lingered requests on this network, don't tear it down,
4297 // but resume lingering instead.
4298 final long now = SystemClock.elapsedRealtime();
4299 if (updateInactivityState(nai, now)) {
4300 notifyNetworkLosing(nai, now);
4301 }
4302 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4303 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4304 teardownUnneededNetwork(nai);
4305 } else {
4306 wasKept = true;
4307 }
4308 nri.setSatisfier(null, null);
4309 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4310 // Went from foreground to background.
4311 updateCapabilitiesForNetwork(nai);
4312 }
4313
4314 // Maintain the illusion. When this request arrived, we might have pretended
4315 // that a network connected to serve it, even though the network was already
4316 // connected. Now that this request has gone away, we might have to pretend
4317 // that the network disconnected. LegacyTypeTracker will generate that
4318 // phantom disconnect for this type.
4319 if (requestLegacyType != TYPE_NONE) {
4320 boolean doRemove = true;
4321 if (wasKept) {
4322 // check if any of the remaining requests for this network are for the
4323 // same legacy type - if so, don't remove the nai
4324 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4325 NetworkRequest otherRequest = nai.requestAt(i);
4326 if (otherRequest.legacyType == requestLegacyType
4327 && otherRequest.isRequest()) {
4328 if (DBG) log(" still have other legacy request - leaving");
4329 doRemove = false;
4330 }
4331 }
4332 }
4333
4334 if (doRemove) {
4335 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4336 }
4337 }
4338 }
4339 }
4340
4341 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4342 return checkAnyPermissionOf(
4343 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4344 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4345 }
4346
4347 @Override
4348 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4349 enforceNetworkStackSettingsOrSetup();
4350 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4351 encodeBool(accept), encodeBool(always), network));
4352 }
4353
4354 @Override
4355 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4356 enforceNetworkStackSettingsOrSetup();
4357 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4358 encodeBool(accept), encodeBool(always), network));
4359 }
4360
4361 @Override
4362 public void setAvoidUnvalidated(Network network) {
4363 enforceNetworkStackSettingsOrSetup();
4364 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4365 }
4366
Chiachang Wangfad30e32021-06-23 02:08:44 +00004367 @Override
4368 public void setTestAllowBadWifiUntil(long timeMs) {
4369 enforceSettingsPermission();
4370 if (!Build.isDebuggable()) {
4371 throw new IllegalStateException("Does not support in non-debuggable build");
4372 }
4373
4374 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4375 throw new IllegalArgumentException("It should not exceed "
4376 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4377 }
4378
4379 mHandler.sendMessage(
4380 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4381 }
4382
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004383 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4384 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4385 " accept=" + accept + " always=" + always);
4386
4387 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4388 if (nai == null) {
4389 // Nothing to do.
4390 return;
4391 }
4392
4393 if (nai.everValidated) {
4394 // The network validated while the dialog box was up. Take no action.
4395 return;
4396 }
4397
4398 if (!nai.networkAgentConfig.explicitlySelected) {
4399 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4400 }
4401
4402 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4403 nai.networkAgentConfig.acceptUnvalidated = accept;
4404 // If network becomes partial connectivity and user already accepted to use this
4405 // network, we should respect the user's option and don't need to popup the
4406 // PARTIAL_CONNECTIVITY notification to user again.
4407 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4408 nai.updateScoreForNetworkAgentUpdate();
4409 rematchAllNetworksAndRequests();
4410 }
4411
4412 if (always) {
4413 nai.onSaveAcceptUnvalidated(accept);
4414 }
4415
4416 if (!accept) {
4417 // Tell the NetworkAgent to not automatically reconnect to the network.
4418 nai.onPreventAutomaticReconnect();
4419 // Teardown the network.
4420 teardownUnneededNetwork(nai);
4421 }
4422
4423 }
4424
4425 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4426 boolean always) {
4427 if (DBG) {
4428 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4429 + " always=" + always);
4430 }
4431
4432 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4433 if (nai == null) {
4434 // Nothing to do.
4435 return;
4436 }
4437
4438 if (nai.lastValidated) {
4439 // The network validated while the dialog box was up. Take no action.
4440 return;
4441 }
4442
4443 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4444 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4445 }
4446
4447 // TODO: Use the current design or save the user choice into IpMemoryStore.
4448 if (always) {
4449 nai.onSaveAcceptUnvalidated(accept);
4450 }
4451
4452 if (!accept) {
4453 // Tell the NetworkAgent to not automatically reconnect to the network.
4454 nai.onPreventAutomaticReconnect();
4455 // Tear down the network.
4456 teardownUnneededNetwork(nai);
4457 } else {
4458 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4459 // result in a partial connectivity result which will be processed by
4460 // maybeHandleNetworkMonitorMessage.
4461 //
4462 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4463 // per network. Therefore, NetworkMonitor may still do https probe.
4464 nai.networkMonitor().setAcceptPartialConnectivity();
4465 }
4466 }
4467
4468 private void handleSetAvoidUnvalidated(Network network) {
4469 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4470 if (nai == null || nai.lastValidated) {
4471 // Nothing to do. The network either disconnected or revalidated.
4472 return;
4473 }
4474 if (!nai.avoidUnvalidated) {
4475 nai.avoidUnvalidated = true;
4476 nai.updateScoreForNetworkAgentUpdate();
4477 rematchAllNetworksAndRequests();
4478 }
4479 }
4480
4481 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4482 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4483 mHandler.sendMessageDelayed(
4484 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4485 PROMPT_UNVALIDATED_DELAY_MS);
4486 }
4487
4488 @Override
4489 public void startCaptivePortalApp(Network network) {
4490 enforceNetworkStackOrSettingsPermission();
4491 mHandler.post(() -> {
4492 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4493 if (nai == null) return;
4494 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4495 nai.networkMonitor().launchCaptivePortalApp();
4496 });
4497 }
4498
4499 /**
4500 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4501 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4502 * @param network Network on which the captive portal was detected.
4503 * @param appExtras Bundle to use as intent extras for the captive portal application.
4504 * Must be treated as opaque to avoid preventing the captive portal app to
4505 * update its arguments.
4506 */
4507 @Override
4508 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4509 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4510 "ConnectivityService");
4511
4512 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4513 appIntent.putExtras(appExtras);
4514 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4515 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4516 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4517
4518 final long token = Binder.clearCallingIdentity();
4519 try {
4520 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4521 } finally {
4522 Binder.restoreCallingIdentity(token);
4523 }
4524 }
4525
4526 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4527 private final Network mNetwork;
4528
4529 private CaptivePortalImpl(Network network) {
4530 mNetwork = network;
4531 }
4532
4533 @Override
4534 public void appResponse(final int response) {
4535 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4536 enforceSettingsPermission();
4537 }
4538
4539 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4540 if (nm == null) return;
4541 nm.notifyCaptivePortalAppFinished(response);
4542 }
4543
4544 @Override
4545 public void appRequest(final int request) {
4546 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4547 if (nm == null) return;
4548
4549 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4550 checkNetworkStackPermission();
4551 nm.forceReevaluation(mDeps.getCallingUid());
4552 }
4553 }
4554
4555 @Nullable
4556 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4557 // getNetworkAgentInfoForNetwork is thread-safe
4558 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4559 if (nai == null) return null;
4560
4561 // nai.networkMonitor() is thread-safe
4562 return nai.networkMonitor();
4563 }
4564 }
4565
4566 public boolean avoidBadWifi() {
4567 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4568 }
4569
4570 /**
4571 * Return whether the device should maintain continuous, working connectivity by switching away
4572 * from WiFi networks having no connectivity.
4573 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4574 */
4575 public boolean shouldAvoidBadWifi() {
4576 if (!checkNetworkStackPermission()) {
4577 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4578 }
4579 return avoidBadWifi();
4580 }
4581
4582 private void updateAvoidBadWifi() {
4583 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4584 nai.updateScoreForNetworkAgentUpdate();
4585 }
4586 rematchAllNetworksAndRequests();
4587 }
4588
4589 // TODO: Evaluate whether this is of interest to other consumers of
4590 // MultinetworkPolicyTracker and worth moving out of here.
4591 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4592 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4593 if (!configRestrict) {
4594 pw.println("Bad Wi-Fi avoidance: unrestricted");
4595 return;
4596 }
4597
4598 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4599 pw.increaseIndent();
4600 pw.println("Config restrict: " + configRestrict);
4601
4602 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4603 String description;
4604 // Can't use a switch statement because strings are legal case labels, but null is not.
4605 if ("0".equals(value)) {
4606 description = "get stuck";
4607 } else if (value == null) {
4608 description = "prompt";
4609 } else if ("1".equals(value)) {
4610 description = "avoid";
4611 } else {
4612 description = value + " (?)";
4613 }
4614 pw.println("User setting: " + description);
4615 pw.println("Network overrides:");
4616 pw.increaseIndent();
4617 for (NetworkAgentInfo nai : networksSortedById()) {
4618 if (nai.avoidUnvalidated) {
4619 pw.println(nai.toShortString());
4620 }
4621 }
4622 pw.decreaseIndent();
4623 pw.decreaseIndent();
4624 }
4625
4626 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4627 // unify the method.
4628 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4629 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4630 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4631 return settingsComponent != null
4632 ? settingsComponent.getPackageName() : "com.android.settings";
4633 }
4634
4635 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4636 final String action;
4637 final boolean highPriority;
4638 switch (type) {
4639 case NO_INTERNET:
4640 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4641 // High priority because it is only displayed for explicitly selected networks.
4642 highPriority = true;
4643 break;
4644 case PRIVATE_DNS_BROKEN:
4645 action = Settings.ACTION_WIRELESS_SETTINGS;
4646 // High priority because we should let user know why there is no internet.
4647 highPriority = true;
4648 break;
4649 case LOST_INTERNET:
4650 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4651 // High priority because it could help the user avoid unexpected data usage.
4652 highPriority = true;
4653 break;
4654 case PARTIAL_CONNECTIVITY:
4655 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4656 // Don't bother the user with a high-priority notification if the network was not
4657 // explicitly selected by the user.
4658 highPriority = nai.networkAgentConfig.explicitlySelected;
4659 break;
4660 default:
4661 Log.wtf(TAG, "Unknown notification type " + type);
4662 return;
4663 }
4664
4665 Intent intent = new Intent(action);
4666 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4667 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4668 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4669 // Some OEMs have their own Settings package. Thus, need to get the current using
4670 // Settings package name instead of just use default name "com.android.settings".
4671 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4672 intent.setClassName(settingsPkgName,
4673 settingsPkgName + ".wifi.WifiNoInternetDialog");
4674 }
4675
4676 PendingIntent pendingIntent = PendingIntent.getActivity(
4677 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4678 0 /* requestCode */,
4679 intent,
4680 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4681
4682 mNotifier.showNotification(
4683 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4684 }
4685
4686 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4687 // Don't prompt if the network is validated, and don't prompt on captive portals
4688 // because we're already prompting the user to sign in.
4689 if (nai.everValidated || nai.everCaptivePortalDetected) {
4690 return false;
4691 }
4692
4693 // If a network has partial connectivity, always prompt unless the user has already accepted
4694 // partial connectivity and selected don't ask again. This ensures that if the device
4695 // automatically connects to a network that has partial Internet access, the user will
4696 // always be able to use it, either because they've already chosen "don't ask again" or
4697 // because we have prompt them.
4698 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4699 return true;
4700 }
4701
4702 // If a network has no Internet access, only prompt if the network was explicitly selected
4703 // and if the user has not already told us to use the network regardless of whether it
4704 // validated or not.
4705 if (nai.networkAgentConfig.explicitlySelected
4706 && !nai.networkAgentConfig.acceptUnvalidated) {
4707 return true;
4708 }
4709
4710 return false;
4711 }
4712
4713 private void handlePromptUnvalidated(Network network) {
4714 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4715 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4716
4717 if (nai == null || !shouldPromptUnvalidated(nai)) {
4718 return;
4719 }
4720
4721 // Stop automatically reconnecting to this network in the future. Automatically connecting
4722 // to a network that provides no or limited connectivity is not useful, because the user
4723 // cannot use that network except through the notification shown by this method, and the
4724 // notification is only shown if the network is explicitly selected by the user.
4725 nai.onPreventAutomaticReconnect();
4726
4727 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4728 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4729 // popup the notification immediately when the network is partial connectivity.
4730 if (nai.partialConnectivity) {
4731 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4732 } else {
4733 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4734 }
4735 }
4736
4737 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4738 NetworkCapabilities nc = nai.networkCapabilities;
4739 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4740
4741 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4742 return;
4743 }
4744
4745 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4746 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4747 }
4748 }
4749
4750 @Override
4751 public int getMultipathPreference(Network network) {
4752 enforceAccessPermission();
4753
4754 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4755 if (nai != null && nai.networkCapabilities
4756 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4757 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4758 }
4759
4760 final NetworkPolicyManager netPolicyManager =
4761 mContext.getSystemService(NetworkPolicyManager.class);
4762
4763 final long token = Binder.clearCallingIdentity();
4764 final int networkPreference;
4765 try {
4766 networkPreference = netPolicyManager.getMultipathPreference(network);
4767 } finally {
4768 Binder.restoreCallingIdentity(token);
4769 }
4770 if (networkPreference != 0) {
4771 return networkPreference;
4772 }
4773 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4774 }
4775
4776 @Override
4777 public NetworkRequest getDefaultRequest() {
4778 return mDefaultRequest.mRequests.get(0);
4779 }
4780
4781 private class InternalHandler extends Handler {
4782 public InternalHandler(Looper looper) {
4783 super(looper);
4784 }
4785
4786 @Override
4787 public void handleMessage(Message msg) {
4788 switch (msg.what) {
4789 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4790 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4791 handleReleaseNetworkTransitionWakelock(msg.what);
4792 break;
4793 }
4794 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4795 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4796 break;
4797 }
4798 case EVENT_PROXY_HAS_CHANGED: {
4799 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4800 handleApplyDefaultProxy(arg.second);
4801 break;
4802 }
4803 case EVENT_REGISTER_NETWORK_PROVIDER: {
4804 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4805 break;
4806 }
4807 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4808 handleUnregisterNetworkProvider((Messenger) msg.obj);
4809 break;
4810 }
4811 case EVENT_REGISTER_NETWORK_OFFER: {
4812 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4813 break;
4814 }
4815 case EVENT_UNREGISTER_NETWORK_OFFER: {
4816 final NetworkOfferInfo offer =
4817 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4818 if (null != offer) {
4819 handleUnregisterNetworkOffer(offer);
4820 }
4821 break;
4822 }
4823 case EVENT_REGISTER_NETWORK_AGENT: {
4824 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4825 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4826 handleRegisterNetworkAgent(arg.first, arg.second);
4827 break;
4828 }
4829 case EVENT_REGISTER_NETWORK_REQUEST:
4830 case EVENT_REGISTER_NETWORK_LISTENER: {
4831 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4832 break;
4833 }
4834 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4835 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4836 handleRegisterNetworkRequestWithIntent(msg);
4837 break;
4838 }
4839 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4840 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4841 handleTimedOutNetworkRequest(nri);
4842 break;
4843 }
4844 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4845 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4846 break;
4847 }
4848 case EVENT_RELEASE_NETWORK_REQUEST: {
4849 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4850 /* callOnUnavailable */ false);
4851 break;
4852 }
4853 case EVENT_SET_ACCEPT_UNVALIDATED: {
4854 Network network = (Network) msg.obj;
4855 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4856 break;
4857 }
4858 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4859 Network network = (Network) msg.obj;
4860 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4861 toBool(msg.arg2));
4862 break;
4863 }
4864 case EVENT_SET_AVOID_UNVALIDATED: {
4865 handleSetAvoidUnvalidated((Network) msg.obj);
4866 break;
4867 }
4868 case EVENT_PROMPT_UNVALIDATED: {
4869 handlePromptUnvalidated((Network) msg.obj);
4870 break;
4871 }
4872 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4873 handleConfigureAlwaysOnNetworks();
4874 break;
4875 }
4876 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4877 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4878 mKeepaliveTracker.handleStartKeepalive(msg);
4879 break;
4880 }
4881 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4882 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4883 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4884 int slot = msg.arg1;
4885 int reason = msg.arg2;
4886 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4887 break;
4888 }
4889 case EVENT_REVALIDATE_NETWORK: {
4890 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
4891 break;
4892 }
4893 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4894 handlePrivateDnsSettingsChanged();
4895 break;
4896 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4897 handlePrivateDnsValidationUpdate(
4898 (PrivateDnsValidationUpdate) msg.obj);
4899 break;
4900 case EVENT_UID_BLOCKED_REASON_CHANGED:
4901 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4902 break;
4903 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4904 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4905 break;
4906 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4907 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4908 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4909 handleSetOemNetworkPreference(arg.first, arg.second);
4910 break;
4911 }
4912 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4913 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4914 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4915 msg.obj;
4916 handleSetProfileNetworkPreference(arg.first, arg.second);
4917 break;
4918 }
4919 case EVENT_REPORT_NETWORK_ACTIVITY:
4920 mNetworkActivityTracker.handleReportNetworkActivity();
4921 break;
paulhu71ad4f12021-05-25 14:56:27 +08004922 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
4923 handleMobileDataPreferredUidsChanged();
4924 break;
Chiachang Wangfad30e32021-06-23 02:08:44 +00004925 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
4926 final long timeMs = ((Long) msg.obj).longValue();
4927 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
4928 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004929 }
4930 }
4931 }
4932
4933 @Override
4934 @Deprecated
4935 public int getLastTetherError(String iface) {
4936 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4937 Context.TETHERING_SERVICE);
4938 return tm.getLastTetherError(iface);
4939 }
4940
4941 @Override
4942 @Deprecated
4943 public String[] getTetherableIfaces() {
4944 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4945 Context.TETHERING_SERVICE);
4946 return tm.getTetherableIfaces();
4947 }
4948
4949 @Override
4950 @Deprecated
4951 public String[] getTetheredIfaces() {
4952 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4953 Context.TETHERING_SERVICE);
4954 return tm.getTetheredIfaces();
4955 }
4956
4957
4958 @Override
4959 @Deprecated
4960 public String[] getTetheringErroredIfaces() {
4961 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4962 Context.TETHERING_SERVICE);
4963
4964 return tm.getTetheringErroredIfaces();
4965 }
4966
4967 @Override
4968 @Deprecated
4969 public String[] getTetherableUsbRegexs() {
4970 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4971 Context.TETHERING_SERVICE);
4972
4973 return tm.getTetherableUsbRegexs();
4974 }
4975
4976 @Override
4977 @Deprecated
4978 public String[] getTetherableWifiRegexs() {
4979 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4980 Context.TETHERING_SERVICE);
4981 return tm.getTetherableWifiRegexs();
4982 }
4983
4984 // Called when we lose the default network and have no replacement yet.
4985 // This will automatically be cleared after X seconds or a new default network
4986 // becomes CONNECTED, whichever happens first. The timer is started by the
4987 // first caller and not restarted by subsequent callers.
4988 private void ensureNetworkTransitionWakelock(String forWhom) {
4989 synchronized (this) {
4990 if (mNetTransitionWakeLock.isHeld()) {
4991 return;
4992 }
4993 mNetTransitionWakeLock.acquire();
4994 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4995 mTotalWakelockAcquisitions++;
4996 }
4997 mWakelockLogs.log("ACQUIRE for " + forWhom);
4998 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4999 final int lockTimeout = mResources.get().getInteger(
5000 R.integer.config_networkTransitionTimeout);
5001 mHandler.sendMessageDelayed(msg, lockTimeout);
5002 }
5003
5004 // Called when we gain a new default network to release the network transition wakelock in a
5005 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5006 // message is cancelled.
5007 private void scheduleReleaseNetworkTransitionWakelock() {
5008 synchronized (this) {
5009 if (!mNetTransitionWakeLock.isHeld()) {
5010 return; // expiry message released the lock first.
5011 }
5012 }
5013 // Cancel self timeout on wakelock hold.
5014 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5015 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5016 mHandler.sendMessageDelayed(msg, 1000);
5017 }
5018
5019 // Called when either message of ensureNetworkTransitionWakelock or
5020 // scheduleReleaseNetworkTransitionWakelock is processed.
5021 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5022 String event = eventName(eventId);
5023 synchronized (this) {
5024 if (!mNetTransitionWakeLock.isHeld()) {
5025 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
5026 Log.w(TAG, "expected Net Transition WakeLock to be held");
5027 return;
5028 }
5029 mNetTransitionWakeLock.release();
5030 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5031 mTotalWakelockDurationMs += lockDuration;
5032 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5033 mTotalWakelockReleases++;
5034 }
5035 mWakelockLogs.log(String.format("RELEASE (%s)", event));
5036 }
5037
5038 // 100 percent is full good, 0 is full bad.
5039 @Override
5040 public void reportInetCondition(int networkType, int percentage) {
5041 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
5042 if (nai == null) return;
5043 reportNetworkConnectivity(nai.network, percentage > 50);
5044 }
5045
5046 @Override
5047 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
5048 enforceAccessPermission();
5049 enforceInternetPermission();
5050 final int uid = mDeps.getCallingUid();
5051 final int connectivityInfo = encodeBool(hasConnectivity);
5052
5053 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
5054 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
5055 // does not match the known connectivity of the network - this causes NetworkMonitor to
5056 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
5057 final NetworkAgentInfo nai;
5058 if (network == null) {
5059 nai = getDefaultNetwork();
5060 } else {
5061 nai = getNetworkAgentInfoForNetwork(network);
5062 }
5063 if (nai != null) {
5064 mConnectivityDiagnosticsHandler.sendMessage(
5065 mConnectivityDiagnosticsHandler.obtainMessage(
5066 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5067 connectivityInfo, 0, nai));
5068 }
5069
5070 mHandler.sendMessage(
5071 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
5072 }
5073
5074 private void handleReportNetworkConnectivity(
5075 Network network, int uid, boolean hasConnectivity) {
5076 final NetworkAgentInfo nai;
5077 if (network == null) {
5078 nai = getDefaultNetwork();
5079 } else {
5080 nai = getNetworkAgentInfoForNetwork(network);
5081 }
5082 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
5083 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
5084 return;
5085 }
5086 // Revalidate if the app report does not match our current validated state.
5087 if (hasConnectivity == nai.lastValidated) {
5088 return;
5089 }
5090 if (DBG) {
5091 int netid = nai.network.getNetId();
5092 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
5093 }
5094 // Validating a network that has not yet connected could result in a call to
5095 // rematchNetworkAndRequests() which is not meant to work on such networks.
5096 if (!nai.everConnected) {
5097 return;
5098 }
5099 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5100 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
5101 return;
5102 }
5103 nai.networkMonitor().forceReevaluation(uid);
5104 }
5105
5106 // TODO: call into netd.
5107 private boolean queryUserAccess(int uid, Network network) {
5108 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5109 if (nai == null) return false;
5110
5111 // Any UID can use its default network.
5112 if (nai == getDefaultNetworkForUid(uid)) return true;
5113
5114 // Privileged apps can use any network.
5115 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5116 return true;
5117 }
5118
5119 // An unprivileged UID can use a VPN iff the VPN applies to it.
5120 if (nai.isVPN()) {
5121 return nai.networkCapabilities.appliesToUid(uid);
5122 }
5123
5124 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5125 // sockets, i.e., if it is the owner.
5126 final NetworkAgentInfo vpn = getVpnForUid(uid);
5127 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5128 && uid != vpn.networkCapabilities.getOwnerUid()) {
5129 return false;
5130 }
5131
5132 // The UID's permission must be at least sufficient for the network. Since the restricted
5133 // permission was already checked above, that just leaves background networks.
5134 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5135 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5136 }
5137
5138 // Unrestricted network. Anyone gets to use it.
5139 return true;
5140 }
5141
5142 /**
5143 * Returns information about the proxy a certain network is using. If given a null network, it
5144 * it will return the proxy for the bound network for the caller app or the default proxy if
5145 * none.
5146 *
5147 * @param network the network we want to get the proxy information for.
5148 * @return Proxy information if a network has a proxy configured, or otherwise null.
5149 */
5150 @Override
5151 public ProxyInfo getProxyForNetwork(Network network) {
5152 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5153 if (globalProxy != null) return globalProxy;
5154 if (network == null) {
5155 // Get the network associated with the calling UID.
5156 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5157 true);
5158 if (activeNetwork == null) {
5159 return null;
5160 }
5161 return getLinkPropertiesProxyInfo(activeNetwork);
5162 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5163 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5164 // caller may not have.
5165 return getLinkPropertiesProxyInfo(network);
5166 }
5167 // No proxy info available if the calling UID does not have network access.
5168 return null;
5169 }
5170
5171
5172 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5173 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5174 if (nai == null) return null;
5175 synchronized (nai) {
5176 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5177 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5178 }
5179 }
5180
5181 @Override
5182 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5183 PermissionUtils.enforceNetworkStackPermission(mContext);
5184 mProxyTracker.setGlobalProxy(proxyProperties);
5185 }
5186
5187 @Override
5188 @Nullable
5189 public ProxyInfo getGlobalProxy() {
5190 return mProxyTracker.getGlobalProxy();
5191 }
5192
5193 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5194 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5195 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5196 proxy = null;
5197 }
5198 mProxyTracker.setDefaultProxy(proxy);
5199 }
5200
5201 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5202 // when any network changes proxy.
5203 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5204 // multi-network world where an app might be bound to a non-default network.
5205 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5206 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5207 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5208
5209 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5210 mProxyTracker.sendProxyBroadcast();
5211 }
5212 }
5213
5214 private static class SettingsObserver extends ContentObserver {
5215 final private HashMap<Uri, Integer> mUriEventMap;
5216 final private Context mContext;
5217 final private Handler mHandler;
5218
5219 SettingsObserver(Context context, Handler handler) {
5220 super(null);
5221 mUriEventMap = new HashMap<>();
5222 mContext = context;
5223 mHandler = handler;
5224 }
5225
5226 void observe(Uri uri, int what) {
5227 mUriEventMap.put(uri, what);
5228 final ContentResolver resolver = mContext.getContentResolver();
5229 resolver.registerContentObserver(uri, false, this);
5230 }
5231
5232 @Override
5233 public void onChange(boolean selfChange) {
5234 Log.wtf(TAG, "Should never be reached.");
5235 }
5236
5237 @Override
5238 public void onChange(boolean selfChange, Uri uri) {
5239 final Integer what = mUriEventMap.get(uri);
5240 if (what != null) {
5241 mHandler.obtainMessage(what).sendToTarget();
5242 } else {
5243 loge("No matching event to send for URI=" + uri);
5244 }
5245 }
5246 }
5247
5248 private static void log(String s) {
5249 Log.d(TAG, s);
5250 }
5251
5252 private static void logw(String s) {
5253 Log.w(TAG, s);
5254 }
5255
5256 private static void logwtf(String s) {
5257 Log.wtf(TAG, s);
5258 }
5259
5260 private static void logwtf(String s, Throwable t) {
5261 Log.wtf(TAG, s, t);
5262 }
5263
5264 private static void loge(String s) {
5265 Log.e(TAG, s);
5266 }
5267
5268 private static void loge(String s, Throwable t) {
5269 Log.e(TAG, s, t);
5270 }
5271
5272 /**
5273 * Return the information of all ongoing VPNs.
5274 *
5275 * <p>This method is used to update NetworkStatsService.
5276 *
5277 * <p>Must be called on the handler thread.
5278 */
5279 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5280 ensureRunningOnConnectivityServiceThread();
5281 if (mLockdownEnabled) {
5282 return new UnderlyingNetworkInfo[0];
5283 }
5284 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5285 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5286 UnderlyingNetworkInfo info = createVpnInfo(nai);
5287 if (info != null) {
5288 infoList.add(info);
5289 }
5290 }
5291 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5292 }
5293
5294 /**
5295 * @return VPN information for accounting, or null if we can't retrieve all required
5296 * information, e.g underlying ifaces.
5297 */
5298 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005299 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5300 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5301 // the underlyingNetworks list.
Treehugger Robot4703a8c2021-07-02 13:55:33 +00005302 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5303 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5304 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005305 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5306 nai.networkCapabilities.getOwnerUid());
5307 if (defaultNai != null) {
5308 underlyingNetworks = new Network[] { defaultNai.network };
5309 }
5310 }
5311
5312 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5313
5314 List<String> interfaces = new ArrayList<>();
5315 for (Network network : underlyingNetworks) {
5316 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5317 if (underlyingNai == null) continue;
5318 LinkProperties lp = underlyingNai.linkProperties;
5319 for (String iface : lp.getAllInterfaceNames()) {
5320 if (!TextUtils.isEmpty(iface)) {
5321 interfaces.add(iface);
5322 }
5323 }
5324 }
5325
5326 if (interfaces.isEmpty()) return null;
5327
5328 // Must be non-null or NetworkStatsService will crash.
5329 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5330 // tun or ipsec interface is created.
5331 // TODO: Remove this check.
5332 if (nai.linkProperties.getInterfaceName() == null) return null;
5333
5334 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5335 nai.linkProperties.getInterfaceName(), interfaces);
5336 }
5337
5338 // TODO This needs to be the default network that applies to the NAI.
5339 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5340 Network[] underlyingNetworks) {
5341 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5342 if (underlyingNetworks == null && defaultNetwork != null) {
5343 // null underlying networks means to track the default.
5344 underlyingNetworks = new Network[] { defaultNetwork };
5345 }
5346 return underlyingNetworks;
5347 }
5348
5349 // Returns true iff |network| is an underlying network of |nai|.
5350 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5351 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5352 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Treehugger Robot4703a8c2021-07-02 13:55:33 +00005353 if (!nai.propagateUnderlyingCapabilities()) return false;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005354 final Network[] underlying = underlyingNetworksOrDefault(
5355 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5356 return CollectionUtils.contains(underlying, network);
5357 }
5358
5359 /**
5360 * Recompute the capabilities for any networks that had a specific network as underlying.
5361 *
5362 * When underlying networks change, such networks may have to update capabilities to reflect
5363 * things like the metered bit, their transports, and so on. The capabilities are calculated
5364 * immediately. This method runs on the ConnectivityService thread.
5365 */
5366 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5367 ensureRunningOnConnectivityServiceThread();
5368 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5369 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5370 updateCapabilitiesForNetwork(nai);
5371 }
5372 }
5373 }
5374
5375 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5376 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5377 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5378 // a VPN is not up.
5379 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5380 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5381 for (UidRange range : blockedUidRanges) {
5382 if (range.contains(uid)) return true;
5383 }
5384 return false;
5385 }
5386
5387 @Override
5388 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5389 enforceNetworkStackOrSettingsPermission();
5390 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5391 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5392 }
5393
5394 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5395 if (DBG) {
5396 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5397 + Arrays.toString(ranges));
5398 }
5399 // Cannot use a Set since the list of UID ranges might contain duplicates.
5400 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5401 for (int i = 0; i < ranges.length; i++) {
5402 if (requireVpn) {
5403 newVpnBlockedUidRanges.add(ranges[i]);
5404 } else {
5405 newVpnBlockedUidRanges.remove(ranges[i]);
5406 }
5407 }
5408
5409 try {
5410 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5411 } catch (RemoteException | ServiceSpecificException e) {
5412 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5413 + Arrays.toString(ranges) + "): netd command failed: " + e);
5414 }
5415
5416 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5417 final boolean curMetered = nai.networkCapabilities.isMetered();
5418 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5419 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5420 }
5421
5422 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5423 }
5424
5425 @Override
5426 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5427 enforceNetworkStackOrSettingsPermission();
5428 mHandler.post(() -> mLockdownEnabled = enabled);
5429 }
5430
5431 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5432 return mLockdownEnabled
5433 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5434 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5435 }
5436
5437 private NetworkAgentInfo getLegacyLockdownNai() {
5438 if (!mLockdownEnabled) {
5439 return null;
5440 }
5441 // The legacy lockdown VPN always only applies to userId 0.
5442 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5443 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5444
5445 // The legacy lockdown VPN must always have exactly one underlying network.
5446 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5447 // a local variable. There is no need to make a copy because its contents cannot change.
5448 final Network[] underlying = nai.declaredUnderlyingNetworks;
5449 if (underlying == null || underlying.length != 1) {
5450 return null;
5451 }
5452
5453 // The legacy lockdown VPN always uses the default network.
5454 // If the VPN's underlying network is no longer the current default network, it means that
5455 // the default network has just switched, and the VPN is about to disconnect.
5456 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5457 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5458 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5459 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5460 return null;
5461 }
5462
5463 return nai;
5464 };
5465
5466 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5467 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5468 // just a DetailedState object.
5469 private DetailedState getLegacyLockdownState(DetailedState origState) {
5470 if (origState != DetailedState.CONNECTED) {
5471 return origState;
5472 }
5473 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5474 ? DetailedState.CONNECTING
5475 : DetailedState.CONNECTED;
5476 }
5477
5478 private void filterForLegacyLockdown(NetworkInfo ni) {
5479 if (!mLockdownEnabled || !ni.isConnected()) return;
5480 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5481 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5482 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5483 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5484 // network, this time with a state of CONNECTED.
5485 //
5486 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5487 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5488 // is not too far off the truth, since an always-on VPN, when not connected, is always
5489 // trying to reconnect.
5490 if (getLegacyLockdownNai() == null) {
5491 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5492 }
5493 }
5494
5495 @Override
5496 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5497 String action) {
5498 enforceSettingsPermission();
5499 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5500 return;
5501 }
5502 final long ident = Binder.clearCallingIdentity();
5503 try {
5504 // Concatenate the range of types onto the range of NetIDs.
5505 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5506 mNotifier.setProvNotificationVisible(visible, id, action);
5507 } finally {
5508 Binder.restoreCallingIdentity(ident);
5509 }
5510 }
5511
5512 @Override
5513 public void setAirplaneMode(boolean enable) {
5514 enforceAirplaneModePermission();
5515 final long ident = Binder.clearCallingIdentity();
5516 try {
5517 final ContentResolver cr = mContext.getContentResolver();
5518 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5519 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5520 intent.putExtra("state", enable);
5521 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5522 } finally {
5523 Binder.restoreCallingIdentity(ident);
5524 }
5525 }
5526
5527 private void onUserAdded(@NonNull final UserHandle user) {
5528 mPermissionMonitor.onUserAdded(user);
5529 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5530 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5531 }
5532 }
5533
5534 private void onUserRemoved(@NonNull final UserHandle user) {
5535 mPermissionMonitor.onUserRemoved(user);
5536 // If there was a network preference for this user, remove it.
5537 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5538 null /* listener */);
5539 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5540 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5541 }
5542 }
5543
5544 private void onPackageChanged(@NonNull final String packageName) {
5545 // This is necessary in case a package is added or removed, but also when it's replaced to
5546 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5547 // as one in the preferences, then it should follow the same routing as that other package,
5548 // which means updating the rules is never to be needed in this case (whether it joins or
5549 // leaves a UID with a preference).
5550 if (isMappedInOemNetworkPreference(packageName)) {
5551 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5552 }
5553 }
5554
5555 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5556 @Override
5557 public void onReceive(Context context, Intent intent) {
5558 ensureRunningOnConnectivityServiceThread();
5559 final String action = intent.getAction();
5560 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5561
5562 // User should be filled for below intents, check the existence.
5563 if (user == null) {
5564 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5565 return;
5566 }
5567
5568 if (Intent.ACTION_USER_ADDED.equals(action)) {
5569 onUserAdded(user);
5570 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5571 onUserRemoved(user);
5572 } else {
5573 Log.wtf(TAG, "received unexpected intent: " + action);
5574 }
5575 }
5576 };
5577
5578 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5579 @Override
5580 public void onReceive(Context context, Intent intent) {
5581 ensureRunningOnConnectivityServiceThread();
5582 switch (intent.getAction()) {
5583 case Intent.ACTION_PACKAGE_ADDED:
5584 case Intent.ACTION_PACKAGE_REMOVED:
5585 case Intent.ACTION_PACKAGE_REPLACED:
5586 onPackageChanged(intent.getData().getSchemeSpecificPart());
5587 break;
5588 default:
5589 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5590 }
5591 }
5592 };
5593
5594 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5595 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5596
5597 private static class NetworkProviderInfo {
5598 public final String name;
5599 public final Messenger messenger;
5600 private final IBinder.DeathRecipient mDeathRecipient;
5601 public final int providerId;
5602
5603 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5604 @NonNull IBinder.DeathRecipient deathRecipient) {
5605 this.name = name;
5606 this.messenger = messenger;
5607 this.providerId = providerId;
5608 mDeathRecipient = deathRecipient;
5609
5610 if (mDeathRecipient == null) {
5611 throw new AssertionError("Must pass a deathRecipient");
5612 }
5613 }
5614
5615 void connect(Context context, Handler handler) {
5616 try {
5617 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5618 } catch (RemoteException e) {
5619 mDeathRecipient.binderDied();
5620 }
5621 }
5622 }
5623
5624 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5625 for (int i = 0; i < requests.size(); i++) {
5626 ensureNetworkRequestHasType(requests.get(i));
5627 }
5628 }
5629
5630 private void ensureNetworkRequestHasType(NetworkRequest request) {
5631 if (request.type == NetworkRequest.Type.NONE) {
5632 throw new IllegalArgumentException(
5633 "All NetworkRequests in ConnectivityService must have a type");
5634 }
5635 }
5636
5637 /**
5638 * Tracks info about the requester.
5639 * Also used to notice when the calling process dies so as to self-expire
5640 */
5641 @VisibleForTesting
5642 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5643 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5644 // single NetworkRequest in mRequests.
5645 final List<NetworkRequest> mRequests;
5646
5647 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5648 void setSatisfier(
5649 @Nullable final NetworkAgentInfo satisfier,
5650 @Nullable final NetworkRequest activeRequest) {
5651 mSatisfier = satisfier;
5652 mActiveRequest = activeRequest;
5653 }
5654
5655 // The network currently satisfying this NRI. Only one request in an NRI can have a
5656 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5657 @Nullable
5658 private NetworkAgentInfo mSatisfier;
5659 NetworkAgentInfo getSatisfier() {
5660 return mSatisfier;
5661 }
5662
5663 // The request in mRequests assigned to a network agent. This is null if none of the
5664 // requests in mRequests can be satisfied. This member has the constraint of only being
5665 // accessible on the handler thread.
5666 @Nullable
5667 private NetworkRequest mActiveRequest;
5668 NetworkRequest getActiveRequest() {
5669 return mActiveRequest;
5670 }
5671
5672 final PendingIntent mPendingIntent;
5673 boolean mPendingIntentSent;
5674 @Nullable
5675 final Messenger mMessenger;
5676
5677 // Information about the caller that caused this object to be created.
5678 @Nullable
5679 private final IBinder mBinder;
5680 final int mPid;
5681 final int mUid;
5682 final @NetworkCallback.Flag int mCallbackFlags;
5683 @Nullable
5684 final String mCallingAttributionTag;
5685
5686 // Counter keeping track of this NRI.
5687 final PerUidCounter mPerUidCounter;
5688
5689 // Effective UID of this request. This is different from mUid when a privileged process
5690 // files a request on behalf of another UID. This UID is used to determine blocked status,
5691 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5692 // maximum limit of registered callbacks per UID.
5693 final int mAsUid;
5694
paulhuc2198772021-05-26 15:19:20 +08005695 // Default network priority of this request.
paulhude5efb92021-05-26 21:56:03 +08005696 final int mPreferencePriority;
paulhuc2198772021-05-26 15:19:20 +08005697
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005698 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5699 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5700 // maintained for keying off of. This is only a concern when the original nri
5701 // mNetworkRequests changes which happens currently for apps that register callbacks to
5702 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5703 // that match the per-app default nri that currently tracks the calling app's uid so that
5704 // callbacks are fired at the appropriate time. When the callbacks fire,
5705 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5706 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5707 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5708 @NonNull
5709 private final NetworkRequest mNetworkRequestForCallback;
5710 NetworkRequest getNetworkRequestForCallback() {
5711 return mNetworkRequestForCallback;
5712 }
5713
5714 /**
5715 * Get the list of UIDs this nri applies to.
5716 */
5717 @NonNull
paulhu71ad4f12021-05-25 14:56:27 +08005718 Set<UidRange> getUids() {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005719 // networkCapabilities.getUids() returns a defensive copy.
5720 // multilayer requests will all have the same uids so return the first one.
5721 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5722 return (null == uids) ? new ArraySet<>() : uids;
5723 }
5724
5725 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5726 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhuc2198772021-05-26 15:19:20 +08005727 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhude5efb92021-05-26 21:56:03 +08005728 PREFERENCE_PRIORITY_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005729 }
5730
5731 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5732 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhude5efb92021-05-26 21:56:03 +08005733 @Nullable String callingAttributionTag, final int preferencePriority) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005734 ensureAllNetworkRequestsHaveType(r);
5735 mRequests = initializeRequests(r);
5736 mNetworkRequestForCallback = requestForCallback;
5737 mPendingIntent = pi;
5738 mMessenger = null;
5739 mBinder = null;
5740 mPid = getCallingPid();
5741 mUid = mDeps.getCallingUid();
5742 mAsUid = asUid;
5743 mPerUidCounter = getRequestCounter(this);
5744 mPerUidCounter.incrementCountOrThrow(mUid);
5745 /**
5746 * Location sensitive data not included in pending intent. Only included in
5747 * {@link NetworkCallback}.
5748 */
5749 mCallbackFlags = NetworkCallback.FLAG_NONE;
5750 mCallingAttributionTag = callingAttributionTag;
paulhude5efb92021-05-26 21:56:03 +08005751 mPreferencePriority = preferencePriority;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005752 }
5753
5754 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5755 @Nullable final IBinder binder,
5756 @NetworkCallback.Flag int callbackFlags,
5757 @Nullable String callingAttributionTag) {
5758 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5759 callingAttributionTag);
5760 }
5761
5762 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5763 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5764 @Nullable final IBinder binder,
5765 @NetworkCallback.Flag int callbackFlags,
5766 @Nullable String callingAttributionTag) {
5767 super();
5768 ensureAllNetworkRequestsHaveType(r);
5769 mRequests = initializeRequests(r);
5770 mNetworkRequestForCallback = requestForCallback;
5771 mMessenger = m;
5772 mBinder = binder;
5773 mPid = getCallingPid();
5774 mUid = mDeps.getCallingUid();
5775 mAsUid = asUid;
5776 mPendingIntent = null;
5777 mPerUidCounter = getRequestCounter(this);
5778 mPerUidCounter.incrementCountOrThrow(mUid);
5779 mCallbackFlags = callbackFlags;
5780 mCallingAttributionTag = callingAttributionTag;
paulhude5efb92021-05-26 21:56:03 +08005781 mPreferencePriority = PREFERENCE_PRIORITY_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005782 linkDeathRecipient();
5783 }
5784
5785 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5786 @NonNull final List<NetworkRequest> r) {
5787 super();
5788 ensureAllNetworkRequestsHaveType(r);
5789 mRequests = initializeRequests(r);
5790 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5791 final NetworkAgentInfo satisfier = nri.getSatisfier();
5792 if (null != satisfier) {
5793 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5794 // The active request is necessary to figure out what callbacks to send, in
5795 // particular then a network updates its capabilities.
5796 // As this code creates a new NRI with a new set of requests, figure out which of
5797 // the list of requests should be the active request. It is always the first
5798 // request of the list that can be satisfied by the satisfier since the order of
5799 // requests is a priority order.
5800 // Note even in the presence of a satisfier there may not be an active request,
5801 // when the satisfier is the no-service network.
5802 NetworkRequest activeRequest = null;
5803 for (final NetworkRequest candidate : r) {
5804 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5805 activeRequest = candidate;
5806 break;
5807 }
5808 }
5809 setSatisfier(satisfier, activeRequest);
5810 }
5811 mMessenger = nri.mMessenger;
5812 mBinder = nri.mBinder;
5813 mPid = nri.mPid;
5814 mUid = nri.mUid;
5815 mAsUid = nri.mAsUid;
5816 mPendingIntent = nri.mPendingIntent;
5817 mPerUidCounter = getRequestCounter(this);
5818 mPerUidCounter.incrementCountOrThrow(mUid);
5819 mCallbackFlags = nri.mCallbackFlags;
5820 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhude5efb92021-05-26 21:56:03 +08005821 mPreferencePriority = PREFERENCE_PRIORITY_INVALID;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005822 linkDeathRecipient();
5823 }
5824
5825 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhude5efb92021-05-26 21:56:03 +08005826 this(asUid, Collections.singletonList(r), PREFERENCE_PRIORITY_INVALID);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005827 }
5828
paulhuc2198772021-05-26 15:19:20 +08005829 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhude5efb92021-05-26 21:56:03 +08005830 final int preferencePriority) {
paulhuc2198772021-05-26 15:19:20 +08005831 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhude5efb92021-05-26 21:56:03 +08005832 preferencePriority);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005833 }
5834
5835 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5836 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5837 // false.
5838 boolean isBeingSatisfied() {
5839 return (null != mSatisfier && null != mActiveRequest);
5840 }
5841
5842 boolean isMultilayerRequest() {
5843 return mRequests.size() > 1;
5844 }
5845
5846 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5847 // Creating a defensive copy to prevent the sender from modifying the list being
5848 // reflected in the return value of this method.
5849 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5850 return Collections.unmodifiableList(tempRequests);
5851 }
5852
5853 void decrementRequestCount() {
5854 mPerUidCounter.decrementCount(mUid);
5855 }
5856
5857 void linkDeathRecipient() {
5858 if (null != mBinder) {
5859 try {
5860 mBinder.linkToDeath(this, 0);
5861 } catch (RemoteException e) {
5862 binderDied();
5863 }
5864 }
5865 }
5866
5867 void unlinkDeathRecipient() {
5868 if (null != mBinder) {
5869 mBinder.unlinkToDeath(this, 0);
5870 }
5871 }
5872
paulhude5efb92021-05-26 21:56:03 +08005873 boolean hasHigherPriorityThan(@NonNull final NetworkRequestInfo target) {
5874 // Compare two priorities, larger value means lower priority.
5875 return mPreferencePriority < target.mPreferencePriority;
5876 }
5877
5878 int getPriorityForNetd() {
5879 if (mPreferencePriority >= PREFERENCE_PRIORITY_NONE
5880 && mPreferencePriority <= PREFERENCE_PRIORITY_LOWEST) {
5881 return mPreferencePriority;
5882 }
5883 return PREFERENCE_PRIORITY_NONE;
5884 }
5885
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005886 @Override
5887 public void binderDied() {
5888 log("ConnectivityService NetworkRequestInfo binderDied(" +
5889 mRequests + ", " + mBinder + ")");
5890 releaseNetworkRequests(mRequests);
5891 }
5892
5893 @Override
5894 public String toString() {
5895 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5896 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5897 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5898 + " callbackRequest: "
5899 + mNetworkRequestForCallback.requestId
5900 + " " + mRequests
5901 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhude5efb92021-05-26 21:56:03 +08005902 + " callback flags: " + mCallbackFlags
5903 + " priority: " + mPreferencePriority;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005904 }
5905 }
5906
5907 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5908 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5909 if (badCapability != null) {
5910 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5911 }
5912 }
5913
5914 // This checks that the passed capabilities either do not request a
5915 // specific SSID/SignalStrength, or the calling app has permission to do so.
5916 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5917 int callerPid, int callerUid, String callerPackageName) {
5918 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5919 throw new SecurityException("Insufficient permissions to request a specific SSID");
5920 }
5921
5922 if (nc.hasSignalStrength()
5923 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5924 throw new SecurityException(
5925 "Insufficient permissions to request a specific signal strength");
5926 }
5927 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5928
5929 if (!nc.getSubscriptionIds().isEmpty()) {
5930 enforceNetworkFactoryPermission();
5931 }
5932 }
5933
5934 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5935 final SortedSet<Integer> thresholds = new TreeSet<>();
5936 synchronized (nai) {
5937 // mNetworkRequests may contain the same value multiple times in case of
5938 // multilayer requests. It won't matter in this case because the thresholds
5939 // will then be the same and be deduplicated as they enter the `thresholds` set.
5940 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5941 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5942 for (final NetworkRequest req : nri.mRequests) {
5943 if (req.networkCapabilities.hasSignalStrength()
5944 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5945 thresholds.add(req.networkCapabilities.getSignalStrength());
5946 }
5947 }
5948 }
5949 }
5950 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5951 }
5952
5953 private void updateSignalStrengthThresholds(
5954 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5955 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5956
5957 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5958 String detail;
5959 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5960 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5961 } else {
5962 detail = reason;
5963 }
5964 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5965 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5966 }
5967
5968 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5969 }
5970
5971 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5972 if (nc == null) {
5973 return;
5974 }
5975 NetworkSpecifier ns = nc.getNetworkSpecifier();
5976 if (ns == null) {
5977 return;
5978 }
5979 if (ns instanceof MatchAllNetworkSpecifier) {
5980 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5981 }
5982 }
5983
5984 private void ensureValid(NetworkCapabilities nc) {
5985 ensureValidNetworkSpecifier(nc);
5986 if (nc.isPrivateDnsBroken()) {
5987 throw new IllegalArgumentException("Can't request broken private DNS");
5988 }
5989 }
5990
5991 private boolean isTargetSdkAtleast(int version, int callingUid,
5992 @NonNull String callingPackageName) {
5993 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
5994 final PackageManager pm =
5995 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
5996 try {
5997 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
5998 if (callingVersion < version) return false;
5999 } catch (PackageManager.NameNotFoundException e) { }
6000 return true;
6001 }
6002
6003 @Override
6004 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
6005 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
6006 int legacyType, int callbackFlags, @NonNull String callingPackageName,
6007 @Nullable String callingAttributionTag) {
6008 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
6009 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6010 callingPackageName)) {
6011 throw new SecurityException("Insufficient permissions to specify legacy type");
6012 }
6013 }
6014 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
6015 final int callingUid = mDeps.getCallingUid();
6016 // Privileged callers can track the default network of another UID by passing in a UID.
6017 if (asUid != Process.INVALID_UID) {
6018 enforceSettingsPermission();
6019 } else {
6020 asUid = callingUid;
6021 }
6022 final NetworkRequest.Type reqType;
6023 try {
6024 reqType = NetworkRequest.Type.values()[reqTypeInt];
6025 } catch (ArrayIndexOutOfBoundsException e) {
6026 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6027 }
6028 switch (reqType) {
6029 case TRACK_DEFAULT:
6030 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
6031 // is unused and will be replaced by ones appropriate for the UID (usually, the
6032 // calling app). This allows callers to keep track of the default network.
6033 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
6034 defaultNc, asUid, callingUid, callingPackageName);
6035 enforceAccessPermission();
6036 break;
6037 case TRACK_SYSTEM_DEFAULT:
6038 enforceSettingsPermission();
6039 networkCapabilities = new NetworkCapabilities(defaultNc);
6040 break;
6041 case BACKGROUND_REQUEST:
6042 enforceNetworkStackOrSettingsPermission();
6043 // Fall-through since other checks are the same with normal requests.
6044 case REQUEST:
6045 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6046 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6047 callingAttributionTag);
6048 // TODO: this is incorrect. We mark the request as metered or not depending on
6049 // the state of the app when the request is filed, but we never change the
6050 // request if the app changes network state. http://b/29964605
6051 enforceMeteredApnPolicy(networkCapabilities);
6052 break;
6053 case LISTEN_FOR_BEST:
6054 enforceAccessPermission();
6055 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6056 break;
6057 default:
6058 throw new IllegalArgumentException("Unsupported request type " + reqType);
6059 }
6060 ensureRequestableCapabilities(networkCapabilities);
6061 ensureSufficientPermissionsForRequest(networkCapabilities,
6062 Binder.getCallingPid(), callingUid, callingPackageName);
6063
6064 // Enforce FOREGROUND if the caller does not have permission to use background network.
6065 if (reqType == LISTEN_FOR_BEST) {
6066 restrictBackgroundRequestForCaller(networkCapabilities);
6067 }
6068
6069 // Set the UID range for this request to the single UID of the requester, unless the
6070 // requester has the permission to specify other UIDs.
6071 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6072 // are no visible methods to set the UIDs, an app could use reflection to try and get
6073 // networks for other apps so it's essential that the UIDs are overwritten.
6074 // Also set the requester UID and package name in the request.
6075 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6076 callingUid, callingPackageName);
6077
6078 if (timeoutMs < 0) {
6079 throw new IllegalArgumentException("Bad timeout specified");
6080 }
6081 ensureValid(networkCapabilities);
6082
6083 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
6084 nextNetworkRequestId(), reqType);
6085 final NetworkRequestInfo nri = getNriToRegister(
6086 asUid, networkRequest, messenger, binder, callbackFlags,
6087 callingAttributionTag);
6088 if (DBG) log("requestNetwork for " + nri);
6089
6090 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6091 // copied from the default request above. (This is necessary to ensure, for example, that
6092 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6093 // changes don't alter request matching.
6094 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6095 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
6096 throw new IllegalStateException(
6097 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
6098 + networkCapabilities + " vs. " + defaultNc);
6099 }
6100
6101 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
6102 if (timeoutMs > 0) {
6103 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
6104 nri), timeoutMs);
6105 }
6106 return networkRequest;
6107 }
6108
6109 /**
6110 * Return the nri to be used when registering a network request. Specifically, this is used with
6111 * requests registered to track the default request. If there is currently a per-app default
6112 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6113 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
6114 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6115 * when a privileged caller is tracking the default network for another uid.
6116 * @param nr the network request for the nri.
6117 * @param msgr the messenger for the nri.
6118 * @param binder the binder for the nri.
6119 * @param callingAttributionTag the calling attribution tag for the nri.
6120 * @return the nri to register.
6121 */
6122 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6123 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6124 @NetworkCallback.Flag int callbackFlags,
6125 @Nullable String callingAttributionTag) {
6126 final List<NetworkRequest> requests;
6127 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6128 requests = copyDefaultNetworkRequestsForUid(
6129 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6130 } else {
6131 requests = Collections.singletonList(nr);
6132 }
6133 return new NetworkRequestInfo(
6134 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6135 }
6136
6137 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6138 String callingPackageName, String callingAttributionTag) {
6139 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6140 enforceConnectivityRestrictedNetworksPermission();
6141 } else {
6142 enforceChangePermission(callingPackageName, callingAttributionTag);
6143 }
6144 }
6145
6146 @Override
6147 public boolean requestBandwidthUpdate(Network network) {
6148 enforceAccessPermission();
6149 NetworkAgentInfo nai = null;
6150 if (network == null) {
6151 return false;
6152 }
6153 synchronized (mNetworkForNetId) {
6154 nai = mNetworkForNetId.get(network.getNetId());
6155 }
6156 if (nai != null) {
6157 nai.onBandwidthUpdateRequested();
6158 synchronized (mBandwidthRequests) {
6159 final int uid = mDeps.getCallingUid();
6160 Integer uidReqs = mBandwidthRequests.get(uid);
6161 if (uidReqs == null) {
6162 uidReqs = 0;
6163 }
6164 mBandwidthRequests.put(uid, ++uidReqs);
6165 }
6166 return true;
6167 }
6168 return false;
6169 }
6170
6171 private boolean isSystem(int uid) {
6172 return uid < Process.FIRST_APPLICATION_UID;
6173 }
6174
6175 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6176 final int uid = mDeps.getCallingUid();
6177 if (isSystem(uid)) {
6178 // Exemption for system uid.
6179 return;
6180 }
6181 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6182 // Policy already enforced.
6183 return;
6184 }
6185 final long ident = Binder.clearCallingIdentity();
6186 try {
6187 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6188 // If UID is restricted, don't allow them to bring up metered APNs.
6189 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6190 }
6191 } finally {
6192 Binder.restoreCallingIdentity(ident);
6193 }
6194 }
6195
6196 @Override
6197 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6198 PendingIntent operation, @NonNull String callingPackageName,
6199 @Nullable String callingAttributionTag) {
6200 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6201 final int callingUid = mDeps.getCallingUid();
6202 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6203 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6204 callingAttributionTag);
6205 enforceMeteredApnPolicy(networkCapabilities);
6206 ensureRequestableCapabilities(networkCapabilities);
6207 ensureSufficientPermissionsForRequest(networkCapabilities,
6208 Binder.getCallingPid(), callingUid, callingPackageName);
6209 ensureValidNetworkSpecifier(networkCapabilities);
6210 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6211 callingUid, callingPackageName);
6212
6213 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6214 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6215 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6216 callingAttributionTag);
6217 if (DBG) log("pendingRequest for " + nri);
6218 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6219 nri));
6220 return networkRequest;
6221 }
6222
6223 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6224 mHandler.sendMessageDelayed(
6225 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6226 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6227 }
6228
6229 @Override
6230 public void releasePendingNetworkRequest(PendingIntent operation) {
6231 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6233 mDeps.getCallingUid(), 0, operation));
6234 }
6235
6236 // In order to implement the compatibility measure for pre-M apps that call
6237 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6238 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6239 // This ensures it has permission to do so.
6240 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6241 if (nc == null) {
6242 return false;
6243 }
6244 int[] transportTypes = nc.getTransportTypes();
6245 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6246 return false;
6247 }
6248 try {
6249 mContext.enforceCallingOrSelfPermission(
6250 android.Manifest.permission.ACCESS_WIFI_STATE,
6251 "ConnectivityService");
6252 } catch (SecurityException e) {
6253 return false;
6254 }
6255 return true;
6256 }
6257
6258 @Override
6259 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6260 Messenger messenger, IBinder binder,
6261 @NetworkCallback.Flag int callbackFlags,
6262 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6263 final int callingUid = mDeps.getCallingUid();
6264 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6265 enforceAccessPermission();
6266 }
6267
6268 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6269 ensureSufficientPermissionsForRequest(networkCapabilities,
6270 Binder.getCallingPid(), callingUid, callingPackageName);
6271 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6272 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6273 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6274 // onLost and onAvailable callbacks when networks move in and out of the background.
6275 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6276 // can't request networks.
6277 restrictBackgroundRequestForCaller(nc);
6278 ensureValid(nc);
6279
6280 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6281 NetworkRequest.Type.LISTEN);
6282 NetworkRequestInfo nri =
6283 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6284 callingAttributionTag);
6285 if (VDBG) log("listenForNetwork for " + nri);
6286
6287 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6288 return networkRequest;
6289 }
6290
6291 @Override
6292 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6293 PendingIntent operation, @NonNull String callingPackageName,
6294 @Nullable String callingAttributionTag) {
6295 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6296 final int callingUid = mDeps.getCallingUid();
6297 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6298 enforceAccessPermission();
6299 }
6300 ensureValid(networkCapabilities);
6301 ensureSufficientPermissionsForRequest(networkCapabilities,
6302 Binder.getCallingPid(), callingUid, callingPackageName);
6303 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6304 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6305
6306 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6307 NetworkRequest.Type.LISTEN);
6308 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6309 callingAttributionTag);
6310 if (VDBG) log("pendingListenForNetwork for " + nri);
6311
Treehugger Robot282f7432021-06-30 21:59:16 +00006312 mHandler.sendMessage(mHandler.obtainMessage(
6313 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006314 }
6315
6316 /** Returns the next Network provider ID. */
6317 public final int nextNetworkProviderId() {
6318 return mNextNetworkProviderId.getAndIncrement();
6319 }
6320
6321 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
6322 for (int i = 0; i < networkRequests.size(); i++) {
6323 releaseNetworkRequest(networkRequests.get(i));
6324 }
6325 }
6326
6327 @Override
6328 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6329 ensureNetworkRequestHasType(networkRequest);
6330 mHandler.sendMessage(mHandler.obtainMessage(
6331 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6332 }
6333
6334 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6335 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6336 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6337 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6338 // as that will throw if a duplicate provider is registered.
6339 loge("Attempt to register existing NetworkProviderInfo "
6340 + mNetworkProviderInfos.get(npi.messenger).name);
6341 return;
6342 }
6343
6344 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6345 mNetworkProviderInfos.put(npi.messenger, npi);
6346 npi.connect(mContext, mTrackerHandler);
6347 }
6348
6349 @Override
6350 public int registerNetworkProvider(Messenger messenger, String name) {
6351 enforceNetworkFactoryOrSettingsPermission();
6352 Objects.requireNonNull(messenger, "messenger must be non-null");
6353 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6354 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6355 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6356 return npi.providerId;
6357 }
6358
6359 @Override
6360 public void unregisterNetworkProvider(Messenger messenger) {
6361 enforceNetworkFactoryOrSettingsPermission();
6362 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6363 }
6364
6365 @Override
6366 public void offerNetwork(final int providerId,
6367 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6368 @NonNull final INetworkOfferCallback callback) {
6369 Objects.requireNonNull(score);
6370 Objects.requireNonNull(caps);
6371 Objects.requireNonNull(callback);
6372 final NetworkOffer offer = new NetworkOffer(
6373 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6374 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6375 }
6376
6377 @Override
6378 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6379 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6380 }
6381
6382 private void handleUnregisterNetworkProvider(Messenger messenger) {
6383 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6384 if (npi == null) {
6385 loge("Failed to find Messenger in unregisterNetworkProvider");
6386 return;
6387 }
6388 // Unregister all the offers from this provider
6389 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6390 for (final NetworkOfferInfo noi : mNetworkOffers) {
6391 if (noi.offer.providerId == npi.providerId) {
6392 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6393 toRemove.add(noi);
6394 }
6395 }
6396 for (final NetworkOfferInfo noi : toRemove) {
6397 handleUnregisterNetworkOffer(noi);
6398 }
6399 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6400 }
6401
6402 @Override
6403 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6404 if (request.hasTransport(TRANSPORT_TEST)) {
6405 enforceNetworkFactoryOrTestNetworksPermission();
6406 } else {
6407 enforceNetworkFactoryPermission();
6408 }
6409 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6410 if (nri != null) {
6411 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6412 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6413 mHandler.post(() -> handleReleaseNetworkRequest(
6414 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6415 }
6416 }
6417
6418 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6419 @GuardedBy("mNetworkForNetId")
6420 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6421 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6422 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6423 // there may not be a strict 1:1 correlation between the two.
6424 private final NetIdManager mNetIdManager;
6425
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00006426 // Tracks all NetworkAgents that are currently registered.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006427 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6428 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6429
6430 // UID ranges for users that are currently blocked by VPNs.
6431 // This array is accessed and iterated on multiple threads without holding locks, so its
6432 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6433 // (on the handler thread).
6434 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6435
6436 // Must only be accessed on the handler thread
6437 @NonNull
6438 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6439
6440 @GuardedBy("mBlockedAppUids")
6441 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6442
6443 // Current OEM network preferences. This object must only be written to on the handler thread.
6444 // Since it is immutable and always non-null, other threads may read it if they only care
6445 // about seeing a consistent object but not that it is current.
6446 @NonNull
6447 private OemNetworkPreferences mOemNetworkPreferences =
6448 new OemNetworkPreferences.Builder().build();
6449 // Current per-profile network preferences. This object follows the same threading rules as
6450 // the OEM network preferences above.
6451 @NonNull
6452 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6453
paulhu71ad4f12021-05-25 14:56:27 +08006454 // A set of UIDs that should use mobile data preferentially if available. This object follows
6455 // the same threading rules as the OEM network preferences above.
6456 @NonNull
6457 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6458
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006459 // OemNetworkPreferences activity String log entries.
6460 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6461 @NonNull
6462 private final LocalLog mOemNetworkPreferencesLogs =
6463 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6464
6465 /**
6466 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6467 * @param packageName the package name to check existence of a mapping for.
6468 * @return true if a mapping exists, false otherwise
6469 */
6470 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6471 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6472 }
6473
6474 // The always-on request for an Internet-capable network that apps without a specific default
6475 // fall back to.
6476 @VisibleForTesting
6477 @NonNull
6478 final NetworkRequestInfo mDefaultRequest;
6479 // Collection of NetworkRequestInfo's used for default networks.
6480 @VisibleForTesting
6481 @NonNull
6482 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6483
6484 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6485 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6486 }
6487
6488 /**
6489 * Return the default network request currently tracking the given uid.
6490 * @param uid the uid to check.
6491 * @return the NetworkRequestInfo tracking the given uid.
6492 */
6493 @NonNull
6494 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006495 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006496 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006497 // Checking the first request is sufficient as only multilayer requests will have more
6498 // than one request and for multilayer, all requests will track the same uids.
6499 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006500 // Find out the highest priority request.
6501 if (nri.hasHigherPriorityThan(highestPriorityNri)) {
6502 highestPriorityNri = nri;
6503 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006504 }
6505 }
paulhude5efb92021-05-26 21:56:03 +08006506 return highestPriorityNri;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006507 }
6508
6509 /**
6510 * Get a copy of the network requests of the default request that is currently tracking the
6511 * given uid.
6512 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6513 * when a privileged caller is tracking the default network for another uid.
6514 * @param requestorUid the uid to check the default for.
6515 * @param requestorPackageName the requestor's package name.
6516 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6517 */
6518 @NonNull
6519 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6520 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6521 return copyNetworkRequestsForUid(
6522 getDefaultRequestTrackingUid(asUid).mRequests,
6523 asUid, requestorUid, requestorPackageName);
6524 }
6525
6526 /**
6527 * Copy the given nri's NetworkRequest collection.
6528 * @param requestsToCopy the NetworkRequest collection to be copied.
6529 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6530 * when a privileged caller is tracking the default network for another uid.
6531 * @param requestorUid the uid to set on the copied collection.
6532 * @param requestorPackageName the package name to set on the copied collection.
6533 * @return the copied NetworkRequest collection.
6534 */
6535 @NonNull
6536 private List<NetworkRequest> copyNetworkRequestsForUid(
6537 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6538 final int requestorUid, @NonNull final String requestorPackageName) {
6539 final List<NetworkRequest> requests = new ArrayList<>();
6540 for (final NetworkRequest nr : requestsToCopy) {
6541 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6542 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6543 nr.legacyType, nextNetworkRequestId(), nr.type));
6544 }
6545 return requests;
6546 }
6547
6548 @NonNull
6549 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6550 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6551 final int requestorUid, @NonNull final String requestorPackageName) {
6552 // These capabilities are for a TRACK_DEFAULT callback, so:
6553 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6554 // mDefaultRequest and a per-UID default request.
6555 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6556 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6557 // not do this in the case of a privileged application.
6558 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6559 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6560 netCap.setSingleUid(asUid);
6561 restrictRequestUidsForCallerAndSetRequestorInfo(
6562 netCap, requestorUid, requestorPackageName);
6563 return netCap;
6564 }
6565
6566 /**
6567 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6568 * @param nr the network request to check for equality against.
6569 * @return the nri if one exists, null otherwise.
6570 */
6571 @Nullable
6572 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6573 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6574 if (nri.getNetworkRequestForCallback().equals(nr)) {
6575 return nri;
6576 }
6577 }
6578 return null;
6579 }
6580
6581 /**
6582 * Check if an nri is currently being managed by per-app default networking.
6583 * @param nri the nri to check.
6584 * @return true if this nri is currently being managed by per-app default networking.
6585 */
6586 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6587 // nri.mRequests.get(0) is only different from the original request filed in
6588 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6589 // functionality therefore if these two don't match, it means this particular nri is
6590 // currently being managed by a per-app default.
6591 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6592 }
6593
6594 /**
6595 * Determine if an nri is a managed default request that disallows default networking.
6596 * @param nri the request to evaluate
6597 * @return true if device-default networking is disallowed
6598 */
6599 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6600 // Check if this nri is a managed default that supports the default network at its
6601 // lowest priority request.
6602 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6603 final NetworkCapabilities lowestPriorityNetCap =
6604 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6605 return isPerAppDefaultRequest(nri)
6606 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6607 lowestPriorityNetCap));
6608 }
6609
6610 // Request used to optionally keep mobile data active even when higher
6611 // priority networks like Wi-Fi are active.
6612 private final NetworkRequest mDefaultMobileDataRequest;
6613
6614 // Request used to optionally keep wifi data active even when higher
6615 // priority networks like ethernet are active.
6616 private final NetworkRequest mDefaultWifiRequest;
6617
6618 // Request used to optionally keep vehicle internal network always active
6619 private final NetworkRequest mDefaultVehicleRequest;
6620
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006621 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6622 // network with no service. This NAI should never be matched against, nor should any public API
6623 // ever return the associated network. For this reason, this NAI is not in the list of available
6624 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6625 // default requests that don't support using the device default network which will ultimately
6626 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6627 @VisibleForTesting
6628 final NetworkAgentInfo mNoServiceNetwork;
6629
6630 // The NetworkAgentInfo currently satisfying the default request, if any.
6631 private NetworkAgentInfo getDefaultNetwork() {
6632 return mDefaultRequest.mSatisfier;
6633 }
6634
6635 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhude5efb92021-05-26 21:56:03 +08006636 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006637 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6638 // Currently, all network requests will have the same uids therefore checking the first
6639 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6640 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6641 if (null == uids) {
6642 continue;
6643 }
6644 for (final UidRange range : uids) {
6645 if (range.contains(uid)) {
paulhude5efb92021-05-26 21:56:03 +08006646 if (nri.hasHigherPriorityThan(highestPriorityNri)) {
6647 highestPriorityNri = nri;
6648 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006649 }
6650 }
6651 }
paulhude5efb92021-05-26 21:56:03 +08006652 return highestPriorityNri.getSatisfier();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006653 }
6654
6655 @Nullable
6656 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6657 return nai != null ? nai.network : null;
6658 }
6659
6660 private void ensureRunningOnConnectivityServiceThread() {
6661 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6662 throw new IllegalStateException(
6663 "Not running on ConnectivityService thread: "
6664 + Thread.currentThread().getName());
6665 }
6666 }
6667
6668 @VisibleForTesting
6669 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6670 return nai == getDefaultNetwork();
6671 }
6672
6673 /**
6674 * Register a new agent with ConnectivityService to handle a network.
6675 *
6676 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6677 * @param networkInfo the initial info associated with this network. It can be updated later :
6678 * see {@link #updateNetworkInfo}.
6679 * @param linkProperties the initial link properties of this network. They can be updated
6680 * later : see {@link #updateLinkProperties}.
6681 * @param networkCapabilities the initial capabilites of this network. They can be updated
6682 * later : see {@link #updateCapabilities}.
6683 * @param initialScore the initial score of the network. See
6684 * {@link NetworkAgentInfo#getCurrentScore}.
6685 * @param networkAgentConfig metadata about the network. This is never updated.
6686 * @param providerId the ID of the provider owning this NetworkAgent.
6687 * @return the network created for this agent.
6688 */
6689 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6690 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6691 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6692 int providerId) {
6693 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6694 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6695 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6696 Objects.requireNonNull(initialScore, "initialScore must not be null");
6697 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6698 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6699 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6700 } else {
6701 enforceNetworkFactoryPermission();
6702 }
6703
6704 final int uid = mDeps.getCallingUid();
6705 final long token = Binder.clearCallingIdentity();
6706 try {
6707 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6708 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6709 } finally {
6710 Binder.restoreCallingIdentity(token);
6711 }
6712 }
6713
6714 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6715 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6716 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6717 int uid) {
6718 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6719 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6720 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6721 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6722 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6723 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6724 }
6725
6726 LinkProperties lp = new LinkProperties(linkProperties);
6727
6728 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6729 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6730 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6731 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6732 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6733 mQosCallbackTracker, mDeps);
6734
6735 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6736 processCapabilitiesFromAgent(nai, nc);
6737 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6738 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6739
6740 final String extraInfo = networkInfo.getExtraInfo();
6741 final String name = TextUtils.isEmpty(extraInfo)
6742 ? nai.networkCapabilities.getSsid() : extraInfo;
6743 if (DBG) log("registerNetworkAgent " + nai);
6744 mDeps.getNetworkStack().makeNetworkMonitor(
6745 nai.network, name, new NetworkMonitorCallbacks(nai));
6746 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6747 // If the network disconnects or sends any other event before that, messages are deferred by
6748 // NetworkAgent until nai.connect(), which will be called when finalizing the
6749 // registration.
6750 return nai.network;
6751 }
6752
6753 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6754 nai.onNetworkMonitorCreated(networkMonitor);
6755 if (VDBG) log("Got NetworkAgent Messenger");
6756 mNetworkAgentInfos.add(nai);
6757 synchronized (mNetworkForNetId) {
6758 mNetworkForNetId.put(nai.network.getNetId(), nai);
6759 }
6760
6761 try {
6762 networkMonitor.start();
6763 } catch (RemoteException e) {
6764 e.rethrowAsRuntimeException();
6765 }
6766 nai.notifyRegistered();
6767 NetworkInfo networkInfo = nai.networkInfo;
6768 updateNetworkInfo(nai, networkInfo);
6769 updateUids(nai, null, nai.networkCapabilities);
6770 }
6771
6772 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6773 @NonNull public final NetworkOffer offer;
6774
6775 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6776 this.offer = offer;
6777 }
6778
6779 @Override
6780 public void binderDied() {
6781 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6782 }
6783 }
6784
6785 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6786 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6787 if (npi.providerId == providerId) return true;
6788 }
6789 return false;
6790 }
6791
6792 /**
6793 * Register or update a network offer.
6794 * @param newOffer The new offer. If the callback member is the same as an existing
6795 * offer, it is an update of that offer.
6796 */
6797 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6798 ensureRunningOnConnectivityServiceThread();
6799 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6800 // This may actually happen if a provider updates its score or registers and then
6801 // immediately unregisters. The offer would still be in the handler queue, but the
6802 // provider would have been removed.
6803 if (DBG) log("Received offer from an unregistered provider");
6804 return;
6805 }
6806 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6807 if (null != existingOffer) {
6808 handleUnregisterNetworkOffer(existingOffer);
6809 newOffer.migrateFrom(existingOffer.offer);
6810 }
6811 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6812 try {
6813 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6814 } catch (RemoteException e) {
6815 noi.binderDied();
6816 return;
6817 }
6818 mNetworkOffers.add(noi);
6819 issueNetworkNeeds(noi);
6820 }
6821
6822 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6823 ensureRunningOnConnectivityServiceThread();
6824 mNetworkOffers.remove(noi);
6825 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6826 }
6827
6828 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6829 @NonNull final INetworkOfferCallback callback) {
6830 ensureRunningOnConnectivityServiceThread();
6831 for (final NetworkOfferInfo noi : mNetworkOffers) {
6832 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6833 }
6834 return null;
6835 }
6836
6837 /**
6838 * Called when receiving LinkProperties directly from a NetworkAgent.
6839 * Stores into |nai| any data coming from the agent that might also be written to the network's
6840 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6841 * agent is not lost when updateLinkProperties is called.
6842 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6843 */
6844 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6845 lp.ensureDirectlyConnectedRoutes();
6846 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6847 nai.networkAgentPortalData = lp.getCaptivePortalData();
6848 }
6849
6850 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6851 @NonNull LinkProperties oldLp) {
6852 int netId = networkAgent.network.getNetId();
6853
6854 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6855 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6856 // the LinkProperties for the network are accurate.
6857 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6858
6859 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6860
6861 // update filtering rules, need to happen after the interface update so netd knows about the
6862 // new interface (the interface name -> index map becomes initialized)
6863 updateVpnFiltering(newLp, oldLp, networkAgent);
6864
6865 updateMtu(newLp, oldLp);
6866 // TODO - figure out what to do for clat
6867// for (LinkProperties lp : newLp.getStackedLinks()) {
6868// updateMtu(lp, null);
6869// }
6870 if (isDefaultNetwork(networkAgent)) {
6871 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6872 }
6873
6874 updateRoutes(newLp, oldLp, netId);
6875 updateDnses(newLp, oldLp, netId);
6876 // Make sure LinkProperties represents the latest private DNS status.
6877 // This does not need to be done before updateDnses because the
6878 // LinkProperties are not the source of the private DNS configuration.
6879 // updateDnses will fetch the private DNS configuration from DnsManager.
6880 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6881
6882 if (isDefaultNetwork(networkAgent)) {
6883 handleApplyDefaultProxy(newLp.getHttpProxy());
6884 } else {
6885 updateProxy(newLp, oldLp);
6886 }
6887
6888 updateWakeOnLan(newLp);
6889
6890 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6891 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6892 // does, it needs to be merged here.
6893 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6894 networkAgent.capportApiData));
6895
6896 // TODO - move this check to cover the whole function
6897 if (!Objects.equals(newLp, oldLp)) {
6898 synchronized (networkAgent) {
6899 networkAgent.linkProperties = newLp;
6900 }
6901 // Start or stop DNS64 detection and 464xlat according to network state.
6902 networkAgent.clatd.update();
6903 notifyIfacesChangedForNetworkStats();
6904 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6905 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6906 if (networkAgent.everConnected) {
6907 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6908 }
6909 }
6910
6911 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6912 }
6913
6914 /**
6915 * @param naData captive portal data from NetworkAgent
6916 * @param apiData captive portal data from capport API
6917 */
6918 @Nullable
6919 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6920 CaptivePortalData apiData) {
6921 if (naData == null || apiData == null) {
6922 return naData == null ? apiData : naData;
6923 }
6924 final CaptivePortalData.Builder captivePortalBuilder =
6925 new CaptivePortalData.Builder(naData);
6926
6927 if (apiData.isCaptive()) {
6928 captivePortalBuilder.setCaptive(true);
6929 }
6930 if (apiData.isSessionExtendable()) {
6931 captivePortalBuilder.setSessionExtendable(true);
6932 }
6933 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6934 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6935 // otherwise data would be inconsistent. Prefer the capport API info if present,
6936 // as it can generally be refreshed more often.
6937 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6938 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6939 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6940 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6941 // No source has time / bytes remaining information: surface the newest refresh time
6942 // for other fields
6943 captivePortalBuilder.setRefreshTime(
6944 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6945 }
6946
6947 // Prioritize the user portal URL from the network agent if the source is authenticated.
6948 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6949 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6950 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6951 apiData.getUserPortalUrlSource());
6952 }
6953 // Prioritize the venue information URL from the network agent if the source is
6954 // authenticated.
6955 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6956 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6957 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6958 apiData.getVenueInfoUrlSource());
6959 }
6960 return captivePortalBuilder.build();
6961 }
6962
6963 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6964 // Marks are only available on WiFi interfaces. Checking for
6965 // marks on unsupported interfaces is harmless.
6966 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6967 return;
6968 }
6969
6970 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6971 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6972
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006973 // Mask/mark of zero will not detect anything interesting.
6974 // Don't install rules unless both values are nonzero.
6975 if (mark == 0 || mask == 0) {
6976 return;
6977 }
6978
6979 final String prefix = "iface:" + iface;
6980 try {
6981 if (add) {
6982 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
6983 } else {
6984 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
6985 }
6986 } catch (Exception e) {
6987 loge("Exception modifying wakeup packet monitoring: " + e);
6988 }
6989
6990 }
6991
6992 private void updateInterfaces(final @Nullable LinkProperties newLp,
6993 final @Nullable LinkProperties oldLp, final int netId,
6994 final @NonNull NetworkCapabilities caps) {
6995 final CompareResult<String> interfaceDiff = new CompareResult<>(
6996 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6997 newLp != null ? newLp.getAllInterfaceNames() : null);
6998 if (!interfaceDiff.added.isEmpty()) {
6999 for (final String iface : interfaceDiff.added) {
7000 try {
7001 if (DBG) log("Adding iface " + iface + " to network " + netId);
7002 mNetd.networkAddInterface(netId, iface);
7003 wakeupModifyInterface(iface, caps, true);
7004 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7005 caps.getTransportTypes());
7006 } catch (Exception e) {
7007 logw("Exception adding interface: " + e);
7008 }
7009 }
7010 }
7011 for (final String iface : interfaceDiff.removed) {
7012 try {
7013 if (DBG) log("Removing iface " + iface + " from network " + netId);
7014 wakeupModifyInterface(iface, caps, false);
7015 mNetd.networkRemoveInterface(netId, iface);
7016 } catch (Exception e) {
7017 loge("Exception removing interface: " + e);
7018 }
7019 }
7020 }
7021
7022 // TODO: move to frameworks/libs/net.
7023 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7024 final String nextHop;
7025
7026 switch (route.getType()) {
7027 case RouteInfo.RTN_UNICAST:
7028 if (route.hasGateway()) {
7029 nextHop = route.getGateway().getHostAddress();
7030 } else {
7031 nextHop = INetd.NEXTHOP_NONE;
7032 }
7033 break;
7034 case RouteInfo.RTN_UNREACHABLE:
7035 nextHop = INetd.NEXTHOP_UNREACHABLE;
7036 break;
7037 case RouteInfo.RTN_THROW:
7038 nextHop = INetd.NEXTHOP_THROW;
7039 break;
7040 default:
7041 nextHop = INetd.NEXTHOP_NONE;
7042 break;
7043 }
7044
7045 final RouteInfoParcel rip = new RouteInfoParcel();
7046 rip.ifName = route.getInterface();
7047 rip.destination = route.getDestination().toString();
7048 rip.nextHop = nextHop;
7049 rip.mtu = route.getMtu();
7050
7051 return rip;
7052 }
7053
7054 /**
7055 * Have netd update routes from oldLp to newLp.
7056 * @return true if routes changed between oldLp and newLp
7057 */
7058 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
7059 // compare the route diff to determine which routes have been updated
7060 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7061 new CompareOrUpdateResult<>(
7062 oldLp != null ? oldLp.getAllRoutes() : null,
7063 newLp != null ? newLp.getAllRoutes() : null,
7064 (r) -> r.getRouteKey());
7065
7066 // add routes before removing old in case it helps with continuous connectivity
7067
7068 // do this twice, adding non-next-hop routes first, then routes they are dependent on
7069 for (RouteInfo route : routeDiff.added) {
7070 if (route.hasGateway()) continue;
7071 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7072 try {
7073 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7074 } catch (Exception e) {
7075 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
7076 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
7077 }
7078 }
7079 }
7080 for (RouteInfo route : routeDiff.added) {
7081 if (!route.hasGateway()) continue;
7082 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
7083 try {
7084 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
7085 } catch (Exception e) {
7086 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
7087 loge("Exception in networkAddRouteParcel for gateway: " + e);
7088 }
7089 }
7090 }
7091
7092 for (RouteInfo route : routeDiff.removed) {
7093 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
7094 try {
7095 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
7096 } catch (Exception e) {
7097 loge("Exception in networkRemoveRouteParcel: " + e);
7098 }
7099 }
7100
7101 for (RouteInfo route : routeDiff.updated) {
7102 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7103 try {
7104 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7105 } catch (Exception e) {
7106 loge("Exception in networkUpdateRouteParcel: " + e);
7107 }
7108 }
7109 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7110 || !routeDiff.updated.isEmpty();
7111 }
7112
7113 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7114 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7115 return; // no updating necessary
7116 }
7117
7118 if (DBG) {
7119 final Collection<InetAddress> dnses = newLp.getDnsServers();
7120 log("Setting DNS servers for network " + netId + " to " + dnses);
7121 }
7122 try {
7123 mDnsManager.noteDnsServersForNetwork(netId, newLp);
7124 mDnsManager.flushVmDnsCache();
7125 } catch (Exception e) {
7126 loge("Exception in setDnsConfigurationForNetwork: " + e);
7127 }
7128 }
7129
7130 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7131 NetworkAgentInfo nai) {
7132 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7133 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7134 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7135 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7136
7137 if (!wasFiltering && !needsFiltering) {
7138 // Nothing to do.
7139 return;
7140 }
7141
7142 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7143 // Nothing changed.
7144 return;
7145 }
7146
7147 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7148 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7149 // TODO: this create a window of opportunity for apps to receive traffic between the time
7150 // when the old rules are removed and the time when new rules are added. To fix this,
7151 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7152 // old rules are being removed.
7153 if (wasFiltering) {
7154 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7155 }
7156 if (needsFiltering) {
7157 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7158 }
7159 }
7160
7161 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7162 if (mWolSupportedInterfaces == null) {
7163 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7164 R.array.config_wakeonlan_supported_interfaces));
7165 }
7166 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7167 }
7168
7169 private int getNetworkPermission(NetworkCapabilities nc) {
7170 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7171 return INetd.PERMISSION_SYSTEM;
7172 }
7173 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7174 return INetd.PERMISSION_NETWORK;
7175 }
7176 return INetd.PERMISSION_NONE;
7177 }
7178
7179 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7180 @NonNull final NetworkCapabilities newNc) {
7181 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7182 final int newPermission = getNetworkPermission(newNc);
7183 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7184 try {
7185 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7186 } catch (RemoteException | ServiceSpecificException e) {
7187 loge("Exception in networkSetPermissionForNetwork: " + e);
7188 }
7189 }
7190 }
7191
7192 /**
7193 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7194 * Stores into |nai| any data coming from the agent that might also be written to the network's
7195 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7196 * agent is not lost when updateCapabilities is called.
7197 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7198 */
7199 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7200 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7201 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7202 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7203 // the owner UID here and behave as if the agent had never tried to change it.
7204 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7205 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7206 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7207 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7208 }
7209 nai.declaredCapabilities = new NetworkCapabilities(nc);
7210 }
7211
7212 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7213 @VisibleForTesting
7214 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7215 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7216 underlyingNetworks = underlyingNetworksOrDefault(
7217 agentCaps.getOwnerUid(), underlyingNetworks);
7218 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7219 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7220 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7221 // metered if any underlying is metered, or originally declared metered by the agent.
7222 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7223 boolean roaming = false; // roaming if any underlying is roaming
7224 boolean congested = false; // congested if any underlying is congested
7225 boolean suspended = true; // suspended if all underlying are suspended
7226
7227 boolean hadUnderlyingNetworks = false;
7228 if (null != underlyingNetworks) {
7229 for (Network underlyingNetwork : underlyingNetworks) {
7230 final NetworkAgentInfo underlying =
7231 getNetworkAgentInfoForNetwork(underlyingNetwork);
7232 if (underlying == null) continue;
7233
7234 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7235 hadUnderlyingNetworks = true;
7236 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7237 transportTypes |= 1L << underlyingType;
7238 }
7239
7240 // Merge capabilities of this underlying network. For bandwidth, assume the
7241 // worst case.
7242 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7243 underlyingCaps.getLinkDownstreamBandwidthKbps());
7244 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7245 underlyingCaps.getLinkUpstreamBandwidthKbps());
7246 // If this underlying network is metered, the VPN is metered (it may cost money
7247 // to send packets on this network).
7248 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7249 // If this underlying network is roaming, the VPN is roaming (the billing structure
7250 // is different than the usual, local one).
7251 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7252 // If this underlying network is congested, the VPN is congested (the current
7253 // condition of the network affects the performance of this network).
7254 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7255 // If this network is not suspended, the VPN is not suspended (the VPN
7256 // is able to transfer some data).
7257 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7258 }
7259 }
7260 if (!hadUnderlyingNetworks) {
7261 // No idea what the underlying networks are; assume reasonable defaults
7262 metered = true;
7263 roaming = false;
7264 congested = false;
7265 suspended = false;
7266 }
7267
7268 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7269 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7270 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7271 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7272 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7273 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7274 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7275 }
7276
7277 /**
7278 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7279 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7280 * and foreground status).
7281 */
7282 @NonNull
7283 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7284 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7285 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7286 // causing a connect/teardown loop.
7287 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7288 // avoid connect/teardown loops.
7289 if (nai.everConnected &&
7290 !nai.isVPN() &&
7291 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7292 // TODO: consider not complaining when a network agent degrades its capabilities if this
7293 // does not cause any request (that is not a listen) currently matching that agent to
7294 // stop being matched by the updated agent.
7295 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7296 if (!TextUtils.isEmpty(diff)) {
7297 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7298 }
7299 }
7300
7301 // Don't modify caller's NetworkCapabilities.
7302 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7303 if (nai.lastValidated) {
7304 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7305 } else {
7306 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7307 }
7308 if (nai.lastCaptivePortalDetected) {
7309 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7310 } else {
7311 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7312 }
7313 if (nai.isBackgroundNetwork()) {
7314 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7315 } else {
7316 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7317 }
7318 if (nai.partialConnectivity) {
7319 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7320 } else {
7321 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7322 }
7323 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7324
7325 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7326 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7327 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7328 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7329 }
7330
Treehugger Robot4703a8c2021-07-02 13:55:33 +00007331 if (nai.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007332 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7333 newNc);
7334 }
7335
7336 return newNc;
7337 }
7338
7339 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7340 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7341 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7342 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7343 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7344 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7345 if (prevSuspended != suspended) {
7346 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7347 // onResumed have been removed.
7348 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7349 : ConnectivityManager.CALLBACK_RESUMED);
7350 }
7351 if (prevSuspended != suspended || prevRoaming != roaming) {
7352 // updateNetworkInfo will mix in the suspended info from the capabilities and
7353 // take appropriate action for the network having possibly changed state.
7354 updateNetworkInfo(nai, nai.networkInfo);
7355 }
7356 }
7357
7358 /**
7359 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7360 *
7361 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7362 * capabilities we manage and store in {@code nai}, such as validated status and captive
7363 * portal status)
7364 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7365 * potentially triggers rematches.
7366 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7367 * change.)
7368 *
7369 * @param oldScore score of the network before any of the changes that prompted us
7370 * to call this function.
7371 * @param nai the network having its capabilities updated.
7372 * @param nc the new network capabilities.
7373 */
7374 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7375 @NonNull final NetworkCapabilities nc) {
7376 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7377 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7378 updateNetworkPermissions(nai, newNc);
7379 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7380
7381 updateUids(nai, prevNc, newNc);
7382 nai.updateScoreForNetworkAgentUpdate();
7383
7384 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7385 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7386 // the change we're processing can't affect any requests, it can only affect the listens
7387 // on this network. We might have been called by rematchNetworkAndRequests when a
7388 // network changed foreground state.
7389 processListenRequests(nai);
7390 } else {
7391 // If the requestable capabilities have changed or the score changed, we can't have been
7392 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7393 rematchAllNetworksAndRequests();
7394 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7395 }
7396 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7397
7398 final boolean oldMetered = prevNc.isMetered();
7399 final boolean newMetered = newNc.isMetered();
7400 final boolean meteredChanged = oldMetered != newMetered;
7401
7402 if (meteredChanged) {
7403 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7404 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7405 }
7406
7407 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7408 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7409
7410 // Report changes that are interesting for network statistics tracking.
7411 if (meteredChanged || roamingChanged) {
7412 notifyIfacesChangedForNetworkStats();
7413 }
7414
7415 // This network might have been underlying another network. Propagate its capabilities.
7416 propagateUnderlyingNetworkCapabilities(nai.network);
7417
7418 if (!newNc.equalsTransportTypes(prevNc)) {
7419 mDnsManager.updateTransportsForNetwork(
7420 nai.network.getNetId(), newNc.getTransportTypes());
7421 }
Lucas Lin950a65f2021-06-15 09:28:16 +00007422
7423 maybeSendProxyBroadcast(nai, prevNc, newNc);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007424 }
7425
7426 /** Convenience method to update the capabilities for a given network. */
7427 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7428 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7429 }
7430
7431 /**
7432 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7433 * network.
7434 *
7435 * Ingress interface filtering enforces that all apps under the given network can only receive
7436 * packets from the network's interface (and loopback). This is important for VPNs because
7437 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7438 * non-VPN interfaces.
7439 *
7440 * As a result, this method should return true iff
7441 * 1. the network is an app VPN (not legacy VPN)
7442 * 2. the VPN does not allow bypass
7443 * 3. the VPN is fully-routed
7444 * 4. the VPN interface is non-null
7445 *
7446 * @see INetd#firewallAddUidInterfaceRules
7447 * @see INetd#firewallRemoveUidInterfaceRules
7448 */
7449 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7450 LinkProperties lp) {
7451 if (nc == null || lp == null) return false;
7452 return nai.isVPN()
7453 && !nai.networkAgentConfig.allowBypass
7454 && nc.getOwnerUid() != Process.SYSTEM_UID
7455 && lp.getInterfaceName() != null
7456 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7457 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7458 }
7459
7460 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7461 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7462 int index = 0;
7463 for (UidRange range : ranges) {
7464 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7465 index++;
7466 }
7467 return stableRanges;
7468 }
7469
7470 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7471 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7472 for (int i = 0; i < ranges.length; i++) {
7473 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7474 }
7475 return stableRanges;
7476 }
7477
7478 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7479 int[] exemptUids) {
7480 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7481 try {
7482 mNetd.socketDestroy(ranges, exemptUids);
7483 } catch (Exception e) {
7484 loge("Exception in socket destroy: ", e);
7485 }
7486 }
7487 }
7488
paulhude5efb92021-05-26 21:56:03 +08007489 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007490 int[] exemptUids = new int[2];
7491 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7492 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7493 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7494 exemptUids[0] = VPN_UID;
7495 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7496 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7497
7498 maybeCloseSockets(nai, ranges, exemptUids);
7499 try {
7500 if (add) {
paulhude2a2392021-06-09 16:11:35 +08007501 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhude5efb92021-05-26 21:56:03 +08007502 nai.network.netId, ranges, PREFERENCE_PRIORITY_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007503 } else {
paulhude2a2392021-06-09 16:11:35 +08007504 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhude5efb92021-05-26 21:56:03 +08007505 nai.network.netId, ranges, PREFERENCE_PRIORITY_VPN));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007506 }
7507 } catch (Exception e) {
7508 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7509 " on netId " + nai.network.netId + ". " + e);
7510 }
7511 maybeCloseSockets(nai, ranges, exemptUids);
7512 }
7513
Lucas Lin950a65f2021-06-15 09:28:16 +00007514 private boolean isProxySetOnAnyDefaultNetwork() {
7515 ensureRunningOnConnectivityServiceThread();
7516 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7517 final NetworkAgentInfo nai = nri.getSatisfier();
7518 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7519 return true;
7520 }
7521 }
7522 return false;
7523 }
7524
7525 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7526 NetworkCapabilities newNc) {
7527 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7528 // the proxy might be changed since the default network satisfied by the apps might also
7529 // changed.
7530 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7531 // that happens to prevent false alarms.
7532 if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc)
7533 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7534 mProxyTracker.sendProxyBroadcast();
7535 }
7536 }
7537
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007538 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7539 NetworkCapabilities newNc) {
7540 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7541 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7542 if (null == prevRanges) prevRanges = new ArraySet<>();
7543 if (null == newRanges) newRanges = new ArraySet<>();
7544 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7545
7546 prevRanges.removeAll(newRanges);
7547 newRanges.removeAll(prevRangesCopy);
7548
7549 try {
7550 // When updating the VPN uid routing rules, add the new range first then remove the old
7551 // range. If old range were removed first, there would be a window between the old
7552 // range being removed and the new range being added, during which UIDs contained
7553 // in both ranges are not subject to any VPN routing rules. Adding new range before
7554 // removing old range works because, unlike the filtering rules below, it's possible to
7555 // add duplicate UID routing rules.
7556 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7557 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7558 // [1-5] & [1-2],[4-5] == [3]
7559 // Then we can do:
7560 // maybeCloseSockets([3])
7561 // mNetd.networkAddUidRanges([1-2],[4-5])
7562 // mNetd.networkRemoveUidRanges([1-5])
7563 // maybeCloseSockets([3])
7564 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7565 // number of binder calls from 6 to 4.
7566 if (!newRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007567 updateVpnUidRanges(true, nai, newRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007568 }
7569 if (!prevRanges.isEmpty()) {
paulhude5efb92021-05-26 21:56:03 +08007570 updateVpnUidRanges(false, nai, prevRanges);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007571 }
7572 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7573 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7574 final String iface = nai.linkProperties.getInterfaceName();
7575 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7576 // be added, due to the range being expanded and stored as individual UIDs. For example
7577 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7578 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7579 // were added first and then newRanges got removed later, there would be only one uid
7580 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7581 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7582 // Note that this is in contrast with the (more robust) update of VPN routing rules
7583 // above, where the addition of new ranges happens before the removal of old ranges.
7584 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7585 // to be removed will never overlap with the new range to be added.
7586 if (wasFiltering && !prevRanges.isEmpty()) {
7587 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7588 }
7589 if (shouldFilter && !newRanges.isEmpty()) {
7590 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7591 }
7592 } catch (Exception e) {
7593 // Never crash!
7594 loge("Exception in updateUids: ", e);
7595 }
7596 }
7597
7598 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7599 ensureRunningOnConnectivityServiceThread();
7600
Lorenzo Colittibeb7d922021-06-09 08:33:36 +00007601 if (!mNetworkAgentInfos.contains(nai)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007602 // Ignore updates for disconnected networks
7603 return;
7604 }
7605 if (VDBG || DDBG) {
7606 log("Update of LinkProperties for " + nai.toShortString()
7607 + "; created=" + nai.created
7608 + "; everConnected=" + nai.everConnected);
7609 }
7610 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7611 // modify its oldLp parameter.
7612 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7613 }
7614
7615 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7616 int notificationType) {
7617 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7618 Intent intent = new Intent();
7619 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7620 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7621 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7622 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN4cb61892021-06-28 07:27:47 +00007623 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7624 // need to be sent as a separate extra.
7625 final NetworkRequest req = nri.isMultilayerRequest()
7626 ? nri.getActiveRequest()
7627 // Non-multilayer listen requests do not have an active request
7628 : nri.mRequests.get(0);
7629 if (req == null) {
7630 Log.wtf(TAG, "No request in NRI " + nri);
7631 }
7632 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007633 nri.mPendingIntentSent = true;
7634 sendIntent(nri.mPendingIntent, intent);
7635 }
7636 // else not handled
7637 }
7638
7639 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7640 mPendingIntentWakeLock.acquire();
7641 try {
7642 if (DBG) log("Sending " + pendingIntent);
7643 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7644 } catch (PendingIntent.CanceledException e) {
7645 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7646 mPendingIntentWakeLock.release();
7647 releasePendingNetworkRequest(pendingIntent);
7648 }
7649 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7650 }
7651
7652 @Override
7653 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7654 String resultData, Bundle resultExtras) {
7655 if (DBG) log("Finished sending " + pendingIntent);
7656 mPendingIntentWakeLock.release();
7657 // Release with a delay so the receiving client has an opportunity to put in its
7658 // own request.
7659 releasePendingNetworkRequestWithDelay(pendingIntent);
7660 }
7661
7662 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7663 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7664 final int arg1) {
7665 if (nri.mMessenger == null) {
7666 // Default request has no msgr. Also prevents callbacks from being invoked for
7667 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7668 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7669 return;
7670 }
7671 Bundle bundle = new Bundle();
7672 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7673 // TODO: check if defensive copies of data is needed.
7674 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7675 putParcelable(bundle, nrForCallback);
7676 Message msg = Message.obtain();
7677 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7678 putParcelable(bundle, networkAgent.network);
7679 }
7680 final boolean includeLocationSensitiveInfo =
7681 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7682 switch (notificationType) {
7683 case ConnectivityManager.CALLBACK_AVAILABLE: {
7684 final NetworkCapabilities nc =
7685 networkCapabilitiesRestrictedForCallerPermissions(
7686 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7687 putParcelable(
7688 bundle,
7689 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7690 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7691 nrForCallback.getRequestorPackageName(),
7692 nri.mCallingAttributionTag));
7693 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7694 networkAgent.linkProperties, nri.mPid, nri.mUid));
7695 // For this notification, arg1 contains the blocked status.
7696 msg.arg1 = arg1;
7697 break;
7698 }
7699 case ConnectivityManager.CALLBACK_LOSING: {
7700 msg.arg1 = arg1;
7701 break;
7702 }
7703 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7704 // networkAgent can't be null as it has been accessed a few lines above.
7705 final NetworkCapabilities netCap =
7706 networkCapabilitiesRestrictedForCallerPermissions(
7707 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7708 putParcelable(
7709 bundle,
7710 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7711 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7712 nrForCallback.getRequestorPackageName(),
7713 nri.mCallingAttributionTag));
7714 break;
7715 }
7716 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7717 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7718 networkAgent.linkProperties, nri.mPid, nri.mUid));
7719 break;
7720 }
7721 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7722 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7723 msg.arg1 = arg1;
7724 break;
7725 }
7726 }
7727 msg.what = notificationType;
7728 msg.setData(bundle);
7729 try {
7730 if (VDBG) {
7731 String notification = ConnectivityManager.getCallbackName(notificationType);
7732 log("sending notification " + notification + " for " + nrForCallback);
7733 }
7734 nri.mMessenger.send(msg);
7735 } catch (RemoteException e) {
7736 // may occur naturally in the race of binder death.
7737 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7738 }
7739 }
7740
7741 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7742 bundle.putParcelable(t.getClass().getSimpleName(), t);
7743 }
7744
7745 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7746 if (nai.numRequestNetworkRequests() != 0) {
7747 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7748 NetworkRequest nr = nai.requestAt(i);
7749 // Ignore listening and track default requests.
7750 if (!nr.isRequest()) continue;
7751 loge("Dead network still had at least " + nr);
7752 break;
7753 }
7754 }
7755 nai.disconnect();
7756 }
7757
7758 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7759 if (oldNetwork == null) {
7760 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7761 return;
7762 }
7763 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7764
7765 // If we get here it means that the last linger timeout for this network expired. So there
7766 // must be no other active linger timers, and we must stop lingering.
7767 oldNetwork.clearInactivityState();
7768
7769 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7770 // Tear the network down.
7771 teardownUnneededNetwork(oldNetwork);
7772 } else {
7773 // Put the network in the background if it doesn't satisfy any foreground request.
7774 updateCapabilitiesForNetwork(oldNetwork);
7775 }
7776 }
7777
7778 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7779 boolean isDefaultChanged = false;
7780 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7781 final NetworkReassignment.RequestReassignment reassignment =
7782 changes.getReassignment(defaultRequestInfo);
7783 if (null == reassignment) {
7784 continue;
7785 }
7786 // reassignment only contains those instances where the satisfying network changed.
7787 isDefaultChanged = true;
7788 // Notify system services of the new default.
7789 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7790 }
7791
7792 if (isDefaultChanged) {
7793 // Hold a wakelock for a short time to help apps in migrating to a new default.
7794 scheduleReleaseNetworkTransitionWakelock();
7795 }
7796 }
7797
7798 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7799 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7800 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7801 if (DBG) {
7802 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7803 }
7804
7805 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7806 if (newDefaultNetwork != null) {
7807 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7808 }
7809
7810 // Set an app level managed default and return since further processing only applies to the
7811 // default network.
7812 if (mDefaultRequest != nri) {
7813 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7814 return;
7815 }
7816
7817 makeDefaultNetwork(newDefaultNetwork);
7818
7819 if (oldDefaultNetwork != null) {
7820 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7821 }
7822 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7823 handleApplyDefaultProxy(null != newDefaultNetwork
7824 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7825 updateTcpBufferSizes(null != newDefaultNetwork
7826 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7827 notifyIfacesChangedForNetworkStats();
7828 }
7829
7830 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7831 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7832 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7833 try {
7834 if (VDBG) {
7835 log("Setting default network for " + nri
7836 + " using UIDs " + nri.getUids()
7837 + " with old network " + (oldDefaultNetwork != null
7838 ? oldDefaultNetwork.network().getNetId() : "null")
7839 + " and new network " + (newDefaultNetwork != null
7840 ? newDefaultNetwork.network().getNetId() : "null"));
7841 }
7842 if (nri.getUids().isEmpty()) {
7843 throw new IllegalStateException("makeDefaultForApps called without specifying"
7844 + " any applications to set as the default." + nri);
7845 }
7846 if (null != newDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007847 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007848 newDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007849 toUidRangeStableParcels(nri.getUids()),
paulhude5efb92021-05-26 21:56:03 +08007850 nri.getPriorityForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007851 }
7852 if (null != oldDefaultNetwork) {
paulhude2a2392021-06-09 16:11:35 +08007853 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007854 oldDefaultNetwork.network.getNetId(),
paulhude2a2392021-06-09 16:11:35 +08007855 toUidRangeStableParcels(nri.getUids()),
paulhude5efb92021-05-26 21:56:03 +08007856 nri.getPriorityForNetd()));
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00007857 }
7858 } catch (RemoteException | ServiceSpecificException e) {
7859 loge("Exception setting app default network", e);
7860 }
7861 }
7862
7863 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7864 try {
7865 if (null != newDefaultNetwork) {
7866 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7867 } else {
7868 mNetd.networkClearDefault();
7869 }
7870 } catch (RemoteException | ServiceSpecificException e) {
7871 loge("Exception setting default network :" + e);
7872 }
7873 }
7874
7875 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7876 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7877 processNewlyLostListenRequests(nai);
7878 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7879 processNewlySatisfiedListenRequests(nai);
7880 }
7881
7882 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7883 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7884 if (nri.isMultilayerRequest()) {
7885 continue;
7886 }
7887 final NetworkRequest nr = nri.mRequests.get(0);
7888 if (!nr.isListen()) continue;
7889 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7890 nai.removeRequest(nr.requestId);
7891 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7892 }
7893 }
7894 }
7895
7896 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7897 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7898 if (nri.isMultilayerRequest()) {
7899 continue;
7900 }
7901 final NetworkRequest nr = nri.mRequests.get(0);
7902 if (!nr.isListen()) continue;
7903 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7904 nai.addRequest(nr);
7905 notifyNetworkAvailable(nai, nri);
7906 }
7907 }
7908 }
7909
7910 // An accumulator class to gather the list of changes that result from a rematch.
7911 private static class NetworkReassignment {
7912 static class RequestReassignment {
7913 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7914 @Nullable public final NetworkRequest mOldNetworkRequest;
7915 @Nullable public final NetworkRequest mNewNetworkRequest;
7916 @Nullable public final NetworkAgentInfo mOldNetwork;
7917 @Nullable public final NetworkAgentInfo mNewNetwork;
7918 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7919 @Nullable final NetworkRequest oldNetworkRequest,
7920 @Nullable final NetworkRequest newNetworkRequest,
7921 @Nullable final NetworkAgentInfo oldNetwork,
7922 @Nullable final NetworkAgentInfo newNetwork) {
7923 mNetworkRequestInfo = networkRequestInfo;
7924 mOldNetworkRequest = oldNetworkRequest;
7925 mNewNetworkRequest = newNetworkRequest;
7926 mOldNetwork = oldNetwork;
7927 mNewNetwork = newNetwork;
7928 }
7929
7930 public String toString() {
7931 final NetworkRequest requestToShow = null != mNewNetworkRequest
7932 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7933 return requestToShow.requestId + " : "
7934 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7935 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7936 }
7937 }
7938
7939 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7940
7941 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7942 return mReassignments;
7943 }
7944
7945 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7946 if (Build.isDebuggable()) {
7947 // The code is never supposed to add two reassignments of the same request. Make
7948 // sure this stays true, but without imposing this expensive check on all
7949 // reassignments on all user devices.
7950 for (final RequestReassignment existing : mReassignments) {
7951 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7952 throw new IllegalStateException("Trying to reassign ["
7953 + reassignment + "] but already have ["
7954 + existing + "]");
7955 }
7956 }
7957 }
7958 mReassignments.add(reassignment);
7959 }
7960
7961 // Will return null if this reassignment does not change the network assigned to
7962 // the passed request.
7963 @Nullable
7964 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7965 for (final RequestReassignment event : getRequestReassignments()) {
7966 if (nri == event.mNetworkRequestInfo) return event;
7967 }
7968 return null;
7969 }
7970
7971 public String toString() {
7972 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7973 "NetReassign [" /* prefix */, "]" /* suffix */);
7974 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
7975 for (final RequestReassignment rr : getRequestReassignments()) {
7976 sj.add(rr.toString());
7977 }
7978 return sj.toString();
7979 }
7980
7981 public String debugString() {
7982 final StringBuilder sb = new StringBuilder();
7983 sb.append("NetworkReassignment :");
7984 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
7985 for (final RequestReassignment rr : getRequestReassignments()) {
7986 sb.append("\n ").append(rr);
7987 }
7988 return sb.append("\n").toString();
7989 }
7990 }
7991
7992 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
7993 @Nullable final NetworkRequest previousRequest,
7994 @Nullable final NetworkRequest newRequest,
7995 @Nullable final NetworkAgentInfo previousSatisfier,
7996 @Nullable final NetworkAgentInfo newSatisfier,
7997 final long now) {
7998 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
7999 if (VDBG) log("rematch for " + newSatisfier.toShortString());
8000 if (null != previousRequest && null != previousSatisfier) {
8001 if (VDBG || DDBG) {
8002 log(" accepting network in place of " + previousSatisfier.toShortString());
8003 }
8004 previousSatisfier.removeRequest(previousRequest.requestId);
8005 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8006 } else {
8007 if (VDBG || DDBG) log(" accepting network in place of null");
8008 }
8009
8010 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8011 // and immediately satisfies a request then remove the timer. This will happen for
8012 // all networks except in the case of an underlying network for a VCN.
8013 if (newSatisfier.isNascent()) {
8014 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
8015 newSatisfier.unsetInactive();
8016 }
8017
8018 // if newSatisfier is not null, then newRequest may not be null.
8019 newSatisfier.unlingerRequest(newRequest.requestId);
8020 if (!newSatisfier.addRequest(newRequest)) {
8021 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
8022 + newRequest);
8023 }
8024 } else if (null != previousRequest && null != previousSatisfier) {
8025 if (DBG) {
8026 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
8027 + " request " + previousRequest.requestId);
8028 }
8029 previousSatisfier.removeRequest(previousRequest.requestId);
8030 }
8031 nri.setSatisfier(newSatisfier, newRequest);
8032 }
8033
8034 /**
8035 * This function is triggered when something can affect what network should satisfy what
8036 * request, and it computes the network reassignment from the passed collection of requests to
8037 * network match to the one that the system should now have. That data is encoded in an
8038 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8039 * satisfier.
8040 *
8041 * After the reassignment is computed, it is applied to the state objects.
8042 *
8043 * @param networkRequests the nri objects to evaluate for possible network reassignment
8044 * @return NetworkReassignment listing of proposed network assignment changes
8045 */
8046 @NonNull
8047 private NetworkReassignment computeNetworkReassignment(
8048 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
8049 final NetworkReassignment changes = new NetworkReassignment();
8050
8051 // Gather the list of all relevant agents.
8052 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
8053 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8054 if (!nai.everConnected) {
8055 continue;
8056 }
8057 nais.add(nai);
8058 }
8059
8060 for (final NetworkRequestInfo nri : networkRequests) {
8061 // Non-multilayer listen requests can be ignored.
8062 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8063 continue;
8064 }
8065 NetworkAgentInfo bestNetwork = null;
8066 NetworkRequest bestRequest = null;
8067 for (final NetworkRequest req : nri.mRequests) {
8068 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
8069 // Stop evaluating as the highest possible priority request is satisfied.
8070 if (null != bestNetwork) {
8071 bestRequest = req;
8072 break;
8073 }
8074 }
8075 if (null == bestNetwork && isDefaultBlocked(nri)) {
8076 // Remove default networking if disallowed for managed default requests.
8077 bestNetwork = mNoServiceNetwork;
8078 }
8079 if (nri.getSatisfier() != bestNetwork) {
8080 // bestNetwork may be null if no network can satisfy this request.
8081 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
8082 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
8083 }
8084 }
8085 return changes;
8086 }
8087
8088 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8089 return new HashSet<>(mNetworkRequests.values());
8090 }
8091
8092 /**
8093 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
8094 * being disconnected.
8095 */
8096 private void rematchAllNetworksAndRequests() {
8097 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8098 }
8099
8100 /**
8101 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8102 * being disconnected.
8103 */
8104 private void rematchNetworksAndRequests(
8105 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8106 ensureRunningOnConnectivityServiceThread();
8107 // TODO: This may be slow, and should be optimized.
8108 final long now = SystemClock.elapsedRealtime();
8109 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
8110 if (VDBG || DDBG) {
8111 log(changes.debugString());
8112 } else if (DBG) {
8113 log(changes.toString()); // Shorter form, only one line of log
8114 }
8115 applyNetworkReassignment(changes, now);
8116 issueNetworkNeeds();
8117 }
8118
8119 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
8120 final long now) {
8121 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
8122
8123 // Since most of the time there are only 0 or 1 background networks, it would probably
8124 // be more efficient to just use an ArrayList here. TODO : measure performance
8125 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8126 for (final NetworkAgentInfo nai : nais) {
8127 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8128 }
8129
8130 // First, update the lists of satisfied requests in the network agents. This is necessary
8131 // because some code later depends on this state to be correct, most prominently computing
8132 // the linger status.
8133 for (final NetworkReassignment.RequestReassignment event :
8134 changes.getRequestReassignments()) {
8135 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8136 event.mOldNetworkRequest, event.mNewNetworkRequest,
8137 event.mOldNetwork, event.mNewNetwork,
8138 now);
8139 }
8140
8141 // Process default network changes if applicable.
8142 processDefaultNetworkChanges(changes);
8143
8144 // Notify requested networks are available after the default net is switched, but
8145 // before LegacyTypeTracker sends legacy broadcasts
8146 for (final NetworkReassignment.RequestReassignment event :
8147 changes.getRequestReassignments()) {
8148 if (null != event.mNewNetwork) {
8149 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
8150 } else {
8151 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
8152 ConnectivityManager.CALLBACK_LOST, 0);
8153 }
8154 }
8155
8156 // Update the inactivity state before processing listen callbacks, because the background
8157 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
8158 // just yet though, because they have to be sent after the listens are processed to keep
8159 // backward compatibility.
8160 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
8161 for (final NetworkAgentInfo nai : nais) {
8162 // Rematching may have altered the inactivity state of some networks, so update all
8163 // inactivity timers. updateInactivityState reads the state from the network agent
8164 // and does nothing if the state has not changed : the source of truth is controlled
8165 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8166 // have been called while rematching the individual networks above.
8167 if (updateInactivityState(nai, now)) {
8168 inactiveNetworks.add(nai);
8169 }
8170 }
8171
8172 for (final NetworkAgentInfo nai : nais) {
8173 if (!nai.everConnected) continue;
8174 final boolean oldBackground = oldBgNetworks.contains(nai);
8175 // Process listen requests and update capabilities if the background state has
8176 // changed for this network. For consistency with previous behavior, send onLost
8177 // callbacks before onAvailable.
8178 processNewlyLostListenRequests(nai);
8179 if (oldBackground != nai.isBackgroundNetwork()) {
8180 applyBackgroundChangeForRematch(nai);
8181 }
8182 processNewlySatisfiedListenRequests(nai);
8183 }
8184
8185 for (final NetworkAgentInfo nai : inactiveNetworks) {
8186 // For nascent networks, if connecting with no foreground request, skip broadcasting
8187 // LOSING for backward compatibility. This is typical when mobile data connected while
8188 // wifi connected with mobile data always-on enabled.
8189 if (nai.isNascent()) continue;
8190 notifyNetworkLosing(nai, now);
8191 }
8192
8193 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8194
8195 // Tear down all unneeded networks.
8196 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8197 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8198 if (nai.getInactivityExpiry() > 0) {
8199 // This network has active linger timers and no requests, but is not
8200 // lingering. Linger it.
8201 //
8202 // One way (the only way?) this can happen if this network is unvalidated
8203 // and became unneeded due to another network improving its score to the
8204 // point where this network will no longer be able to satisfy any requests
8205 // even if it validates.
8206 if (updateInactivityState(nai, now)) {
8207 notifyNetworkLosing(nai, now);
8208 }
8209 } else {
8210 if (DBG) log("Reaping " + nai.toShortString());
8211 teardownUnneededNetwork(nai);
8212 }
8213 }
8214 }
8215 }
8216
8217 /**
8218 * Apply a change in background state resulting from rematching networks with requests.
8219 *
8220 * During rematch, a network may change background states by starting to satisfy or stopping
8221 * to satisfy a foreground request. Listens don't count for this. When a network changes
8222 * background states, its capabilities need to be updated and callbacks fired for the
8223 * capability change.
8224 *
8225 * @param nai The network that changed background states
8226 */
8227 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8228 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8229 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8230 updateNetworkPermissions(nai, newNc);
8231 nai.getAndSetNetworkCapabilities(newNc);
8232 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8233 }
8234
8235 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8236 @NonNull final NetworkReassignment changes,
8237 @NonNull final Collection<NetworkAgentInfo> nais) {
8238 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8239 changes.getReassignment(mDefaultRequest);
8240 final NetworkAgentInfo oldDefaultNetwork =
8241 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8242 final NetworkAgentInfo newDefaultNetwork =
8243 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8244
8245 if (oldDefaultNetwork != newDefaultNetwork) {
8246 // Maintain the illusion : since the legacy API only understands one network at a time,
8247 // if the default network changed, apps should see a disconnected broadcast for the
8248 // old default network before they see a connected broadcast for the new one.
8249 if (oldDefaultNetwork != null) {
8250 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8251 oldDefaultNetwork, true);
8252 }
8253 if (newDefaultNetwork != null) {
8254 // The new default network can be newly null if and only if the old default
8255 // network doesn't satisfy the default request any more because it lost a
8256 // capability.
8257 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8258 mLegacyTypeTracker.add(
8259 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8260 }
8261 }
8262
8263 // Now that all the callbacks have been sent, send the legacy network broadcasts
8264 // as needed. This is necessary so that legacy requests correctly bind dns
8265 // requests to this network. The legacy users are listening for this broadcast
8266 // and will generally do a dns request so they can ensureRouteToHost and if
8267 // they do that before the callbacks happen they'll use the default network.
8268 //
8269 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8270 // callbacks, but if apps can receive the broadcast before the callback, they still might
8271 // have an inconsistent view of networking.
8272 //
8273 // This *does* introduce a race where if the user uses the new api
8274 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8275 // they may get old info. Reverse this after the old startUsing api is removed.
8276 // This is on top of the multiple intent sequencing referenced in the todo above.
8277 for (NetworkAgentInfo nai : nais) {
8278 if (nai.everConnected) {
8279 addNetworkToLegacyTypeTracker(nai);
8280 }
8281 }
8282 }
8283
8284 private void issueNetworkNeeds() {
8285 ensureRunningOnConnectivityServiceThread();
8286 for (final NetworkOfferInfo noi : mNetworkOffers) {
8287 issueNetworkNeeds(noi);
8288 }
8289 }
8290
8291 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8292 ensureRunningOnConnectivityServiceThread();
8293 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8294 informOffer(nri, noi.offer, mNetworkRanker);
8295 }
8296 }
8297
8298 /**
8299 * Inform a NetworkOffer about any new situation of a request.
8300 *
8301 * This function handles updates to offers. A number of events may happen that require
8302 * updating the registrant for this offer about the situation :
8303 * • The offer itself was updated. This may lead the offer to no longer being able
8304 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8305 * or conversely being strengthened enough to beat the satisfier (and therefore
8306 * start being needed)
8307 * • The network satisfying a request changed (including cases where the request
8308 * starts or stops being satisfied). The new network may be a stronger or weaker
8309 * match than the old one, possibly affecting whether the offer is needed.
8310 * • The network satisfying a request updated their score. This may lead the offer
8311 * to no longer be able to beat it if the current satisfier got better, or
8312 * conversely start being a good choice if the current satisfier got weaker.
8313 *
8314 * @param nri The request
8315 * @param offer The offer. This may be an updated offer.
8316 */
8317 private static void informOffer(@NonNull NetworkRequestInfo nri,
8318 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8319 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8320 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8321
8322 // Multi-layer requests have a currently active request, the one being satisfied.
8323 // Since the system will try to bring up a better network than is currently satisfying
8324 // the request, NetworkProviders need to be told the offers matching the requests *above*
8325 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8326 // not needed, and the offer is needed for the active request iff the offer can beat
8327 // the satisfier.
8328 // For non-multilayer requests, the logic above gracefully degenerates to only the
8329 // last case.
8330 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8331 // providers that the offer is needed for this request, until the active request is found.
8332 // In a second phase, deal with the currently active request. In a third phase, inform
8333 // the providers that offer is unneeded for the remaining requests.
8334
8335 // First phase : inform providers of all requests above the active request.
8336 int i;
8337 for (i = 0; nri.mRequests.size() > i; ++i) {
8338 final NetworkRequest request = nri.mRequests.get(i);
8339 if (activeRequest == request) break; // Found the active request : go to phase 2
8340 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8341 // Since this request is higher-priority than the one currently satisfied, if the
8342 // offer can satisfy it, the provider should try and bring up the network for sure ;
8343 // no need to even ask the ranker – an offer that can satisfy is always better than
8344 // no network. Hence tell the provider so unless it already knew.
8345 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8346 offer.onNetworkNeeded(request);
8347 }
8348 }
8349
8350 // Second phase : deal with the active request (if any)
8351 if (null != activeRequest && activeRequest.isRequest()) {
8352 final boolean oldNeeded = offer.neededFor(activeRequest);
8353 // An offer is needed if it is currently served by this provider or if this offer
8354 // can beat the current satisfier.
8355 final boolean currentlyServing = satisfier != null
8356 && satisfier.factorySerialNumber == offer.providerId;
8357 final boolean newNeeded = (currentlyServing
8358 || (activeRequest.canBeSatisfiedBy(offer.caps)
8359 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
8360 if (newNeeded != oldNeeded) {
8361 if (newNeeded) {
8362 offer.onNetworkNeeded(activeRequest);
8363 } else {
8364 // The offer used to be able to beat the satisfier. Now it can't.
8365 offer.onNetworkUnneeded(activeRequest);
8366 }
8367 }
8368 }
8369
8370 // Third phase : inform the providers that the offer isn't needed for any request
8371 // below the active one.
8372 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8373 final NetworkRequest request = nri.mRequests.get(i);
8374 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8375 // Since this request is lower-priority than the one currently satisfied, if the
8376 // offer can satisfy it, the provider should not try and bring up the network.
8377 // Hence tell the provider so unless it already knew.
8378 if (offer.neededFor(request)) {
8379 offer.onNetworkUnneeded(request);
8380 }
8381 }
8382 }
8383
8384 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8385 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8386 NetworkRequest nr = nai.requestAt(i);
8387 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8388 // legacy type tracker filters out repeat adds
8389 mLegacyTypeTracker.add(nr.legacyType, nai);
8390 }
8391 }
8392
8393 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8394 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8395 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8396 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8397 if (nai.isVPN()) {
8398 mLegacyTypeTracker.add(TYPE_VPN, nai);
8399 }
8400 }
8401
8402 private void updateInetCondition(NetworkAgentInfo nai) {
8403 // Don't bother updating until we've graduated to validated at least once.
8404 if (!nai.everValidated) return;
8405 // For now only update icons for the default connection.
8406 // TODO: Update WiFi and cellular icons separately. b/17237507
8407 if (!isDefaultNetwork(nai)) return;
8408
8409 int newInetCondition = nai.lastValidated ? 100 : 0;
8410 // Don't repeat publish.
8411 if (newInetCondition == mDefaultInetConditionPublished) return;
8412
8413 mDefaultInetConditionPublished = newInetCondition;
8414 sendInetConditionBroadcast(nai.networkInfo);
8415 }
8416
8417 @NonNull
8418 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8419 final NetworkInfo newInfo = new NetworkInfo(info);
8420 // The suspended and roaming bits are managed in NetworkCapabilities.
8421 final boolean suspended =
8422 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8423 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8424 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8425 // state. This is because the network could have been suspended before connecting,
8426 // or it could be disconnecting while being suspended, and in both these cases
8427 // the state should not be overridden. Note that the only detailed state that
8428 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8429 // worry about multiple different substates of CONNECTED.
8430 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8431 info.getExtraInfo());
8432 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8433 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8434 // network agent is created, then goes to suspended, then goes out of suspended without
8435 // ever setting connected. Check if network agent is ever connected to update the state.
8436 newInfo.setDetailedState(nai.everConnected
8437 ? NetworkInfo.DetailedState.CONNECTED
8438 : NetworkInfo.DetailedState.CONNECTING,
8439 info.getReason(),
8440 info.getExtraInfo());
8441 }
8442 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8443 return newInfo;
8444 }
8445
8446 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8447 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8448
8449 final NetworkInfo.State state = newInfo.getState();
8450 NetworkInfo oldInfo = null;
8451 synchronized (networkAgent) {
8452 oldInfo = networkAgent.networkInfo;
8453 networkAgent.networkInfo = newInfo;
8454 }
8455
8456 if (DBG) {
8457 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8458 + oldInfo.getState() + " to " + state);
8459 }
8460
8461 if (!networkAgent.created
8462 && (state == NetworkInfo.State.CONNECTED
8463 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8464
8465 // A network that has just connected has zero requests and is thus a foreground network.
8466 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8467
8468 if (!createNativeNetwork(networkAgent)) return;
Treehugger Robot4703a8c2021-07-02 13:55:33 +00008469 if (networkAgent.propagateUnderlyingCapabilities()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008470 // Initialize the network's capabilities to their starting values according to the
8471 // underlying networks. This ensures that the capabilities are correct before
8472 // anything happens to the network.
8473 updateCapabilitiesForNetwork(networkAgent);
8474 }
8475 networkAgent.created = true;
8476 networkAgent.onNetworkCreated();
8477 }
8478
8479 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8480 networkAgent.everConnected = true;
8481
8482 // NetworkCapabilities need to be set before sending the private DNS config to
8483 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8484 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8485
8486 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8487 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8488 null);
8489
8490 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8491 // command must be sent after updating LinkProperties to maximize chances of
8492 // NetworkMonitor seeing the correct LinkProperties when starting.
8493 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8494 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8495 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8496 }
8497 networkAgent.networkMonitor().notifyNetworkConnected(
8498 new LinkProperties(networkAgent.linkProperties,
8499 true /* parcelSensitiveFields */),
8500 networkAgent.networkCapabilities);
8501 scheduleUnvalidatedPrompt(networkAgent);
8502
8503 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8504 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8505 // capabilities, so it only needs to be done once on initial connect, not every time the
8506 // network's capabilities change. Note that we do this before rematching the network,
8507 // so we could decide to tear it down immediately afterwards. That's fine though - on
8508 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8509 // doing.
8510 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8511
8512 // Before first rematching networks, put an inactivity timer without any request, this
8513 // allows {@code updateInactivityState} to update the state accordingly and prevent
8514 // tearing down for any {@code unneeded} evaluation in this period.
8515 // Note that the timer will not be rescheduled since the expiry time is
8516 // fixed after connection regardless of the network satisfying other requests or not.
8517 // But it will be removed as soon as the network satisfies a request for the first time.
8518 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8519 SystemClock.elapsedRealtime(), mNascentDelayMs);
8520 networkAgent.setInactive();
8521
8522 // Consider network even though it is not yet validated.
8523 rematchAllNetworksAndRequests();
8524
8525 // This has to happen after matching the requests, because callbacks are just requests.
8526 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8527 } else if (state == NetworkInfo.State.DISCONNECTED) {
8528 networkAgent.disconnect();
8529 if (networkAgent.isVPN()) {
8530 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8531 }
8532 disconnectAndDestroyNetwork(networkAgent);
8533 if (networkAgent.isVPN()) {
8534 // As the active or bound network changes for apps, broadcast the default proxy, as
8535 // apps may need to update their proxy data. This is called after disconnecting from
8536 // VPN to make sure we do not broadcast the old proxy data.
8537 // TODO(b/122649188): send the broadcast only to VPN users.
8538 mProxyTracker.sendProxyBroadcast();
8539 }
8540 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8541 state == NetworkInfo.State.SUSPENDED)) {
8542 mLegacyTypeTracker.update(networkAgent);
8543 }
8544 }
8545
8546 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8547 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8548 nai.setScore(score);
8549 rematchAllNetworksAndRequests();
8550 }
8551
8552 // Notify only this one new request of the current state. Transfer all the
8553 // current state by calling NetworkCapabilities and LinkProperties callbacks
8554 // so that callers can be guaranteed to have as close to atomicity in state
8555 // transfer as can be supported by this current API.
8556 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8557 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8558 if (nri.mPendingIntent != null) {
8559 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8560 // Attempt no subsequent state pushes where intents are involved.
8561 return;
8562 }
8563
8564 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8565 final boolean metered = nai.networkCapabilities.isMetered();
8566 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8567 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8568 getBlockedState(blockedReasons, metered, vpnBlocked));
8569 }
8570
8571 // Notify the requests on this NAI that the network is now lingered.
8572 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8573 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8574 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8575 }
8576
8577 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8578 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8579 return vpnBlocked
8580 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8581 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8582 }
8583
8584 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8585 if (blockedReasons == BLOCKED_REASON_NONE) {
8586 mUidBlockedReasons.delete(uid);
8587 } else {
8588 mUidBlockedReasons.put(uid, blockedReasons);
8589 }
8590 }
8591
8592 /**
8593 * Notify of the blocked state apps with a registered callback matching a given NAI.
8594 *
8595 * Unlike other callbacks, blocked status is different between each individual uid. So for
8596 * any given nai, all requests need to be considered according to the uid who filed it.
8597 *
8598 * @param nai The target NetworkAgentInfo.
8599 * @param oldMetered True if the previous network capabilities were metered.
8600 * @param newMetered True if the current network capabilities are metered.
8601 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8602 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8603 */
8604 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8605 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8606 List<UidRange> newBlockedUidRanges) {
8607
8608 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8609 NetworkRequest nr = nai.requestAt(i);
8610 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8611
8612 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8613 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8614 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8615 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8616 : oldVpnBlocked;
8617
8618 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8619 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8620 if (oldBlockedState != newBlockedState) {
8621 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8622 newBlockedState);
8623 }
8624 }
8625 }
8626
8627 /**
8628 * Notify apps with a given UID of the new blocked state according to new uid state.
8629 * @param uid The uid for which the rules changed.
8630 * @param blockedReasons The reasons for why an uid is blocked.
8631 */
8632 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8633 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8634 final boolean metered = nai.networkCapabilities.isMetered();
8635 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8636
8637 final int oldBlockedState = getBlockedState(
8638 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8639 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8640 if (oldBlockedState == newBlockedState) {
8641 continue;
8642 }
8643 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8644 NetworkRequest nr = nai.requestAt(i);
8645 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8646 if (nri != null && nri.mAsUid == uid) {
8647 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8648 newBlockedState);
8649 }
8650 }
8651 }
8652 }
8653
8654 @VisibleForTesting
8655 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8656 // The NetworkInfo we actually send out has no bearing on the real
8657 // state of affairs. For example, if the default connection is mobile,
8658 // and a request for HIPRI has just gone away, we need to pretend that
8659 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8660 // the state to DISCONNECTED, even though the network is of type MOBILE
8661 // and is still connected.
8662 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8663 info.setType(type);
8664 filterForLegacyLockdown(info);
8665 if (state != DetailedState.DISCONNECTED) {
8666 info.setDetailedState(state, null, info.getExtraInfo());
8667 sendConnectedBroadcast(info);
8668 } else {
8669 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8670 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8671 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8672 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8673 if (info.isFailover()) {
8674 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8675 nai.networkInfo.setFailover(false);
8676 }
8677 if (info.getReason() != null) {
8678 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8679 }
8680 if (info.getExtraInfo() != null) {
8681 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8682 }
8683 NetworkAgentInfo newDefaultAgent = null;
8684 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8685 newDefaultAgent = mDefaultRequest.getSatisfier();
8686 if (newDefaultAgent != null) {
8687 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8688 newDefaultAgent.networkInfo);
8689 } else {
8690 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8691 }
8692 }
8693 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8694 mDefaultInetConditionPublished);
8695 sendStickyBroadcast(intent);
8696 if (newDefaultAgent != null) {
8697 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8698 }
8699 }
8700 }
8701
8702 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8703 if (VDBG || DDBG) {
8704 String notification = ConnectivityManager.getCallbackName(notifyType);
8705 log("notifyType " + notification + " for " + networkAgent.toShortString());
8706 }
8707 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8708 NetworkRequest nr = networkAgent.requestAt(i);
8709 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8710 if (VDBG) log(" sending notification for " + nr);
8711 if (nri.mPendingIntent == null) {
8712 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8713 } else {
8714 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8715 }
8716 }
8717 }
8718
8719 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8720 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8721 }
8722
8723 /**
8724 * Returns the list of all interfaces that could be used by network traffic that does not
8725 * explicitly specify a network. This includes the default network, but also all VPNs that are
8726 * currently connected.
8727 *
8728 * Must be called on the handler thread.
8729 */
8730 @NonNull
8731 private ArrayList<Network> getDefaultNetworks() {
8732 ensureRunningOnConnectivityServiceThread();
8733 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8734 final Set<Integer> activeNetIds = new ArraySet<>();
8735 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8736 if (nri.isBeingSatisfied()) {
8737 activeNetIds.add(nri.getSatisfier().network().netId);
8738 }
8739 }
8740 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8741 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8742 defaultNetworks.add(nai.network);
8743 }
8744 }
8745 return defaultNetworks;
8746 }
8747
8748 /**
8749 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8750 * active iface's tracked properties has changed.
8751 */
8752 private void notifyIfacesChangedForNetworkStats() {
8753 ensureRunningOnConnectivityServiceThread();
8754 String activeIface = null;
8755 LinkProperties activeLinkProperties = getActiveLinkProperties();
8756 if (activeLinkProperties != null) {
8757 activeIface = activeLinkProperties.getInterfaceName();
8758 }
8759
8760 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8761 try {
8762 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai0f570222021-03-05 14:46:25 +08008763 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008764 snapshots.add(snapshot);
8765 }
8766 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8767 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8768 } catch (Exception ignored) {
8769 }
8770 }
8771
8772 @Override
8773 public String getCaptivePortalServerUrl() {
8774 enforceNetworkStackOrSettingsPermission();
8775 String settingUrl = mResources.get().getString(
8776 R.string.config_networkCaptivePortalServerUrl);
8777
8778 if (!TextUtils.isEmpty(settingUrl)) {
8779 return settingUrl;
8780 }
8781
8782 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8783 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8784 if (!TextUtils.isEmpty(settingUrl)) {
8785 return settingUrl;
8786 }
8787
8788 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8789 }
8790
8791 @Override
8792 public void startNattKeepalive(Network network, int intervalSeconds,
8793 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8794 enforceKeepalivePermission();
8795 mKeepaliveTracker.startNattKeepalive(
8796 getNetworkAgentInfoForNetwork(network), null /* fd */,
8797 intervalSeconds, cb,
8798 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8799 }
8800
8801 @Override
8802 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8803 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8804 String dstAddr) {
8805 try {
8806 final FileDescriptor fd = pfd.getFileDescriptor();
8807 mKeepaliveTracker.startNattKeepalive(
8808 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8809 intervalSeconds, cb,
8810 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8811 } finally {
8812 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8813 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8814 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8815 IoUtils.closeQuietly(pfd);
8816 }
8817 }
8818 }
8819
8820 @Override
8821 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8822 ISocketKeepaliveCallback cb) {
8823 try {
8824 enforceKeepalivePermission();
8825 final FileDescriptor fd = pfd.getFileDescriptor();
8826 mKeepaliveTracker.startTcpKeepalive(
8827 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8828 } finally {
8829 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8830 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8831 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8832 IoUtils.closeQuietly(pfd);
8833 }
8834 }
8835 }
8836
8837 @Override
8838 public void stopKeepalive(Network network, int slot) {
8839 mHandler.sendMessage(mHandler.obtainMessage(
8840 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8841 }
8842
8843 @Override
8844 public void factoryReset() {
8845 enforceSettingsPermission();
8846
Treehugger Robotfac2a722021-05-21 02:42:59 +00008847 final int uid = mDeps.getCallingUid();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008848 final long token = Binder.clearCallingIdentity();
8849 try {
Treehugger Robotfac2a722021-05-21 02:42:59 +00008850 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
8851 UserHandle.getUserHandleForUid(uid))) {
8852 return;
8853 }
8854
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008855 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8856 ipMemoryStore.factoryReset();
Treehugger Robotfac2a722021-05-21 02:42:59 +00008857
8858 // Turn airplane mode off
8859 setAirplaneMode(false);
8860
8861 // restore private DNS settings to default mode (opportunistic)
8862 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
8863 UserHandle.getUserHandleForUid(uid))) {
8864 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
8865 PRIVATE_DNS_MODE_OPPORTUNISTIC);
8866 }
8867
8868 Settings.Global.putString(mContext.getContentResolver(),
8869 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008870 } finally {
8871 Binder.restoreCallingIdentity(token);
8872 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00008873 }
8874
8875 @Override
8876 public byte[] getNetworkWatchlistConfigHash() {
8877 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8878 if (nwm == null) {
8879 loge("Unable to get NetworkWatchlistManager");
8880 return null;
8881 }
8882 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8883 return nwm.getWatchlistConfigHash();
8884 }
8885
8886 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8887 int[] transports = nai.networkCapabilities.getTransportTypes();
8888 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8889 }
8890
8891 private static boolean toBool(int encodedBoolean) {
8892 return encodedBoolean != 0; // Only 0 means false.
8893 }
8894
8895 private static int encodeBool(boolean b) {
8896 return b ? 1 : 0;
8897 }
8898
8899 @Override
8900 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8901 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8902 @NonNull String[] args) {
8903 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8904 err.getFileDescriptor(), args);
8905 }
8906
8907 private class ShellCmd extends BasicShellCommandHandler {
8908 @Override
8909 public int onCommand(String cmd) {
8910 if (cmd == null) {
8911 return handleDefaultCommands(cmd);
8912 }
8913 final PrintWriter pw = getOutPrintWriter();
8914 try {
8915 switch (cmd) {
8916 case "airplane-mode":
8917 final String action = getNextArg();
8918 if ("enable".equals(action)) {
8919 setAirplaneMode(true);
8920 return 0;
8921 } else if ("disable".equals(action)) {
8922 setAirplaneMode(false);
8923 return 0;
8924 } else if (action == null) {
8925 final ContentResolver cr = mContext.getContentResolver();
8926 final int enabled = Settings.Global.getInt(cr,
8927 Settings.Global.AIRPLANE_MODE_ON);
8928 pw.println(enabled == 0 ? "disabled" : "enabled");
8929 return 0;
8930 } else {
8931 onHelp();
8932 return -1;
8933 }
8934 default:
8935 return handleDefaultCommands(cmd);
8936 }
8937 } catch (Exception e) {
8938 pw.println(e);
8939 }
8940 return -1;
8941 }
8942
8943 @Override
8944 public void onHelp() {
8945 PrintWriter pw = getOutPrintWriter();
8946 pw.println("Connectivity service commands:");
8947 pw.println(" help");
8948 pw.println(" Print this help text.");
8949 pw.println(" airplane-mode [enable|disable]");
8950 pw.println(" Turn airplane mode on or off.");
8951 pw.println(" airplane-mode");
8952 pw.println(" Get airplane mode.");
8953 }
8954 }
8955
8956 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8957 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8958 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8959 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8960 return ((VpnTransportInfo) ti).getType();
8961 }
8962
8963 /**
8964 * @param connectionInfo the connection to resolve.
8965 * @return {@code uid} if the connection is found and the app has permission to observe it
8966 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8967 * connection is not found.
8968 */
8969 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8970 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8971 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8972 }
8973
8974 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
8975 connectionInfo.local, connectionInfo.remote);
8976
8977 if (uid == INVALID_UID) return uid; // Not found.
8978
8979 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8980 // VPN, if any, that applies to the UID that owns the connection.
8981 if (checkNetworkStackPermission()) return uid;
8982
8983 final NetworkAgentInfo vpn = getVpnForUid(uid);
8984 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
8985 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
8986 return INVALID_UID;
8987 }
8988
8989 return uid;
8990 }
8991
8992 /**
8993 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8994 *
8995 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8996 */
8997 @Override
8998 public IBinder startOrGetTestNetworkService() {
8999 synchronized (mTNSLock) {
9000 TestNetworkService.enforceTestNetworkPermissions(mContext);
9001
9002 if (mTNS == null) {
9003 mTNS = new TestNetworkService(mContext);
9004 }
9005
9006 return mTNS;
9007 }
9008 }
9009
9010 /**
9011 * Handler used for managing all Connectivity Diagnostics related functions.
9012 *
9013 * @see android.net.ConnectivityDiagnosticsManager
9014 *
9015 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9016 */
9017 @VisibleForTesting
9018 class ConnectivityDiagnosticsHandler extends Handler {
9019 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9020
9021 /**
9022 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9023 * android.net.ConnectivityDiagnosticsManager}.
9024 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9025 * NetworkRequestInfo to be registered
9026 */
9027 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9028
9029 /**
9030 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9031 * android.net.ConnectivityDiagnosticsManager}.
9032 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9033 * arg1 = the uid of the caller
9034 */
9035 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9036
9037 /**
9038 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9039 * after processing {@link #EVENT_NETWORK_TESTED} events.
9040 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9041 * NetworkMonitor.
9042 * data = PersistableBundle of extras passed from NetworkMonitor.
9043 *
9044 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9045 */
9046 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9047
9048 /**
9049 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9050 * been detected on the network.
9051 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9052 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9053 * arg2 = NetID.
9054 * data = PersistableBundle of extras passed from NetworkMonitor.
9055 */
9056 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9057
9058 /**
9059 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9060 * the platform. This event will invoke {@link
9061 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9062 * callbacks.
9063 * obj = Network that was reported on
9064 * arg1 = boolint for the quality reported
9065 */
9066 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9067
9068 private ConnectivityDiagnosticsHandler(Looper looper) {
9069 super(looper);
9070 }
9071
9072 @Override
9073 public void handleMessage(Message msg) {
9074 switch (msg.what) {
9075 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9076 handleRegisterConnectivityDiagnosticsCallback(
9077 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9078 break;
9079 }
9080 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9081 handleUnregisterConnectivityDiagnosticsCallback(
9082 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9083 break;
9084 }
9085 case EVENT_NETWORK_TESTED: {
9086 final ConnectivityReportEvent reportEvent =
9087 (ConnectivityReportEvent) msg.obj;
9088
9089 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
9090 break;
9091 }
9092 case EVENT_DATA_STALL_SUSPECTED: {
9093 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
9094 final Pair<Long, PersistableBundle> arg =
9095 (Pair<Long, PersistableBundle>) msg.obj;
9096 if (nai == null) break;
9097
9098 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
9099 break;
9100 }
9101 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
9102 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
9103 break;
9104 }
9105 default: {
9106 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9107 }
9108 }
9109 }
9110 }
9111
9112 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9113 @VisibleForTesting
9114 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9115 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9116 @NonNull private final NetworkRequestInfo mRequestInfo;
9117 @NonNull private final String mCallingPackageName;
9118
9119 @VisibleForTesting
9120 ConnectivityDiagnosticsCallbackInfo(
9121 @NonNull IConnectivityDiagnosticsCallback cb,
9122 @NonNull NetworkRequestInfo nri,
9123 @NonNull String callingPackageName) {
9124 mCb = cb;
9125 mRequestInfo = nri;
9126 mCallingPackageName = callingPackageName;
9127 }
9128
9129 @Override
9130 public void binderDied() {
9131 log("ConnectivityDiagnosticsCallback IBinder died.");
9132 unregisterConnectivityDiagnosticsCallback(mCb);
9133 }
9134 }
9135
9136 /**
9137 * Class used for sending information from {@link
9138 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9139 */
9140 private static class NetworkTestedResults {
9141 private final int mNetId;
9142 private final int mTestResult;
9143 private final long mTimestampMillis;
9144 @Nullable private final String mRedirectUrl;
9145
9146 private NetworkTestedResults(
9147 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9148 mNetId = netId;
9149 mTestResult = testResult;
9150 mTimestampMillis = timestampMillis;
9151 mRedirectUrl = redirectUrl;
9152 }
9153 }
9154
9155 /**
9156 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9157 * ConnectivityDiagnosticsHandler}.
9158 */
9159 private static class ConnectivityReportEvent {
9160 private final long mTimestampMillis;
9161 @NonNull private final NetworkAgentInfo mNai;
9162 private final PersistableBundle mExtras;
9163
9164 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9165 PersistableBundle p) {
9166 mTimestampMillis = timestampMillis;
9167 mNai = nai;
9168 mExtras = p;
9169 }
9170 }
9171
9172 private void handleRegisterConnectivityDiagnosticsCallback(
9173 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9174 ensureRunningOnConnectivityServiceThread();
9175
9176 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
9177 final IBinder iCb = cb.asBinder();
9178 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9179
9180 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9181 // confusing for these networks to change when an NRI is satisfied in another layer.
9182 if (nri.isMultilayerRequest()) {
9183 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9184 + "network requests.");
9185 }
9186
9187 // This means that the client registered the same callback multiple times. Do
9188 // not override the previous entry, and exit silently.
9189 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9190 if (VDBG) log("Diagnostics callback is already registered");
9191
9192 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9193 // incremented when the NetworkRequestInfo is created as part of
9194 // enforceRequestCountLimit().
9195 nri.decrementRequestCount();
9196 return;
9197 }
9198
9199 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9200
9201 try {
9202 iCb.linkToDeath(cbInfo, 0);
9203 } catch (RemoteException e) {
9204 cbInfo.binderDied();
9205 return;
9206 }
9207
9208 // Once registered, provide ConnectivityReports for matching Networks
9209 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9210 synchronized (mNetworkForNetId) {
9211 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9212 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9213 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9214 if (nai.satisfies(nri.mRequests.get(0))) {
9215 matchingNetworks.add(nai);
9216 }
9217 }
9218 }
9219 for (final NetworkAgentInfo nai : matchingNetworks) {
9220 final ConnectivityReport report = nai.getConnectivityReport();
9221 if (report == null) {
9222 continue;
9223 }
9224 if (!checkConnectivityDiagnosticsPermissions(
9225 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9226 continue;
9227 }
9228
9229 try {
9230 cb.onConnectivityReportAvailable(report);
9231 } catch (RemoteException e) {
9232 // Exception while sending the ConnectivityReport. Move on to the next network.
9233 }
9234 }
9235 }
9236
9237 private void handleUnregisterConnectivityDiagnosticsCallback(
9238 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9239 ensureRunningOnConnectivityServiceThread();
9240 final IBinder iCb = cb.asBinder();
9241
9242 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9243 mConnectivityDiagnosticsCallbacks.remove(iCb);
9244 if (cbInfo == null) {
9245 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9246 return;
9247 }
9248
9249 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9250
9251 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9252 // (if the Binder died)
9253 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9254 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9255 return;
9256 }
9257
9258 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9259 // incremented when the NetworkRequestInfo is created as part of
9260 // enforceRequestCountLimit().
9261 nri.decrementRequestCount();
9262
9263 iCb.unlinkToDeath(cbInfo, 0);
9264 }
9265
9266 private void handleNetworkTestedWithExtras(
9267 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9268 final NetworkAgentInfo nai = reportEvent.mNai;
9269 final NetworkCapabilities networkCapabilities =
9270 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9271 final ConnectivityReport report =
9272 new ConnectivityReport(
9273 reportEvent.mNai.network,
9274 reportEvent.mTimestampMillis,
9275 nai.linkProperties,
9276 networkCapabilities,
9277 extras);
9278 nai.setConnectivityReport(report);
9279 final List<IConnectivityDiagnosticsCallback> results =
9280 getMatchingPermissionedCallbacks(nai);
9281 for (final IConnectivityDiagnosticsCallback cb : results) {
9282 try {
9283 cb.onConnectivityReportAvailable(report);
9284 } catch (RemoteException ex) {
9285 loge("Error invoking onConnectivityReport", ex);
9286 }
9287 }
9288 }
9289
9290 private void handleDataStallSuspected(
9291 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9292 @NonNull PersistableBundle extras) {
9293 final NetworkCapabilities networkCapabilities =
9294 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9295 final DataStallReport report =
9296 new DataStallReport(
9297 nai.network,
9298 timestampMillis,
9299 detectionMethod,
9300 nai.linkProperties,
9301 networkCapabilities,
9302 extras);
9303 final List<IConnectivityDiagnosticsCallback> results =
9304 getMatchingPermissionedCallbacks(nai);
9305 for (final IConnectivityDiagnosticsCallback cb : results) {
9306 try {
9307 cb.onDataStallSuspected(report);
9308 } catch (RemoteException ex) {
9309 loge("Error invoking onDataStallSuspected", ex);
9310 }
9311 }
9312 }
9313
9314 private void handleNetworkConnectivityReported(
9315 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9316 final List<IConnectivityDiagnosticsCallback> results =
9317 getMatchingPermissionedCallbacks(nai);
9318 for (final IConnectivityDiagnosticsCallback cb : results) {
9319 try {
9320 cb.onNetworkConnectivityReported(nai.network, connectivity);
9321 } catch (RemoteException ex) {
9322 loge("Error invoking onNetworkConnectivityReported", ex);
9323 }
9324 }
9325 }
9326
9327 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9328 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9329 NetworkCapabilities.REDACT_ALL);
9330 sanitized.setUids(null);
9331 sanitized.setAdministratorUids(new int[0]);
9332 sanitized.setOwnerUid(Process.INVALID_UID);
9333 return sanitized;
9334 }
9335
9336 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9337 @NonNull NetworkAgentInfo nai) {
9338 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9339 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9340 mConnectivityDiagnosticsCallbacks.entrySet()) {
9341 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9342 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9343 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9344 if (nai.satisfies(nri.mRequests.get(0))) {
9345 if (checkConnectivityDiagnosticsPermissions(
9346 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9347 results.add(entry.getValue().mCb);
9348 }
9349 }
9350 }
9351 return results;
9352 }
9353
Treehugger Robot27b68882021-06-07 19:42:39 +00009354 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9355 @NonNull NetworkAgentInfo nai) {
9356 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9357 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9358 }
9359
Cody Kesting0b4be022021-05-20 22:57:07 +00009360 private boolean hasLocationPermission(String packageName, int uid) {
9361 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9362 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9363 // call in a try-catch.
9364 try {
9365 if (!mLocationPermissionChecker.checkLocationPermission(
9366 packageName, null /* featureId */, uid, null /* message */)) {
9367 return false;
9368 }
9369 } catch (SecurityException e) {
9370 return false;
9371 }
9372
9373 return true;
9374 }
9375
9376 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9377 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Treehugger Robot4703a8c2021-07-02 13:55:33 +00009378 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting0b4be022021-05-20 22:57:07 +00009379 && virtual.networkCapabilities.getOwnerUid() == uid
9380 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9381 return true;
9382 }
9383 }
9384
9385 return false;
9386 }
9387
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009388 @VisibleForTesting
9389 boolean checkConnectivityDiagnosticsPermissions(
9390 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9391 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9392 return true;
9393 }
9394
Cody Kesting0b4be022021-05-20 22:57:07 +00009395 // Administrator UIDs also contains the Owner UID
9396 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9397 if (!CollectionUtils.contains(administratorUids, callbackUid)
9398 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009399 return false;
9400 }
9401
Treehugger Robot27b68882021-06-07 19:42:39 +00009402 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9403 || hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009404 }
9405
9406 @Override
9407 public void registerConnectivityDiagnosticsCallback(
9408 @NonNull IConnectivityDiagnosticsCallback callback,
9409 @NonNull NetworkRequest request,
9410 @NonNull String callingPackageName) {
9411 if (request.legacyType != TYPE_NONE) {
9412 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9413 + " Please use NetworkCapabilities instead.");
9414 }
9415 final int callingUid = mDeps.getCallingUid();
9416 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9417
9418 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9419 // and administrator uids to be safe.
9420 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9421 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9422
9423 final NetworkRequest requestWithId =
9424 new NetworkRequest(
9425 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9426
9427 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9428 //
9429 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9430 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9431 // callback's binder death.
9432 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9433 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9434 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9435
9436 mConnectivityDiagnosticsHandler.sendMessage(
9437 mConnectivityDiagnosticsHandler.obtainMessage(
9438 ConnectivityDiagnosticsHandler
9439 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9440 cbInfo));
9441 }
9442
9443 @Override
9444 public void unregisterConnectivityDiagnosticsCallback(
9445 @NonNull IConnectivityDiagnosticsCallback callback) {
9446 Objects.requireNonNull(callback, "callback must be non-null");
9447 mConnectivityDiagnosticsHandler.sendMessage(
9448 mConnectivityDiagnosticsHandler.obtainMessage(
9449 ConnectivityDiagnosticsHandler
9450 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9451 mDeps.getCallingUid(),
9452 0,
9453 callback));
9454 }
9455
9456 @Override
9457 public void simulateDataStall(int detectionMethod, long timestampMillis,
9458 @NonNull Network network, @NonNull PersistableBundle extras) {
9459 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9460 android.Manifest.permission.NETWORK_STACK);
9461 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9462 if (!nc.hasTransport(TRANSPORT_TEST)) {
9463 throw new SecurityException("Data Stall simluation is only possible for test networks");
9464 }
9465
9466 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9467 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9468 throw new SecurityException("Data Stall simulation is only possible for network "
9469 + "creators");
9470 }
9471
9472 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9473 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9474 // Data Stall information as a DataStallReportParcelable and passing to
9475 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9476 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9477 final DataStallReportParcelable p = new DataStallReportParcelable();
9478 p.timestampMillis = timestampMillis;
9479 p.detectionMethod = detectionMethod;
9480
9481 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9482 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9483 }
9484 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9485 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9486 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9487 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9488 }
9489
9490 notifyDataStallSuspected(p, network.getNetId());
9491 }
9492
9493 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9494 @Override
9495 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9496 long timestampNs, int uid) {
9497 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9498 }
9499
9500 @Override
9501 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9502 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9503 nai.clatd.interfaceLinkStateChanged(iface, up);
9504 }
9505 }
9506
9507 @Override
9508 public void onInterfaceRemoved(String iface) {
9509 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9510 nai.clatd.interfaceRemoved(iface);
9511 }
9512 }
9513 }
9514
9515 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9516
9517 /**
9518 * Class used for updating network activity tracking with netd and notify network activity
9519 * changes.
9520 */
9521 private static final class LegacyNetworkActivityTracker {
9522 private static final int NO_UID = -1;
9523 private final Context mContext;
9524 private final INetd mNetd;
9525 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9526 new RemoteCallbackList<>();
9527 // Indicate the current system default network activity is active or not.
9528 @GuardedBy("mActiveIdleTimers")
9529 private boolean mNetworkActive;
9530 @GuardedBy("mActiveIdleTimers")
9531 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9532 private final Handler mHandler;
9533
9534 private class IdleTimerParams {
9535 public final int timeout;
9536 public final int transportType;
9537
9538 IdleTimerParams(int timeout, int transport) {
9539 this.timeout = timeout;
9540 this.transportType = transport;
9541 }
9542 }
9543
9544 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9545 @NonNull INetd netd) {
9546 mContext = context;
9547 mNetd = netd;
9548 mHandler = handler;
9549 }
9550
9551 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9552 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9553 synchronized (mActiveIdleTimers) {
9554 mNetworkActive = active;
9555 // If there are no idle timers, it means that system is not monitoring
9556 // activity, so the system default network for those default network
9557 // unspecified apps is always considered active.
9558 //
9559 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9560 // any network activity change event. Whenever this event is received,
9561 // the mActiveIdleTimers should be always not empty. The legacy behavior
9562 // is no-op. Remove to refer to mNetworkActive only.
9563 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9564 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9565 }
9566 }
9567 }
9568
9569 // The network activity should only be updated from ConnectivityService handler thread
9570 // when mActiveIdleTimers lock is held.
9571 @GuardedBy("mActiveIdleTimers")
9572 private void reportNetworkActive() {
9573 final int length = mNetworkActivityListeners.beginBroadcast();
9574 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9575 try {
9576 for (int i = 0; i < length; i++) {
9577 try {
9578 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9579 } catch (RemoteException | RuntimeException e) {
9580 loge("Fail to send network activie to listener " + e);
9581 }
9582 }
9583 } finally {
9584 mNetworkActivityListeners.finishBroadcast();
9585 }
9586 }
9587
9588 @GuardedBy("mActiveIdleTimers")
9589 public void handleReportNetworkActivity() {
9590 synchronized (mActiveIdleTimers) {
9591 reportNetworkActive();
9592 }
9593 }
9594
9595 // This is deprecated and only to support legacy use cases.
9596 private int transportTypeToLegacyType(int type) {
9597 switch (type) {
9598 case NetworkCapabilities.TRANSPORT_CELLULAR:
9599 return TYPE_MOBILE;
9600 case NetworkCapabilities.TRANSPORT_WIFI:
9601 return TYPE_WIFI;
9602 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9603 return TYPE_BLUETOOTH;
9604 case NetworkCapabilities.TRANSPORT_ETHERNET:
9605 return TYPE_ETHERNET;
9606 default:
9607 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9608 }
9609 return ConnectivityManager.TYPE_NONE;
9610 }
9611
9612 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9613 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9614 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9615 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9616 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9617 final long ident = Binder.clearCallingIdentity();
9618 try {
9619 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9620 RECEIVE_DATA_ACTIVITY_CHANGE,
9621 null /* resultReceiver */,
9622 null /* scheduler */,
9623 0 /* initialCode */,
9624 null /* initialData */,
9625 null /* initialExtra */);
9626 } finally {
9627 Binder.restoreCallingIdentity(ident);
9628 }
9629 }
9630
9631 /**
9632 * Setup data activity tracking for the given network.
9633 *
9634 * Every {@code setupDataActivityTracking} should be paired with a
9635 * {@link #removeDataActivityTracking} for cleanup.
9636 */
9637 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9638 final String iface = networkAgent.linkProperties.getInterfaceName();
9639
9640 final int timeout;
9641 final int type;
9642
9643 if (networkAgent.networkCapabilities.hasTransport(
9644 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9645 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9646 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9647 10);
9648 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9649 } else if (networkAgent.networkCapabilities.hasTransport(
9650 NetworkCapabilities.TRANSPORT_WIFI)) {
9651 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9652 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9653 15);
9654 type = NetworkCapabilities.TRANSPORT_WIFI;
9655 } else {
9656 return; // do not track any other networks
9657 }
9658
9659 updateRadioPowerState(true /* isActive */, type);
9660
9661 if (timeout > 0 && iface != null) {
9662 try {
9663 synchronized (mActiveIdleTimers) {
9664 // Networks start up.
9665 mNetworkActive = true;
9666 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9667 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9668 reportNetworkActive();
9669 }
9670 } catch (Exception e) {
9671 // You shall not crash!
9672 loge("Exception in setupDataActivityTracking " + e);
9673 }
9674 }
9675 }
9676
9677 /**
9678 * Remove data activity tracking when network disconnects.
9679 */
9680 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9681 final String iface = networkAgent.linkProperties.getInterfaceName();
9682 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9683
9684 if (iface == null) return;
9685
9686 final int type;
9687 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9688 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9689 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9690 type = NetworkCapabilities.TRANSPORT_WIFI;
9691 } else {
9692 return; // do not track any other networks
9693 }
9694
9695 try {
9696 updateRadioPowerState(false /* isActive */, type);
9697 synchronized (mActiveIdleTimers) {
9698 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9699 // The call fails silently if no idle timer setup for this interface
9700 mNetd.idletimerRemoveInterface(iface, params.timeout,
9701 Integer.toString(params.transportType));
9702 }
9703 } catch (Exception e) {
9704 // You shall not crash!
9705 loge("Exception in removeDataActivityTracking " + e);
9706 }
9707 }
9708
9709 /**
9710 * Update data activity tracking when network state is updated.
9711 */
9712 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9713 NetworkAgentInfo oldNetwork) {
9714 if (newNetwork != null) {
9715 setupDataActivityTracking(newNetwork);
9716 }
9717 if (oldNetwork != null) {
9718 removeDataActivityTracking(oldNetwork);
9719 }
9720 }
9721
9722 private void updateRadioPowerState(boolean isActive, int transportType) {
9723 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9724 switch (transportType) {
9725 case NetworkCapabilities.TRANSPORT_CELLULAR:
9726 bs.reportMobileRadioPowerState(isActive, NO_UID);
9727 break;
9728 case NetworkCapabilities.TRANSPORT_WIFI:
9729 bs.reportWifiRadioPowerState(isActive, NO_UID);
9730 break;
9731 default:
9732 logw("Untracked transport type:" + transportType);
9733 }
9734 }
9735
9736 public boolean isDefaultNetworkActive() {
9737 synchronized (mActiveIdleTimers) {
9738 // If there are no idle timers, it means that system is not monitoring activity,
9739 // so the default network is always considered active.
9740 //
9741 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9742 // tracking is disabled (negative idle timer value configured), or no active default
9743 // network. In the latter case, this reports active but it should report inactive.
9744 return mNetworkActive || mActiveIdleTimers.isEmpty();
9745 }
9746 }
9747
9748 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9749 mNetworkActivityListeners.register(l);
9750 }
9751
9752 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9753 mNetworkActivityListeners.unregister(l);
9754 }
9755
9756 public void dump(IndentingPrintWriter pw) {
9757 synchronized (mActiveIdleTimers) {
9758 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9759 pw.println("Idle timers:");
9760 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9761 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9762 final IdleTimerParams params = ent.getValue();
9763 pw.print(" timeout="); pw.print(params.timeout);
9764 pw.print(" type="); pw.println(params.transportType);
9765 }
9766 }
9767 }
9768 }
9769
9770 /**
9771 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9772 *
9773 * @param socketInfo the socket information
9774 * @param callback the callback to register
9775 */
9776 @Override
9777 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9778 @NonNull final IQosCallback callback) {
9779 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9780 if (nai == null || nai.networkCapabilities == null) {
9781 try {
9782 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9783 } catch (final RemoteException ex) {
9784 loge("registerQosCallbackInternal: RemoteException", ex);
9785 }
9786 return;
9787 }
9788 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9789 }
9790
9791 /**
9792 * Register a {@link IQosCallback} with base {@link QosFilter}.
9793 *
9794 * @param filter the filter to register
9795 * @param callback the callback to register
9796 * @param nai the agent information related to the filter's network
9797 */
9798 @VisibleForTesting
9799 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9800 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9801 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9802 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9803
9804 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9805 enforceConnectivityRestrictedNetworksPermission();
9806 }
9807 mQosCallbackTracker.registerCallback(callback, filter, nai);
9808 }
9809
9810 /**
9811 * Unregisters the given callback.
9812 *
9813 * @param callback the callback to unregister
9814 */
9815 @Override
9816 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9817 Objects.requireNonNull(callback, "callback must be non-null");
9818 mQosCallbackTracker.unregisterCallback(callback);
9819 }
9820
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009821 /**
9822 * Request that a user profile is put by default on a network matching a given preference.
9823 *
9824 * See the documentation for the individual preferences for a description of the supported
9825 * behaviors.
9826 *
9827 * @param profile the profile concerned.
9828 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9829 * constants.
9830 * @param listener an optional listener to listen for completion of the operation.
9831 */
9832 @Override
9833 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9834 @ConnectivityManager.ProfileNetworkPreference final int preference,
9835 @Nullable final IOnCompleteListener listener) {
9836 Objects.requireNonNull(profile);
9837 PermissionUtils.enforceNetworkStackPermission(mContext);
9838 if (DBG) {
9839 log("setProfileNetworkPreference " + profile + " to " + preference);
9840 }
9841 if (profile.getIdentifier() < 0) {
9842 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9843 + "UserHandle.CURRENT not supported)");
9844 }
9845 final UserManager um = mContext.getSystemService(UserManager.class);
9846 if (!um.isManagedProfile(profile.getIdentifier())) {
9847 throw new IllegalArgumentException("Profile must be a managed profile");
9848 }
paulhude5efb92021-05-26 21:56:03 +08009849
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009850 final NetworkCapabilities nc;
9851 switch (preference) {
9852 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9853 nc = null;
9854 break;
9855 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9856 final UidRange uids = UidRange.createForUser(profile);
9857 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9858 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9859 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9860 break;
9861 default:
9862 throw new IllegalArgumentException(
9863 "Invalid preference in setProfileNetworkPreference");
9864 }
9865 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9866 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9867 }
9868
9869 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9870 @Nullable final NetworkCapabilities nc) {
9871 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9872 ensureRequestableCapabilities(nc);
9873 }
9874
9875 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9876 @NonNull final ProfileNetworkPreferences prefs) {
9877 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9878 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9879 // The NRI for a user should be comprised of two layers:
9880 // - The request for the capabilities
9881 // - The request for the default network, for fallback. Create an image of it to
9882 // have the correct UIDs in it (also a request can only be part of one NRI, because
9883 // of lookups in 1:1 associations like mNetworkRequests).
9884 // Note that denying a fallback can be implemented simply by not adding the second
9885 // request.
9886 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9887 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9888 nrs.add(createDefaultInternetRequestForTransport(
9889 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9890 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhuc2198772021-05-26 15:19:20 +08009891 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhude5efb92021-05-26 21:56:03 +08009892 PREFERENCE_PRIORITY_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009893 result.add(nri);
9894 }
9895 return result;
9896 }
9897
9898 private void handleSetProfileNetworkPreference(
9899 @NonNull final ProfileNetworkPreferences.Preference preference,
9900 @Nullable final IOnCompleteListener listener) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009901 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9902
9903 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9904 mSystemNetworkRequestCounter.transact(
9905 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9906 () -> {
9907 final ArraySet<NetworkRequestInfo> nris =
9908 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
paulhude5efb92021-05-26 21:56:03 +08009909 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_PRIORITY_PROFILE);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009910 });
9911 // Finally, rematch.
9912 rematchAllNetworksAndRequests();
9913
9914 if (null != listener) {
9915 try {
9916 listener.onComplete();
9917 } catch (RemoteException e) {
9918 loge("Listener for setProfileNetworkPreference has died");
9919 }
9920 }
9921 }
9922
paulhu71ad4f12021-05-25 14:56:27 +08009923 @VisibleForTesting
9924 @NonNull
9925 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
9926 @NonNull final Set<Integer> uids) {
9927 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9928 if (uids.size() == 0) {
9929 // Should not create NetworkRequestInfo if no preferences. Without uid range in
9930 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
9931 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
9932 return nris;
9933 }
9934
9935 final List<NetworkRequest> requests = new ArrayList<>();
9936 // The NRI should be comprised of two layers:
9937 // - The request for the mobile network preferred.
9938 // - The request for the default network, for fallback.
9939 requests.add(createDefaultInternetRequestForTransport(
Paul Hu07950df2021-07-02 01:44:52 +00009940 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu71ad4f12021-05-25 14:56:27 +08009941 requests.add(createDefaultInternetRequestForTransport(
9942 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9943 final Set<UidRange> ranges = new ArraySet<>();
9944 for (final int uid : uids) {
9945 ranges.add(new UidRange(uid, uid));
9946 }
9947 setNetworkRequestUids(requests, ranges);
paulhuc2198772021-05-26 15:19:20 +08009948 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhude5efb92021-05-26 21:56:03 +08009949 PREFERENCE_PRIORITY_MOBILE_DATA_PREFERERRED));
paulhu71ad4f12021-05-25 14:56:27 +08009950 return nris;
9951 }
9952
9953 private void handleMobileDataPreferredUidsChanged() {
paulhu71ad4f12021-05-25 14:56:27 +08009954 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
9955 mSystemNetworkRequestCounter.transact(
9956 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
9957 () -> {
9958 final ArraySet<NetworkRequestInfo> nris =
9959 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
paulhude5efb92021-05-26 21:56:03 +08009960 replaceDefaultNetworkRequestsForPreference(nris,
9961 PREFERENCE_PRIORITY_MOBILE_DATA_PREFERERRED);
paulhu71ad4f12021-05-25 14:56:27 +08009962 });
9963 // Finally, rematch.
9964 rematchAllNetworksAndRequests();
9965 }
9966
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009967 private void enforceAutomotiveDevice() {
9968 final boolean isAutomotiveDevice =
9969 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9970 if (!isAutomotiveDevice) {
9971 throw new UnsupportedOperationException(
9972 "setOemNetworkPreference() is only available on automotive devices.");
9973 }
9974 }
9975
9976 /**
9977 * Used by automotive devices to set the network preferences used to direct traffic at an
9978 * application level as per the given OemNetworkPreferences. An example use-case would be an
9979 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9980 * vehicle via a particular network.
9981 *
9982 * Calling this will overwrite the existing preference.
9983 *
9984 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
9985 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
9986 * to communicate completion of setOemNetworkPreference();
9987 */
9988 @Override
9989 public void setOemNetworkPreference(
9990 @NonNull final OemNetworkPreferences preference,
9991 @Nullable final IOnCompleteListener listener) {
9992
James Mattisb7ca0342021-06-16 01:30:05 +00009993 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9994 // Only bypass the permission/device checks if this is a valid test request.
9995 if (isValidTestOemNetworkPreference(preference)) {
9996 enforceManageTestNetworksPermission();
9997 } else {
9998 enforceAutomotiveDevice();
9999 enforceOemNetworkPreferencesPermission();
10000 validateOemNetworkPreferences(preference);
10001 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010002
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010003 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10004 new Pair<>(preference, listener)));
10005 }
10006
James Mattisb7ca0342021-06-16 01:30:05 +000010007 /**
10008 * Check the validity of an OEM network preference to be used for testing purposes.
10009 * @param preference the preference to validate
10010 * @return true if this is a valid OEM network preference test request.
10011 */
10012 private boolean isValidTestOemNetworkPreference(
10013 @NonNull final OemNetworkPreferences preference) {
10014 // Allow for clearing of an existing OemNetworkPreference used for testing.
10015 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10016 // changes after this check is complete. This is an unlikely scenario as calling of this API
10017 // is controlled by the OEM therefore the added complexity is not worth adding given those
10018 // circumstances. That said, it is an edge case to be aware of hence this comment.
10019 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10020 && isTestOemNetworkPreference(mOemNetworkPreferences);
10021 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10022 }
10023
10024 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10025 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10026 return prefMap.size() == 1
10027 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10028 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10029 }
10030
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010031 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10032 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10033 : preference.getNetworkPreferences().values()) {
James Mattisb7ca0342021-06-16 01:30:05 +000010034 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10035 throw new IllegalArgumentException(
10036 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10037 + " is an invalid value.");
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010038 }
10039 }
10040 }
10041
10042 private void handleSetOemNetworkPreference(
10043 @NonNull final OemNetworkPreferences preference,
10044 @Nullable final IOnCompleteListener listener) {
10045 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10046 if (DBG) {
10047 log("set OEM network preferences :" + preference.toString());
10048 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010049
10050 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
10051 final int uniquePreferenceCount = new ArraySet<>(
10052 preference.getNetworkPreferences().values()).size();
10053 mSystemNetworkRequestCounter.transact(
10054 mDeps.getCallingUid(), uniquePreferenceCount,
10055 () -> {
10056 final ArraySet<NetworkRequestInfo> nris =
10057 new OemNetworkRequestFactory()
10058 .createNrisFromOemNetworkPreferences(preference);
paulhude5efb92021-05-26 21:56:03 +080010059 replaceDefaultNetworkRequestsForPreference(nris, PREFERENCE_PRIORITY_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010060 });
10061 mOemNetworkPreferences = preference;
10062
10063 if (null != listener) {
10064 try {
10065 listener.onComplete();
10066 } catch (RemoteException e) {
10067 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
10068 }
10069 }
10070 }
10071
10072 private void replaceDefaultNetworkRequestsForPreference(
paulhude5efb92021-05-26 21:56:03 +080010073 @NonNull final Set<NetworkRequestInfo> nris, final int preferencePriority) {
10074 // Skip the requests which are set by other network preference. Because the uid range rules
10075 // should stay in netd.
10076 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
10077 requests.removeIf(request -> request.mPreferencePriority != preferencePriority);
10078 handleRemoveNetworkRequests(requests);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010079 addPerAppDefaultNetworkRequests(nris);
10080 }
10081
10082 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10083 ensureRunningOnConnectivityServiceThread();
10084 mDefaultNetworkRequests.addAll(nris);
10085 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10086 getPerAppCallbackRequestsToUpdate();
10087 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
10088 mSystemNetworkRequestCounter.transact(
10089 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
10090 () -> {
10091 nrisToRegister.addAll(
10092 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10093 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10094 handleRegisterNetworkRequests(nrisToRegister);
10095 });
10096 }
10097
10098 /**
10099 * All current requests that are tracking the default network need to be assessed as to whether
10100 * or not the current set of per-application default requests will be changing their default
10101 * network. If so, those requests will need to be updated so that they will send callbacks for
10102 * default network changes at the appropriate time. Additionally, those requests tracking the
10103 * default that were previously updated by this flow will need to be reassessed.
10104 * @return the nris which will need to be updated.
10105 */
10106 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10107 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10108 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10109 // same nri in the map's values for each of its NetworkRequest objects.
10110 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
10111 for (final NetworkRequestInfo nri : nris) {
10112 // Include this nri if it is currently being tracked.
10113 if (isPerAppTrackedNri(nri)) {
10114 defaultCallbackRequests.add(nri);
10115 continue;
10116 }
10117 // We only track callbacks for requests tracking the default.
10118 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10119 continue;
10120 }
10121 // Include this nri if it will be tracked by the new per-app default requests.
10122 final boolean isNriGoingToBeTracked =
10123 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
10124 if (isNriGoingToBeTracked) {
10125 defaultCallbackRequests.add(nri);
10126 }
10127 }
10128 return defaultCallbackRequests;
10129 }
10130
10131 /**
10132 * Create nris for those network requests that are currently tracking the default network that
10133 * are being controlled by a per-application default.
10134 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10135 * foundation when creating the nri. Important items include the calling uid's original
10136 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10137 * requests are assumed to have already been validated as needing to be updated.
10138 * @return the Set of nris to use when registering network requests.
10139 */
10140 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10141 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10142 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10143 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10144 final NetworkRequestInfo trackingNri =
10145 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10146
10147 // If this nri is not being tracked, the change it back to an untracked nri.
10148 if (trackingNri == mDefaultRequest) {
10149 callbackRequestsToRegister.add(new NetworkRequestInfo(
10150 callbackRequest,
10151 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10152 continue;
10153 }
10154
10155 final NetworkRequest request = callbackRequest.mRequests.get(0);
10156 callbackRequestsToRegister.add(new NetworkRequestInfo(
10157 callbackRequest,
10158 copyNetworkRequestsForUid(
10159 trackingNri.mRequests, callbackRequest.mAsUid,
10160 callbackRequest.mUid, request.getRequestorPackageName())));
10161 }
10162 return callbackRequestsToRegister;
10163 }
10164
10165 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10166 @NonNull final Set<UidRange> uids) {
10167 for (final NetworkRequest req : requests) {
10168 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10169 }
10170 }
10171
10172 /**
10173 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10174 */
10175 @VisibleForTesting
10176 final class OemNetworkRequestFactory {
10177 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10178 @NonNull final OemNetworkPreferences preference) {
10179 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10180 final SparseArray<Set<Integer>> uids =
10181 createUidsFromOemNetworkPreferences(preference);
10182 for (int i = 0; i < uids.size(); i++) {
10183 final int key = uids.keyAt(i);
10184 final Set<Integer> value = uids.valueAt(i);
10185 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10186 // No need to add an nri without any requests.
10187 if (0 == nri.mRequests.size()) {
10188 continue;
10189 }
10190 nris.add(nri);
10191 }
10192
10193 return nris;
10194 }
10195
10196 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10197 @NonNull final OemNetworkPreferences preference) {
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010198 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010199 final PackageManager pm = mContext.getPackageManager();
10200 final List<UserHandle> users =
10201 mContext.getSystemService(UserManager.class).getUserHandles(true);
10202 if (null == users || users.size() == 0) {
10203 if (VDBG || DDBG) {
10204 log("No users currently available for setting the OEM network preference.");
10205 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010206 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010207 }
10208 for (final Map.Entry<String, Integer> entry :
10209 preference.getNetworkPreferences().entrySet()) {
10210 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010211 // Add the rules for all users as this policy is device wide.
10212 for (final UserHandle user : users) {
10213 try {
10214 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10215 if (!prefToUids.contains(pref)) {
10216 prefToUids.put(pref, new ArraySet<>());
10217 }
10218 prefToUids.get(pref).add(uid);
10219 } catch (PackageManager.NameNotFoundException e) {
10220 // Although this may seem like an error scenario, it is ok that uninstalled
10221 // packages are sent on a network preference as the system will watch for
10222 // package installations associated with this network preference and update
10223 // accordingly. This is done to minimize race conditions on app install.
10224 continue;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010225 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010226 }
10227 }
Lorenzo Colitti659a0e12021-06-14 06:32:56 +000010228 return prefToUids;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010229 }
10230
10231 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10232 @OemNetworkPreferences.OemNetworkPreference final int preference,
10233 @NonNull final Set<Integer> uids) {
10234 final List<NetworkRequest> requests = new ArrayList<>();
10235 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10236 switch (preference) {
10237 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10238 requests.add(createUnmeteredNetworkRequest());
10239 requests.add(createOemPaidNetworkRequest());
10240 requests.add(createDefaultInternetRequestForTransport(
10241 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10242 break;
10243 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10244 requests.add(createUnmeteredNetworkRequest());
10245 requests.add(createOemPaidNetworkRequest());
10246 break;
10247 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10248 requests.add(createOemPaidNetworkRequest());
10249 break;
10250 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10251 requests.add(createOemPrivateNetworkRequest());
10252 break;
James Mattisb7ca0342021-06-16 01:30:05 +000010253 case OEM_NETWORK_PREFERENCE_TEST:
10254 requests.add(createUnmeteredNetworkRequest());
10255 requests.add(createTestNetworkRequest());
10256 requests.add(createDefaultRequest());
10257 break;
10258 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10259 requests.add(createTestNetworkRequest());
10260 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010261 default:
10262 // This should never happen.
10263 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10264 + " called with invalid preference of " + preference);
10265 }
10266
James Mattisb7ca0342021-06-16 01:30:05 +000010267 final ArraySet<UidRange> ranges = new ArraySet<>();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010268 for (final int uid : uids) {
10269 ranges.add(new UidRange(uid, uid));
10270 }
10271 setNetworkRequestUids(requests, ranges);
paulhude5efb92021-05-26 21:56:03 +080010272 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_PRIORITY_OEM);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010273 }
10274
10275 private NetworkRequest createUnmeteredNetworkRequest() {
10276 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10277 .addCapability(NET_CAPABILITY_NOT_METERED)
10278 .addCapability(NET_CAPABILITY_VALIDATED);
10279 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10280 }
10281
10282 private NetworkRequest createOemPaidNetworkRequest() {
10283 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10284 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10285 .addCapability(NET_CAPABILITY_OEM_PAID)
10286 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10287 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10288 }
10289
10290 private NetworkRequest createOemPrivateNetworkRequest() {
10291 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10292 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10293 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10294 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10295 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10296 }
10297
10298 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisb7ca0342021-06-16 01:30:05 +000010299 final NetworkCapabilities netcap = new NetworkCapabilities();
10300 netcap.addCapability(NET_CAPABILITY_INTERNET);
10301 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10302 return netcap;
10303 }
10304
10305 private NetworkRequest createTestNetworkRequest() {
10306 final NetworkCapabilities netcap = new NetworkCapabilities();
10307 netcap.clearAll();
10308 netcap.addTransportType(TRANSPORT_TEST);
10309 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000010310 }
10311 }
10312}