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