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