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